Skip to content

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

chore: backend + frontend follow-ons for v1.4.0-beta

Bingxi Zhao (Frank)90a2c14c812b
diff --git a/deeptutor/api/main.py b/deeptutor/api/main.py
index bbb07f080..368832913 100644
--- a/deeptutor/api/main.py
+++ b/deeptutor/api/main.py
@@ -166,6 +166,17 @@ async def lifespan(app: FastAPI):
except Exception as e:
logger.warning(f"PocketBase startup check failed: {e}")
+ # Migrate any v1 memory files (PROFILE.md / SUMMARY.md) into a
+ # backup folder so the v2 three-layer subsystem starts clean.
+ try:
+ from deeptutor.services.memory import migrate_v1_if_needed
+
+ backup = migrate_v1_if_needed()
+ if backup is not None:
+ logger.info("v1 memory archived to %s", backup)
+ except Exception as e:
+ logger.warning(f"v1 memory migration failed: {e}")
+
yield
# Execute on shutdown
@@ -259,6 +270,7 @@ from deeptutor.api.routers import (
attachments,
auth,
book,
+ capabilities_settings,
chat,
co_writer,
dashboard,
@@ -268,15 +280,18 @@ from deeptutor.api.routers import (
plugins_api,
question,
question_notebook,
+ quiz_judge,
sessions,
settings,
skills,
- solve,
system,
tutorbot,
unified_ws,
vision_solver,
)
+from deeptutor.api.routers import (
+ tools as tools_router,
+)
from deeptutor.multi_user.router import router as multi_user_router # noqa: E402
# Auth router is public — login/logout/register/status require no token
@@ -295,7 +310,6 @@ app.include_router(
dependencies=_auth,
)
-app.include_router(solve.router, prefix="/api/v1", tags=["solve"], dependencies=_auth)
app.include_router(chat.router, prefix="/api/v1", tags=["chat"], dependencies=_auth)
app.include_router(
question.router, prefix="/api/v1/question", tags=["question"], dependencies=_auth
@@ -314,6 +328,12 @@ app.include_router(
)
app.include_router(book.router, prefix="/api/v1/book", tags=["book"], dependencies=_auth)
app.include_router(memory.router, prefix="/api/v1/memory", tags=["memory"], dependencies=_auth)
+app.include_router(
+ capabilities_settings.router,
+ prefix="/api/v1/capabilities",
+ tags=["capabilities"],
+ dependencies=_auth,
+)
app.include_router(
sessions.router, prefix="/api/v1/sessions", tags=["sessions"], dependencies=_auth
)
@@ -327,6 +347,7 @@ app.include_router(
settings.router, prefix="/api/v1/settings", tags=["settings"], dependencies=_auth
)
app.include_router(skills.router, prefix="/api/v1/skills", tags=["skills"], dependencies=_auth)
+app.include_router(tools_router.router, prefix="/api/v1/tools", tags=["tools"], dependencies=_auth)
app.include_router(system.router, prefix="/api/v1/system", tags=["system"], dependencies=_auth)
app.include_router(
plugins_api.router, prefix="/api/v1/plugins", tags=["plugins"], dependencies=_auth
@@ -351,6 +372,10 @@ app.include_router(
# cannot use FastAPI dependencies in the standard way)
app.include_router(unified_ws.router, prefix="/api/v1", tags=["unified-ws"])
+# Quiz AI-judge WebSocket — same caveat as unified_ws above; auth is checked
+# inside the handler so the WS upgrade isn't rejected by an HTTP-style dep.
+app.include_router(quiz_judge.router, prefix="/api/v1", tags=["quiz-judge"])
+
@app.get("/")
async def root():
diff --git a/deeptutor/api/routers/question_notebook.py b/deeptutor/api/routers/question_notebook.py
index 151a33545..fb89f93a0 100644
--- a/deeptutor/api/routers/question_notebook.py
+++ b/deeptutor/api/routers/question_notebook.py
@@ -4,12 +4,15 @@ Question Notebook API — persists quiz questions, bookmarks, and categories.
from __future__ import annotations
+import base64 as _b64
import logging
+import uuid as _uuid
from fastapi import APIRouter, HTTPException, Query
from pydantic import BaseModel, Field
from deeptutor.services.session import get_sqlite_session_store
+from deeptutor.services.storage import get_attachment_store
logger = logging.getLogger(__name__)
@@ -19,10 +22,24 @@ router = APIRouter()
# ── Models ────────────────────────────────────────────────────────
+class AnswerImageItem(BaseModel):
+ """Persisted reference to one image attached to a learner's answer.
+
+ The bytes live in the AttachmentStore at ``url``; we never round-trip
+ base64 back to the client so notebook lookups stay cheap.
+ """
+
+ id: str = ""
+ url: str = ""
+ filename: str = ""
+ mime_type: str = ""
+
+
class NotebookEntryItem(BaseModel):
id: int
session_id: str
session_title: str = ""
+ turn_id: str = ""
question_id: str = ""
question: str
question_type: str = ""
@@ -31,9 +48,11 @@ class NotebookEntryItem(BaseModel):
explanation: str = ""
difficulty: str = ""
user_answer: str = ""
+ user_answer_images: list[AnswerImageItem] = []
is_correct: bool = False
bookmarked: bool = False
followup_session_id: str = ""
+ ai_judgment: str = ""
created_at: float
updated_at: float
categories: list[CategoryItem] | None = None
@@ -47,6 +66,7 @@ class NotebookEntryListResponse(BaseModel):
class EntryUpdateRequest(BaseModel):
bookmarked: bool | None = None
followup_session_id: str | None = None
+ ai_judgment: str | None = None
class CategoryItem(BaseModel):
@@ -68,8 +88,25 @@ class CategoryAddRequest(BaseModel):
category_id: int
+class AnswerImageUpload(BaseModel):
+ """One image attached to the learner's answer.
+
+ Either ``base64`` (new upload) or ``url`` (re-submit of an already
+ persisted image) must be set. ``id`` is preserved when the client
+ sends one so the same logical image keeps a stable AttachmentStore
+ record across resubmissions.
+ """
+
+ id: str = ""
+ base64: str = ""
+ url: str = ""
+ filename: str = "answer.png"
+ mime_type: str = "image/png"
+
+
class UpsertEntryRequest(BaseModel):
session_id: str
+ turn_id: str = ""
question_id: str
question: str
question_type: str = ""
@@ -78,20 +115,88 @@ class UpsertEntryRequest(BaseModel):
explanation: str = ""
difficulty: str = ""
user_answer: str = ""
+ # Optional: list of images attached as part of the learner's answer.
+ # ``None`` means "don't touch any previously-stored images on update";
+ # an empty list explicitly clears them.
+ user_answer_images: list[AnswerImageUpload] | None = None
is_correct: bool = False
# ── Entry endpoints ──────────────────────────────────────────────
+async def _persist_answer_images(
+ session_id: str, images: list[AnswerImageUpload] | None
+) -> list[dict[str, str]] | None:
+ """Materialise base64 image uploads into the AttachmentStore.
+
+ Returns a list of ``{id, url, filename, mime_type}`` records suitable
+ for ``notebook_entries.user_answer_images_json``. ``None`` is returned
+ when ``images`` is ``None`` (no change to existing stored images).
+ Records whose bytes fail to upload are dropped from the result with
+ a warning — losing an image is better than failing the whole upsert.
+ """
+ if images is None:
+ return None
+
+ attachment_store = get_attachment_store()
+ records: list[dict[str, str]] = []
+ for image in images:
+ record_id = (image.id or _uuid.uuid4().hex[:12]).strip()
+ filename = (image.filename or "answer.png").strip() or "answer.png"
+ mime_type = (image.mime_type or "image/png").strip() or "image/png"
+ url = (image.url or "").strip()
+
+ if not url and image.base64:
+ try:
+ raw_bytes = _b64.b64decode(image.base64, validate=False)
+ except Exception as exc:
+ logger.warning("answer image %s rejected: invalid base64 (%s)", filename, exc)
+ continue
+ try:
+ url = await attachment_store.put(
+ session_id=session_id,
+ attachment_id=record_id,
+ filename=filename,
+ data=raw_bytes,
+ mime_type=mime_type,
+ )
+ except Exception as exc:
+ logger.warning("attachment store rejected answer image %s: %s", filename, exc)
+ continue
+
+ if not url:
+ # No url and no base64 — nothing usable.
+ continue
+ records.append(
+ {
+ "id": record_id,
+ "url": url,
+ "filename": filename,
+ "mime_type": mime_type,
+ }
+ )
+ return records
+
+
@router.post("/entries/upsert")
async def upsert_single_entry(payload: UpsertEntryRequest):
store = get_sqlite_session_store()
+ images_records = await _persist_answer_images(payload.session_id, payload.user_answer_images)
+ item = payload.model_dump()
+ # The store expects ``user_answer_images`` as a plain list of dicts
+ # (or absent to mean "leave the stored images alone"). Strip the
+ # upload payload version and replace with the persisted records.
+ item.pop("user_answer_images", None)
+ if images_records is not None:
+ item["user_answer_images"] = images_records
try:
- await store.upsert_notebook_entries(payload.session_id, [payload.model_dump()])
+ await store.upsert_notebook_entries(payload.session_id, [item])
except ValueError as e:
raise HTTPException(status_code=404, detail=str(e))
- entry = await store.find_notebook_entry(payload.session_id, payload.question_id)
+ entry = await store.find_notebook_entry(
+ payload.session_id, payload.question_id, turn_id=payload.turn_id
+ )
if entry is None:
raise HTTPException(status_code=500, detail="Upsert failed")
return entry
@@ -120,9 +225,13 @@ async def list_entries(
@router.get("/entries/lookup/by-question")
-async def lookup_entry(session_id: str = Query(...), question_id: str = Query(...)):
+async def lookup_entry(
+ session_id: str = Query(...),
+ question_id: str = Query(...),
+ turn_id: str | None = Query(default=None),
+):
store = get_sqlite_session_store()
- entry = await store.find_notebook_entry(session_id, question_id)
+ entry = await store.find_notebook_entry(session_id, question_id, turn_id=turn_id)
if entry is None:
raise HTTPException(status_code=404, detail="Entry not found")
return entry
diff --git a/deeptutor/api/routers/sessions.py b/deeptutor/api/routers/sessions.py
index b09e99360..60798981a 100644
--- a/deeptutor/api/routers/sessions.py
+++ b/deeptutor/api/routers/sessions.py
@@ -55,6 +55,7 @@ class QuizResultItem(BaseModel):
class QuizResultsRequest(BaseModel):
answers: list[QuizResultItem] = Field(default_factory=list)
+ turn_id: str = ""
def _format_quiz_results_message(answers: list[QuizResultItem]) -> str:
@@ -79,16 +80,9 @@ 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, kind=kind)
+ sessions = await store.list_sessions(limit=limit, offset=offset)
return {"sessions": sessions}
@@ -176,7 +170,7 @@ async def record_quiz_results(session_id: str, payload: QuizResultsRequest):
try:
notebook_count = await store.upsert_notebook_entries(
session_id,
- [item.model_dump() for item in payload.answers],
+ [{**item.model_dump(), "turn_id": payload.turn_id} for item in payload.answers],
)
except Exception:
logger.warning(
diff --git a/deeptutor/api/routers/settings.py b/deeptutor/api/routers/settings.py
index c21327c39..9bc9bcc1f 100644
--- a/deeptutor/api/routers/settings.py
+++ b/deeptutor/api/routers/settings.py
@@ -27,6 +27,7 @@ from deeptutor.services.llm.client import reset_llm_client
from deeptutor.services.llm.config import clear_llm_config_cache
from deeptutor.services.model_selection import list_llm_options
from deeptutor.services.path_service import get_path_service
+from deeptutor.tools.builtin import USER_TOGGLEABLE_TOOL_NAMES
router = APIRouter()
@@ -53,6 +54,11 @@ DEFAULT_UI_SETTINGS = {
"language": "en",
"sidebar_description": "✨ Data Intelligence Lab @ HKU",
"sidebar_nav_order": DEFAULT_SIDEBAR_NAV_ORDER,
+ # User-toggleable chat tools. Default = all on; the /settings/tools page
+ # is the single switchboard. Removed names (e.g. tools that ship later
+ # and the user hasn't seen yet) are ignored on read; missing names from a
+ # legacy file fall back to the default (all on).
+ "enabled_optional_tools": list(USER_TOGGLEABLE_TOOL_NAMES),
}
@@ -84,6 +90,10 @@ class SidebarNavOrderUpdate(BaseModel):
nav_order: SidebarNavOrder
+class EnabledToolsUpdate(BaseModel):
+ enabled_tools: List[str]
+
+
class CatalogPayload(BaseModel):
catalog: dict[str, Any]
@@ -111,12 +121,41 @@ def load_ui_settings() -> dict[str, Any]:
try:
with open(settings_file, encoding="utf-8") as handle:
saved = json.load(handle)
- return {**DEFAULT_UI_SETTINGS, **saved}
+ merged = {**DEFAULT_UI_SETTINGS, **saved}
+ # Filter persisted enabled_optional_tools to current
+ # toggleable set so retired tool names can't leak into
+ # the per-turn payload.
+ merged["enabled_optional_tools"] = _sanitize_enabled_tools(
+ merged.get("enabled_optional_tools")
+ )
+ return merged
except Exception:
pass
return DEFAULT_UI_SETTINGS.copy()
+def _sanitize_enabled_tools(value: Any) -> list[str]:
+ if not isinstance(value, list):
+ return list(USER_TOGGLEABLE_TOOL_NAMES)
+ allowed = set(USER_TOGGLEABLE_TOOL_NAMES)
+ seen: set[str] = set()
+ out: list[str] = []
+ for name in value:
+ if isinstance(name, str) and name in allowed and name not in seen:
+ seen.add(name)
+ out.append(name)
+ return out
+
+
+def get_enabled_optional_tools() -> list[str]:
+ """Return the user's currently-enabled toggleable tool names.
+
+ Source of truth for the chat pipeline when a turn doesn't ship an
+ explicit ``tools`` list.
+ """
+ return _sanitize_enabled_tools(load_ui_settings().get("enabled_optional_tools"))
+
+
def save_ui_settings(settings: dict[str, Any]) -> None:
settings_file = _settings_file()
settings_file.parent.mkdir(parents=True, exist_ok=True)
@@ -298,6 +337,15 @@ async def update_sidebar_nav_order(update: SidebarNavOrderUpdate):
return {"nav_order": update.nav_order.model_dump()}
[email protected]("/enabled-tools")
+async def update_enabled_tools(update: EnabledToolsUpdate):
+ sanitized = _sanitize_enabled_tools(update.enabled_tools)
+ current_ui = load_ui_settings()
+ current_ui["enabled_optional_tools"] = sanitized
+ save_ui_settings(current_ui)
+ return {"enabled_optional_tools": sanitized}
+
+
@router.post("/tests/{service}/start")
async def start_service_test(service: str, payload: CatalogPayload | None = None):
_require_settings_admin()
diff --git a/deeptutor/api/routers/tutorbot.py b/deeptutor/api/routers/tutorbot.py
index be8c805c6..be15567a5 100644
--- a/deeptutor/api/routers/tutorbot.py
+++ b/deeptutor/api/routers/tutorbot.py
@@ -464,10 +464,11 @@ async def bot_chat_ws(ws: WebSocket, bot_id: str):
await _safe_send({"type": "thinking", "content": text})
try:
+ chat_id_value = data.get("chat_id", "web")
response = await mgr.send_message(
bot_id,
content,
- chat_id=data.get("chat_id", "web"),
+ chat_id=chat_id_value,
on_progress=on_progress,
)
if not await _safe_send({"type": "content", "content": response}):
diff --git a/deeptutor/api/routers/unified_ws.py b/deeptutor/api/routers/unified_ws.py
index 6a263623a..527404351 100644
--- a/deeptutor/api/routers/unified_ws.py
+++ b/deeptutor/api/routers/unified_ws.py
@@ -12,6 +12,8 @@ Supported client message ``type`` values:
- ``resume_from`` — resume an in-flight turn after reconnection.
- ``unsubscribe`` — stop a previously created subscription.
- ``cancel_turn`` — cancel a running turn.
+- ``submit_user_reply`` — deliver the user's reply for an ``ask_user``
+ paused turn so the agentic loop can resume on the same turn.
- ``regenerate`` — re-run the last user message in the given session as a
brand-new turn. Replaces the trailing assistant message (if any) and
reuses the session's stored capability/tools/preferences. Optional
@@ -177,6 +179,42 @@ async def unified_websocket(ws: WebSocket) -> None:
await safe_send({"type": "error", "content": f"Turn not found: {turn_id}"})
continue
+ if msg_type == "submit_user_reply":
+ turn_id = str(msg.get("turn_id") or "").strip()
+ if not turn_id:
+ await safe_send({"type": "error", "content": "Missing turn_id."})
+ continue
+ # Accept either the legacy ``text`` (single free-form
+ # reply) or the v2 ``answers`` (list of {questionId, text}
+ # pairs). Empty text is allowed (lets the user signal "I
+ # have no answer" without typing).
+ text = msg.get("text")
+ text_str = str(text) if text is not None else None
+ answers_raw = msg.get("answers")
+ answers: list[dict[str, Any]] | None = None
+ if isinstance(answers_raw, list):
+ cleaned: list[dict[str, Any]] = []
+ for entry in answers_raw:
+ if not isinstance(entry, dict):
+ continue
+ qid = str(entry.get("questionId") or entry.get("id") or "").strip()
+ if not qid:
+ continue
+ cleaned.append({"questionId": qid, "text": str(entry.get("text") or "")})
+ answers = cleaned or None
+ from deeptutor.services.session import get_turn_runtime_manager
+
+ runtime = get_turn_runtime_manager()
+ accepted = await runtime.submit_user_reply(turn_id, text=text_str, answers=answers)
+ if not accepted:
+ await safe_send(
+ {
+ "type": "error",
+ "content": (f"Turn {turn_id} is not awaiting a user reply."),
+ }
+ )
+ continue
+
if msg_type == "regenerate":
session_id = str(msg.get("session_id") or "").strip()
if not session_id:
diff --git a/deeptutor/runtime/banner.py b/deeptutor/runtime/banner.py
index 53b4d1845..a571f1b86 100644
--- a/deeptutor/runtime/banner.py
+++ b/deeptutor/runtime/banner.py
@@ -30,20 +30,64 @@ LABELS: dict[str, dict[str, str]] = {
"init.mode": "Workspace initializer",
"init.workspace": "Workspace",
"init.note_settings_dir": "Settings will be written under data/user/settings.",
+ "init.cancelled": "Setup cancelled. Nothing was saved.",
+ "init.step_ports": "Step {n}/{total} · Ports",
+ "init.step_llm": "Step {n}/{total} · LLM provider",
+ "init.step_embedding": "Step {n}/{total} · Embedding (RAG / Knowledge Base)",
+ "init.step_search": "Step {n}/{total} · Web search",
+ "init.step_review": "Step {n}/{total} · Review & save",
"init.backend_port": "Backend port",
"init.frontend_port": "Frontend port",
"init.llm_section": "LLM provider",
+ "init.pick_provider": "Pick an LLM provider",
+ "init.pick_embedding_provider": "Pick an embedding provider",
+ "init.show_all": "Show all providers",
+ "init.custom_provider": "Custom / Other",
+ "init.skip_step": "Skip / configure later",
+ "init.back": "Back",
+ "init.skipped": "Skipped — you can configure this later in Web Settings.",
"init.binding": "Binding",
"init.base_url": "Base URL",
"init.api_key": "API key",
+ "init.api_key_env_detected": "Detected {env_var}={masked} in your environment. Use it?",
+ "init.api_key_prompt": "API key (input hidden, Enter to skip)",
+ "init.api_key_reuse_llm": "Reuse the LLM API key {masked}?",
+ "init.edit_base_url": "Edit Base URL?",
+ "init.new_base_url": "New Base URL",
"init.model": "Model",
- "init.confirm_embedding": "Configure embedding for Knowledge Base/RAG now?",
+ "init.fetch_models": "Fetching available models from {url} ...",
+ "init.fetch_models_ok": "Found {count} model(s).",
+ "init.fetch_models_fail": "Could not list models ({error}). Using fallback list.",
+ "init.pick_model": "Pick a model — or type {marker} to enter your own",
+ "init.custom_model": "Custom model name",
"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.search_section": "Web search provider",
+ "init.pick_search_provider": "Pick a web-search provider",
+ "init.search_api_key_prompt": "API key (input hidden, Enter to skip)",
+ "init.search_base_url_prompt": "Base URL",
+ "init.search_no_key_note": "{label} does not need an API key.",
+ "init.search_disabled_note": "Web search will be disabled. Agents will skip search tools.",
+ "init.review_search": "Search",
+ "init.review_search_disabled": "disabled",
+ "init.probe_offer": "Test connection now?",
+ "init.probe_running": "Testing {what} ...",
+ "init.probe_ok": "{what} OK · {ms}ms",
+ "init.probe_fail": "{what} failed: {error}",
+ "init.probe_retry": "Re-enter API key and retry?",
+ "init.review_title": "Review",
+ "init.review_llm": "LLM",
+ "init.review_embedding": "Embedding",
+ "init.review_ports": "Ports",
+ "init.review_ports_value": "backend {backend}, frontend {frontend}",
+ "init.confirm_save": "Save these settings?",
"init.saved": "Settings saved. You can edit them later in the Web Settings page or data/user/settings/.",
+ "init.next_step": "Run `deeptutor start` to launch DeepTutor.",
+ "init.choice": "Choice",
+ "init.choice_invalid": "Invalid choice. Try again.",
# start (launcher)
"start.mode": "Launching backend + frontend",
"start.backend": "Backend",
@@ -54,6 +98,14 @@ LABELS: dict[str, dict[str, str]] = {
"start.press_ctrl_c": "Press Ctrl+C to stop.",
"start.starting_backend": "Starting backend ...",
"start.starting_frontend": "Starting frontend ...",
+ "start.reusing_frontend": "Reusing existing frontend at {url} (PID {pid}).",
+ "start.restarting_frontend": (
+ "Existing frontend at {url} is not responding; restarting it (PID {pid})."
+ ),
+ "start.frontend_restart_failed": (
+ "Existing frontend at {url} is not responding and could not be stopped automatically. "
+ "Stop PID {pid} and run `deeptutor start` again."
+ ),
"start.waiting_for": "Waiting for {name} at {url} ...",
"start.ready": "{name} is ready.",
"start.open_in_browser": "Open {url} in your browser.",
@@ -73,20 +125,64 @@ LABELS: dict[str, dict[str, str]] = {
"init.mode": "工作目录初始化",
"init.workspace": "工作目录",
"init.note_settings_dir": "配置文件将写入 data/user/settings 目录。",
+ "init.cancelled": "已取消,未保存任何更改。",
+ "init.step_ports": "第 {n}/{total} 步 · 端口",
+ "init.step_llm": "第 {n}/{total} 步 · 大模型服务",
+ "init.step_embedding": "第 {n}/{total} 步 · 向量模型 (知识库 / RAG)",
+ "init.step_search": "第 {n}/{total} 步 · 联网搜索",
+ "init.step_review": "第 {n}/{total} 步 · 确认并保存",
"init.backend_port": "后端端口",
"init.frontend_port": "前端端口",
"init.llm_section": "大模型服务",
+ "init.pick_provider": "请选择大模型服务",
+ "init.pick_embedding_provider": "请选择向量模型服务",
+ "init.show_all": "查看全部服务商",
+ "init.custom_provider": "其他 / 自定义",
+ "init.skip_step": "跳过 / 稍后配置",
+ "init.back": "返回上一步",
+ "init.skipped": "已跳过 —— 后续可在 Web 设置页中配置。",
"init.binding": "服务类型",
"init.base_url": "Base URL",
"init.api_key": "API Key",
+ "init.api_key_env_detected": "已检测到环境变量 {env_var}={masked},是否使用?",
+ "init.api_key_prompt": "API Key (输入不显示,直接回车跳过)",
+ "init.api_key_reuse_llm": "复用大模型的 API Key ({masked})?",
+ "init.edit_base_url": "需要修改 Base URL 吗?",
+ "init.new_base_url": "新的 Base URL",
"init.model": "模型",
- "init.confirm_embedding": "现在配置知识库 / RAG 所用的向量模型?",
+ "init.fetch_models": "正在从 {url} 拉取可用模型列表 ...",
+ "init.fetch_models_ok": "找到 {count} 个模型。",
+ "init.fetch_models_fail": "无法获取模型列表 ({error}),将使用本地推荐列表。",
+ "init.pick_model": "请选择模型 —— 或输入 {marker} 手动填写",
+ "init.custom_model": "自定义模型名称",
"init.embedding_section": "向量模型服务",
"init.embedding_endpoint": "向量服务地址",
"init.embedding_api_key": "向量服务 API Key",
"init.embedding_model": "向量模型",
"init.embedding_dimension": "向量维度 (留空自动检测)",
+ "init.search_section": "联网搜索服务",
+ "init.pick_search_provider": "请选择联网搜索服务",
+ "init.search_api_key_prompt": "API Key (输入不显示,直接回车跳过)",
+ "init.search_base_url_prompt": "Base URL",
+ "init.search_no_key_note": "{label} 无需 API Key。",
+ "init.search_disabled_note": "联网搜索将被禁用。Agent 将跳过搜索工具。",
+ "init.review_search": "搜索",
+ "init.review_search_disabled": "已禁用",
+ "init.probe_offer": "立即测试连接?",
+ "init.probe_running": "正在测试 {what} ...",
+ "init.probe_ok": "{what} 连接成功 · {ms}ms",
+ "init.probe_fail": "{what} 连接失败: {error}",
+ "init.probe_retry": "重新输入 API Key 并重试?",
+ "init.review_title": "配置确认",
+ "init.review_llm": "大模型",
+ "init.review_embedding": "向量",
+ "init.review_ports": "端口",
+ "init.review_ports_value": "后端 {backend},前端 {frontend}",
+ "init.confirm_save": "确认保存以上配置?",
"init.saved": "配置已保存。后续可在 Web 设置页或 data/user/settings/ 中修改。",
+ "init.next_step": "运行 `deeptutor start` 启动 DeepTutor。",
+ "init.choice": "请选择",
+ "init.choice_invalid": "无效选项,请重新输入。",
# start (launcher)
"start.mode": "启动后端 + 前端",
"start.backend": "后端",
@@ -97,6 +193,12 @@ LABELS: dict[str, dict[str, str]] = {
"start.press_ctrl_c": "按 Ctrl+C 停止。",
"start.starting_backend": "正在启动后端服务 ...",
"start.starting_frontend": "正在启动前端服务 ...",
+ "start.reusing_frontend": "复用已运行的前端 {url} (PID {pid})。",
+ "start.restarting_frontend": "已运行的前端 {url} 无响应,正在重启 (PID {pid})。",
+ "start.frontend_restart_failed": (
+ "已运行的前端 {url} 无响应,且无法自动停止。"
+ "请先停止 PID {pid},然后重新运行 `deeptutor start`。"
+ ),
"start.waiting_for": "正在等待 {name} ({url}) ...",
"start.ready": "{name} 已就绪。",
"start.open_in_browser": "请在浏览器中打开 {url}。",
diff --git a/deeptutor/runtime/launcher.py b/deeptutor/runtime/launcher.py
index f1b7a2bff..ee747f02b 100644
--- a/deeptutor/runtime/launcher.py
+++ b/deeptutor/runtime/launcher.py
@@ -16,6 +16,7 @@ import threading
import time
from typing import Callable
from urllib import error as urlerror
+from urllib import parse as urlparse
from urllib import request as urlrequest
from deeptutor.runtime.banner import labels_for, print_banner, resolve_language
@@ -23,6 +24,7 @@ from deeptutor.runtime.home import DEEPTUTOR_HOME_ENV, PACKAGE_ROOT, get_runtime
BACKEND_READY_TIMEOUT = 60
FRONTEND_READY_TIMEOUT = 120
+FRONTEND_REUSE_PROBE_TIMEOUT = 2
KILL_SIGNAL = getattr(signal, "SIGKILL", signal.SIGTERM)
WEB_CACHE_DIR = Path("data") / "user" / "runtime" / "web"
@@ -55,6 +57,14 @@ class FrontendRuntime:
cwd: Path
+@dataclass(frozen=True, slots=True)
+class ExistingFrontendRuntime:
+ url: str
+ port: int
+ pid: int | None
+ lock_path: Path
+
+
def _log(message: str) -> None:
print(message, flush=True)
@@ -95,6 +105,8 @@ def _is_pid_alive(pid: int | None) -> bool:
return False
try:
os.kill(pid, 0)
+ except PermissionError:
+ return True
except OSError:
return False
return True
@@ -178,7 +190,7 @@ def _wait_for_http(
*,
name: str,
url: str,
- process: ManagedProcess,
+ process: ManagedProcess | None,
timeout: int,
should_stop: Callable[[], bool],
) -> None:
@@ -187,7 +199,7 @@ def _wait_for_http(
while time.monotonic() < deadline:
if should_stop():
return
- if process.process.poll() is not None:
+ if process is not None and process.process.poll() is not None:
raise RuntimeError(_t("start.exited", name=name, code=process.process.returncode))
try:
with urlrequest.urlopen(url, timeout=1): # noqa: S310 # nosec B310 - http(s) health-check URL constructed by caller
@@ -198,6 +210,14 @@ def _wait_for_http(
raise RuntimeError(_t("start.not_ready", name=name, timeout=timeout))
+def _http_ready(url: str, *, timeout: float) -> bool:
+ try:
+ with urlrequest.urlopen(url, timeout=timeout): # noqa: S310 # nosec B310 - launcher health check
+ return True
+ except (urlerror.URLError, TimeoutError, OSError):
+ return False
+
+
def _packaged_web_dir() -> Path | None:
try:
import deeptutor_web
@@ -322,6 +342,141 @@ def _resolve_frontend(
)
+def _coerce_pid(value: object) -> int | None:
+ if isinstance(value, bool) or not isinstance(value, int | str):
+ return None
+ try:
+ pid = int(value)
+ except (TypeError, ValueError):
+ return None
+ return pid if pid > 0 else None
+
+
+def _coerce_port(value: object) -> int | None:
+ if isinstance(value, bool) or not isinstance(value, int | str):
+ return None
+ try:
+ port = int(value)
+ except (TypeError, ValueError):
+ return None
+ return port if 1 <= port <= 65535 else None
+
+
+def _local_app_url(value: object, port: int) -> str:
+ fallback = f"http://localhost:{port}"
+ if not isinstance(value, str) or not value.strip():
+ return fallback
+ raw = value.strip().rstrip("/")
+ try:
+ parsed = urlparse.urlparse(raw)
+ except ValueError:
+ return fallback
+ if parsed.scheme not in {"http", "https"}:
+ return fallback
+ if parsed.hostname not in {"localhost", "127.0.0.1", "::1"}:
+ return fallback
+ if parsed.port != port:
+ return fallback
+ return raw
+
+
+def _detect_existing_source_frontend(frontend: FrontendRuntime) -> ExistingFrontendRuntime | None:
+ """Return an already-running Next dev server for this source checkout."""
+
+ if frontend.kind != "source":
+ return None
+
+ lock_candidates = [
+ frontend.cwd / ".next" / "dev" / "lock",
+ frontend.cwd / ".next" / "lock",
+ ]
+ for lock_path in lock_candidates:
+ try:
+ payload = json.loads(lock_path.read_text(encoding="utf-8"))
+ except Exception:
+ continue
+ if not isinstance(payload, dict):
+ continue
+ port = _coerce_port(payload.get("port"))
+ if port is None:
+ continue
+ pid = _coerce_pid(payload.get("pid"))
+ if not _is_pid_alive(pid) and not _port_accepts_connection(port):
+ continue
+ return ExistingFrontendRuntime(
+ url=_local_app_url(payload.get("appUrl"), port),
+ port=port,
+ pid=pid,
+ lock_path=lock_path,
+ )
+ return None
+
+
+def _process_command(pid: int | None) -> str:
+ if pid is None or os.name == "nt":
+ return ""
+ ps = shutil.which("ps")
+ if not ps:
+ return ""
+ try:
+ completed = subprocess.run(
+ [ps, "-p", str(pid), "-o", "command="],
+ check=False,
+ capture_output=True,
+ text=True,
+ timeout=2,
+ )
+ except Exception:
+ return ""
+ return completed.stdout.strip()
+
+
+def _looks_like_next_process(pid: int | None) -> bool:
+ command = _process_command(pid).lower()
+ return bool(
+ command
+ and ("next-server" in command or "next/dist/bin/next" in command or " next dev" in command)
+ )
+
+
+def _stop_unhealthy_source_frontend(frontend: ExistingFrontendRuntime) -> bool:
+ """Stop a locked Next dev server only when the lock points at Next itself."""
+
+ if frontend.pid is None:
+ return False
+ if not _is_pid_alive(frontend.pid):
+ try:
+ frontend.lock_path.unlink(missing_ok=True)
+ except OSError:
+ pass
+ return True
+ if not _looks_like_next_process(frontend.pid):
+ return False
+
+ pgid = _get_pgid(frontend.pid)
+ try:
+ _send_tree_signal(frontend.pid, pgid, signal.SIGTERM)
+ except Exception:
+ return False
+
+ deadline = time.monotonic() + 5
+ while time.monotonic() < deadline and _is_pid_alive(frontend.pid):
+ time.sleep(0.2)
+
+ if _is_pid_alive(frontend.pid):
+ try:
+ _send_tree_signal(frontend.pid, pgid, KILL_SIGNAL)
+ except Exception:
+ return False
+ time.sleep(0.5)
+
+ try:
+ frontend.lock_path.unlink(missing_ok=True)
+ except OSError:
+ pass
+ return not _http_ready(frontend.url, timeout=0.5)
+
+
def _install_signal_handlers(request_shutdown: Callable[[str | None], None]) -> None:
def _handler(signum: int, _frame) -> None:
try:
@@ -378,17 +533,38 @@ def start(home: str | Path | None = None) -> None:
api_base=api_base,
auth_enabled=auth_enabled,
)
+ existing_frontend = _detect_existing_source_frontend(frontend)
+ if existing_frontend is not None and not _http_ready(
+ existing_frontend.url, timeout=FRONTEND_REUSE_PROBE_TIMEOUT
+ ):
+ pid = existing_frontend.pid if existing_frontend.pid is not None else "unknown"
+ _log(_t("start.restarting_frontend", url=existing_frontend.url, pid=pid))
+ if not _stop_unhealthy_source_frontend(existing_frontend):
+ raise SystemExit(
+ _t("start.frontend_restart_failed", url=existing_frontend.url, pid=pid)
+ )
+ existing_frontend = None
+ if existing_frontend is not None:
+ frontend_port = existing_frontend.port
+ frontend_url = (
+ existing_frontend.url
+ if existing_frontend is not None
+ else f"http://localhost:{frontend_port}"
+ )
print_banner(language=language, mode_key="start.mode")
_log(f"{_t('start.backend'):<10} {backend_url}")
if api_base != backend_url:
_log(f"{_t('start.browser_api'):<10} {api_base}")
- _log(f"{_t('start.frontend'):<10} http://localhost:{frontend_port}")
+ _log(f"{_t('start.frontend'):<10} {frontend_url}")
_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)
+ if existing_frontend is None:
+ _ensure_ports_available(backend_port, frontend_port)
+ else:
+ _ensure_ports_available(backend_port)
common_env = os.environ.copy()
common_env.update(runtime_env)
@@ -453,17 +629,28 @@ def start(home: str | Path | None = None) -> None:
should_stop=lambda: shutdown_requested,
)
- _log(_t("start.starting_frontend"))
- web = _spawn(frontend.command, cwd=frontend.cwd, env=common_env, name="frontend")
- processes.append(web)
- _wait_for_http(
- 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(_t("start.open_in_browser", url=f"http://localhost:{frontend_port}"))
+ if existing_frontend is not None:
+ pid = existing_frontend.pid if existing_frontend.pid is not None else "unknown"
+ _log(_t("start.reusing_frontend", url=frontend_url, pid=pid))
+ _wait_for_http(
+ name=_t("start.frontend"),
+ url=frontend_url,
+ process=None,
+ timeout=FRONTEND_READY_TIMEOUT,
+ should_stop=lambda: shutdown_requested,
+ )
+ else:
+ _log(_t("start.starting_frontend"))
+ web = _spawn(frontend.command, cwd=frontend.cwd, env=common_env, name="frontend")
+ processes.append(web)
+ _wait_for_http(
+ 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(_t("start.open_in_browser", url=frontend_url))
while not shutdown_requested:
for proc in processes:
diff --git a/deeptutor/runtime/orchestrator.py b/deeptutor/runtime/orchestrator.py
index 7d877df59..bf0aa719d 100644
--- a/deeptutor/runtime/orchestrator.py
+++ b/deeptutor/runtime/orchestrator.py
@@ -44,10 +44,10 @@ class ChatOrchestrator:
context.session_id = str(uuid.uuid4())
# "Answer now" is a universal escape hatch but the actual fast-path
- # is *capability-specific* (deep_solve jumps to writing, deep_question
- # jumps to generation, math_animator skips analysis/design but still
- # renders, etc.). Each capability inspects ``answer_now_context`` at
- # the top of its own ``run()``; the orchestrator only adds a defensive
+ # is *capability-specific*: chat / visualize / math_animator each
+ # inspect ``answer_now_context`` at the top of their own ``run()``.
+ # Solve / quiz / research deliberately do NOT expose Answer Now
+ # (the UI hides the button). The orchestrator only adds a defensive
# fallback here: if the requested capability has been removed from
# the registry but the user is mid-``answer_now``, route to ``chat``
# so they still get *some* response instead of a hard error.
diff --git a/deeptutor/services/config/context_window_detection.py b/deeptutor/services/config/context_window_detection.py
index 9f82de71b..de42ffc52 100644
--- a/deeptutor/services/config/context_window_detection.py
+++ b/deeptutor/services/config/context_window_detection.py
@@ -31,9 +31,7 @@ _CONTEXT_WINDOW_KEYS = (
"max_sequence_length",
)
-_KNOWN_CONTEXT_WINDOWS: tuple[tuple[str, int], ...] = (
- ("deepseek-v4", 1_000_000),
-)
+_KNOWN_CONTEXT_WINDOWS: tuple[tuple[str, int], ...] = (("deepseek-v4", 1_000_000),)
@dataclass(frozen=True)
diff --git a/deeptutor/services/config/loader.py b/deeptutor/services/config/loader.py
index 2e9170103..3706384b6 100644
--- a/deeptutor/services/config/loader.py
+++ b/deeptutor/services/config/loader.py
@@ -254,13 +254,10 @@ def get_agent_params(module_name: str) -> dict:
DEFAULT_CHAT_PARAMS: dict[str, Any] = {
- "temperature": 0.2,
- "responding": {"max_tokens": 8000},
- "answer_now": {"max_tokens": 8000},
- "thinking": {"max_tokens": 2000},
- "observing": {"max_tokens": 2000},
- "acting": {"max_tokens": 2000},
- "react_fallback": {"max_tokens": 1500},
+ "temperature": 0.5,
+ "max_iterations": 20,
+ "responding": {"max_tokens": 8192},
+ "answer_now": {"max_tokens": 8192},
}
@@ -269,9 +266,9 @@ def get_chat_params() -> dict[str, Any]:
Read ``capabilities.chat`` from agents.yaml with deep-merged defaults.
Unlike :func:`get_agent_params`, the chat capability has per-stage
- sub-sections (``responding``, ``answer_now``, ``thinking``, ``observing``,
- ``acting``, ``react_fallback``), each with its own ``max_tokens``. A single
- ``temperature`` is shared across all stages.
+ sub-sections (``responding``, ``answer_now``), each with its own
+ ``max_tokens``. A single ``temperature`` and ``max_iterations`` value
+ are shared across the chat loop.
Returns:
dict: Deep-merged chat configuration. Always contains every stage key
diff --git a/deeptutor/services/config/test_runner.py b/deeptutor/services/config/test_runner.py
index 0a8081cde..f85f70703 100644
--- a/deeptutor/services/config/test_runner.py
+++ b/deeptutor/services/config/test_runner.py
@@ -9,9 +9,6 @@ import time
from typing import Any
from uuid import uuid4
-from deeptutor.services.llm.client import reset_llm_client
-from deeptutor.services.llm.config import clear_llm_config_cache
-
from .context_window_detection import detect_context_window
from .model_catalog import get_model_catalog_service
from .provider_runtime import (
@@ -132,26 +129,6 @@ class ConfigTestRunner:
run.status = "failed"
run.emit("failed", str(exc))
- def _persist_llm_context_window(
- self,
- *,
- catalog: dict[str, Any],
- context_window: int,
- source: str,
- detected_at: str,
- ) -> dict[str, Any]:
- service = get_model_catalog_service()
- llm_model = service.get_active_model(catalog, "llm")
- if llm_model is None:
- return catalog
- llm_model["context_window"] = str(context_window)
- llm_model["context_window_source"] = source
- llm_model["context_window_detected_at"] = detected_at
- saved = service.save(catalog)
- clear_llm_config_cache()
- reset_llm_client()
- return saved
-
def _persist_embedding_dimension(
self,
catalog: dict[str, Any],
@@ -283,22 +260,15 @@ class ConfigTestRunner:
)
run.emit(
"context_window",
- (f"Context window set to {detection.context_window} tokens ({detection.source})."),
+ (f"Detected context window {detection.context_window} tokens ({detection.source})."),
context_window=detection.context_window,
source=detection.source,
detail=detection.detail,
detected_at=detection.detected_at,
)
- saved_catalog = self._persist_llm_context_window(
- catalog=catalog,
- context_window=detection.context_window,
- source=detection.source,
- detected_at=detection.detected_at,
- )
run.emit(
- "catalog",
- "Saved updated model metadata to model_catalog.json.",
- catalog=saved_catalog,
+ "info",
+ "Context window detection is available in Settings and was not written automatically.",
)
async def _test_embedding(
diff --git a/deeptutor/services/llm/multimodal.py b/deeptutor/services/llm/multimodal.py
index 112c1100a..2ee955d81 100644
--- a/deeptutor/services/llm/multimodal.py
+++ b/deeptutor/services/llm/multimodal.py
@@ -246,18 +246,29 @@ def _inject_images(
if not b64 and not url:
continue
- # If the provider needs base64 and the attachment only carries a URL,
- # resolve it from the local AttachmentStore. External URLs cannot be
- # resolved synchronously here and are dropped with a warning.
- if not b64 and require_base64 and url:
+ # Local AttachmentStore URLs ("/api/attachments/...") are server-
+ # relative paths and are never valid to send to an external LLM
+ # provider — even providers that accept image URLs would receive a
+ # path they can't fetch. Resolve them to base64 unconditionally so
+ # the inline-base64 branch below takes over.
+ is_local_attachment_url = url.startswith(_LOCAL_ATTACHMENT_PREFIX) if url else False
+ if not b64 and url and (require_base64 or is_local_attachment_url):
resolved = _resolve_local_attachment_url(url)
if resolved is not None:
b64, resolved_mime = resolved
mime = mime or resolved_mime
- else:
+ elif require_base64:
logger.warning(
"Dropping url-only image %r: provider requires base64 but"
- " URL is not a local attachment-store path",
+ " URL is not a resolvable local attachment-store path",
+ url,
+ )
+ dropped += 1
+ continue
+ elif is_local_attachment_url:
+ logger.warning(
+ "Dropping local attachment URL %r that could not be"
+ " resolved from the AttachmentStore",
url,
)
dropped += 1
diff --git a/deeptutor/services/llm/provider_core/openai_compat_provider.py b/deeptutor/services/llm/provider_core/openai_compat_provider.py
index e188068c3..e9bcd0864 100644
--- a/deeptutor/services/llm/provider_core/openai_compat_provider.py
+++ b/deeptutor/services/llm/provider_core/openai_compat_provider.py
@@ -56,9 +56,7 @@ _THINKING_STYLE_MAP = {
"enable_thinking": lambda enabled: {"enable_thinking": enabled},
"reasoning_split": lambda enabled: {"reasoning_split": enabled},
}
-_THINKING_DISABLED_BY_DEFAULT: tuple[tuple[str, str], ...] = (
- ("deepseek", "deepseek-v4-flash"),
-)
+_THINKING_DISABLED_BY_DEFAULT: tuple[tuple[str, str], ...] = (("deepseek", "deepseek-v4-flash"),)
def _short_tool_id() -> str:
@@ -336,14 +334,8 @@ class OpenAICompatProvider(LLMProvider):
)
if extra:
kwargs.setdefault("extra_body", {}).update(extra)
- elif (
- spec
- and spec.thinking_style
- and _disable_thinking_by_default(spec, model_name)
- ):
- extra = _THINKING_STYLE_MAP.get(spec.thinking_style, lambda _enabled: None)(
- False
- )
+ elif spec and spec.thinking_style and _disable_thinking_by_default(spec, model_name):
+ extra = _THINKING_STYLE_MAP.get(spec.thinking_style, lambda _enabled: None)(False)
if extra:
kwargs.setdefault("extra_body", {}).update(extra)
diff --git a/deeptutor/services/path_service.py b/deeptutor/services/path_service.py
index ee1b2ec0f..c848055f5 100644
--- a/deeptutor/services/path_service.py
+++ b/deeptutor/services/path_service.py
@@ -411,9 +411,9 @@ def get_path_service() -> PathService:
return get_current_path_service()
except Exception:
import logging as _logging
+
_logging.getLogger(__name__).warning(
- "get_path_service() fell back to default instance; "
- "multi-user path resolution failed",
+ "get_path_service() fell back to default instance; multi-user path resolution failed",
exc_info=True,
)
return PathService.get_instance()
diff --git a/deeptutor/services/prompt/manager.py b/deeptutor/services/prompt/manager.py
index 034d3fedb..bdcf231cb 100644
--- a/deeptutor/services/prompt/manager.py
+++ b/deeptutor/services/prompt/manager.py
@@ -43,6 +43,7 @@ class PromptManager:
NON_AGENT_MODULES: dict[str, str] = {
"book": "book",
"co_writer": "co_writer",
+ "capabilities": "capabilities",
}
def __new__(cls) -> "PromptManager":
diff --git a/deeptutor/services/rag/pipelines/llamaindex/config.py b/deeptutor/services/rag/pipelines/llamaindex/config.py
index 713911109..b6eecf8b3 100644
--- a/deeptutor/services/rag/pipelines/llamaindex/config.py
+++ b/deeptutor/services/rag/pipelines/llamaindex/config.py
@@ -5,7 +5,6 @@ from __future__ import annotations
from dataclasses import dataclass
import os
-
VECTOR_PROFILE = "vector"
HYBRID_PROFILE = "hybrid"
SUPPORTED_RETRIEVAL_PROFILES = {VECTOR_PROFILE, HYBRID_PROFILE}
@@ -44,8 +43,7 @@ def retrieval_config_from_env() -> RetrievalConfig:
return RetrievalConfig(
profile=normalize_retrieval_profile(
- os.getenv("DEEPTUTOR_RAG_RETRIEVAL_PROFILE")
- or os.getenv("RAG_RETRIEVAL_PROFILE")
+ os.getenv("DEEPTUTOR_RAG_RETRIEVAL_PROFILE") or os.getenv("RAG_RETRIEVAL_PROFILE")
)
)
diff --git a/deeptutor/services/rag/pipelines/llamaindex/document_loader.py b/deeptutor/services/rag/pipelines/llamaindex/document_loader.py
index 42dfb6b70..2d3323d44 100644
--- a/deeptutor/services/rag/pipelines/llamaindex/document_loader.py
+++ b/deeptutor/services/rag/pipelines/llamaindex/document_loader.py
@@ -166,9 +166,7 @@ class LlamaIndexDocumentLoader:
self.logger.info(f"Loaded image: {path.name} ({len(embedding)}D vector)")
return nodes
- async def _describe_image(
- self, file_path: Path, image_base64: str, mimetype: str
- ) -> str:
+ async def _describe_image(self, file_path: Path, image_base64: str, mimetype: str) -> str:
llm_client = get_llm_client()
response = await llm_client.complete(
IMAGE_DESCRIPTION_PROMPT,
diff --git a/deeptutor/services/rag/pipelines/llamaindex/retrievers.py b/deeptutor/services/rag/pipelines/llamaindex/retrievers.py
index 1833eea15..089786097 100644
--- a/deeptutor/services/rag/pipelines/llamaindex/retrievers.py
+++ b/deeptutor/services/rag/pipelines/llamaindex/retrievers.py
@@ -43,8 +43,7 @@ def build_bm25_retriever(index: Any, storage_dir: Path, *, top_k: int) -> Any |
bm25_cls = _import_bm25_retriever()
if bm25_cls is None:
logger.info(
- "LlamaIndex BM25 retriever package is not installed; "
- "falling back to vector retrieval."
+ "LlamaIndex BM25 retriever package is not installed; falling back to vector retrieval."
)
return None
diff --git a/deeptutor/services/rag/service.py b/deeptutor/services/rag/service.py
index 8aba9fd70..c30c0c9a0 100644
--- a/deeptutor/services/rag/service.py
+++ b/deeptutor/services/rag/service.py
@@ -122,6 +122,25 @@ class RAGService:
},
)
+ # L1 memory trace — best-effort, never blocks the search path.
+ try:
+ from deeptutor.services.memory import get_memory_store
+ from deeptutor.services.memory.trace import TraceEvent
+
+ await get_memory_store().emit(
+ TraceEvent.new(
+ "kb",
+ "query",
+ {
+ "query": query,
+ "kb_name": kb_name,
+ "answer_chars": len(answer),
+ },
+ )
+ )
+ except Exception:
+ pass
+
return result
async def _emit_tool_event(
diff --git a/deeptutor/services/session/base_session_manager.py b/deeptutor/services/session/base_session_manager.py
index 51e1d00d4..45ae14334 100644
--- a/deeptutor/services/session/base_session_manager.py
+++ b/deeptutor/services/session/base_session_manager.py
@@ -46,6 +46,7 @@ class BaseSessionManager(ABC):
@property
def path_service(self):
from deeptutor.services.path_service import get_path_service
+
return get_path_service()
@property
diff --git a/deeptutor/services/session/pocketbase_store.py b/deeptutor/services/session/pocketbase_store.py
index 6b78b55f5..1d3ed748d 100644
--- a/deeptutor/services/session/pocketbase_store.py
+++ b/deeptutor/services/session/pocketbase_store.py
@@ -67,12 +67,10 @@ 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 (
@@ -87,15 +85,12 @@ class PocketBaseSessionStore:
"preferences_json": {},
"capability": "",
"status": "idle",
- "kind": resolved_kind,
}
)
)
record = await asyncio.to_thread(_create)
- result = self._session_record_to_dict(record, resolved_id, resolved_title, now)
- result.setdefault("kind", resolved_kind)
- return result
+ return self._session_record_to_dict(record, resolved_id, resolved_title, now)
async def get_session(self, session_id: str) -> dict[str, Any] | None:
def _get():
@@ -117,13 +112,12 @@ class PocketBaseSessionStore:
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(kind=kind)
+ return await self.create_session()
def _session_record_to_dict(
self,
@@ -149,7 +143,6 @@ 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:
@@ -194,20 +187,11 @@ class PocketBaseSessionStore:
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():
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:
@@ -310,17 +294,9 @@ class PocketBaseSessionStore:
"msg_created_at": now,
}
record = _pb().collection("messages").create(payload)
- # Update session title if still default
- sessions = (
- _pb()
- .collection("sessions")
- .get_full_list(query_params={"filter": f'session_id="{session_id}"'})
- )
- if sessions and sessions[0].title == "New conversation" and role == "user":
- trimmed = (content or "").strip()
- if trimmed:
- new_title = trimmed[:50] + ("..." if len(trimmed) > 50 else "")
- _pb().collection("sessions").update(sessions[0].id, {"title": new_title})
+ # Title generation is owned by the turn runtime (LLM-driven
+ # after the first user+assistant pair). Until that runs the
+ # session keeps the ``New conversation`` sentinel.
return record
try:
diff --git a/deeptutor/services/session/protocol.py b/deeptutor/services/session/protocol.py
index b1c1c1a40..e6cb184c3 100644
--- a/deeptutor/services/session/protocol.py
+++ b/deeptutor/services/session/protocol.py
@@ -16,7 +16,6 @@ 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: ...
@@ -24,7 +23,6 @@ class SessionStoreProtocol(Protocol):
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]: ...
@@ -73,7 +71,6 @@ class SessionStoreProtocol(Protocol):
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/source_inventory.py b/deeptutor/services/session/source_inventory.py
index 841be4564..3839908f9 100644
--- a/deeptutor/services/session/source_inventory.py
+++ b/deeptutor/services/session/source_inventory.py
@@ -29,8 +29,8 @@ The output is decoupled from the rest of ``turn_runtime``:
from __future__ import annotations
-import logging
from dataclasses import dataclass, field
+import logging
from typing import Any, Sequence
from deeptutor.services.session.protocol import SessionStoreProtocol
@@ -150,9 +150,7 @@ async def build_inventory(
question_entry_ids=fresh_question_entry_ids,
current_turn_ordinal=current_turn_ordinal,
)
- await _add_historical(
- inv, store=store, session_id=session_id, leaf_message_id=leaf_message_id
- )
+ await _add_historical(inv, store=store, session_id=session_id, leaf_message_id=leaf_message_id)
return inv
@@ -216,10 +214,7 @@ def _format_size(char_count: int) -> str:
def _render_row(entry: SourceEntry) -> str:
if entry.fresh:
preview = _clip_preview(entry.full_text)
- return (
- f"- id={entry.sid} type={entry.kind} name={entry.name!r}\n"
- f" preview: {preview!r}"
- )
+ return f"- id={entry.sid} type={entry.kind} name={entry.name!r}\n preview: {preview!r}"
return (
f"- id={entry.sid} type={entry.kind} name={entry.name!r}"
f" size={_format_size(entry.char_count)} "
@@ -374,9 +369,7 @@ async def _add_historical(
if msg.get("role") != "user":
continue
user_turn_ordinal += 1
- await _collect_from_user_message(
- inv, store=store, msg=msg, turn_ordinal=user_turn_ordinal
- )
+ await _collect_from_user_message(inv, store=store, msg=msg, turn_ordinal=user_turn_ordinal)
async def _collect_from_user_message(
@@ -580,7 +573,7 @@ def _extract_book_title(section: str, *, fallback: str) -> str:
first_line = section.lstrip().split("\n", 1)[0]
prefix = "# Book: "
if first_line.startswith(prefix):
- return first_line[len(prefix):].strip() or fallback
+ return first_line[len(prefix) :].strip() or fallback
return fallback
@@ -601,9 +594,7 @@ def _resolve_book_section(book_reference: dict[str, Any]) -> tuple[str, str]:
text = (result.text or "").strip()
if not text:
return "", ""
- name = _extract_book_title(
- text, fallback=f"Book {book_reference.get('book_id', '?')}"
- )
+ name = _extract_book_title(text, fallback=f"Book {book_reference.get('book_id', '?')}")
return text, name
@@ -634,9 +625,7 @@ async def _load_history_session(
return "\n\n".join(transcript_lines), name
-async def _load_question_entry(
- store: SessionStoreProtocol, entry_id: int
-) -> tuple[str, str]:
+async def _load_question_entry(store: SessionStoreProtocol, entry_id: int) -> tuple[str, str]:
"""Fetch and render one question-bank entry into a markdown block +
short stem (used as the manifest name). Returns ``("", "")`` on
missing entry. Imports the renderer lazily to avoid pulling
diff --git a/deeptutor/services/session/sqlite_store.py b/deeptutor/services/session/sqlite_store.py
index c23fd8fca..5c53008f0 100644
--- a/deeptutor/services/session/sqlite_store.py
+++ b/deeptutor/services/session/sqlite_store.py
@@ -104,12 +104,7 @@ class SQLiteSessionStore:
updated_at REAL NOT NULL,
compressed_summary TEXT DEFAULT '',
summary_up_to_msg_id INTEGER DEFAULT 0,
- 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'
+ preferences_json TEXT DEFAULT '{}'
);
CREATE TABLE IF NOT EXISTS messages (
@@ -176,6 +171,7 @@ class SQLiteSessionStore:
CREATE TABLE IF NOT EXISTS notebook_entries (
id INTEGER PRIMARY KEY AUTOINCREMENT,
session_id TEXT NOT NULL REFERENCES sessions(id) ON DELETE CASCADE,
+ turn_id TEXT NOT NULL DEFAULT '',
question_id TEXT NOT NULL,
question TEXT NOT NULL,
question_type TEXT DEFAULT '',
@@ -184,12 +180,14 @@ class SQLiteSessionStore:
explanation TEXT DEFAULT '',
difficulty TEXT DEFAULT '',
user_answer TEXT DEFAULT '',
+ user_answer_images_json TEXT DEFAULT '[]',
is_correct INTEGER DEFAULT 0,
bookmarked INTEGER DEFAULT 0,
followup_session_id TEXT DEFAULT '',
+ ai_judgment TEXT DEFAULT '',
created_at REAL NOT NULL,
updated_at REAL NOT NULL,
- UNIQUE(session_id, question_id)
+ UNIQUE(session_id, turn_id, question_id)
);
CREATE INDEX IF NOT EXISTS idx_notebook_entries_session
@@ -214,10 +212,13 @@ 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'")
+ if "kind" in columns:
+ try:
+ conn.execute("ALTER TABLE sessions DROP COLUMN kind")
+ except sqlite3.OperationalError:
+ # Older SQLite builds may not support DROP COLUMN. The
+ # application no longer reads or writes this legacy field.
+ pass
message_columns = {
row[1] for row in conn.execute("PRAGMA table_info(messages)").fetchall()
}
@@ -251,8 +252,126 @@ class SQLiteSessionStore:
"CREATE INDEX IF NOT EXISTS idx_messages_parent "
"ON messages(session_id, parent_message_id)"
)
+ self._migrate_notebook_entries_add_turn_id(conn)
+ self._migrate_notebook_entries_add_user_answer_images(conn)
+ self._migrate_notebook_entries_add_ai_judgment(conn)
conn.commit()
+ @staticmethod
+ def _migrate_notebook_entries_add_turn_id(conn: sqlite3.Connection) -> None:
+ """Add ``turn_id`` to legacy notebook_entries and re-scope the UNIQUE
+ constraint to ``(session_id, turn_id, question_id)``.
+
+ The old unique constraint conflated quizzes generated in the same chat
+ (issue #487): regenerating a quiz with the same positional
+ ``question_id`` (e.g. ``q_1``) would collide with the previous quiz's
+ notebook entries and the UI hydrated stale answers. Scoping by
+ ``turn_id`` keeps each quiz isolated.
+ """
+ notebook_cols = {
+ row[1] for row in conn.execute("PRAGMA table_info(notebook_entries)").fetchall()
+ }
+ if not notebook_cols:
+ return
+ if "turn_id" not in notebook_cols:
+ conn.execute("ALTER TABLE notebook_entries ADD COLUMN turn_id TEXT NOT NULL DEFAULT ''")
+ # SQLite stores table-level UNIQUE constraints as auto-indexes whose
+ # names start with ``sqlite_autoindex_notebook_entries_``; the columns
+ # they cover live in PRAGMA index_info. Detect whether any existing
+ # auto-index still covers only (session_id, question_id) and, if so,
+ # rebuild the table to swap in the new scope.
+ needs_rebuild = False
+ for idx_row in conn.execute("PRAGMA index_list(notebook_entries)").fetchall():
+ idx_name = idx_row[1]
+ if not idx_name.startswith("sqlite_autoindex_notebook_entries_"):
+ continue
+ cols = [r[2] for r in conn.execute(f"PRAGMA index_info({idx_name})").fetchall()]
+ if cols == ["session_id", "question_id"]:
+ needs_rebuild = True
+ break
+ if not needs_rebuild:
+ return
+ conn.executescript(
+ """
+ CREATE TABLE notebook_entries_new (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ session_id TEXT NOT NULL REFERENCES sessions(id) ON DELETE CASCADE,
+ turn_id TEXT NOT NULL DEFAULT '',
+ question_id TEXT NOT NULL,
+ question TEXT NOT NULL,
+ question_type TEXT DEFAULT '',
+ options_json TEXT DEFAULT '{}',
+ correct_answer TEXT DEFAULT '',
+ explanation TEXT DEFAULT '',
+ difficulty TEXT DEFAULT '',
+ user_answer TEXT DEFAULT '',
+ is_correct INTEGER DEFAULT 0,
+ bookmarked INTEGER DEFAULT 0,
+ followup_session_id TEXT DEFAULT '',
+ created_at REAL NOT NULL,
+ updated_at REAL NOT NULL,
+ UNIQUE(session_id, turn_id, question_id)
+ );
+
+ INSERT INTO notebook_entries_new (
+ id, session_id, turn_id, question_id, question, question_type,
+ options_json, correct_answer, explanation, difficulty,
+ user_answer, is_correct, bookmarked, followup_session_id,
+ created_at, updated_at
+ )
+ SELECT
+ id, session_id, COALESCE(turn_id, ''), question_id, question,
+ question_type, options_json, correct_answer, explanation,
+ difficulty, user_answer, is_correct, bookmarked,
+ followup_session_id, created_at, updated_at
+ FROM notebook_entries;
+
+ DROP TABLE notebook_entries;
+ ALTER TABLE notebook_entries_new RENAME TO notebook_entries;
+
+ CREATE INDEX IF NOT EXISTS idx_notebook_entries_session
+ ON notebook_entries(session_id, created_at DESC);
+
+ CREATE INDEX IF NOT EXISTS idx_notebook_entries_bookmarked
+ ON notebook_entries(bookmarked, created_at DESC);
+ """
+ )
+
+ @staticmethod
+ def _migrate_notebook_entries_add_user_answer_images(
+ conn: sqlite3.Connection,
+ ) -> None:
+ """Back-fill ``user_answer_images_json`` on legacy DBs.
+
+ The column stores a JSON array of ``{id, url, filename, mime_type}``
+ records for image attachments uploaded as part of the learner's
+ answer. The bytes themselves live in the AttachmentStore; we only
+ keep references in the row so notebook_entries stays lean.
+ """
+ cols = {row[1] for row in conn.execute("PRAGMA table_info(notebook_entries)").fetchall()}
+ if not cols:
+ return
+ if "user_answer_images_json" not in cols:
+ conn.execute(
+ "ALTER TABLE notebook_entries ADD COLUMN user_answer_images_json TEXT DEFAULT '[]'"
+ )
+
+ @staticmethod
+ def _migrate_notebook_entries_add_ai_judgment(
+ conn: sqlite3.Connection,
+ ) -> None:
+ """Back-fill ``ai_judgment`` on legacy DBs.
+
+ Stores the latest AI-judge text per entry as plain markdown. Empty
+ string means the learner has not run the AI judge for this entry
+ yet.
+ """
+ cols = {row[1] for row in conn.execute("PRAGMA table_info(notebook_entries)").fetchall()}
+ if not cols:
+ return
+ if "ai_judgment" not in cols:
+ conn.execute("ALTER TABLE notebook_entries ADD COLUMN ai_judgment TEXT DEFAULT ''")
+
async def _run(self, fn, *args):
async with self._lock:
return await asyncio.to_thread(fn, *args)
@@ -267,22 +386,20 @@ class SQLiteSessionStore:
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, kind
+ compressed_summary, summary_up_to_msg_id
)
- VALUES (?, ?, ?, ?, '', 0, ?)
+ VALUES (?, ?, ?, ?, '', 0)
""",
- (resolved_id, resolved_title[:100], now, now, resolved_kind),
+ (resolved_id, resolved_title[:100], now, now),
)
conn.commit()
return {
@@ -293,16 +410,14 @@ 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,
- kind: str = "chat",
) -> dict[str, Any]:
- return await self._run(self._create_session_sync, title, session_id, kind)
+ return await self._run(self._create_session_sync, title, session_id)
def _get_session_sync(self, session_id: str) -> dict[str, Any] | None:
with self._connect() as conn:
@@ -316,7 +431,6 @@ class SQLiteSessionStore:
s.compressed_summary,
s.summary_up_to_msg_id,
s.preferences_json,
- s.kind,
COALESCE(
(
SELECT t.status
@@ -366,13 +480,12 @@ class SQLiteSessionStore:
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(kind=kind)
+ return await self.create_session()
@staticmethod
def _serialize_turn(row: sqlite3.Row) -> dict[str, Any]:
@@ -668,21 +781,15 @@ class SQLiteSessionStore:
),
)
- title = None
- if session["title"] == "New conversation" and role == "user":
- trimmed = (content or "").strip()
- if trimmed:
- title = trimmed[:50] + ("..." if len(trimmed) > 50 else "")
-
+ # Title is no longer derived from the first user message — the
+ # turn runtime calls an LLM to generate a real summary title
+ # once the first user+assistant pair is complete. Until then
+ # the session keeps the default sentinel ``New conversation``
+ # which the frontend renders as a breathing "New chat" chip.
conn.execute(
"UPDATE sessions SET updated_at = ? WHERE id = ?",
(now, session_id),
)
- if title:
- conn.execute(
- "UPDATE sessions SET title = ? WHERE id = ?",
- (title, session_id),
- )
conn.commit()
return int(cur.lastrowid)
@@ -904,9 +1011,7 @@ class SQLiteSessionStore:
).fetchall()
return [self._serialize_message(row) for row in rows]
- def _get_message_path_sync(
- self, session_id: str, leaf_message_id: int
- ) -> list[dict[str, Any]]:
+ def _get_message_path_sync(self, session_id: str, leaf_message_id: int) -> list[dict[str, Any]]:
"""Return the chain of messages from the session root down to
``leaf_message_id`` (inclusive), in chronological order.
@@ -938,9 +1043,7 @@ class SQLiteSessionStore:
chain.reverse()
return chain
- async def get_message_path(
- self, session_id: str, leaf_message_id: int
- ) -> list[dict[str, Any]]:
+ async def get_message_path(self, session_id: str, leaf_message_id: int) -> list[dict[str, Any]]:
return await self._run(self._get_message_path_sync, session_id, int(leaf_message_id))
async def get_messages(self, session_id: str) -> list[dict[str, Any]]:
@@ -1002,28 +1105,16 @@ class SQLiteSessionStore:
async def get_messages_for_context(
self, session_id: str, leaf_message_id: int | None = None
) -> list[dict[str, Any]]:
- return await self._run(
- self._get_messages_for_context_sync, session_id, leaf_message_id
- )
+ return await self._run(self._get_messages_for_context_sync, session_id, leaf_message_id)
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,
@@ -1032,7 +1123,6 @@ class SQLiteSessionStore:
s.compressed_summary,
s.summary_up_to_msg_id,
s.preferences_json,
- s.kind,
COUNT(m.id) AS message_count,
COALESCE(
(
@@ -1077,12 +1167,11 @@ 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 ?
- """, # nosec B608 - where_sql is a fixed literal selected from constants
- params,
+ """,
+ (limit, offset),
).fetchall()
sessions = []
for row in rows:
@@ -1096,9 +1185,8 @@ class SQLiteSessionStore:
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)
+ return await self._run(self._list_sessions_sync, limit, offset)
def _update_summary_sync(self, session_id: str, summary: str, up_to_msg_id: int) -> bool:
with self._connect() as conn:
@@ -1172,34 +1260,77 @@ class SQLiteSessionStore:
question_id = (item.get("question_id") or "").strip()
if not question or not question_id:
continue
- conn.execute(
- """
- INSERT INTO notebook_entries (
- session_id, question_id, question, question_type,
- options_json, correct_answer, explanation, difficulty,
- user_answer, is_correct, bookmarked, followup_session_id,
- created_at, updated_at
- ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 0, '', ?, ?)
- ON CONFLICT(session_id, question_id) DO UPDATE SET
- user_answer = excluded.user_answer,
- is_correct = excluded.is_correct,
- updated_at = excluded.updated_at
- """,
- (
- session_id,
- question_id,
- question,
- item.get("question_type") or "",
- _json_dumps(item.get("options") or {}),
- item.get("correct_answer") or "",
- item.get("explanation") or "",
- item.get("difficulty") or "",
- item.get("user_answer") or "",
- 1 if item.get("is_correct") else 0,
- now,
- now,
- ),
- )
+ turn_id = (item.get("turn_id") or "").strip()
+ # ``user_answer_images`` is an optional list of records
+ # ``[{id, url, filename, mime_type}, …]``. We serialise it
+ # here so callers that only know about text don't need to
+ # know JSON. ``None`` keeps the existing column value on
+ # UPDATE (avoid clobbering stored images on a partial
+ # upsert that only changes ``is_correct``).
+ images_value = item.get("user_answer_images")
+ images_json = _json_dumps(images_value) if isinstance(images_value, list) else None
+ if images_json is None:
+ conn.execute(
+ """
+ INSERT INTO notebook_entries (
+ session_id, turn_id, question_id, question, question_type,
+ options_json, correct_answer, explanation, difficulty,
+ user_answer, user_answer_images_json, is_correct,
+ bookmarked, followup_session_id, created_at, updated_at
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, '[]', ?, 0, '', ?, ?)
+ ON CONFLICT(session_id, turn_id, question_id) DO UPDATE SET
+ user_answer = excluded.user_answer,
+ is_correct = excluded.is_correct,
+ updated_at = excluded.updated_at
+ """,
+ (
+ session_id,
+ turn_id,
+ question_id,
+ question,
+ item.get("question_type") or "",
+ _json_dumps(item.get("options") or {}),
+ item.get("correct_answer") or "",
+ item.get("explanation") or "",
+ item.get("difficulty") or "",
+ item.get("user_answer") or "",
+ 1 if item.get("is_correct") else 0,
+ now,
+ now,
+ ),
+ )
+ else:
+ conn.execute(
+ """
+ INSERT INTO notebook_entries (
+ session_id, turn_id, question_id, question, question_type,
+ options_json, correct_answer, explanation, difficulty,
+ user_answer, user_answer_images_json, is_correct,
+ bookmarked, followup_session_id, created_at, updated_at
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 0, '', ?, ?)
+ ON CONFLICT(session_id, turn_id, question_id) DO UPDATE SET
+ user_answer = excluded.user_answer,
+ user_answer_images_json = excluded.user_answer_images_json,
+ is_correct = excluded.is_correct,
+ updated_at = excluded.updated_at
+ """,
+ (
+ session_id,
+ turn_id,
+ question_id,
+ question,
+ item.get("question_type") or "",
+ _json_dumps(item.get("options") or {}),
+ item.get("correct_answer") or "",
+ item.get("explanation") or "",
+ item.get("difficulty") or "",
+ item.get("user_answer") or "",
+ images_json,
+ 1 if item.get("is_correct") else 0,
+ now,
+ now,
+ ),
+ )
upserted += 1
conn.commit()
return upserted
@@ -1209,10 +1340,17 @@ class SQLiteSessionStore:
@staticmethod
def _serialize_notebook_entry(row: sqlite3.Row) -> dict[str, Any]:
+ keys = set(row.keys())
+ images: list[dict[str, Any]] = []
+ if "user_answer_images_json" in keys:
+ raw_images = _json_loads(row["user_answer_images_json"], [])
+ if isinstance(raw_images, list):
+ images = [r for r in raw_images if isinstance(r, dict)]
return {
"id": int(row["id"]),
"session_id": row["session_id"],
- "session_title": row["session_title"] or "" if "session_title" in row.keys() else "",
+ "session_title": row["session_title"] or "" if "session_title" in keys else "",
+ "turn_id": (row["turn_id"] or "") if "turn_id" in keys else "",
"question_id": row["question_id"] or "",
"question": row["question"],
"question_type": row["question_type"] or "",
@@ -1221,9 +1359,11 @@ class SQLiteSessionStore:
"explanation": row["explanation"] or "",
"difficulty": row["difficulty"] or "",
"user_answer": row["user_answer"] or "",
+ "user_answer_images": images,
"is_correct": bool(row["is_correct"]),
"bookmarked": bool(row["bookmarked"]),
"followup_session_id": row["followup_session_id"] or "",
+ "ai_judgment": (row["ai_judgment"] or "") if "ai_judgment" in keys else "",
"created_at": float(row["created_at"]),
"updated_at": float(row["updated_at"]),
}
@@ -1235,14 +1375,15 @@ class SQLiteSessionStore:
is_correct: bool | None,
limit: int,
offset: int,
+ session_id: str | None = None,
) -> dict[str, Any]:
base = """
SELECT
n.id, n.session_id, COALESCE(s.title, '') AS session_title,
- n.question_id, n.question, n.question_type, n.options_json,
+ n.turn_id, n.question_id, n.question, n.question_type, n.options_json,
n.correct_answer, n.explanation, n.difficulty,
- n.user_answer, n.is_correct, n.bookmarked,
- n.followup_session_id, n.created_at, n.updated_at
+ n.user_answer, n.user_answer_images_json, n.is_correct, n.bookmarked,
+ n.followup_session_id, n.ai_judgment, n.created_at, n.updated_at
FROM notebook_entries n
LEFT JOIN sessions s ON s.id = n.session_id
"""
@@ -1261,6 +1402,9 @@ class SQLiteSessionStore:
if is_correct is not None:
conditions.append("n.is_correct = ?")
params.append(1 if is_correct else 0)
+ if session_id is not None:
+ conditions.append("n.session_id = ?")
+ params.append(session_id)
where = (" WHERE " + " AND ".join(conditions)) if conditions else ""
with self._connect() as conn:
total_row = conn.execute(count_base + where, tuple(params)).fetchone()
@@ -1279,6 +1423,8 @@ class SQLiteSessionStore:
is_correct: bool | None = None,
limit: int = 50,
offset: int = 0,
+ *,
+ session_id: str | None = None,
) -> dict[str, Any]:
return await self._run(
self._list_notebook_entries_sync,
@@ -1287,6 +1433,7 @@ class SQLiteSessionStore:
is_correct,
limit,
offset,
+ session_id,
)
def _get_notebook_entry_sync(self, entry_id: int) -> dict[str, Any] | None:
@@ -1320,26 +1467,62 @@ class SQLiteSessionStore:
async def get_notebook_entry(self, entry_id: int) -> dict[str, Any] | None:
return await self._run(self._get_notebook_entry_sync, entry_id)
- def _find_notebook_entry_sync(self, session_id: str, question_id: str) -> dict[str, Any] | None:
+ def _find_notebook_entry_sync(
+ self,
+ session_id: str,
+ question_id: str,
+ turn_id: str | None = None,
+ ) -> dict[str, Any] | None:
with self._connect() as conn:
- row = conn.execute(
- """
- SELECT n.*, COALESCE(s.title, '') AS session_title
- FROM notebook_entries n
- LEFT JOIN sessions s ON s.id = n.session_id
- WHERE n.session_id = ? AND n.question_id = ?
- """,
- (session_id, question_id),
- ).fetchone()
+ if turn_id is not None:
+ row = conn.execute(
+ """
+ SELECT n.*, COALESCE(s.title, '') AS session_title
+ FROM notebook_entries n
+ LEFT JOIN sessions s ON s.id = n.session_id
+ WHERE n.session_id = ?
+ AND n.turn_id = ?
+ AND n.question_id = ?
+ """,
+ (session_id, turn_id, question_id),
+ ).fetchone()
+ else:
+ # Legacy lookup: return the most recent matching entry across
+ # turns. Two quizzes in the same session can share a question_id
+ # (positional IDs like ``q_1``), so we explicitly pick the
+ # newest one to keep behavior deterministic for callers that
+ # don't yet pass a turn_id.
+ row = conn.execute(
+ """
+ SELECT n.*, COALESCE(s.title, '') AS session_title
+ FROM notebook_entries n
+ LEFT JOIN sessions s ON s.id = n.session_id
+ WHERE n.session_id = ? AND n.question_id = ?
+ ORDER BY n.updated_at DESC, n.id DESC
+ LIMIT 1
+ """,
+ (session_id, question_id),
+ ).fetchone()
if row is None:
return None
return self._serialize_notebook_entry(row)
- async def find_notebook_entry(self, session_id: str, question_id: str) -> dict[str, Any] | None:
- return await self._run(self._find_notebook_entry_sync, session_id, question_id)
+ async def find_notebook_entry(
+ self,
+ session_id: str,
+ question_id: str,
+ turn_id: str | None = None,
+ ) -> dict[str, Any] | None:
+ return await self._run(self._find_notebook_entry_sync, session_id, question_id, turn_id)
def _update_notebook_entry_sync(self, entry_id: int, updates: dict[str, Any]) -> bool:
- allowed = {"bookmarked", "followup_session_id", "user_answer", "is_correct"}
+ allowed = {
+ "bookmarked",
+ "followup_session_id",
+ "user_answer",
+ "is_correct",
+ "ai_judgment",
+ }
fields = {k: v for k, v in updates.items() if k in allowed}
if not fields:
return False
diff --git a/deeptutor/services/session/turn_runtime.py b/deeptutor/services/session/turn_runtime.py
index 5ed48ddce..76c441e66 100644
--- a/deeptutor/services/session/turn_runtime.py
+++ b/deeptutor/services/session/turn_runtime.py
@@ -14,6 +14,7 @@ import logging
from typing import TYPE_CHECKING, Any, Literal
from deeptutor.core.stream import StreamEvent, StreamEventType
+from deeptutor.services.llm.utils import clean_thinking_tags
from deeptutor.services.path_service import get_path_service
from deeptutor.services.session.protocol import SessionStoreProtocol
@@ -22,7 +23,7 @@ if TYPE_CHECKING:
logger = logging.getLogger(__name__)
-MemoryReference = Literal["summary", "profile"]
+MemoryReference = Literal["recent", "profile", "scope", "preferences", "summary"]
def _should_capture_assistant_content(event: StreamEvent) -> bool:
@@ -42,15 +43,74 @@ def _clip_text(value: str, limit: int = 4000) -> str:
return text[:limit].rstrip() + "\n...[truncated]"
+_TITLE_QUOTE_PAIRS: tuple[tuple[str, str], ...] = (
+ ('"', '"'),
+ ("'", "'"),
+ ("“", "”"),
+ ("‘", "’"),
+ ("「", "」"),
+ ("『", "』"),
+ ("`", "`"),
+)
+_TITLE_PREFIXES: tuple[str, ...] = (
+ "Title:",
+ "title:",
+ "TITLE:",
+ "Title-",
+ "标题:",
+ "标题:",
+ "对话标题:",
+ "对话标题:",
+)
+_TITLE_TRAILING_PUNCT = ".。!!??,,;;、 \t"
+
+
+def _sanitize_session_title(raw: str) -> str:
+ """Trim the noise LLMs love to add to short titles.
+
+ Strips model reasoning tags, surrounding quotes, leading "Title:" labels,
+ trailing punctuation, and Markdown bold/italic markers. Caps length at
+ 80 characters so a chatty model can't blow past the sidebar layout.
+ """
+ text = clean_thinking_tags(raw or "").strip()
+ if not text:
+ return ""
+ text = text.splitlines()[0].strip()
+ # Iterate until the text stops shrinking — models often nest the
+ # noise (e.g. ``**Title:** "Hello"``) so a single pass leaves
+ # leftover wrappers.
+ for _ in range(8):
+ prev = text
+ text = text.lstrip("*_#- \t").rstrip("*_ \t")
+ for prefix in _TITLE_PREFIXES:
+ if text.startswith(prefix):
+ text = text[len(prefix) :].strip()
+ break
+ for opener, closer in _TITLE_QUOTE_PAIRS:
+ if len(text) >= 2 and text.startswith(opener) and text.endswith(closer):
+ text = text[len(opener) : len(text) - len(closer)].strip()
+ break
+ text = text.rstrip(_TITLE_TRAILING_PUNCT)
+ if text == prev:
+ break
+ return text[:80]
+
+
def _extract_memory_references(payload: dict[str, Any]) -> list[MemoryReference]:
- """Return the explicit public memory files requested for this turn."""
+ """Return the L3 slot names the client opted in for this turn.
+
+ Any non-empty list triggers ``read_l3_concat`` injection in v2 — the
+ individual names are kept for forward-compat with workbench UI hints
+ (e.g. "I want preferences in this turn") even though the read tool
+ returns the full concat.
+ """
refs = payload.get("memory_references", []) or []
if not isinstance(refs, list):
return []
-
+ allowed = {"recent", "profile", "scope", "preferences", "summary"}
out: list[MemoryReference] = []
for item in refs:
- if item in {"summary", "profile"} and item not in out:
+ if item in allowed and item not in out:
out.append(item)
return out
@@ -222,6 +282,33 @@ async def _build_question_bank_context(
return "\n\n---\n\n".join(blocks)
+def _normalize_filename_list(raw: dict[str, Any]) -> list[str]:
+ """Coalesce legacy single-filename and modern multi-filename inputs.
+
+ Returns the cleaned list (possibly empty). Empty / whitespace-only
+ entries are dropped, and the singular ``user_answer_image_filename``
+ is honoured as a fallback so older clients still surface their
+ filename in the system prompt.
+ """
+ candidates: list[Any] = []
+ plural = raw.get("user_answer_image_filenames")
+ if isinstance(plural, list):
+ candidates.extend(plural)
+ elif isinstance(plural, str):
+ candidates.append(plural)
+ legacy = raw.get("user_answer_image_filename")
+ if isinstance(legacy, str) and legacy.strip():
+ candidates.append(legacy)
+ cleaned: list[str] = []
+ for item in candidates:
+ if not isinstance(item, str):
+ continue
+ name = item.strip()
+ if name:
+ cleaned.append(name)
+ return cleaned
+
+
def _extract_followup_question_context(
config: dict[str, Any] | None,
) -> dict[str, Any] | None:
@@ -258,6 +345,17 @@ def _extract_followup_question_context(
"knowledge_context": _clip_text(str(raw.get("knowledge_context", "") or "").strip()),
"user_answer": str(raw.get("user_answer", "") or "").strip(),
"is_correct": raw.get("is_correct"),
+ # Filenames of the learner's image answers, when any were attached.
+ # The bytes are sent as regular WS attachments on the first
+ # follow-up turn — we just record the filenames here so the system
+ # prompt can tell the LLM *what* those attached images actually
+ # are. Accept both the legacy single ``user_answer_image_filename``
+ # string and the new ``user_answer_image_filenames`` list.
+ "user_answer_image_filenames": _normalize_filename_list(raw),
+ # Most recent AI-judge output the learner saw, if they ran the
+ # judge. Forwarded so the follow-up tutor can build on the same
+ # assessment rather than starting fresh.
+ "ai_judgment": _clip_text(str(raw.get("ai_judgment", "") or "").strip()),
}
@@ -324,6 +422,28 @@ def _format_followup_question_context(context: dict[str, Any], language: str = "
context.get("explanation") or "(none)",
]
)
+ image_filenames = context.get("user_answer_image_filenames") or []
+ if isinstance(image_filenames, list) and image_filenames:
+ filename_text = "、".join(image_filenames)
+ count_text = f"{len(image_filenames)} 张" if len(image_filenames) > 1 else "一张"
+ lines.extend(
+ [
+ "",
+ "学习者作答附图:",
+ f"该作答共附了{count_text}图片(文件名:{filename_text}),"
+ f"随首条追问消息一起发送,是用户提交的作答内容的一部分,不是无关上下文。"
+ f"请结合图片中的文字/公式/草图进行解读,并将其视为对上面 “User answer” 文本的补充。",
+ ]
+ )
+ ai_judgment = context.get("ai_judgment")
+ if ai_judgment:
+ lines.extend(
+ [
+ "",
+ "AI 评判(之前已对学习者作答给出的评判,请基于此继续,不要重复完整重写):",
+ ai_judgment,
+ ]
+ )
if context.get("knowledge_context"):
lines.extend(
[
@@ -362,6 +482,32 @@ def _format_followup_question_context(context: dict[str, Any], language: str = "
context.get("explanation") or "(none)",
]
)
+ image_filenames = context.get("user_answer_image_filenames") or []
+ if isinstance(image_filenames, list) and image_filenames:
+ joined = ", ".join(image_filenames)
+ plural = "images were" if len(image_filenames) > 1 else "image was"
+ plural_noun = (
+ "Learner answer images" if len(image_filenames) > 1 else "Learner answer image"
+ )
+ lines.extend(
+ [
+ "",
+ f"{plural_noun}:",
+ f"{len(image_filenames)} {plural} attached to the first follow-up message "
+ f"(filenames: {joined}). They are part of the learner's answer — read their "
+ "text/formulas/sketches and treat them as a supplement to the typed `User answer` "
+ "above, not unrelated context.",
+ ]
+ )
+ ai_judgment = context.get("ai_judgment")
+ if ai_judgment:
+ lines.extend(
+ [
+ "",
+ "Prior AI judgment (already shown to the learner — build on it instead of restating it in full):",
+ ai_judgment,
+ ]
+ )
if context.get("knowledge_context"):
lines.extend(
[
@@ -400,6 +546,17 @@ class TurnRuntimeManager:
self.store = store or get_session_store()
self._lock = asyncio.Lock()
self._executions: dict[str, _TurnExecution] = {}
+ # Per-turn reply queues used by tools that pause the agentic
+ # loop (e.g. ``ask_user``). Queue is created in ``_run_turn``
+ # before the orchestrator is invoked and cleaned up in the
+ # ``finally`` block, so callers of ``submit_user_reply`` see
+ # ``False`` for any turn that is no longer awaiting input.
+ # Each entry is a dict of shape:
+ # {"text": str, "answers": list[{"questionId": str, "text": str}] | None}
+ # ``text`` is always present (flat fallback for legacy callers);
+ # ``answers`` carries the structured per-question replies when the
+ # frontend sends the v2 ``ask_user`` shape.
+ self._reply_queues: dict[str, asyncio.Queue[dict[str, Any] | None]] = {}
async def start_turn(self, payload: dict[str, Any]) -> tuple[dict[str, Any], dict[str, Any]]:
capability = str(payload.get("capability") or "chat")
@@ -426,15 +583,7 @@ class TurnRuntimeManager:
"capability": capability,
"config": {**validated_public_config, **runtime_only_config},
}
- # ``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,
- )
+ session = await self.store.ensure_session(payload.get("session_id"))
preferences = session.get("preferences") or {}
raw_llm_selection = payload.get("llm_selection")
if raw_llm_selection is None:
@@ -487,6 +636,19 @@ class TurnRuntimeManager:
)
except ValueError as exc:
raise RuntimeError(str(exc)) from exc
+ # If the caller didn't pin a per-turn tool list (e.g. non-web
+ # channels or the new web UI which sources tools from
+ # /settings/tools), back-fill from the user's saved toggleable-tool
+ # preference so the chat pipeline sees the same set the user picked
+ # in Settings. Callers that explicitly pass ``tools`` (including
+ # an empty list) keep their value untouched.
+ if payload.get("tools") is None:
+ try:
+ from deeptutor.api.routers.settings import get_enabled_optional_tools
+
+ payload = {**payload, "tools": list(get_enabled_optional_tools())}
+ except Exception:
+ payload = {**payload, "tools": []}
payload = {**payload, "llm_selection": llm_selection}
preference_update: dict[str, Any] = {
"capability": capability,
@@ -651,6 +813,35 @@ class TurnRuntimeManager:
execution.task.cancel()
return True
+ async def submit_user_reply(
+ self,
+ turn_id: str,
+ text: str | None = None,
+ *,
+ answers: list[dict[str, Any]] | None = None,
+ ) -> bool:
+ """Deliver a user reply to a turn that's paused on ``ask_user``.
+
+ Returns ``True`` if the turn was waiting and the reply was
+ accepted; ``False`` if no waiter is registered (turn finished,
+ was cancelled, or the model never asked).
+
+ Accepts either ``text`` (single free-form reply, legacy single-
+ question shape) or ``answers`` (list of ``{questionId, text}``
+ pairs, v2 multi-question shape). Both may be passed; the
+ consumer prefers structured ``answers`` when present and falls
+ back to ``text`` for the legacy case. The payload is enqueued —
+ the pipeline's ``await waiter()`` call unblocks on the next
+ event-loop tick and substitutes the reply into the matching
+ ``role=tool`` message.
+ """
+ queue = self._reply_queues.get(turn_id)
+ if queue is None:
+ return False
+ payload: dict[str, Any] = {"text": text or "", "answers": answers}
+ await queue.put(payload)
+ return True
+
async def subscribe_turn(
self,
turn_id: str,
@@ -658,9 +849,22 @@ class TurnRuntimeManager:
) -> AsyncIterator[dict[str, Any]]:
backlog = await self.store.get_turn_events(turn_id, after_seq=after_seq)
last_seq = after_seq
+ # Track whether we ever yielded a terminal event (DONE) — if the live
+ # queue ends WITHOUT one (e.g. a transient send-side stall on
+ # ``safe_send`` swallowed it), we synthesise one before returning so
+ # the frontend's ``isStreaming`` state clears immediately rather than
+ # waiting on the 45s heartbeat-timeout + reconnect catchup path.
+ done_yielded = False
+
+ def _track(item: dict[str, Any]) -> dict[str, Any]:
+ nonlocal done_yielded
+ if str(item.get("type") or "") == "done":
+ done_yielded = True
+ return item
+
for item in backlog:
last_seq = max(last_seq, int(item.get("seq") or 0))
- yield item
+ yield _track(item)
queue: asyncio.Queue[dict[str, Any] | None] = asyncio.Queue()
subscriber = _LiveSubscriber(queue=queue)
@@ -671,9 +875,7 @@ class TurnRuntimeManager:
if execution is not None:
execution.subscribers.append(subscriber)
live_backlog = [
- item
- for item in execution.events
- if int(item.get("seq") or 0) > last_seq
+ item for item in execution.events if int(item.get("seq") or 0) > last_seq
]
for item in live_backlog:
@@ -681,7 +883,7 @@ class TurnRuntimeManager:
if seq <= last_seq:
continue
last_seq = seq
- yield item
+ yield _track(item)
catchup = []
if execution is None:
@@ -691,11 +893,16 @@ class TurnRuntimeManager:
if seq <= last_seq:
continue
last_seq = seq
- yield item
+ yield _track(item)
turn = await self.store.get_turn(turn_id)
if execution is None:
if turn is None or turn.get("status") != "running":
+ # Turn already finished and we didn't see a DONE in any of the
+ # persisted history above — synthesise one so the caller can
+ # still close out its streaming state cleanly.
+ if not done_yielded:
+ yield self._synthesize_done_event(turn_id, turn)
return
try:
while True:
@@ -706,7 +913,7 @@ class TurnRuntimeManager:
if seq <= last_seq:
continue
last_seq = seq
- yield item
+ yield _track(item)
finally:
async with self._lock:
execution = self._executions.get(turn_id)
@@ -714,6 +921,53 @@ class TurnRuntimeManager:
execution.subscribers = [
sub for sub in execution.subscribers if sub is not subscriber
]
+ # Safety net: if we drained the live queue (None sentinel arrived)
+ # without ever yielding a DONE, the turn is over server-side but
+ # the frontend wouldn't know. Read the persisted turn status one
+ # more time and synthesise a terminal DONE only for genuinely
+ # terminal turns so ``isStreaming`` clears without waiting on
+ # the heartbeat-reconnect fallback. A running turn may be paused
+ # on ``ask_user`` or may have had this subscription replaced; in
+ # that case a synthetic DONE would falsely mark the turn
+ # completed while the backend is still awaiting input.
+ if not done_yielded:
+ final_turn = await self.store.get_turn(turn_id)
+ final_status = str((final_turn or {}).get("status") or "").strip()
+ if final_turn is None or final_status in {"failed", "cancelled", "completed"}:
+ yield self._synthesize_done_event(turn_id, final_turn)
+
+ @staticmethod
+ def _synthesize_done_event(turn_id: str, turn: dict[str, Any] | None) -> dict[str, Any]:
+ """Build a DONE event payload from the persisted turn status.
+
+ Used as a recovery path when ``subscribe_turn`` finishes without
+ ever observing a live or persisted DONE event for a turn that has
+ nonetheless terminated server-side. Mirrors the shape of the
+ events the runtime would normally publish so the frontend doesn't
+ need a special code path to consume it.
+ """
+ status = "completed"
+ error: str | None = None
+ if turn is not None:
+ raw_status = str(turn.get("status") or "").strip()
+ if raw_status in {"failed", "cancelled", "completed"}:
+ status = raw_status
+ error_text = str(turn.get("error") or "").strip()
+ if error_text:
+ error = error_text
+ metadata: dict[str, Any] = {"status": status, "synthesized": True}
+ if error:
+ metadata["error"] = error
+ return {
+ "type": "done",
+ "source": "turn_runtime",
+ "stage": "",
+ "content": "",
+ "metadata": metadata,
+ "session_id": "",
+ "turn_id": turn_id,
+ "seq": 0,
+ }
async def subscribe_session(
self,
@@ -738,13 +992,22 @@ class TurnRuntimeManager:
stream_done_sent = False
llm_scope_token: Token[LLMConfig | None] | None = None
reset_active_llm_selection: Callable[[Token[LLMConfig | None] | None], None] | None = None
+ # One queue per turn for ``ask_user`` style pause-resume.
+ # Created here (BEFORE the orchestrator runs) so the pipeline can
+ # await on the awaitable we publish into ``context.metadata``.
+ # Cleaned up unconditionally in the outer ``finally``.
+ reply_queue: asyncio.Queue[dict[str, Any] | None] = asyncio.Queue()
+ self._reply_queues[turn_id] = reply_queue
+
+ async def _wait_for_user_reply() -> dict[str, Any] | None:
+ return await reply_queue.get()
try:
from deeptutor.agents.notebook import NotebookAnalysisAgent
from deeptutor.book.context import build_book_context
from deeptutor.core.context import Attachment, UnifiedContext
from deeptutor.runtime.orchestrator import ChatOrchestrator
- from deeptutor.services.memory import get_memory_service
+ from deeptutor.services.memory import get_memory_store
from deeptutor.services.model_selection.runtime import (
activate_llm_selection,
)
@@ -901,8 +1164,8 @@ class TurnRuntimeManager:
on_event=_emit_context_event,
leaf_message_id=branch_parent_id,
)
- memory_service = get_memory_service()
- memory_context = memory_service.build_memory_context(memory_references)
+ memory_store = get_memory_store()
+ memory_context = memory_store.read_l3_concat() if memory_references else ""
# Skill resolution differs for admin vs non-admin users:
# - Admin: use the user-scope SkillService (which is the admin
@@ -981,9 +1244,9 @@ class TurnRuntimeManager:
# ancestor chain) + 1. ``_count_branch_user_turns`` walks
# the same lineage the inventory builder uses, so we agree
# on what "turn N" means for the historical labels.
- current_turn_ordinal = await _count_branch_user_turns(
- self.store, session_id, branch_parent_id
- ) + 1
+ current_turn_ordinal = (
+ await _count_branch_user_turns(self.store, session_id, branch_parent_id) + 1
+ )
inventory = await build_inventory(
self.store,
session_id=session_id,
@@ -1024,7 +1287,9 @@ class TurnRuntimeManager:
if not history_session:
continue
- history_messages = await self.store.get_messages_for_context(history_session_id)
+ history_messages = await self.store.get_messages_for_context(
+ history_session_id
+ )
transcript_lines = [
f"## {str(message.get('role', '')).title()}\n{message.get('content', '')}"
for message in history_messages
@@ -1053,7 +1318,9 @@ class TurnRuntimeManager:
"id": history_session_id,
"notebook_id": "__history__",
"notebook_name": "History",
- "title": str(history_session.get("title", "") or "Untitled session"),
+ "title": str(
+ history_session.get("title", "") or "Untitled session"
+ ),
"summary": history_summary,
"output": "\n\n".join(transcript_lines),
"metadata": {
@@ -1120,9 +1387,7 @@ class TurnRuntimeManager:
# both branched edits with a positive id and root edits
# with explicit null). Otherwise let the store auto-append.
parent_kwargs: dict[str, Any] = (
- {"parent_message_id": branch_parent_id}
- if branch_parent_explicit
- else {}
+ {"parent_message_id": branch_parent_id} if branch_parent_explicit else {}
)
new_user_message_id = await self.store.add_message(
session_id=session_id,
@@ -1185,6 +1450,12 @@ class TurnRuntimeManager:
# turns with no attached sources). Consumed by the chat
# pipeline's tool kwargs injector.
"source_index": source_index,
+ # Pause-resume hook: the agentic chat pipeline awaits
+ # this callable when ``ask_user`` (or any other
+ # ``pause_for_user``-emitting tool) pauses the loop.
+ # The callable resolves when the frontend POSTs a
+ # reply via the ``submit_user_reply`` WS message.
+ "wait_for_user_reply": _wait_for_user_reply,
},
)
@@ -1234,16 +1505,21 @@ class TurnRuntimeManager:
await self._flush_buffered_events(execution)
await self.store.update_turn_status(turn_id, "completed")
if not is_regenerate:
+ # The frontend disconnects from this turn's WS subscription
+ # shortly after ``done`` (with a small grace window), so we
+ # generate the title here — inside the try block, before
+ # finally sends the ``None`` sentinel to subscribers — so
+ # the ``session_meta`` event still reaches them. The LLM
+ # scope set up at turn start is still active in this
+ # context, meaning the user's selected model is used.
try:
- await memory_service.refresh_from_turn(
- user_message=raw_user_content,
- assistant_message=assistant_content,
+ await self._maybe_generate_session_title(
+ execution=execution,
session_id=session_id,
- capability=capability_name or "chat",
- language=str(payload.get("language", "en") or "en"),
+ ui_language=str(payload.get("language", "en") or "en"),
)
except Exception:
- logger.debug("Failed to refresh lightweight memory", exc_info=True)
+ logger.debug("Failed to generate session title", exc_info=True)
except asyncio.CancelledError:
if not stream_done_sent:
await self._publish_live_event(
@@ -1301,6 +1577,10 @@ class TurnRuntimeManager:
finally:
if llm_scope_token is not None and reset_active_llm_selection is not None:
reset_active_llm_selection(llm_scope_token)
+ # Drop the reply queue first — any in-flight ``submit_user_reply``
+ # that finds the queue gone will return ``False`` rather than
+ # accumulating on a dead turn.
+ self._reply_queues.pop(turn_id, None)
async with self._lock:
current = self._executions.get(turn_id)
if current is not None:
@@ -1340,6 +1620,121 @@ class TurnRuntimeManager:
subscriber.queue.put_nowait(payload)
return payload
+ async def _maybe_generate_session_title(
+ self,
+ *,
+ execution: _TurnExecution,
+ session_id: str,
+ ui_language: str,
+ ) -> None:
+ """Generate a short LLM-written title for a freshly-named session.
+
+ Runs only when the session still carries the ``New conversation``
+ sentinel — once a user manually renames the chat (or this method
+ has already filled in a title), it short-circuits. Uses the LLM
+ scope already active on the calling task, which is the user's
+ currently selected model.
+ """
+ if not session_id:
+ return
+ session = await self.store.get_session(session_id)
+ if not session:
+ return
+ current_title = str(session.get("title") or "").strip()
+ if current_title and current_title != "New conversation":
+ return
+
+ messages = await self.store.get_messages(session_id)
+ first_user = ""
+ first_assistant = ""
+ for m in messages:
+ role = str(m.get("role") or "")
+ content = str(m.get("content") or "").strip()
+ if not content:
+ continue
+ if role == "user" and not first_user:
+ first_user = content
+ elif role == "assistant" and not first_assistant:
+ first_assistant = content
+ if first_user and first_assistant:
+ break
+ if not first_user or not first_assistant:
+ return
+
+ title = ""
+ try:
+ from deeptutor.services.llm import stream as llm_stream
+
+ zh = str(ui_language or "").lower().startswith("zh")
+ if zh:
+ sys_prompt = (
+ "你需要为一段对话生成一个简洁的标题。"
+ "直接输出标题文本,不要引号、不要 Markdown 格式、"
+ '不要末尾标点、不要 "标题:" 这类前缀。'
+ "标题控制在 4-10 个汉字以内。"
+ )
+ user_prompt = (
+ "请基于以下对话生成标题:\n\n"
+ f"[用户]\n{_clip_text(first_user, 800)}\n\n"
+ f"[助手]\n{_clip_text(first_assistant, 1500)}"
+ )
+ else:
+ sys_prompt = (
+ "You generate a concise, descriptive title for a "
+ "conversation. Output only the title as plain text "
+ "— no quotes, no markdown, no trailing punctuation, "
+ 'no "Title:" prefix. Keep it 4-8 words.'
+ )
+ user_prompt = (
+ "Generate a title for this conversation:\n\n"
+ f"[User]\n{_clip_text(first_user, 800)}\n\n"
+ f"[Assistant]\n{_clip_text(first_assistant, 1500)}"
+ )
+
+ async def _collect_title() -> str:
+ buf: list[str] = []
+ async for c in llm_stream(
+ prompt=user_prompt,
+ system_prompt=sys_prompt,
+ temperature=0.3,
+ max_tokens=80,
+ ):
+ buf.append(c)
+ return "".join(buf)
+
+ raw_title = await asyncio.wait_for(_collect_title(), timeout=20.0)
+ title = _sanitize_session_title(raw_title)
+ except asyncio.TimeoutError:
+ logger.debug("Title LLM call timed out — falling back")
+ except Exception:
+ logger.debug("Title LLM call failed", exc_info=True)
+
+ if not title:
+ # Fallback: truncate the first user message so the sidebar
+ # doesn't sit on "New conversation" indefinitely when the
+ # title model errors out.
+ title = first_user[:50] + ("..." if len(first_user) > 50 else "")
+
+ if not title:
+ return
+
+ try:
+ await self.store.update_session_title(session_id, title)
+ except Exception:
+ logger.debug("update_session_title failed", exc_info=True)
+ return
+
+ await self._publish_live_event(
+ execution,
+ StreamEvent(
+ type=StreamEventType.SESSION_META,
+ source="turn_runtime",
+ stage="title",
+ content=title,
+ metadata={"title": title, "session_id": session_id},
+ ),
+ )
+
async def _flush_buffered_events(self, execution: _TurnExecution) -> None:
"""Persist buffered turn events after the live stream has already drained."""
async with self._lock:
diff --git a/deeptutor/services/setup/init.py b/deeptutor/services/setup/init.py
index e38838422..c8d93491b 100644
--- a/deeptutor/services/setup/init.py
+++ b/deeptutor/services/setup/init.py
@@ -34,15 +34,6 @@ DEFAULT_MAIN_SETTINGS = {
"save_to_file": True,
"console_output": True,
},
- "personalization": {
- "auto_update": True,
- "max_react_rounds": 6,
- "agents": {
- "reflection": True,
- "summary": True,
- "weakness": True,
- },
- },
"tools": {
"run_code": {
"allowed_roots": ["./data/user"],
@@ -52,19 +43,9 @@ DEFAULT_MAIN_SETTINGS = {
},
},
"capabilities": {
- "question": {
- "max_parallel_questions": 1,
- "idea_loop": {"max_rounds": 3, "ideas_per_round": 5},
- "generation": {"max_retries": 2},
- },
"solve": {
- "max_react_iterations": 10,
- "max_plan_steps": 10,
+ "max_iterations_per_step": 7,
"max_replans": 2,
- "observation_max_tokens": 2000,
- "enable_citations": True,
- "save_intermediate_results": True,
- "detailed_answer": True,
},
"research": {
"researching": {
@@ -74,6 +55,15 @@ DEFAULT_MAIN_SETTINGS = {
"paper_search_years_limit": 3,
},
},
+ "question": {
+ "exploring": {
+ "max_iterations": 8,
+ "tool_summarizer": {
+ "enabled": True,
+ "max_tokens": 800,
+ },
+ },
+ },
},
}
@@ -87,10 +77,6 @@ DEFAULT_AGENTS_SETTINGS = {
"temperature": 0.2,
"responding": {"max_tokens": 8000},
"answer_now": {"max_tokens": 8000},
- "thinking": {"max_tokens": 2000},
- "observing": {"max_tokens": 2000},
- "acting": {"max_tokens": 2000},
- "react_fallback": {"max_tokens": 1500},
},
},
"tools": {
diff --git a/deeptutor/services/tutorbot/manager.py b/deeptutor/services/tutorbot/manager.py
index b85a8584d..cb59dce16 100644
--- a/deeptutor/services/tutorbot/manager.py
+++ b/deeptutor/services/tutorbot/manager.py
@@ -196,7 +196,6 @@ class TutorBotManager:
@property
def _path_service(self):
- from deeptutor.services.path_service import get_path_service
return get_path_service()
# ── Path helpers ──────────────────────────────────────────────
@@ -1119,7 +1118,6 @@ _managers: dict[str, TutorBotManager] = {}
def get_tutorbot_manager() -> TutorBotManager:
- from deeptutor.services.path_service import get_path_service
key = str(get_path_service().workspace_root.resolve())
if key not in _managers:
_managers[key] = TutorBotManager()
diff --git a/deeptutor/tutorbot/channels/zulip.py b/deeptutor/tutorbot/channels/zulip.py
index 29e06ed46..05a2ddb28 100644
--- a/deeptutor/tutorbot/channels/zulip.py
+++ b/deeptutor/tutorbot/channels/zulip.py
@@ -40,6 +40,15 @@ _CODE_BLOCK_RE = re.compile(
)
ZULIP_MAX_MESSAGE_LEN = 10000
+ZULIP_UPLOAD_PREFIX = "/user_uploads/"
+MENTION_FLAGS = frozenset(
+ {
+ "mentioned",
+ "wildcard_mentioned",
+ "stream_wildcard_mentioned",
+ "topic_wildcard_mentioned",
+ }
+)
class ZulipConfig(Base):
@@ -69,7 +78,6 @@ class ZulipChannel(BaseChannel):
self._client: Any = None
self._bot_email: str = ""
self._bot_user_id: int | None = None
- self._bot_full_name: str = ""
self._queue_id: str | None = None
self._last_event_id: int = -1
self._max_message_id: int = 0
@@ -120,7 +128,6 @@ class ZulipChannel(BaseChannel):
self._bot_email = profile.get("email", self.config.email)
self._bot_user_id = profile.get("user_id")
- self._bot_full_name = profile.get("full_name", "")
logger.info(
"Zulip bot connected: {} (user_id={})",
self._bot_email,
@@ -162,28 +169,34 @@ class ZulipChannel(BaseChannel):
logger.warning("Zulip client not running")
return
- if msg.metadata.get("_tool_hint"):
- return
-
- if not msg.metadata.get("msg_type"):
- stored = self._recipient_map.get(msg.chat_id)
- if stored:
- msg.metadata = {**stored, **msg.metadata}
+ metadata = self._metadata_for_send(msg)
- if not msg.metadata.get("_progress", False):
+ if not metadata.get("_progress", False):
self._stop_typing(msg.chat_id)
try:
for media_path in msg.media or []:
- await self._upload_and_send(msg.chat_id, media_path, msg.metadata)
+ await self._upload_and_send(msg.chat_id, media_path, metadata)
if msg.content and msg.content != "[empty message]":
converted = self._convert_latex_to_zulip(msg.content)
for chunk in split_message(converted, ZULIP_MAX_MESSAGE_LEN):
- await self._send_text(msg.chat_id, chunk, msg.metadata)
+ await self._send_text(msg.chat_id, chunk, metadata)
except Exception as e:
logger.error("Zulip send error: {}", e)
+ def _metadata_for_send(self, msg: OutboundMessage) -> dict:
+ metadata = msg.metadata or {}
+ if metadata.get("msg_type"):
+ return metadata
+
+ stored = self._recipient_map.get(msg.chat_id)
+ if not stored:
+ return metadata
+
+ msg.metadata = {**stored, **metadata}
+ return msg.metadata
+
def _call_with_retry(self, fn, *args, max_retries=3, **kwargs):
for attempt in range(max_retries):
try:
@@ -254,60 +267,94 @@ class ZulipChannel(BaseChannel):
logger.info("Zulip listener stopped")
def _subscribe_to_streams(self) -> None:
- streams = self.config.subscribe_streams
- if not streams:
- logger.info("No subscribe_streams configured, skipping auto-subscribe")
+ stream_names = self._stream_names_to_subscribe()
+ if stream_names is None:
return
-
- stream_names: list[str]
- if "*" in streams:
- try:
- result = self._call_with_retry(self._client.get_streams, include_all=True)
- except Exception as e:
- logger.error("Zulip get_streams failed during auto-subscribe: {}", e)
- return
- if result.get("result") != "success":
- logger.error("Failed to fetch streams for auto-subscribe: {}", result.get("msg"))
- return
- fetched = {s["name"] for s in result.get("streams", [])}
- extra = {s for s in streams if s != "*"}
- stream_names = list(fetched | extra)
- else:
- stream_names = list(streams)
-
if not stream_names:
- logger.info("No streams to subscribe to")
+ logger.info("No subscribe_streams configured, skipping auto-subscribe")
return
subscriptions = [{"name": name} for name in stream_names]
try:
- result = self._call_with_retry(
- self._client.add_subscriptions, streams=subscriptions
- )
+ result = self._call_with_retry(self._client.add_subscriptions, streams=subscriptions)
except Exception as e:
logger.error("Zulip auto-subscribe failed: {}", e)
return
+
+ self._log_subscription_result(result, set(stream_names))
+
+ def _stream_names_to_subscribe(self) -> list[str] | None:
+ streams = [s.strip() for s in self.config.subscribe_streams if s.strip()]
+ if not streams:
+ return []
+
+ if "*" not in streams:
+ return sorted(set(streams))
+
+ try:
+ result = self._call_with_retry(self._client.get_streams, include_all=True)
+ except Exception as e:
+ logger.error("Zulip get_streams failed during auto-subscribe: {}", e)
+ return None
+
+ if result.get("result") != "success":
+ logger.error("Failed to fetch streams for auto-subscribe: {}", result.get("msg"))
+ return None
+
+ fetched = {
+ stream.get("name")
+ for stream in result.get("streams", [])
+ if isinstance(stream, dict) and stream.get("name")
+ }
+ explicit = {stream for stream in streams if stream != "*"}
+ return sorted(fetched | explicit)
+
+ @staticmethod
+ def _already_subscribed_names(result: dict) -> set[str]:
+ already_subscribed = result.get("already_subscribed", {})
+ if isinstance(already_subscribed, list):
+ return {name for name in already_subscribed if isinstance(name, str)}
+ if not isinstance(already_subscribed, dict):
+ return set()
+
already_subscribed_names: set[str] = set()
- for names in result.get("already_subscribed", {}).values():
- already_subscribed_names.update(names)
- new_count = len(stream_names) - len(already_subscribed_names)
- if new_count > 0:
- logger.info(
- "Zulip bot subscribed to {} streams ({} new, {} already subscribed)",
- len(stream_names),
- new_count,
- len(stream_names) - new_count,
- )
- else:
- logger.info(
- "Zulip bot already subscribed to {} streams (no new subscriptions)",
- len(stream_names),
- )
- if result.get("result") != "success" and new_count == 0:
+ for names in already_subscribed.values():
+ if isinstance(names, str):
+ already_subscribed_names.add(names)
+ elif isinstance(names, (list, tuple, set)):
+ already_subscribed_names.update(name for name in names if isinstance(name, str))
+ return already_subscribed_names
+
+ def _log_subscription_result(self, result: dict, stream_names: set[str]) -> None:
+ already_subscribed = self._already_subscribed_names(result) & stream_names
+ missing = stream_names - already_subscribed
+
+ if result.get("result") == "success":
+ if missing:
+ logger.info(
+ "Zulip bot subscribed to {} streams ({} new, {} already subscribed)",
+ len(stream_names),
+ len(missing),
+ len(already_subscribed),
+ )
+ else:
+ logger.info(
+ "Zulip bot already subscribed to {} streams (no new subscriptions)",
+ len(stream_names),
+ )
+ return
+
+ if not missing:
logger.debug(
"Zulip add_subscriptions returned non-success but all streams already subscribed: {}",
result.get("msg", "unknown"),
)
+ else:
+ logger.warning(
+ "Zulip auto-subscribe did not subscribe {} streams: {}",
+ len(missing),
+ result.get("msg", "unknown"),
+ )
def _register_queue(self) -> None:
try:
@@ -359,17 +406,13 @@ class ZulipChannel(BaseChannel):
msg_type = message.get("type", "")
content = message.get("content", "")
- flags = message.get("flags", [])
- sender_email = message.get("sender_email", "?")
- subject = message.get("subject", "")
- display_recipient = message.get("display_recipient", "")
- logger.info(
+ logger.debug(
"Zulip message received: type={}, flags={}, sender={}, stream={}, topic={}",
msg_type,
- flags,
- sender_email,
- display_recipient if msg_type == "stream" else "N/A",
- subject,
+ message.get("flags", []),
+ message.get("sender_email", "?"),
+ message.get("display_recipient", "") if msg_type == "stream" else "N/A",
+ message.get("subject", ""),
)
content_type = message.get("content_type", "text/x-markdown")
if content_type == "text/x-markdown":
@@ -382,22 +425,23 @@ class ZulipChannel(BaseChannel):
composite_sender = f"{sender_id}|{sender_email}" if sender_email else str(sender_id)
if msg_type == "stream":
- if isinstance(display_recipient, dict):
- stream_name = display_recipient.get("name", str(display_recipient))
- else:
- stream_name = str(display_recipient)
+ stream_name = self._stream_name(display_recipient)
topic = self._topic_label(subject)
chat_id = self._stream_chat_id(stream_name, topic)
if self.config.group_policy == "mention":
if not self._is_mentioned(message):
- logger.info(
+ logger.debug(
"Zulip stream message ignored (not mentioned): stream={}, topic={}, flags={}",
stream_name,
topic,
message.get("flags", []),
)
return
- logger.info("Zulip stream message will be processed: stream={}, topic={}", stream_name, topic)
+ logger.debug(
+ "Zulip stream message will be processed: stream={}, topic={}",
+ stream_name,
+ topic,
+ )
content = f"**[{stream_name} > {topic}]** {content}"
elif msg_type == "private":
chat_id = f"pm:{sender_id}"
@@ -415,10 +459,7 @@ class ZulipChannel(BaseChannel):
}
if msg_type == "stream":
- if isinstance(display_recipient, dict):
- metadata["stream"] = display_recipient.get("name", str(display_recipient))
- else:
- metadata["stream"] = display_recipient
+ metadata["stream"] = self._stream_name(display_recipient)
metadata["topic"] = topic
else:
metadata["recipient_user_id"] = sender_id
@@ -441,6 +482,12 @@ class ZulipChannel(BaseChannel):
self._loop,
)
+ @staticmethod
+ def _stream_name(display_recipient: Any) -> str:
+ if isinstance(display_recipient, dict):
+ return display_recipient.get("name", str(display_recipient))
+ return str(display_recipient)
+
@staticmethod
def _topic_label(subject: Any) -> str:
topic = str(subject or "").strip()
@@ -457,20 +504,16 @@ class ZulipChannel(BaseChannel):
def _is_mentioned(self, message: dict) -> bool:
if self._bot_user_id is None:
- logger.warning("Zulip _is_mentioned: bot_user_id is None, cannot check mention")
+ logger.debug("Zulip _is_mentioned: bot_user_id is None, cannot check mention")
return False
- mention_flags = {
- "mentioned",
- "wildcard_mentioned",
- "stream_wildcard_mentioned",
- "topic_wildcard_mentioned",
- }
- flags = message.get("flags", [])
- for flag in flags:
- if isinstance(flag, str) and flag in mention_flags:
+ for flag in message.get("flags", []):
+ if isinstance(flag, str) and flag in MENTION_FLAGS:
logger.debug("Zulip _is_mentioned: found flag={}", flag)
return True
- logger.debug("Zulip _is_mentioned: no mention flags found, flags={}", flags)
+ logger.debug(
+ "Zulip _is_mentioned: no mention flags found, flags={}",
+ message.get("flags", []),
+ )
return False
def _download_attachments(self, message: dict) -> list[str]:
@@ -485,25 +528,14 @@ class ZulipChannel(BaseChannel):
media_dir = get_media_dir("zulip")
for name, path_id in upload_links:
- url = f"{self.config.site.rstrip('/')}{path_id}"
- dest = self._attachment_destination(media_dir, name, path_id, len(paths))
-
- if dest.exists():
- paths.append(str(dest))
- continue
-
- try:
- resp = requests.get(
- url,
- auth=(self.config.email, self.config.api_key),
- timeout=self.config.timeout,
- )
- resp.raise_for_status()
- dest.write_bytes(resp.content)
- paths.append(str(dest))
- logger.debug("Downloaded Zulip attachment: {}", name or path_id)
- except Exception as e:
- logger.warning("Failed to download Zulip attachment {}: {}", name or path_id, e)
+ local_path = self._download_upload_path(
+ path_id,
+ media_dir=media_dir,
+ name=name,
+ index=len(paths),
+ )
+ if local_path:
+ paths.append(local_path)
return paths
@@ -557,6 +589,53 @@ class ZulipChannel(BaseChannel):
return links
+ def _path_id_from_media(self, media_path: str) -> str | None:
+ if media_path.startswith(ZULIP_UPLOAD_PREFIX):
+ return media_path
+
+ site = self.config.site.rstrip("/")
+ if not site:
+ return None
+
+ prefix = f"{site}{ZULIP_UPLOAD_PREFIX}"
+ if media_path.startswith(prefix):
+ return f"{ZULIP_UPLOAD_PREFIX}{media_path[len(prefix) :]}"
+ return None
+
+ def _download_upload_path(
+ self,
+ path_id: str,
+ *,
+ media_dir: Path | None = None,
+ name: str | None = None,
+ index: int = 0,
+ ) -> str | None:
+ media_dir = media_dir or get_media_dir("zulip")
+ filename = name or Path(unquote(path_id)).name
+ dest = self._attachment_destination(media_dir, filename, path_id, index)
+
+ if dest.exists():
+ return str(dest)
+
+ url = f"{self.config.site.rstrip('/')}{path_id}"
+ try:
+ resp = requests.get(
+ url,
+ auth=(self.config.email, self.config.api_key),
+ timeout=self.config.timeout,
+ )
+ resp.raise_for_status()
+ dest.write_bytes(resp.content)
+ logger.debug("Downloaded Zulip attachment: {}", filename or path_id)
+ return str(dest)
+ except Exception as e:
+ logger.warning(
+ "Failed to download Zulip attachment {}: {}",
+ filename or path_id,
+ e,
+ )
+ return None
+
@staticmethod
def _convert_latex_to_zulip(text: str) -> str:
placeholders: list[str] = []
@@ -634,38 +713,11 @@ class ZulipChannel(BaseChannel):
if Path(media_path).exists():
return media_path
- path_id: str | None = None
- if media_path.startswith("/user_uploads/"):
- path_id = media_path
- elif self.config.site and media_path.startswith(self.config.site):
- stripped = media_path[len(self.config.site.rstrip("/")):]
- if stripped.startswith("/user_uploads/"):
- path_id = stripped
-
+ path_id = self._path_id_from_media(media_path)
if not path_id:
return None
- media_dir = get_media_dir("zulip")
- name = Path(unquote(path_id)).name
- dest = self._attachment_destination(media_dir, name, path_id, 0)
-
- if dest.exists():
- return str(dest)
-
- url = f"{self.config.site.rstrip('/')}{path_id}"
- try:
- resp = requests.get(
- url,
- auth=(self.config.email, self.config.api_key),
- timeout=self.config.timeout,
- )
- resp.raise_for_status()
- dest.write_bytes(resp.content)
- logger.debug("Downloaded Zulip attachment for re-upload: {}", name)
- return str(dest)
- except Exception as e:
- logger.warning("Failed to download Zulip attachment {}: {}", name, e)
- return None
+ return self._download_upload_path(path_id)
async def _upload_and_send(self, chat_id: str, media_path: str, metadata: dict) -> None:
client = self._client
diff --git a/deeptutor/tutorbot/providers/openai_compat_provider.py b/deeptutor/tutorbot/providers/openai_compat_provider.py
index 851396c5e..59a0f8685 100644
--- a/deeptutor/tutorbot/providers/openai_compat_provider.py
+++ b/deeptutor/tutorbot/providers/openai_compat_provider.py
@@ -40,9 +40,7 @@ _DEFAULT_OPENROUTER_HEADERS = {
"HTTP-Referer": "https://github.com/HKUDS/DeepTutor",
"X-OpenRouter-Title": "DeepTutor",
}
-_THINKING_DISABLED_BY_DEFAULT: tuple[tuple[str, str], ...] = (
- ("deepseek", "deepseek-v4-flash"),
-)
+_THINKING_DISABLED_BY_DEFAULT: tuple[tuple[str, str], ...] = (("deepseek", "deepseek-v4-flash"),)
def _short_tool_id() -> str:
@@ -291,9 +289,7 @@ class OpenAICompatProvider(LLMProvider):
kwargs.setdefault("extra_body", {}).update(extra)
elif spec and _disable_thinking_by_default(spec, model_name):
if spec.name == "deepseek":
- kwargs.setdefault("extra_body", {}).update(
- {"thinking": {"type": "disabled"}}
- )
+ kwargs.setdefault("extra_body", {}).update({"thinking": {"type": "disabled"}})
# Providers that handle thinking via extra_body don't need a
# top-level reasoning_effort when the intent is to disable thinking.
diff --git a/deeptutor/utils/json_parser.py b/deeptutor/utils/json_parser.py
index f4be27321..6afd46733 100644
--- a/deeptutor/utils/json_parser.py
+++ b/deeptutor/utils/json_parser.py
@@ -97,7 +97,10 @@ def parse_json_response(
log.info("Successfully repaired malformed JSON")
return result
except Exception as repair_error:
- log.error(f"JSON repair failed: {repair_error}")
+ # Most callers use this helper as best-effort parsing with an explicit
+ # fallback. Non-JSON prose is common in LLM/tool output and should not
+ # look like a backend failure when the caller can safely continue.
+ log.debug(f"JSON repair failed: {repair_error}")
log.debug(f"Response: {extracted_response[:200]}")
return fallback
diff --git a/tests/api/test_notebook_router.py b/tests/api/test_notebook_router.py
index ef98e1945..a17a28dee 100644
--- a/tests/api/test_notebook_router.py
+++ b/tests/api/test_notebook_router.py
@@ -238,3 +238,102 @@ def test_lookup_entry_by_question(store: SQLiteSessionStore) -> None:
params={"session_id": session["id"], "question_id": "nope"},
)
assert resp404.status_code == 404
+
+
+def test_quiz_state_isolated_per_turn(store: SQLiteSessionStore) -> None:
+ """Regression test for #487 — two quizzes in the same chat session must
+ not share answer state, even when the positional ``question_id`` (e.g.
+ ``q_1``) collides. The producing turn_id scopes notebook entries.
+ """
+ session = asyncio.run(store.create_session())
+ sid = session["id"]
+
+ with TestClient(_build_app(store)) as client:
+ first = _quiz_answers()
+ resp1 = client.post(
+ f"/api/v1/sessions/{sid}/quiz-results",
+ json={"answers": first, "turn_id": "turn_A"},
+ )
+ assert resp1.status_code == 200
+ assert resp1.json()["notebook_count"] == 2
+
+ second = _quiz_answers()
+ second[0]["user_answer"] = ""
+ second[0]["is_correct"] = False
+ resp2 = client.post(
+ f"/api/v1/sessions/{sid}/quiz-results",
+ json={"answers": second, "turn_id": "turn_B"},
+ )
+ assert resp2.status_code == 200
+ assert resp2.json()["notebook_count"] == 2
+
+ listing = client.get("/api/v1/question-notebook/entries").json()
+ assert listing["total"] == 4
+
+ # Looking up q1 scoped to the first turn returns the first quiz's
+ # answer, not the second.
+ scoped_a = client.get(
+ "/api/v1/question-notebook/entries/lookup/by-question",
+ params={"session_id": sid, "question_id": "q1", "turn_id": "turn_A"},
+ )
+ assert scoped_a.status_code == 200
+ assert scoped_a.json()["user_answer"] == "A"
+ assert scoped_a.json()["turn_id"] == "turn_A"
+
+ # The second turn has no recorded answer for q1.
+ scoped_b = client.get(
+ "/api/v1/question-notebook/entries/lookup/by-question",
+ params={"session_id": sid, "question_id": "q1", "turn_id": "turn_B"},
+ )
+ assert scoped_b.status_code == 200
+ assert scoped_b.json()["user_answer"] == ""
+ assert scoped_b.json()["turn_id"] == "turn_B"
+
+
+def test_lookup_without_turn_id_falls_back_to_latest(
+ store: SQLiteSessionStore,
+) -> None:
+ """Callers that don't pass turn_id (legacy entries / external API) get the
+ most recently updated matching entry — deterministic even when multiple
+ turns share a question_id."""
+ session = asyncio.run(store.create_session())
+ sid = session["id"]
+
+ asyncio.run(
+ store.upsert_notebook_entries(
+ sid,
+ [
+ {
+ "turn_id": "turn_old",
+ "question_id": "q1",
+ "question": "Q?",
+ "user_answer": "A",
+ "is_correct": False,
+ }
+ ],
+ )
+ )
+ asyncio.run(
+ store.upsert_notebook_entries(
+ sid,
+ [
+ {
+ "turn_id": "turn_new",
+ "question_id": "q1",
+ "question": "Q?",
+ "user_answer": "B",
+ "is_correct": True,
+ }
+ ],
+ )
+ )
+
+ with TestClient(_build_app(store)) as client:
+ resp = client.get(
+ "/api/v1/question-notebook/entries/lookup/by-question",
+ params={"session_id": sid, "question_id": "q1"},
+ )
+ assert resp.status_code == 200
+ body = resp.json()
+ assert body["turn_id"] == "turn_new"
+ assert body["user_answer"] == "B"
diff --git a/tests/api/test_settings_router.py b/tests/api/test_settings_router.py
index 388b710f7..42c638245 100644
--- a/tests/api/test_settings_router.py
+++ b/tests/api/test_settings_router.py
@@ -300,6 +300,32 @@ async def test_apply_catalog_invalidates_runtime_caches(monkeypatch: pytest.Monk
assert new_embedding_client.config.model == "text-embedding-after-apply"
+async def test_enabled_tools_roundtrip(monkeypatch: pytest.MonkeyPatch, tmp_path) -> None:
+ settings_file = tmp_path / "interface.json"
+ monkeypatch.setattr(settings_router, "_settings_file", lambda: settings_file)
+
+ # Default state — no file yet, so the loader emits the full toggleable set.
+ assert set(settings_router.get_enabled_optional_tools()) == set(
+ settings_router.USER_TOGGLEABLE_TOOL_NAMES
+ )
+
+ # PUT a partial set; unknown tool names get filtered out.
+ update = settings_router.EnabledToolsUpdate(
+ enabled_tools=["web_search", "reason", "not_a_real_tool"]
+ )
+ response = await settings_router.update_enabled_tools(update)
+ assert response == {"enabled_optional_tools": ["web_search", "reason"]}
+ assert settings_router.get_enabled_optional_tools() == ["web_search", "reason"]
+
+ # Empty selection is a valid "all off" state.
+ response = await settings_router.update_enabled_tools(
+ settings_router.EnabledToolsUpdate(enabled_tools=[])
+ )
+ assert response == {"enabled_optional_tools": []}
+ assert settings_router.get_enabled_optional_tools() == []
+
+
@pytest.mark.asyncio
async def test_complete_tour_invalidates_runtime_caches(
monkeypatch: pytest.MonkeyPatch, tmp_path
diff --git a/tests/api/test_unified_ws_turn_runtime.py b/tests/api/test_unified_ws_turn_runtime.py
index 4afb43078..c7525aa95 100644
--- a/tests/api/test_unified_ws_turn_runtime.py
+++ b/tests/api/test_unified_ws_turn_runtime.py
@@ -9,7 +9,7 @@ from deeptutor.services.session.sqlite_store import SQLiteSessionStore
from deeptutor.services.session.turn_runtime import TurnRuntimeManager
-async def _noop_refresh(**_kwargs):
+async def _noop_async(*_args, **_kwargs):
return None
@@ -122,10 +122,10 @@ async def test_turn_runtime_replays_events_and_materializes_messages(
),
)
monkeypatch.setattr(
- "deeptutor.services.memory.get_memory_service",
+ "deeptutor.services.memory.get_memory_store",
lambda: SimpleNamespace(
- build_memory_context=lambda *_args, **_kwargs: "",
- refresh_from_turn=_noop_refresh,
+ read_l3_concat=lambda: "",
+ emit=_noop_async,
),
)
monkeypatch.setattr(
@@ -154,8 +154,15 @@ async def test_turn_runtime_replays_events_and_materializes_messages(
async for event in runtime.subscribe_turn(turn["id"], after_seq=0):
events.append(event)
- assert [event["type"] for event in events] == ["session", "content", "done"]
- assert events[-1]["metadata"]["status"] == "completed"
+ # session_meta may arrive after `done` from the title generator —
+ # filter it out so the timing race doesn't flake the assertion.
+ assert [e["type"] for e in events if e["type"] != "session_meta"] == [
+ "session",
+ "content",
+ "done",
+ ]
+ done_event = next(e for e in events if e["type"] == "done")
+ assert done_event["metadata"]["status"] == "completed"
detail = await store.get_session_with_messages(session["id"])
assert detail is not None
@@ -253,10 +260,10 @@ async def test_turn_runtime_persists_llm_selection_in_turn_snapshot(
)
monkeypatch.setattr("deeptutor.runtime.orchestrator.ChatOrchestrator", FakeOrchestrator)
monkeypatch.setattr(
- "deeptutor.services.memory.get_memory_service",
+ "deeptutor.services.memory.get_memory_store",
lambda: SimpleNamespace(
- build_memory_context=lambda *_args, **_kwargs: "",
- refresh_from_turn=_noop_refresh,
+ read_l3_concat=lambda: "",
+ emit=_noop_async,
),
)
monkeypatch.setattr("deeptutor.services.skill.get_skill_service", _fake_skill_service)
@@ -384,10 +391,10 @@ async def test_turn_runtime_allows_model_switching_within_same_session(
)
monkeypatch.setattr("deeptutor.runtime.orchestrator.ChatOrchestrator", FakeOrchestrator)
monkeypatch.setattr(
- "deeptutor.services.memory.get_memory_service",
+ "deeptutor.services.memory.get_memory_store",
lambda: SimpleNamespace(
- build_memory_context=lambda *_args, **_kwargs: "",
- refresh_from_turn=_noop_refresh,
+ read_l3_concat=lambda: "",
+ emit=_noop_async,
),
)
monkeypatch.setattr("deeptutor.services.skill.get_skill_service", _fake_skill_service)
@@ -532,10 +539,10 @@ async def test_turn_runtime_bootstraps_question_followup_context_once(
)
monkeypatch.setattr("deeptutor.runtime.orchestrator.ChatOrchestrator", FakeOrchestrator)
monkeypatch.setattr(
- "deeptutor.services.memory.get_memory_service",
+ "deeptutor.services.memory.get_memory_store",
lambda: SimpleNamespace(
- build_memory_context=lambda *_args, **_kwargs: "",
- refresh_from_turn=_noop_refresh,
+ read_l3_concat=lambda: "",
+ emit=_noop_async,
),
)
monkeypatch.setattr("deeptutor.services.skill.get_skill_service", _fake_skill_service)
@@ -577,7 +584,13 @@ async def test_turn_runtime_bootstraps_question_followup_context_once(
async for event in runtime.subscribe_turn(turn["id"], after_seq=0):
events.append(event)
- assert [event["type"] for event in events] == ["session", "content", "done"]
+ # session_meta may arrive after `done` from the title generator —
+ # filter it out so the timing race doesn't flake the assertion.
+ assert [e["type"] for e in events if e["type"] != "session_meta"] == [
+ "session",
+ "content",
+ "done",
+ ]
detail = await store.get_session_with_messages(session["id"])
assert detail is not None
assert [message["role"] for message in detail["messages"]] == ["system", "user", "assistant"]
@@ -650,10 +663,10 @@ async def test_turn_runtime_persists_deep_research_session_preference(
)
monkeypatch.setattr("deeptutor.runtime.orchestrator.ChatOrchestrator", FakeOrchestrator)
monkeypatch.setattr(
- "deeptutor.services.memory.get_memory_service",
+ "deeptutor.services.memory.get_memory_store",
lambda: SimpleNamespace(
- build_memory_context=lambda *_args, **_kwargs: "",
- refresh_from_turn=_noop_refresh,
+ read_l3_concat=lambda: "",
+ emit=_noop_async,
),
)
monkeypatch.setattr("deeptutor.services.skill.get_skill_service", _fake_skill_service)
@@ -671,7 +684,6 @@ async def test_turn_runtime_persists_deep_research_session_preference(
"config": {
"mode": "report",
"depth": "standard",
- "sources": ["kb", "web"],
},
}
)
@@ -680,7 +692,13 @@ async def test_turn_runtime_persists_deep_research_session_preference(
async for event in runtime.subscribe_turn(turn["id"], after_seq=0):
events.append(event)
- assert [event["type"] for event in events] == ["session", "content", "done"]
+ # session_meta may arrive after `done` from the title generator —
+ # filter it out so the timing race doesn't flake the assertion.
+ assert [e["type"] for e in events if e["type"] != "session_meta"] == [
+ "session",
+ "content",
+ "done",
+ ]
detail = await store.get_session_with_messages(session["id"])
assert detail is not None
assert detail["preferences"]["capability"] == "deep_research"
@@ -725,10 +743,10 @@ async def test_turn_runtime_injects_memory_and_refreshes_after_completion(
)
yield StreamEvent(type=StreamEventType.DONE, source="chat")
- refresh_calls: list[dict[str, object]] = []
+ emit_calls: list[object] = []
- async def fake_refresh_from_turn(**kwargs):
- refresh_calls.append(kwargs)
+ async def fake_emit(event):
+ emit_calls.append(event)
return None
monkeypatch.setattr("deeptutor.services.llm.config.get_llm_config", lambda: SimpleNamespace())
@@ -737,11 +755,10 @@ async def test_turn_runtime_injects_memory_and_refreshes_after_completion(
)
monkeypatch.setattr("deeptutor.runtime.orchestrator.ChatOrchestrator", FakeOrchestrator)
monkeypatch.setattr(
- "deeptutor.services.memory.get_memory_service",
+ "deeptutor.services.memory.get_memory_store",
lambda: SimpleNamespace(
- build_memory_context=lambda *_args,
- **_kwargs: "## Memory\n## Preferences\n- Prefer concise answers.",
- refresh_from_turn=fake_refresh_from_turn,
+ read_l3_concat=lambda: "## Memory\n## Preferences\n- Prefer concise answers.",
+ emit=fake_emit,
),
)
monkeypatch.setattr("deeptutor.services.skill.get_skill_service", _fake_skill_service)
@@ -755,6 +772,7 @@ async def test_turn_runtime_injects_memory_and_refreshes_after_completion(
"tools": [],
"knowledge_bases": [],
"attachments": [],
+ "memory_references": ["preferences"],
"language": "en",
"config": {},
}
@@ -766,4 +784,5 @@ async def test_turn_runtime_injects_memory_and_refreshes_after_completion(
assert captured["memory_context"] == "## Memory\n## Preferences\n- Prefer concise answers."
assert captured["conversation_history"] == []
assert captured["conversation_context_text"] == "Recent chat summary"
- assert refresh_calls[0]["assistant_message"] == "Stored reply"
+ assert len(emit_calls) == 1
+ assert emit_calls[0].payload["assistant"] == "Stored reply"
diff --git a/tests/core/test_context.py b/tests/core/test_context.py
index 291e71cf7..1288beb94 100644
--- a/tests/core/test_context.py
+++ b/tests/core/test_context.py
@@ -85,7 +85,7 @@ class TestUnifiedContext:
config_overrides={"temperature": 0.5},
language="zh",
memory_context="user preference",
- source_manifest="id=nb-1 name=\"Lecture\" type=notebook preview=\"...\"",
+ source_manifest='id=nb-1 name="Lecture" type=notebook preview="..."',
metadata={"turn_id": "t1"},
)
assert ctx.session_id == "s1"
diff --git a/tests/core/test_prompt_manager.py b/tests/core/test_prompt_manager.py
index 33dcf3496..fbadb3e55 100644
--- a/tests/core/test_prompt_manager.py
+++ b/tests/core/test_prompt_manager.py
@@ -33,12 +33,19 @@ class TestPromptManager:
pm = get_prompt_manager()
prompts = pm.load_prompts(
module_name="research",
- agent_name="research_agent",
+ agent_name="pipeline",
language="en",
)
assert isinstance(prompts, dict)
- # research_agent should have system section
- assert "system" in prompts or prompts == {}
+ # pipeline.yaml carries one section per phase, each of which has
+ # its own ``system`` body.
+ assert (
+ any(
+ isinstance(prompts.get(phase), dict) and "system" in prompts[phase]
+ for phase in ("rephrase", "decompose", "research_step", "report")
+ )
+ or prompts == {}
+ )
def test_load_prompts_solve_module(self):
"""Test loading prompts for solve module."""
@@ -66,10 +73,10 @@ class TestPromptManager:
pm = get_prompt_manager()
# First load
- prompts1 = pm.load_prompts("research", "research_agent", "en")
+ prompts1 = pm.load_prompts("research", "pipeline", "en")
# Second load should return cached version
- prompts2 = pm.load_prompts("research", "research_agent", "en")
+ prompts2 = pm.load_prompts("research", "pipeline", "en")
assert prompts1 is prompts2
@@ -78,7 +85,7 @@ class TestPromptManager:
pm = get_prompt_manager()
# Load some prompts
- pm.load_prompts("research", "research_agent", "en")
+ pm.load_prompts("research", "pipeline", "en")
pm.load_prompts("solve", "solve_agent", "en")
assert len(pm._cache) >= 2
@@ -91,7 +98,7 @@ class TestPromptManager:
pm = get_prompt_manager()
# Load prompts for multiple modules
- pm.load_prompts("research", "research_agent", "en")
+ pm.load_prompts("research", "pipeline", "en")
pm.load_prompts("solve", "solve_agent", "en")
# Clear only research cache
@@ -130,7 +137,7 @@ class TestPromptManager:
pm = get_prompt_manager()
# Even with a potentially missing language, should fallback
- prompts = pm.load_prompts("research", "research_agent", "zh")
+ prompts = pm.load_prompts("research", "pipeline", "zh")
assert isinstance(prompts, dict)
def test_reload_prompts(self):
@@ -138,15 +145,15 @@ class TestPromptManager:
pm = get_prompt_manager()
# Load and cache
- prompts1 = pm.load_prompts("research", "research_agent", "en")
+ prompts1 = pm.load_prompts("research", "pipeline", "en")
# Force reload
- prompts2 = pm.reload_prompts("research", "research_agent", "en")
+ prompts2 = pm.reload_prompts("research", "pipeline", "en")
# They should be equal but not the same object
assert prompts1 == prompts2
# After reload, cache should have fresh entry
- cache_key = "research_research_agent_en"
+ cache_key = "research_pipeline_en"
assert cache_key in pm._cache
@@ -173,7 +180,7 @@ class TestPromptManagerLanguages:
"""Test that invalid language code falls back gracefully."""
pm = get_prompt_manager()
# Should not raise, should fallback
- prompts = pm.load_prompts("research", "research_agent", "invalid")
+ prompts = pm.load_prompts("research", "pipeline", "invalid")
assert isinstance(prompts, dict)
diff --git a/tests/knowledge/test_manager_list.py b/tests/knowledge/test_manager_list.py
index c1f9dfeed..99cce428b 100644
--- a/tests/knowledge/test_manager_list.py
+++ b/tests/knowledge/test_manager_list.py
@@ -8,10 +8,10 @@ keep surfacing zombie KBs the user cannot act on.
from __future__ import annotations
-import json
-import shutil
from datetime import datetime
+import json
from pathlib import Path
+import shutil
from deeptutor.knowledge.manager import KnowledgeBaseManager
diff --git a/tests/runtime/test_launcher.py b/tests/runtime/test_launcher.py
index 3fe1fb5e0..dd020e164 100644
--- a/tests/runtime/test_launcher.py
+++ b/tests/runtime/test_launcher.py
@@ -54,3 +54,43 @@ def test_packaged_web_cache_refreshes_when_public_settings_change(tmp_path: Path
assert first == second
assert "https://api.example" in (second / "server.js").read_text(encoding="utf-8")
+
+
+def test_detect_existing_source_frontend_from_next_dev_lock(tmp_path: Path, monkeypatch) -> None:
+ source = tmp_path / "web"
+ lock = source / ".next" / "dev" / "lock"
+ lock.parent.mkdir(parents=True)
+ lock.write_text(
+ '{"pid":12345,"port":3999,"appUrl":"http://localhost:3999"}',
+ encoding="utf-8",
+ )
+ monkeypatch.setattr(launcher, "_is_pid_alive", lambda pid: pid == 12345)
+ monkeypatch.setattr(launcher, "_port_accepts_connection", lambda port: False)
+
+ existing = launcher._detect_existing_source_frontend(
+ launcher.FrontendRuntime("source", [], source)
+ )
+
+ assert existing is not None
+ assert existing.url == "http://localhost:3999"
+ assert existing.port == 3999
+ assert existing.pid == 12345
+ assert existing.lock_path == lock
+
+
+def test_detect_existing_source_frontend_ignores_stale_lock(tmp_path: Path, monkeypatch) -> None:
+ source = tmp_path / "web"
+ lock = source / ".next" / "dev" / "lock"
+ lock.parent.mkdir(parents=True)
+ lock.write_text(
+ '{"pid":12345,"port":3999,"appUrl":"http://localhost:3999"}',
+ encoding="utf-8",
+ )
+ monkeypatch.setattr(launcher, "_is_pid_alive", lambda pid: False)
+ monkeypatch.setattr(launcher, "_port_accepts_connection", lambda port: False)
+
+ existing = launcher._detect_existing_source_frontend(
+ launcher.FrontendRuntime("source", [], source)
+ )
+
+ assert existing is None
diff --git a/tests/services/config/test_chat_params_config.py b/tests/services/config/test_chat_params_config.py
index 279359715..f547cac81 100644
--- a/tests/services/config/test_chat_params_config.py
+++ b/tests/services/config/test_chat_params_config.py
@@ -40,8 +40,9 @@ class TestGetChatParams:
monkeypatch.setattr(loader_module, "PROJECT_ROOT", project_root)
params = get_chat_params()
assert params["temperature"] == DEFAULT_CHAT_PARAMS["temperature"]
+ assert params["max_iterations"] == 20
assert params["responding"]["max_tokens"] == 8000
- assert params["thinking"]["max_tokens"] == 2000
+ assert params["answer_now"]["max_tokens"] == 8000
def test_overrides_specific_stage_only(self, tmp_path: Path, monkeypatch):
project_root = _write_agents_yaml(
@@ -58,8 +59,8 @@ class TestGetChatParams:
params = get_chat_params()
assert params["responding"]["max_tokens"] == 12000
assert params["answer_now"]["max_tokens"] == 8000
- assert params["thinking"]["max_tokens"] == 2000
assert params["temperature"] == 0.2
+ assert params["max_iterations"] == 20
def test_overrides_temperature(self, tmp_path: Path, monkeypatch):
project_root = _write_agents_yaml(
@@ -71,6 +72,19 @@ class TestGetChatParams:
monkeypatch.setattr(loader_module, "PROJECT_ROOT", project_root)
params = get_chat_params()
assert params["temperature"] == 0.7
+ assert params["max_iterations"] == 20
+ assert params["responding"]["max_tokens"] == 8000
+
+ def test_overrides_max_iterations(self, tmp_path: Path, monkeypatch):
+ project_root = _write_agents_yaml(
+ tmp_path,
+ {
+ "capabilities": {"chat": {"max_iterations": 12}},
+ },
+ )
+ monkeypatch.setattr(loader_module, "PROJECT_ROOT", project_root)
+ params = get_chat_params()
+ assert params["max_iterations"] == 12
assert params["responding"]["max_tokens"] == 8000
def test_full_chat_block_round_trip(self, tmp_path: Path, monkeypatch):
@@ -80,12 +94,9 @@ class TestGetChatParams:
"capabilities": {
"chat": {
"temperature": 0.4,
+ "max_iterations": 16,
"responding": {"max_tokens": 16000},
"answer_now": {"max_tokens": 16000},
- "thinking": {"max_tokens": 3000},
- "observing": {"max_tokens": 3000},
- "acting": {"max_tokens": 3000},
- "react_fallback": {"max_tokens": 2500},
},
},
},
@@ -93,23 +104,39 @@ class TestGetChatParams:
monkeypatch.setattr(loader_module, "PROJECT_ROOT", project_root)
params = get_chat_params()
assert params["temperature"] == 0.4
+ assert params["max_iterations"] == 16
assert params["responding"]["max_tokens"] == 16000
assert params["answer_now"]["max_tokens"] == 16000
- assert params["thinking"]["max_tokens"] == 3000
- assert params["observing"]["max_tokens"] == 3000
- assert params["acting"]["max_tokens"] == 3000
- assert params["react_fallback"]["max_tokens"] == 2500
+
+ def test_unknown_stage_keys_passthrough_without_crashing(self, tmp_path: Path, monkeypatch):
+ """Forward-compat: extra keys in agents.yaml shouldn't break loading.
+
+ The chat pipeline only reads ``responding`` and ``answer_now``; any
+ other stage-shaped keys a user might have lying around from older
+ templates (e.g. ``thinking``, ``observing``, ``acting``,
+ ``react_fallback``) are simply ignored, not rejected.
+ """
+ project_root = _write_agents_yaml(
+ tmp_path,
+ {
+ "capabilities": {
+ "chat": {
+ "responding": {"max_tokens": 9000},
+ "thinking": {"max_tokens": 3000},
+ "acting": {"max_tokens": 3000},
+ },
+ },
+ },
+ )
+ monkeypatch.setattr(loader_module, "PROJECT_ROOT", project_root)
+ params = get_chat_params()
+ assert params["responding"]["max_tokens"] == 9000
+ assert params["answer_now"]["max_tokens"] == 8000
class TestReadIntHelper:
"""Verify ``_read_int`` gracefully resolves the two chat token budgets
- the single-loop pipeline still uses (``responding`` and ``answer_now``).
-
- The legacy four-stage budgets (``thinking``/``acting``/``observing``/
- ``react_fallback``) are no longer consumed by the pipeline — they remain
- valid keys in ``agents.yaml`` for forward/backward compatibility but
- have no behavioral effect here.
- """
+ the single-loop pipeline uses (``responding`` and ``answer_now``)."""
def test_empty_dict_falls_back_to_default(self):
from deeptutor.agents.chat.agentic_pipeline import _read_int
diff --git a/tests/services/config/test_knowledge_base_config.py b/tests/services/config/test_knowledge_base_config.py
index 241338cf0..2bbaed2b1 100644
--- a/tests/services/config/test_knowledge_base_config.py
+++ b/tests/services/config/test_knowledge_base_config.py
@@ -137,9 +137,7 @@ 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:
+ 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
diff --git a/tests/services/config/test_llm_probe_config.py b/tests/services/config/test_llm_probe_config.py
index d1f99a4e3..da48a7d8b 100644
--- a/tests/services/config/test_llm_probe_config.py
+++ b/tests/services/config/test_llm_probe_config.py
@@ -174,9 +174,7 @@ class TestLlmProbeUsesAgentsYaml:
)
@pytest.mark.asyncio
- async def test_probe_passes_runtime_api_version_and_reasoning_effort(
- self, monkeypatch
- ):
+ async def test_probe_passes_runtime_api_version_and_reasoning_effort(self, monkeypatch):
from deeptutor.services import llm as llm_module
from deeptutor.services.config import test_runner as test_runner_module
from deeptutor.services.config.test_runner import ConfigTestRunner, TestRun
@@ -212,7 +210,7 @@ class TestLlmProbeUsesAgentsYaml:
assert captured_kwargs["reasoning_effort"] == "high"
@pytest.mark.asyncio
- async def test_probe_persists_detected_context_window_when_catalog_present(
+ async def test_probe_reports_detected_context_window_without_persisting_catalog(
self, tmp_path, monkeypatch
):
from deeptutor.services import llm as llm_module
@@ -274,8 +272,6 @@ class TestLlmProbeUsesAgentsYaml:
"detect_context_window",
_stub_metadata_context_window_detection,
)
- monkeypatch.setattr(test_runner_module, "clear_llm_config_cache", lambda: None)
- monkeypatch.setattr(test_runner_module, "reset_llm_client", lambda: None)
monkeypatch.setattr(llm_module, "get_token_limit_kwargs", _real_get_token_limit_kwargs)
monkeypatch.setattr(llm_module, "complete", _fake_llm_complete)
monkeypatch.setattr(llm_module, "clear_llm_config_cache", lambda: None)
@@ -286,10 +282,14 @@ class TestLlmProbeUsesAgentsYaml:
saved = service.load()
saved_model = saved["services"]["llm"]["profiles"][0]["models"][0]
- assert saved_model["context_window"] == "128000"
- assert saved_model["context_window_source"] == "metadata"
- assert saved_model["context_window_detected_at"] == "2026-04-24T08:00:00+00:00"
- assert any(event["type"] == "catalog" for event in run.events)
+ assert "context_window" not in saved_model
+ assert "context_window_source" not in saved_model
+ assert "context_window_detected_at" not in saved_model
+ context_event = next(event for event in run.events if event["type"] == "context_window")
+ assert context_event["context_window"] == 128000
+ assert context_event["source"] == "metadata"
+ assert context_event["detected_at"] == "2026-04-24T08:00:00+00:00"
+ assert not any(event["type"] == "catalog" for event in run.events)
# ---------------------------------------------------------------------------
diff --git a/tests/services/embedding/test_multimodal_request.py b/tests/services/embedding/test_multimodal_request.py
index 67f5cd5f7..b706017e5 100644
--- a/tests/services/embedding/test_multimodal_request.py
+++ b/tests/services/embedding/test_multimodal_request.py
@@ -155,31 +155,43 @@ async def test_cohere_v2_translates_contents_to_inputs(monkeypatch: pytest.Monke
def test_model_info_reports_multimodal_at_model_level() -> None:
- assert CohereEmbeddingAdapter(
- {
- "api_key": "co-test",
- "base_url": "https://api.cohere.com/v2/embed",
- "model": "embed-v4.0",
- }
- ).get_model_info()["multimodal"] is True
- assert CohereEmbeddingAdapter(
- {
- "api_key": "co-test",
- "base_url": "https://api.cohere.com/v2/embed",
- "model": "embed-multilingual-v3.0",
- }
- ).get_model_info()["multimodal"] is False
- assert JinaEmbeddingAdapter(
- {
- "api_key": "jina-test",
- "base_url": "https://api.jina.ai/v1/embeddings",
- "model": "jina-embeddings-v4",
- }
- ).get_model_info()["multimodal"] is True
- assert OpenAICompatibleEmbeddingAdapter(
- {
- "api_key": "sk-sf",
- "base_url": "https://api.siliconflow.cn/v1/embeddings",
- "model": "Qwen/Qwen3-Embedding-8B",
- }
- ).get_model_info()["multimodal"] is False
+ assert (
+ CohereEmbeddingAdapter(
+ {
+ "api_key": "co-test",
+ "base_url": "https://api.cohere.com/v2/embed",
+ "model": "embed-v4.0",
+ }
+ ).get_model_info()["multimodal"]
+ is True
+ )
+ assert (
+ CohereEmbeddingAdapter(
+ {
+ "api_key": "co-test",
+ "base_url": "https://api.cohere.com/v2/embed",
+ "model": "embed-multilingual-v3.0",
+ }
+ ).get_model_info()["multimodal"]
+ is False
+ )
+ assert (
+ JinaEmbeddingAdapter(
+ {
+ "api_key": "jina-test",
+ "base_url": "https://api.jina.ai/v1/embeddings",
+ "model": "jina-embeddings-v4",
+ }
+ ).get_model_info()["multimodal"]
+ is True
+ )
+ assert (
+ OpenAICompatibleEmbeddingAdapter(
+ {
+ "api_key": "sk-sf",
+ "base_url": "https://api.siliconflow.cn/v1/embeddings",
+ "model": "Qwen/Qwen3-Embedding-8B",
+ }
+ ).get_model_info()["multimodal"]
+ is False
+ )
diff --git a/tests/services/rag/test_llamaindex_document_loader.py b/tests/services/rag/test_llamaindex_document_loader.py
index ea4dc1873..7e02f2a31 100644
--- a/tests/services/rag/test_llamaindex_document_loader.py
+++ b/tests/services/rag/test_llamaindex_document_loader.py
@@ -170,9 +170,7 @@ def test_loader_skips_images_when_llm_is_text_only(
def supports_multimodal_images(self) -> bool:
return False
- monkeypatch.setattr(
- loader_module, "get_embedding_client", lambda: _MultimodalEmbeddingClient()
- )
+ monkeypatch.setattr(loader_module, "get_embedding_client", lambda: _MultimodalEmbeddingClient())
monkeypatch.setattr(loader_module, "get_llm_client", lambda: _TextOnlyLLMClient())
documents = asyncio.run(loader_module.LlamaIndexDocumentLoader().load([str(image_path)]))
diff --git a/tests/services/rag/test_llamaindex_storage_layout.py b/tests/services/rag/test_llamaindex_storage_layout.py
index 63be6d448..bb98d7c1c 100644
--- a/tests/services/rag/test_llamaindex_storage_layout.py
+++ b/tests/services/rag/test_llamaindex_storage_layout.py
@@ -100,8 +100,8 @@ async def test_incremental_add_migrates_matching_legacy_index_to_flat_version(
def test_hybrid_retriever_uses_official_query_fusion_when_bm25_available(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
- from deeptutor.services.rag.pipelines.llamaindex.config import RetrievalConfig
from deeptutor.services.rag.pipelines.llamaindex import retrievers as retriever_module
+ from deeptutor.services.rag.pipelines.llamaindex.config import RetrievalConfig
captured: dict[str, object] = {}
@@ -145,8 +145,8 @@ def test_hybrid_retriever_uses_official_query_fusion_when_bm25_available(
def test_hybrid_retriever_falls_back_to_vector_when_bm25_missing(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
- from deeptutor.services.rag.pipelines.llamaindex.config import RetrievalConfig
from deeptutor.services.rag.pipelines.llamaindex import retrievers as retriever_module
+ from deeptutor.services.rag.pipelines.llamaindex.config import RetrievalConfig
calls: list[int] = []
diff --git a/tests/services/session/test_regenerate.py b/tests/services/session/test_regenerate.py
index 23c55fd9e..9c70f3545 100644
--- a/tests/services/session/test_regenerate.py
+++ b/tests/services/session/test_regenerate.py
@@ -270,8 +270,8 @@ class TestRegenerateLastTurn:
- The original user message is preserved (no duplicate row).
- The previous assistant message is replaced.
- - ``memory_service.refresh_from_turn`` is **not** invoked for the
- regenerate turn (it would have been invoked for the original).
+ - ``memory_store.emit`` is **not** invoked for the regenerate turn
+ (it would have been invoked for the original).
- The new SESSION event carries ``regenerate``/``regenerated_from_message_id``.
"""
store = SQLiteSessionStore(tmp_path / "regen_e2e.db")
@@ -303,10 +303,10 @@ class TestRegenerateLastTurn:
)
yield StreamEvent(type=StreamEventType.DONE, source="chat")
- refresh_calls: list[dict[str, Any]] = []
+ refresh_calls: list[Any] = []
- async def tracking_refresh(**kwargs):
- refresh_calls.append(kwargs)
+ async def tracking_emit(event):
+ refresh_calls.append(event)
monkeypatch.setattr(
"deeptutor.services.llm.config.get_llm_config", lambda: SimpleNamespace()
@@ -317,10 +317,10 @@ class TestRegenerateLastTurn:
)
monkeypatch.setattr("deeptutor.runtime.orchestrator.ChatOrchestrator", FakeOrchestrator)
monkeypatch.setattr(
- "deeptutor.services.memory.get_memory_service",
+ "deeptutor.services.memory.get_memory_store",
lambda: SimpleNamespace(
- build_memory_context=lambda *_args, **_kwargs: "",
- refresh_from_turn=tracking_refresh,
+ read_l3_concat=lambda: "",
+ emit=tracking_emit,
),
)
diff --git a/tests/services/session/test_source_inventory.py b/tests/services/session/test_source_inventory.py
index 6dfe5b0bc..b6880bcdc 100644
--- a/tests/services/session/test_source_inventory.py
+++ b/tests/services/session/test_source_inventory.py
@@ -54,8 +54,26 @@ class FakeStore:
def test_inventory_dedupe_fresh_wins() -> None:
inv = SourceInventory()
- inv.add(SourceEntry(sid="at-foo", kind="attachment", name="old", full_text="old text", fresh=False, first_seen_turn=1))
- inv.add(SourceEntry(sid="at-foo", kind="attachment", name="fresh", full_text="fresh text", fresh=True, first_seen_turn=2))
+ inv.add(
+ SourceEntry(
+ sid="at-foo",
+ kind="attachment",
+ name="old",
+ full_text="old text",
+ fresh=False,
+ first_seen_turn=1,
+ )
+ )
+ inv.add(
+ SourceEntry(
+ sid="at-foo",
+ kind="attachment",
+ name="fresh",
+ full_text="fresh text",
+ fresh=True,
+ first_seen_turn=2,
+ )
+ )
assert len(inv.entries) == 1
assert inv.entries[0].fresh is True
assert inv.entries[0].name == "fresh"
@@ -63,15 +81,36 @@ def test_inventory_dedupe_fresh_wins() -> None:
def test_inventory_skips_empty_text() -> None:
inv = SourceInventory()
- inv.add(SourceEntry(sid="at-foo", kind="attachment", name="empty", full_text=" ", fresh=True, first_seen_turn=1))
+ inv.add(
+ SourceEntry(
+ sid="at-foo",
+ kind="attachment",
+ name="empty",
+ full_text=" ",
+ fresh=True,
+ first_seen_turn=1,
+ )
+ )
assert inv.is_empty()
def test_inventory_preserves_insertion_order() -> None:
inv = SourceInventory()
- inv.add(SourceEntry(sid="a", kind="attachment", name="A", full_text="A", fresh=True, first_seen_turn=1))
- inv.add(SourceEntry(sid="b", kind="attachment", name="B", full_text="B", fresh=False, first_seen_turn=1))
- inv.add(SourceEntry(sid="c", kind="notebook", name="C", full_text="C", fresh=True, first_seen_turn=1))
+ inv.add(
+ SourceEntry(
+ sid="a", kind="attachment", name="A", full_text="A", fresh=True, first_seen_turn=1
+ )
+ )
+ inv.add(
+ SourceEntry(
+ sid="b", kind="attachment", name="B", full_text="B", fresh=False, first_seen_turn=1
+ )
+ )
+ inv.add(
+ SourceEntry(
+ sid="c", kind="notebook", name="C", full_text="C", fresh=True, first_seen_turn=1
+ )
+ )
assert [e.sid for e in inv.entries] == ["a", "b", "c"]
@@ -88,8 +127,26 @@ def test_render_manifest_empty() -> None:
def test_render_manifest_distinguishes_fresh_vs_historical() -> None:
inv = SourceInventory()
- inv.add(SourceEntry(sid="at-fresh", kind="attachment", name="new.pdf", full_text="hello world", fresh=True, first_seen_turn=3))
- inv.add(SourceEntry(sid="at-old", kind="attachment", name="old.pdf", full_text="x" * 5000, fresh=False, first_seen_turn=1))
+ inv.add(
+ SourceEntry(
+ sid="at-fresh",
+ kind="attachment",
+ name="new.pdf",
+ full_text="hello world",
+ fresh=True,
+ first_seen_turn=3,
+ )
+ )
+ inv.add(
+ SourceEntry(
+ sid="at-old",
+ kind="attachment",
+ name="old.pdf",
+ full_text="x" * 5000,
+ fresh=False,
+ first_seen_turn=1,
+ )
+ )
text, idx = render_manifest(inv)
# Fresh row carries a preview field
assert "preview:" in text
@@ -140,7 +197,12 @@ async def test_build_inventory_historical_attachment_visible_to_next_turn() -> N
"content": "first message",
"parent_message_id": None,
"attachments": [
- {"id": "att-1", "filename": "year1-1.pdf", "extracted_text": "lecture notes", "mime_type": "application/pdf"}
+ {
+ "id": "att-1",
+ "filename": "year1-1.pdf",
+ "extracted_text": "lecture notes",
+ "mime_type": "application/pdf",
+ }
],
"metadata": {"request_snapshot": {}},
},
@@ -181,16 +243,52 @@ async def test_build_inventory_branch_isolated() -> None:
# → 4 (user, branch B, attaches Y.pdf)
# When we ask for branch B (leaf=4), only 1, 2, 4 are in lineage.
msgs = [
- {"id": 1, "role": "user", "content": "q1", "parent_message_id": None,
- "attachments": [], "metadata": {"request_snapshot": {}}},
- {"id": 2, "role": "assistant", "content": "a1", "parent_message_id": 1,
- "attachments": [], "metadata": {}},
- {"id": 3, "role": "user", "content": "branch A", "parent_message_id": 2,
- "attachments": [{"id": "X", "filename": "X.pdf", "extracted_text": "branchA only", "mime_type": "application/pdf"}],
- "metadata": {"request_snapshot": {}}},
- {"id": 4, "role": "user", "content": "branch B", "parent_message_id": 2,
- "attachments": [{"id": "Y", "filename": "Y.pdf", "extracted_text": "branchB only", "mime_type": "application/pdf"}],
- "metadata": {"request_snapshot": {}}},
+ {
+ "id": 1,
+ "role": "user",
+ "content": "q1",
+ "parent_message_id": None,
+ "attachments": [],
+ "metadata": {"request_snapshot": {}},
+ },
+ {
+ "id": 2,
+ "role": "assistant",
+ "content": "a1",
+ "parent_message_id": 1,
+ "attachments": [],
+ "metadata": {},
+ },
+ {
+ "id": 3,
+ "role": "user",
+ "content": "branch A",
+ "parent_message_id": 2,
+ "attachments": [
+ {
+ "id": "X",
+ "filename": "X.pdf",
+ "extracted_text": "branchA only",
+ "mime_type": "application/pdf",
+ }
+ ],
+ "metadata": {"request_snapshot": {}},
+ },
+ {
+ "id": 4,
+ "role": "user",
+ "content": "branch B",
+ "parent_message_id": 2,
+ "attachments": [
+ {
+ "id": "Y",
+ "filename": "Y.pdf",
+ "extracted_text": "branchB only",
+ "mime_type": "application/pdf",
+ }
+ ],
+ "metadata": {"request_snapshot": {}},
+ },
]
store = FakeStore(messages=msgs)
# Render branch B's inventory (leaf=4) — should see Y, not X.
@@ -216,9 +314,14 @@ async def test_build_inventory_fresh_shadows_historical_on_same_sid() -> None:
"""If a notebook record is referenced both in a past turn and this
turn, the manifest shows it as fresh (with preview), not historical."""
msgs = [
- {"id": 1, "role": "user", "content": "earlier",
- "parent_message_id": None, "attachments": [],
- "metadata": {"request_snapshot": {}}},
+ {
+ "id": 1,
+ "role": "user",
+ "content": "earlier",
+ "parent_message_id": None,
+ "attachments": [],
+ "metadata": {"request_snapshot": {}},
+ },
]
store = FakeStore(messages=msgs)
# Fresh record matching what historical *would have* added if it had
@@ -229,7 +332,12 @@ async def test_build_inventory_fresh_shadows_historical_on_same_sid() -> None:
leaf_message_id=None,
current_turn_ordinal=2,
fresh_attachment_records=[
- {"id": "att-1", "filename": "f.pdf", "extracted_text": "fresh body", "mime_type": "application/pdf"}
+ {
+ "id": "att-1",
+ "filename": "f.pdf",
+ "extracted_text": "fresh body",
+ "mime_type": "application/pdf",
+ }
],
fresh_notebook_records=[],
fresh_book_context_text="",
diff --git a/tests/services/tutorbot/test_channel_manager.py b/tests/services/tutorbot/test_channel_manager.py
new file mode 100644
index 000000000..e6b3a67ea
--- /dev/null
+++ b/tests/services/tutorbot/test_channel_manager.py
@@ -0,0 +1,66 @@
+"""Unit tests for TutorBot channel dispatch behavior."""
+
+from __future__ import annotations
+
+import asyncio
+from unittest.mock import AsyncMock
+
+import pytest
+
+from deeptutor.tutorbot.bus.events import OutboundMessage
+from deeptutor.tutorbot.channels.manager import ChannelManager
+from deeptutor.tutorbot.config.schema import ChannelsConfig
+
+
+class _OneShotBus:
+ def __init__(self, msg: OutboundMessage):
+ self._msg = msg
+ self._calls = 0
+
+ async def consume_outbound(self) -> OutboundMessage:
+ self._calls += 1
+ if self._calls == 1:
+ return self._msg
+ raise asyncio.CancelledError
+
+
+class _DummyChannel:
+ def __init__(self):
+ self.send = AsyncMock()
+
+
+async def _dispatch_one(msg: OutboundMessage, config: ChannelsConfig) -> _DummyChannel:
+ channel = _DummyChannel()
+ manager = ChannelManager(config, _OneShotBus(msg)) # type: ignore[arg-type]
+ manager.channels = {msg.channel: channel} # type: ignore[dict-item]
+
+ await manager._dispatch_outbound()
+ return channel
+
+
+class TestChannelManagerToolHints:
+ @pytest.mark.asyncio
+ async def test_tool_hint_progress_skipped_by_default(self):
+ msg = OutboundMessage(
+ channel="zulip",
+ chat_id="pm:42",
+ content='message("Hello")',
+ metadata={"_progress": True, "_tool_hint": True},
+ )
+
+ channel = await _dispatch_one(msg, ChannelsConfig(send_tool_hints=False))
+
+ channel.send.assert_not_awaited()
+
+ @pytest.mark.asyncio
+ async def test_tool_hint_progress_dispatched_when_enabled(self):
+ msg = OutboundMessage(
+ channel="zulip",
+ chat_id="pm:42",
+ content='message("Hello")',
+ metadata={"_progress": True, "_tool_hint": True},
+ )
+
+ channel = await _dispatch_one(msg, ChannelsConfig(send_tool_hints=True))
+
+ channel.send.assert_awaited_once_with(msg)
diff --git a/tests/services/tutorbot/test_zulip_channel.py b/tests/services/tutorbot/test_zulip_channel.py
index 8624c6e08..9820ea0cf 100644
--- a/tests/services/tutorbot/test_zulip_channel.py
+++ b/tests/services/tutorbot/test_zulip_channel.py
@@ -281,14 +281,18 @@ class TestDownloadAttachments:
"content": "Check ![img.png](/user_uploads/2/ce/abc/img.png)",
"content_type": "text/x-markdown",
}
- with patch.object(
- ch,
- "_extract_upload_links",
- return_value=[("img.png", "/user_uploads/2/ce/abc/img.png")],
- ), patch(
- "deeptutor.tutorbot.channels.zulip.get_media_dir",
- return_value=tmp_path,
- ), patch("deeptutor.tutorbot.channels.zulip.requests.get") as mock_get:
+ with (
+ patch.object(
+ ch,
+ "_extract_upload_links",
+ return_value=[("img.png", "/user_uploads/2/ce/abc/img.png")],
+ ),
+ patch(
+ "deeptutor.tutorbot.channels.zulip.get_media_dir",
+ return_value=tmp_path,
+ ),
+ patch("deeptutor.tutorbot.channels.zulip.requests.get") as mock_get,
+ ):
mock_resp = MagicMock()
mock_resp.raise_for_status = MagicMock()
mock_resp.content = b"fake-image-data"
@@ -299,10 +303,7 @@ class TestDownloadAttachments:
assert len(paths) == 1
mock_get.assert_called_once()
call_url = mock_get.call_args[0][0]
- assert (
- call_url
- == "https://example.zulipchat.com/user_uploads/2/ce/abc/img.png"
- )
+ assert call_url == "https://example.zulipchat.com/user_uploads/2/ce/abc/img.png"
def test_no_uploads_returns_empty(self):
ch = _make_channel()
@@ -317,13 +318,16 @@ class TestDownloadAttachments:
"content": "![img.png](/user_uploads/2/ce/abc/img.png)",
"content_type": "text/x-markdown",
}
- with patch.object(
- ch,
- "_extract_upload_links",
- return_value=[("img.png", "/user_uploads/2/ce/abc/img.png")],
- ), patch(
- "deeptutor.tutorbot.channels.zulip.get_media_dir",
- return_value=tmp_path,
+ with (
+ patch.object(
+ ch,
+ "_extract_upload_links",
+ return_value=[("img.png", "/user_uploads/2/ce/abc/img.png")],
+ ),
+ patch(
+ "deeptutor.tutorbot.channels.zulip.get_media_dir",
+ return_value=tmp_path,
+ ),
):
from pathlib import Path as RealPath
@@ -832,9 +836,7 @@ class TestResolveMediaPath:
"deeptutor.tutorbot.channels.zulip.get_media_dir",
return_value=tmp_path,
):
- dest = ZulipChannel._attachment_destination(
- tmp_path, "photo.png", path_id, 0
- )
+ dest = ZulipChannel._attachment_destination(tmp_path, "photo.png", path_id, 0)
dest.write_bytes(b"cached-data")
result = ch._resolve_media_path(path_id)
@@ -845,10 +847,13 @@ class TestResolveMediaPath:
ch = _make_channel()
path_id = "/user_uploads/2/ce/abc123/photo.png"
- with patch(
- "deeptutor.tutorbot.channels.zulip.get_media_dir",
- return_value=tmp_path,
- ), patch("deeptutor.tutorbot.channels.zulip.requests.get") as mock_get:
+ with (
+ patch(
+ "deeptutor.tutorbot.channels.zulip.get_media_dir",
+ return_value=tmp_path,
+ ),
+ patch("deeptutor.tutorbot.channels.zulip.requests.get") as mock_get,
+ ):
mock_resp = MagicMock()
mock_resp.raise_for_status = MagicMock()
mock_resp.content = b"downloaded-data"
@@ -863,10 +868,13 @@ class TestResolveMediaPath:
ch = _make_channel()
url = "https://example.zulipchat.com/user_uploads/2/ce/abc/photo.png"
- with patch(
- "deeptutor.tutorbot.channels.zulip.get_media_dir",
- return_value=tmp_path,
- ), patch("deeptutor.tutorbot.channels.zulip.requests.get") as mock_get:
+ with (
+ patch(
+ "deeptutor.tutorbot.channels.zulip.get_media_dir",
+ return_value=tmp_path,
+ ),
+ patch("deeptutor.tutorbot.channels.zulip.requests.get") as mock_get,
+ ):
mock_resp = MagicMock()
mock_resp.raise_for_status = MagicMock()
mock_resp.content = b"data"
@@ -875,6 +883,26 @@ class TestResolveMediaPath:
result = ch._resolve_media_path(url)
assert result is not None
+ def test_full_url_resolved_when_config_site_has_trailing_slash(self, tmp_path: Path):
+ ch = _make_channel(site="https://example.zulipchat.com/")
+ url = "https://example.zulipchat.com/user_uploads/2/ce/abc/photo.png"
+
+ with (
+ patch(
+ "deeptutor.tutorbot.channels.zulip.get_media_dir",
+ return_value=tmp_path,
+ ),
+ patch("deeptutor.tutorbot.channels.zulip.requests.get") as mock_get,
+ ):
+ mock_resp = MagicMock()
+ mock_resp.raise_for_status = MagicMock()
+ mock_resp.content = b"data"
+ mock_get.return_value = mock_resp
+
+ result = ch._resolve_media_path(url)
+ assert result is not None
+ assert Path(result).read_bytes() == b"data"
+
def test_non_zulip_nonexistent_path_returns_none(self):
ch = _make_channel()
result = ch._resolve_media_path("/some/random/path.png")
@@ -935,11 +963,12 @@ class TestSendMetadataEnrichment:
assert msg.metadata["stream"] == "general"
-class TestSendToolHintFilter:
+class TestSendToolHints:
@pytest.mark.asyncio
- async def test_tool_hint_message_skipped(self):
+ async def test_tool_hint_message_sent_when_dispatched(self):
ch = _make_channel()
mock_client = MagicMock()
+ mock_client.call_endpoint.return_value = {"result": "success"}
ch._client = mock_client
from deeptutor.tutorbot.bus.events import OutboundMessage
@@ -948,11 +977,16 @@ class TestSendToolHintFilter:
channel="zulip",
chat_id="pm:42",
content='message("Hello")',
- metadata={"_progress": True, "_tool_hint": True},
+ metadata={
+ "_progress": True,
+ "_tool_hint": True,
+ "msg_type": "private",
+ "recipient_user_id": "42",
+ },
)
await ch.send(msg)
- mock_client.call_endpoint.assert_not_called()
+ mock_client.call_endpoint.assert_called_once()
@pytest.mark.asyncio
async def test_progress_message_without_tool_hint_sent(self):
@@ -1032,6 +1066,20 @@ class TestSubscribeStreams:
assert "general" in names
assert "dev" in names
+ def test_explicit_stream_names_are_deduplicated_and_sorted(self):
+ ch = _make_channel(subscribe_streams=["general", "dev", "general", " "])
+ mock_client = MagicMock()
+ mock_client.add_subscriptions.return_value = {
+ "result": "success",
+ "already_subscribed": {},
+ }
+ ch._client = mock_client
+
+ ch._subscribe_to_streams()
+
+ streams_arg = mock_client.add_subscriptions.call_args.kwargs["streams"]
+ assert [s["name"] for s in streams_arg] == ["dev", "general"]
+
def test_wildcard_subscribes_all_public_streams(self):
ch = _make_channel(subscribe_streams=["*"])
mock_client = MagicMock()
@@ -1071,8 +1119,31 @@ class TestSubscribeStreams:
"msg": "some error",
}
ch._client = mock_client
- ch._subscribe_to_streams()
+
+ with patch("deeptutor.tutorbot.channels.zulip.logger.warning") as mock_warning:
+ ch._subscribe_to_streams()
+
mock_client.add_subscriptions.assert_called_once()
+ mock_warning.assert_called_once()
+
+ def test_subscribe_non_success_all_already_subscribed_is_debug_only(self):
+ ch = _make_channel(subscribe_streams=["general"])
+ mock_client = MagicMock()
+ mock_client.add_subscriptions.return_value = {
+ "result": "error",
+ "msg": "already subscribed",
+ "already_subscribed": {"[email protected]": ["general"]},
+ }
+ ch._client = mock_client
+
+ with (
+ patch("deeptutor.tutorbot.channels.zulip.logger.warning") as mock_warning,
+ patch("deeptutor.tutorbot.channels.zulip.logger.debug") as mock_debug,
+ ):
+ ch._subscribe_to_streams()
+
+ mock_warning.assert_not_called()
+ mock_debug.assert_called_once()
def test_subscribe_logs_already_subscribed(self):
ch = _make_channel(subscribe_streams=["general", "dev"])
diff --git a/tests/utils/test_json_parser.py b/tests/utils/test_json_parser.py
index 71671e51f..bd7626328 100644
--- a/tests/utils/test_json_parser.py
+++ b/tests/utils/test_json_parser.py
@@ -2,6 +2,7 @@
from __future__ import annotations
+import logging
from unittest.mock import patch
import pytest
@@ -89,6 +90,14 @@ class TestParseJsonResponseRepair:
result = parse_json_response("{bad json", fallback={"err": True})
assert result == {"err": True}
+ def test_invalid_plain_text_is_not_logged_as_error(self, caplog) -> None:
+ caplog.set_level(logging.ERROR)
+
+ result = parse_json_response("not json", fallback={"default": True})
+
+ assert result == {"default": True}
+ assert not [r for r in caplog.records if r.levelno >= logging.ERROR]
+
# ---------------------------------------------------------------------------
# safe_json_loads
diff --git a/web/app/(admin)/admin/users/page.tsx b/web/app/(admin)/admin/users/page.tsx
index aa996f3f2..9030c795b 100644
--- a/web/app/(admin)/admin/users/page.tsx
+++ b/web/app/(admin)/admin/users/page.tsx
@@ -317,7 +317,7 @@ export default function AdminUsersPage() {
{canManageAssignments && expandedUserId === user.id && (
<tr>
<td colSpan={4} className="p-0">
- <GrantEditor userId={user.id} />
+ <GrantEditor key={user.id} userId={user.id} />
</td>
</tr>
)}
@@ -336,7 +336,7 @@ export default function AdminUsersPage() {
{showCreateDialog && (
<div
- className="fixed inset-0 z-50 flex items-center justify-center bg-black/40 px-4"
+ className="fixed inset-0 z-50 flex items-center justify-center bg-[var(--overlay)] px-4"
role="dialog"
aria-modal="true"
onClick={closeCreateDialog}
diff --git a/web/app/(utility)/space/co-learn-history/page.tsx b/web/app/(utility)/space/co-learn-history/page.tsx
deleted file mode 100644
index 95e460fb9..000000000
--- a/web/app/(utility)/space/co-learn-history/page.tsx
+++ /dev/null
@@ -1,19 +0,0 @@
-"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)/agents/[botId]/chat/page.tsx b/web/app/(workspace)/agents/[botId]/chat/page.tsx
index d1da39b5d..7a04d0cd6 100644
--- a/web/app/(workspace)/agents/[botId]/chat/page.tsx
+++ b/web/app/(workspace)/agents/[botId]/chat/page.tsx
@@ -120,6 +120,8 @@ export default function BotChatPage() {
return;
}
let cancelled = false;
+ // Clear stale transcript immediately when navigating between bots.
+ // eslint-disable-next-line react-hooks/set-state-in-effect
setMessages([]);
setThinking([]);
thinkingRef.current = [];
diff --git a/web/app/(workspace)/agents/page.tsx b/web/app/(workspace)/agents/page.tsx
index 2297fb550..8ec1631f7 100644
--- a/web/app/(workspace)/agents/page.tsx
+++ b/web/app/(workspace)/agents/page.tsx
@@ -1756,7 +1756,7 @@ function ProfilesTab({
</div>
)}
{saveModalOpen && activeFile === "SOUL.md" && (
- <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/50 px-4">
+ <div className="fixed inset-0 z-50 flex items-center justify-center bg-[var(--overlay)] px-4">
<div className="w-full max-w-md rounded-xl border border-[var(--border)] bg-[var(--background)] p-5 shadow-xl">
<h3 className="text-[15px] font-medium text-[var(--foreground)]">
{t("Save SOUL.md")}
@@ -1847,7 +1847,7 @@ function ProfilesTab({
</div>
)}
{replaceModalOpen && activeFile === "SOUL.md" && (
- <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/50 px-4">
+ <div className="fixed inset-0 z-50 flex items-center justify-center bg-[var(--overlay)] px-4">
<div className="w-full max-w-md rounded-xl border border-[var(--border)] bg-[var(--background)] p-5 shadow-xl">
<h3 className="text-[15px] font-medium text-[var(--foreground)]">
{t("Replace SOUL.md content?")}
diff --git a/web/app/(workspace)/chat/[[...sessionId]]/page.tsx b/web/app/(workspace)/chat/[[...sessionId]]/page.tsx
index 4d7efdd97..9d9f72e3e 100644
--- a/web/app/(workspace)/chat/[[...sessionId]]/page.tsx
+++ b/web/app/(workspace)/chat/[[...sessionId]]/page.tsx
@@ -1,14 +1,21 @@
"use client";
import dynamic from "next/dynamic";
-import { useCallback, useEffect, useMemo, useRef, useState } from "react";
+import {
+ type KeyboardEvent,
+ useCallback,
+ useEffect,
+ useMemo,
+ useRef,
+ useState,
+} from "react";
import { useParams, useRouter } from "next/navigation";
import {
BarChart3,
BrainCircuit,
- Clapperboard,
Code2,
+ Compass,
Database,
FileSearch,
Globe,
@@ -35,6 +42,14 @@ import SessionActivityPanel, {
import SessionViewerPanel, {
type SessionViewerPanelHandle,
} from "@/components/chat/home/SessionViewerPanel";
+import {
+ QuizFollowupProvider,
+ useQuizFollowupController,
+} from "@/context/QuizFollowupContext";
+import {
+ GeogebraTabProvider,
+ useGeogebraTabOpener,
+} from "@/context/GeogebraTabContext";
import {
BookmarkPlus,
BookOpen,
@@ -72,11 +87,6 @@ import {
buildQuizWSConfig,
type DeepQuestionFormConfig,
} from "@/lib/quiz-types";
-import {
- DEFAULT_MATH_ANIMATOR_CONFIG,
- buildMathAnimatorWSConfig,
- type MathAnimatorFormConfig,
-} from "@/lib/math-animator-types";
import {
DEFAULT_VISUALIZE_CONFIG,
buildVisualizeWSConfig,
@@ -88,10 +98,13 @@ import {
validateResearchConfig,
type DeepResearchFormConfig,
type OutlineItem,
- type ResearchSource,
} from "@/lib/research-types";
import { listKnowledgeBases } from "@/lib/knowledge-api";
import { listLLMOptions, type LLMOption } from "@/lib/llm-options";
+import {
+ getEnabledOptionalTools,
+ invalidateEnabledOptionalToolsCache,
+} from "@/lib/tools-settings";
import { downloadChatMarkdown } from "@/lib/chat-export";
import type { SpaceMemoryFile } from "@/lib/space-items";
import {
@@ -146,10 +159,6 @@ 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 },
@@ -165,6 +174,7 @@ const ResearchConfigPanel = dynamic(
type ToolName =
| "brainstorm"
+ | "geogebra_analysis"
| "web_search"
| "code_execution"
| "reason"
@@ -176,26 +186,15 @@ interface ToolDef {
icon: LucideIcon;
}
-interface ResearchSourceDef {
- name: ResearchSource;
- label: string;
- icon: LucideIcon;
-}
-
const ALL_TOOLS: ToolDef[] = [
{ name: "brainstorm", label: "Brainstorm", icon: Lightbulb },
+ { name: "geogebra_analysis", label: "GeoGebra", icon: Compass },
{ name: "web_search", label: "Web Search", icon: Globe },
{ name: "code_execution", label: "Code", icon: Code2 },
{ name: "reason", label: "Reason", icon: Sparkles },
{ name: "paper_search", label: "Arxiv Search", icon: FileSearch },
];
-const RESEARCH_SOURCES: ResearchSourceDef[] = [
- { name: "kb", label: "Knowledge Base", icon: Database },
- { name: "web", label: "Web", icon: Globe },
- { name: "papers", label: "Papers", icon: FileSearch },
-];
-
interface CapabilityDef {
value: string;
label: string;
@@ -213,6 +212,7 @@ const CAPABILITIES: CapabilityDef[] = [
icon: MessageSquare,
allowedTools: [
"brainstorm",
+ "geogebra_analysis",
"web_search",
"code_execution",
"reason",
@@ -241,21 +241,14 @@ const CAPABILITIES: CapabilityDef[] = [
label: "Research",
description: "Comprehensive multi-agent research",
icon: Microscope,
- allowedTools: [],
- defaultTools: [],
- },
- {
- value: "math_animator",
- label: "Animator",
- description: "Generate math videos or storyboard images",
- icon: Clapperboard,
- allowedTools: [],
- defaultTools: [],
+ allowedTools: ["web_search", "paper_search", "code_execution"],
+ defaultTools: ["web_search", "paper_search", "code_execution"],
},
{
value: "visualize",
label: "Visualize",
- description: "Generate SVG, Chart.js, or Mermaid visualizations",
+ description:
+ "Generate charts, diagrams, interactive pages, or math animations",
icon: BarChart3,
allowedTools: [],
defaultTools: [],
@@ -280,12 +273,6 @@ 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];
}
@@ -309,12 +296,14 @@ export default function ChatPage() {
setLLMSelection,
sendMessage,
cancelStreamingTurn,
+ submitUserReply,
regenerateLastMessage,
deleteTurn,
editMessage,
switchBranch,
newSession,
loadSession,
+ renameSessionTitle,
} = useUnifiedChat();
const [knowledgeBases, setKnowledgeBases] = useState<KnowledgeBase[]>([]);
@@ -326,6 +315,12 @@ export default function ChatPage() {
const [llmOptionsError, setLLMOptionsError] = useState(false);
const [capabilityConfigs, setCapabilityConfigs] =
useState<CapabilityPlaygroundConfigMap>({});
+ // User-toggleable tools the user has enabled in /settings/tools. This is
+ // the single source of truth for which optional tools the chat agent may
+ // use; the chat composer no longer exposes a picker.
+ const [userEnabledTools, setUserEnabledTools] = useState<string[] | null>(
+ null,
+ );
const [attachments, setAttachments] = useState<PendingAttachment[]>([]);
const [dragging, setDragging] = useState(false);
const [attachmentError, setAttachmentError] = useState<string | null>(null);
@@ -351,9 +346,7 @@ export default function ChatPage() {
// 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,
- );
+ setHeaderMeasuredWidth(headerRef.current.getBoundingClientRect().width);
}
});
observer.observe(el);
@@ -381,10 +374,7 @@ export default function ChatPage() {
setActivityPanelOpen((prev) => {
const next = !prev;
if (typeof window !== "undefined") {
- window.localStorage.setItem(
- "dt:chat:activity-panel",
- next ? "1" : "0",
- );
+ window.localStorage.setItem("dt:chat:activity-panel", next ? "1" : "0");
}
return next;
});
@@ -415,10 +405,7 @@ export default function ChatPage() {
setViewerPanelOpen((prev) => {
const next = !prev;
if (typeof window !== "undefined") {
- window.localStorage.setItem(
- "dt:chat:viewer-panel",
- next ? "1" : "0",
- );
+ window.localStorage.setItem("dt:chat:viewer-panel", next ? "1" : "0");
}
return next;
});
@@ -438,10 +425,6 @@ export default function ChatPage() {
...DEFAULT_QUIZ_CONFIG,
});
const [quizPdf, setQuizPdf] = useState<File | null>(null);
- const [mathAnimatorConfig, setMathAnimatorConfig] =
- useState<MathAnimatorFormConfig>({
- ...DEFAULT_MATH_ANIMATOR_CONFIG,
- });
const [visualizeConfig, setVisualizeConfig] = useState<VisualizeFormConfig>({
...DEFAULT_VISUALIZE_CONFIG,
});
@@ -450,13 +433,71 @@ export default function ChatPage() {
);
// 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.
+ // For capabilities that need explicit configuration (Quiz, 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);
+ // Per-session persistence of the capability-config form. The form lives
+ // in local React state, so anything that remounts the page (browser
+ // back/forward to /chat/<id>, URL-driven session swap, etc.) would
+ // otherwise wipe a confirmed-and-already-sent setup back to defaults.
+ // Storing the form by sessionId in localStorage keeps the selections —
+ // and the Confirmed badge — stable for the rest of the session.
+ const capabilityConfigStorageKey = useMemo(() => {
+ const sid = state.sessionId || sessionIdParam || "";
+ return sid ? `dt:chat:capability-config:${sid}` : null;
+ }, [state.sessionId, sessionIdParam]);
+ const lastHydratedConfigKeyRef = useRef<string | null>(null);
+ // Hydrate the form configs on first encounter of each session id, so
+ // the user's prior selections come back when they return to a session.
+ useEffect(() => {
+ if (typeof window === "undefined") return;
+ if (!capabilityConfigStorageKey) return;
+ if (lastHydratedConfigKeyRef.current === capabilityConfigStorageKey) return;
+ lastHydratedConfigKeyRef.current = capabilityConfigStorageKey;
+ const raw = window.localStorage.getItem(capabilityConfigStorageKey);
+ if (!raw) return;
+ try {
+ const parsed = JSON.parse(raw) as {
+ quizConfig?: DeepQuestionFormConfig;
+ visualizeConfig?: VisualizeFormConfig;
+ researchConfig?: DeepResearchFormConfig;
+ capabilityConfigConfirmed?: boolean;
+ };
+ if (parsed.quizConfig) setQuizConfig(parsed.quizConfig);
+ if (parsed.visualizeConfig) setVisualizeConfig(parsed.visualizeConfig);
+ if (parsed.researchConfig) setResearchConfig(parsed.researchConfig);
+ if (typeof parsed.capabilityConfigConfirmed === "boolean") {
+ setCapabilityConfigConfirmed(parsed.capabilityConfigConfirmed);
+ }
+ } catch {
+ /* corrupted entry — ignore */
+ }
+ }, [capabilityConfigStorageKey]);
+ // Persist on every change. Write is synchronous and small, and
+ // localStorage already de-dupes identical writes at the browser level.
+ useEffect(() => {
+ if (typeof window === "undefined") return;
+ if (!capabilityConfigStorageKey) return;
+ window.localStorage.setItem(
+ capabilityConfigStorageKey,
+ JSON.stringify({
+ quizConfig,
+ visualizeConfig,
+ researchConfig,
+ capabilityConfigConfirmed,
+ }),
+ );
+ }, [
+ capabilityConfigStorageKey,
+ quizConfig,
+ visualizeConfig,
+ researchConfig,
+ capabilityConfigConfirmed,
+ ]);
const [showSaveModal, setShowSaveModal] = useState(false);
const [showNotebookPicker, setShowNotebookPicker] = useState(false);
const [showBookPicker, setShowBookPicker] = useState(false);
@@ -464,7 +505,6 @@ export default function ChatPage() {
const [showQuestionBankPicker, setShowQuestionBankPicker] = useState(false);
const [showSkillsPicker, setShowSkillsPicker] = useState(false);
const [showMemoryPicker, setShowMemoryPicker] = useState(false);
- const [toolMenuOpen, setToolMenuOpen] = useState(false);
const [spaceMenuOpen, setSpaceMenuOpen] = useState(false);
const [kbMenuOpen, setKbMenuOpen] = useState(false);
const [selectedNotebookRecords, setSelectedNotebookRecords] = useState<
@@ -487,47 +527,40 @@ export default function ChatPage() {
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);
+ // Bridge ref: ``ChatComposer`` writes a prefill function into this on
+ // mount; ``ChatMessageList`` reads it via ``handlePrefillComposer`` so an
+ // ``AskUserOptions`` chip click can drop text into the composer textarea.
+ const prefillInputRef = useRef<((text: string) => void) | null>(null);
+ const handlePrefillComposer = useCallback((text: string) => {
+ prefillInputRef.current?.(text);
+ }, []);
const activeCap = useMemo(
() => getCapability(state.activeCapability),
[state.activeCapability],
);
const isQuizMode = activeCap.value === "deep_question";
- const isMathAnimatorMode = activeCap.value === "math_animator";
const isVisualizeMode = activeCap.value === "visualize";
const isResearchMode = activeCap.value === "deep_research";
- const capabilityNeedsConfig =
- isQuizMode || isMathAnimatorMode || isVisualizeMode || isResearchMode;
+ const capabilityNeedsConfig = isQuizMode || 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 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);
@@ -565,17 +598,103 @@ export default function ChatPage() {
ensureActivityPanelOpen();
}
}, [capabilityNeedsConfig, ensureActivityPanelOpen]);
- const selectedTools = useMemo(
- () => new Set(state.enabledTools),
- [state.enabledTools],
- );
const hasMessages = state.messages.length > 0;
+ const firstUserTitle = useMemo(
+ () =>
+ state.messages
+ .find((msg) => msg.role === "user")
+ ?.content.trim()
+ .replace(/\s+/g, " ")
+ .slice(0, 80) || "",
+ [state.messages],
+ );
+ const persistedSessionTitle = state.sessionTitle.trim();
+ const displaySessionTitle =
+ persistedSessionTitle || firstUserTitle || t("New chat");
+ const canRenameSession = Boolean(state.sessionId);
+ const titleInputRef = useRef<HTMLInputElement | null>(null);
+ const skipTitleCommitRef = useRef(false);
+ const [sessionTitleDraft, setSessionTitleDraft] =
+ useState(displaySessionTitle);
+ const [sessionTitleEditing, setSessionTitleEditing] = useState(false);
+ const [sessionTitleSaving, setSessionTitleSaving] = useState(false);
+ const [sessionTitleError, setSessionTitleError] = useState<string | null>(
+ null,
+ );
+ useEffect(() => {
+ if (sessionTitleEditing) return;
+ setSessionTitleDraft(displaySessionTitle);
+ }, [displaySessionTitle, sessionTitleEditing]);
+ useEffect(() => {
+ if (!sessionTitleEditing) return;
+ window.requestAnimationFrame(() => {
+ titleInputRef.current?.focus();
+ titleInputRef.current?.select();
+ });
+ }, [sessionTitleEditing]);
+ const startSessionTitleEdit = useCallback(() => {
+ if (!canRenameSession) return;
+ skipTitleCommitRef.current = false;
+ setSessionTitleError(null);
+ setSessionTitleDraft(displaySessionTitle);
+ setSessionTitleEditing(true);
+ }, [canRenameSession, displaySessionTitle]);
+ const cancelSessionTitleEdit = useCallback(() => {
+ skipTitleCommitRef.current = true;
+ setSessionTitleDraft(displaySessionTitle);
+ setSessionTitleError(null);
+ setSessionTitleEditing(false);
+ }, [displaySessionTitle]);
+ const commitSessionTitleEdit = useCallback(async () => {
+ if (skipTitleCommitRef.current) {
+ skipTitleCommitRef.current = false;
+ return;
+ }
+ const next = sessionTitleDraft.trim();
+ if (!next) {
+ setSessionTitleDraft(displaySessionTitle);
+ setSessionTitleEditing(false);
+ return;
+ }
+ if (!canRenameSession || next === persistedSessionTitle) {
+ setSessionTitleDraft(next || displaySessionTitle);
+ setSessionTitleEditing(false);
+ return;
+ }
+ setSessionTitleSaving(true);
+ setSessionTitleError(null);
+ try {
+ await renameSessionTitle(next);
+ setSessionTitleEditing(false);
+ } catch (error) {
+ console.error("Failed to rename session:", error);
+ setSessionTitleError(t("Rename failed"));
+ titleInputRef.current?.focus();
+ } finally {
+ setSessionTitleSaving(false);
+ }
+ }, [
+ canRenameSession,
+ displaySessionTitle,
+ persistedSessionTitle,
+ renameSessionTitle,
+ sessionTitleDraft,
+ t,
+ ]);
+ const handleSessionTitleKeyDown = useCallback(
+ (event: KeyboardEvent<HTMLInputElement>) => {
+ if (event.key === "Enter") {
+ event.preventDefault();
+ void commitSessionTitleEdit();
+ } else if (event.key === "Escape") {
+ event.preventDefault();
+ cancelSessionTitleEdit();
+ }
+ },
+ [cancelSessionTitleEdit, commitSessionTitleEdit],
+ );
const { ref: composerRef, height: composerHeight } =
useMeasuredHeight<HTMLDivElement>();
- const visibleTools = useMemo(
- () => ALL_TOOLS.filter((t) => activeCap.allowedTools.includes(t.name)),
- [activeCap.allowedTools],
- );
const researchValidation = useMemo(
() => validateResearchConfig(researchConfig),
[researchConfig],
@@ -694,11 +813,11 @@ export default function ChatPage() {
metadata: event.metadata ?? {},
}));
cancelStreamingTurn();
- // Preserve the original capability — each capability now owns its
- // own answer-now fast-path (deep_solve jumps to writing,
- // deep_question to direct quiz synthesis, math_animator to
- // code-gen + render, etc.). The backend orchestrator only falls
- // back to ``chat`` if the requested capability is missing.
+ // Preserve the original capability — chat / visualize / math_animator
+ // each own an answer-now fast-path. The backend orchestrator only
+ // falls back to ``chat`` if the requested capability is missing.
+ // Solve / Quiz / Research no longer expose Answer Now (their UI
+ // gate filters the button out), so we never reach here for them.
const answerNowSnapshot: MessageRequestSnapshot = {
...snapshot,
language: appLanguage,
@@ -796,6 +915,23 @@ export default function ChatPage() {
void refreshKnowledgeBases({ force: true });
}, [refreshKnowledgeBases]);
+ const refreshUserEnabledTools = useCallback(
+ async (options?: { force?: boolean }) => {
+ try {
+ const list = await getEnabledOptionalTools({ force: options?.force });
+ setUserEnabledTools(list);
+ } catch {
+ setUserEnabledTools([]);
+ }
+ },
+ [],
+ );
+
+ /* Load user tool prefs */
+ useEffect(() => {
+ void refreshUserEnabledTools({ force: true });
+ }, [refreshUserEnabledTools]);
+
const refreshLLMOptions = useCallback(async () => {
setLLMOptionsLoading(true);
try {
@@ -826,6 +962,9 @@ export default function ChatPage() {
const refresh = () => {
void refreshKnowledgeBases({ force: true });
void refreshLLMOptions();
+ // Picks up toggles the user changed in another tab (/settings/tools).
+ invalidateEnabledOptionalToolsCache();
+ void refreshUserEnabledTools({ force: true });
};
const refreshWhenVisible = () => {
if (document.visibilityState === "visible") refresh();
@@ -838,7 +977,7 @@ export default function ChatPage() {
window.removeEventListener("pageshow", refresh);
document.removeEventListener("visibilitychange", refreshWhenVisible);
};
- }, [refreshKnowledgeBases, refreshLLMOptions]);
+ }, [refreshKnowledgeBases, refreshLLMOptions, refreshUserEnabledTools]);
useEffect(() => {
setCapabilityConfigs(loadCapabilityPlaygroundConfigs());
@@ -870,13 +1009,6 @@ export default function ChatPage() {
!capBtnRef.current.contains(t)
)
setCapMenuOpen(false);
- if (
- toolMenuRef.current &&
- !toolMenuRef.current.contains(t) &&
- toolBtnRef.current &&
- !toolBtnRef.current.contains(t)
- )
- setToolMenuOpen(false);
if (
spaceMenuRef.current &&
!spaceMenuRef.current.contains(t) &&
@@ -896,13 +1028,22 @@ export default function ChatPage() {
return () => document.removeEventListener("mousedown", handler);
}, []);
+ // Keep state.enabledTools = (user's toggleable set) ∩ (capability's allowed
+ // set). Re-runs when the user flips a toggle in /settings/tools or when
+ // the active capability changes. The composer no longer owns this — the
+ // /settings/tools page is the single switchboard.
useEffect(() => {
- const allowed = new Set(visibleTools.map((tool) => tool.name));
- const nextTools = state.enabledTools.filter((tool) =>
+ if (userEnabledTools === null) return;
+ const allowed = new Set(activeCap.allowedTools);
+ const next = userEnabledTools.filter((tool) =>
allowed.has(tool as ToolName),
);
- if (nextTools.length !== state.enabledTools.length) setTools(nextTools);
- }, [setTools, state.enabledTools, visibleTools]);
+ const current = state.enabledTools;
+ const same =
+ current.length === next.length &&
+ current.every((tool, idx) => tool === next[idx]);
+ if (!same) setTools(next);
+ }, [activeCap.allowedTools, setTools, state.enabledTools, userEnabledTools]);
/* ---- handlers ---- */
@@ -917,44 +1058,27 @@ export default function ChatPage() {
cap.allowedTools,
);
setCapability(cap.value || null);
- setTools(
- config.enabledTools.length > 0 || capabilityConfigs[storageKey]
- ? [...config.enabledTools]
- : [...cap.defaultTools],
- );
+ // Per-capability tool selection now derives from the user's saved
+ // settings (/settings/tools) intersected with the capability's
+ // allow-list. Playground-saved configs still override when the user
+ // explicitly pinned tools in the playground for this capability.
+ const baseline =
+ userEnabledTools === null ? cap.allowedTools : userEnabledTools;
+ const enabledToolsForCap = capabilityConfigs[storageKey]
+ ? [...config.enabledTools]
+ : baseline.filter((tool) =>
+ cap.allowedTools.includes(tool as ToolName),
+ );
+ setTools(enabledToolsForCap);
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],
- );
-
- const toggleTool = useCallback(
- (tool: string) => {
- if (!activeCap.allowedTools.includes(tool as ToolName)) return;
- if (selectedTools.has(tool)) {
- setTools(state.enabledTools.filter((t) => t !== tool));
- } else {
- setTools([...state.enabledTools, tool]);
- }
- },
- [activeCap.allowedTools, selectedTools, setTools, state.enabledTools],
+ [capabilityConfigs, setCapability, setKBs, setTools, userEnabledTools],
);
- const toggleResearchSource = useCallback((source: ResearchSource) => {
- setResearchConfig((current) => ({
- ...current,
- sources: current.sources.includes(source)
- ? 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(
(f: File): Promise<PendingAttachment> =>
new Promise((resolve, reject) => {
@@ -1106,21 +1230,6 @@ export default function ChatPage() {
</CapabilityConfigCard>
);
}
- if (isMathAnimatorMode) {
- return (
- <CapabilityConfigCard
- capability="math_animator"
- confirmed={capabilityConfigConfirmed}
- canConfirm
- onConfirm={handleConfirmCapabilityConfig}
- >
- <MathAnimatorConfigPanel
- value={mathAnimatorConfig}
- onChange={handleChangeMathAnimatorConfig}
- />
- </CapabilityConfigCard>
- );
- }
if (isVisualizeMode) {
return (
<CapabilityConfigCard
@@ -1158,7 +1267,6 @@ export default function ChatPage() {
}, [
capabilityNeedsConfig,
isQuizMode,
- isMathAnimatorMode,
isVisualizeMode,
capabilityConfigConfirmed,
handleConfirmCapabilityConfig,
@@ -1166,8 +1274,6 @@ export default function ChatPage() {
quizPdf,
handleChangeQuizConfig,
handleUploadQuizPdf,
- mathAnimatorConfig,
- handleChangeMathAnimatorConfig,
visualizeConfig,
handleChangeVisualizeConfig,
researchConfig,
@@ -1179,12 +1285,9 @@ export default function ChatPage() {
// 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);
- },
- [],
- );
+ 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
@@ -1294,8 +1397,6 @@ export default function ChatPage() {
];
}
}
- if (isMathAnimatorMode)
- config = buildMathAnimatorWSConfig(mathAnimatorConfig);
if (isVisualizeMode) config = buildVisualizeWSConfig(visualizeConfig);
if (isResearchMode) config = buildResearchWSConfig(researchConfig);
@@ -1311,15 +1412,9 @@ export default function ChatPage() {
memoryPayload.length
? t("Please use the selected context to help with this request.")
: "") ||
- (isMathAnimatorMode
- ? attachments.some((a) => a.type === "image")
- ? t(
- "Generate a math animation from the attached reference image(s).",
- )
- : ""
- : attachments.some((a) => a.type === "image")
- ? t("Please analyze the attached image(s).")
- : "");
+ (attachments.some((a) => a.type === "image")
+ ? t("Please analyze the attached image(s).")
+ : "");
sendMessage(
messageContent,
extraAttachments,
@@ -1345,11 +1440,9 @@ export default function ChatPage() {
attachments,
bookReferencesPayload,
historyReferencesPayload,
- isMathAnimatorMode,
isQuizMode,
isResearchMode,
isVisualizeMode,
- mathAnimatorConfig,
memoryReferencesPayload,
notebookReferencesPayload,
questionNotebookReferencesPayload,
@@ -1376,19 +1469,40 @@ export default function ChatPage() {
outline: OutlineItem[],
_topic: string,
originalConfig?: Record<string, unknown> | null,
+ originalSnapshot?: MessageRequestSnapshot | null,
) => {
const config: Record<string, unknown> = {
...(originalConfig ?? {
mode: researchConfig.mode,
depth: researchConfig.depth,
- sources: [...researchConfig.sources],
}),
confirmed_outline: outline,
};
- sendMessage(_topic, [], config, undefined, undefined, {
- displayUserMessage: false,
- persistUserMessage: false,
- });
+ const requestSnapshotOverride: MessageRequestSnapshot | undefined =
+ originalSnapshot
+ ? {
+ ...originalSnapshot,
+ content: _topic,
+ capability: "deep_research",
+ config,
+ }
+ : undefined;
+ sendMessage(
+ _topic,
+ originalSnapshot?.attachments ?? [],
+ config,
+ originalSnapshot?.notebookReferences,
+ originalSnapshot?.historyReferences,
+ {
+ displayUserMessage: false,
+ persistUserMessage: false,
+ requestSnapshotOverride,
+ bookReferences: originalSnapshot?.bookReferences,
+ },
+ originalSnapshot?.questionNotebookReferences,
+ originalSnapshot?.skills,
+ originalSnapshot?.memoryReferences,
+ );
shouldAutoScrollRef.current = true;
},
[researchConfig, sendMessage, shouldAutoScrollRef],
@@ -1538,271 +1652,355 @@ export default function ChatPage() {
}, [state.messages]);
return (
- <div
- // When the preview drawer is open AND the viewport is wide enough,
- // push the chat content to the left by the drawer's width so the two
- // panels live side-by-side (matches Claude desktop). On smaller
- // screens the drawer overlays — squeezing a phone-width chat into
- // the remaining ~30 px would be useless. The actual padding +
- // 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
- 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 shrink-0 flex-wrap items-center gap-1.5">
- <HeaderActionButton
- compact={headerCompact}
- onClick={() => setShowSaveModal(true)}
- disabled={!chatSavePayload}
- icon={BookmarkPlus}
- label={t("Save to Notebook")}
+ <QuizFollowupProvider>
+ <GeogebraTabProvider>
+ <QuizFollowupBridge viewerPanelRef={viewerPanelRef} />
+ <GeogebraTabBridge viewerPanelRef={viewerPanelRef} />
+ <div
+ // When the preview drawer is open AND the viewport is wide enough,
+ // push the chat content to the left by the drawer's width so the two
+ // panels live side-by-side (matches Claude desktop). On smaller
+ // screens the drawer overlays — squeezing a phone-width chat into
+ // the remaining ~30 px would be useless. The actual padding +
+ // 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
+ 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"
+ >
+ <div className="group/title min-w-0 flex flex-1 items-center gap-2">
+ {sessionTitleEditing ? (
+ <input
+ ref={titleInputRef}
+ value={sessionTitleDraft}
+ onChange={(event) => setSessionTitleDraft(event.target.value)}
+ onBlur={() => void commitSessionTitleEdit()}
+ onKeyDown={handleSessionTitleKeyDown}
+ disabled={sessionTitleSaving}
+ aria-label={t("Session title")}
+ className="min-w-0 flex-1 rounded-xl border border-[var(--border)] bg-[var(--background)] px-3 py-1.5 text-[15px] font-semibold tracking-[-0.01em] text-[var(--foreground)] shadow-sm outline-none transition focus:border-[var(--ring)] focus:ring-2 focus:ring-[var(--ring)]/20 disabled:opacity-60"
+ maxLength={100}
+ />
+ ) : (
+ <button
+ type="button"
+ onClick={startSessionTitleEdit}
+ disabled={!canRenameSession}
+ title={
+ canRenameSession
+ ? t("Click to rename session")
+ : t("Start a conversation to rename")
+ }
+ className="inline-flex min-w-0 max-w-full items-center gap-2 rounded-xl px-2 py-1 text-left text-[15px] font-semibold tracking-[-0.01em] text-[var(--foreground)] transition hover:bg-[var(--muted)]/55 disabled:cursor-default disabled:hover:bg-transparent"
+ >
+ <span className="truncate">{displaySessionTitle}</span>
+ {canRenameSession ? (
+ <PenLine className="h-3.5 w-3.5 shrink-0 text-[var(--muted-foreground)] opacity-0 transition-opacity group-hover/title:opacity-100" />
+ ) : null}
+ </button>
+ )}
+ {sessionTitleSaving ? (
+ <span className="shrink-0 text-xs text-[var(--muted-foreground)]">
+ {t("Saving...")}
+ </span>
+ ) : null}
+ {sessionTitleError ? (
+ <span className="shrink-0 text-xs text-[var(--destructive)]">
+ {sessionTitleError}
+ </span>
+ ) : null}
+ </div>
+ <div className="flex shrink-0 flex-wrap items-center gap-1.5">
+ <HeaderActionButton
+ compact={headerCompact}
+ onClick={() => setShowSaveModal(true)}
+ disabled={!chatSavePayload}
+ 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")}
+ />
+ <HeaderActionButton
+ compact={headerCompact}
+ onClick={handleNewChat}
+ 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">
+ {!hasMessages ? (
+ <div className="flex flex-1 min-h-0 flex-col items-center justify-end pb-14 animate-fade-in">
+ <div className="text-center">
+ <h1 className="font-serif text-[44px] font-medium leading-[1.1] tracking-[-0.015em] text-[var(--foreground)]">
+ {t("What would you like to learn?")}
+ </h1>
+ <p className="mt-5 text-[15px] text-[var(--muted-foreground)]">
+ {t("Ask anything — I'm here to help you understand.")}
+ </p>
+ </div>
+ </div>
+ ) : (
+ <div
+ ref={messagesContainerRef}
+ data-chat-scroll-root="true"
+ onScroll={handleMessagesScroll}
+ 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: "48px",
+ WebkitMaskImage: maskImage,
+ maskImage,
+ };
+ })()
+ : undefined
+ }
+ >
+ <ChatMessageList
+ messages={state.messages}
+ isStreaming={state.isStreaming}
+ sessionId={state.sessionId}
+ language={state.language}
+ onAnswerNow={handleAnswerNow}
+ onCopyAssistantMessage={copyAssistantMessage}
+ onRegenerateMessage={handleRegenerateMessage}
+ onConfirmOutline={handleConfirmOutline}
+ onPreviewAttachment={handlePreviewMessageAttachment}
+ onDeleteTurn={deleteTurn}
+ selectedBranches={state.selectedBranches}
+ onEditMessage={editMessage}
+ onSwitchBranch={switchBranch}
+ onSubmitUserReply={submitUserReply}
+ />
+ <div ref={messagesEndRef} className="h-px w-full shrink-0" />
+ </div>
+ )}
+
+ <ChatComposer
+ composerRef={composerRef}
+ capMenuRef={capMenuRef}
+ capBtnRef={capBtnRef}
+ spaceMenuRef={spaceMenuRef}
+ spaceBtnRef={spaceBtnRef}
+ kbMenuRef={kbMenuRef}
+ kbBtnRef={kbBtnRef}
+ dragCounter={dragCounter}
+ dragging={dragging}
+ capMenuOpen={capMenuOpen}
+ spaceMenuOpen={spaceMenuOpen}
+ kbMenuOpen={kbMenuOpen}
+ hasMessages={hasMessages}
+ attachments={attachments}
+ attachmentError={attachmentError}
+ activeCap={activeCap}
+ knowledgeBases={knowledgeBases}
+ llmOptions={llmOptions}
+ activeLLMDefault={activeLLMDefault}
+ llmSelection={state.llmSelection}
+ llmOptionsLoading={llmOptionsLoading}
+ llmOptionsError={llmOptionsError}
+ selectedBookReferences={selectedBookReferences}
+ selectedNotebookRecords={selectedNotebookRecords}
+ selectedHistorySessions={selectedHistorySessions}
+ selectedQuestionEntries={selectedQuestionEntries}
+ notebookReferenceGroups={notebookReferenceGroups}
+ selectedSkills={selectedSkills}
+ skillsAutoMode={skillsAutoMode}
+ selectedMemoryFiles={selectedMemoryFiles}
+ selectedKnowledgeBases={state.knowledgeBases}
+ isStreaming={state.isStreaming}
+ isVisualizeMode={isVisualizeMode}
+ capabilityNeedsConfig={capabilityNeedsConfig}
+ capabilityConfigConfirmed={capabilityConfigConfirmed}
+ onRequestConfigConfirm={ensureActivityPanelOpen}
+ capabilities={CAPABILITIES}
+ onSetCapMenuOpen={setCapMenuOpen}
+ onSetSpaceMenuOpen={setSpaceMenuOpen}
+ onSetKbMenuOpen={setKbMenuOpen}
+ onToggleKB={handleToggleKB}
+ onSelectLLM={setLLMSelection}
+ onSelectNotebookPicker={handleSelectNotebookPicker}
+ onSelectBookPicker={handleSelectBookPicker}
+ onSelectHistoryPicker={handleSelectHistoryPicker}
+ onSelectQuestionBankPicker={handleSelectQuestionBankPicker}
+ onSelectSkillsPicker={handleSelectSkillsPicker}
+ onSelectMemoryPicker={handleSelectMemoryPicker}
+ onToggleSkill={handleToggleSkill}
+ onSetSkillsAuto={handleSetSkillsAuto}
+ onToggleMemoryFile={handleToggleMemoryFile}
+ onSend={handleSend}
+ onRemoveAttachment={removeAttachment}
+ onPreviewAttachment={handlePreviewPendingAttachment}
+ onRemoveHistory={handleRemoveHistory}
+ onRemoveBookReference={handleRemoveBookReference}
+ onRemoveNotebook={handleRemoveNotebook}
+ onRemoveQuestion={handleRemoveQuestion}
+ onDragEnter={handleDragEnter}
+ onDragLeave={handleDragLeave}
+ onDragOver={handleDragOver}
+ onDrop={handleDrop}
+ onPaste={handlePaste}
+ onAddFiles={handleAddFiles}
+ onSelectCapability={handleSelectCapability}
+ onCancelStreaming={cancelStreamingTurn}
+ prefillInputRef={prefillInputRef}
+ />
+ <div
+ aria-hidden="true"
+ className="shrink-0"
+ style={{
+ flexGrow: hasMessages ? 0 : 1.4,
+ transition: "flex-grow 650ms cubic-bezier(0.16, 1, 0.3, 1)",
+ }}
+ />
+ </div>
+ <NotebookRecordPicker
+ open={showNotebookPicker}
+ onClose={handleCloseNotebookPicker}
+ onApply={handleApplyNotebookRecords}
/>
- <HeaderActionButton
- compact={headerCompact}
- onClick={handleDownloadMarkdown}
- disabled={!state.messages.length}
- icon={Download}
- label={t("Download Markdown")}
- title={t("Download chat history as Markdown")}
+ <BookReferencePicker
+ open={showBookPicker}
+ initialReferences={selectedBookReferences}
+ onClose={handleCloseBookPicker}
+ onApply={handleApplyBookReferences}
/>
- <HeaderActionButton
- compact={headerCompact}
- onClick={handleNewChat}
- icon={SquarePen}
- label={t("New chat")}
+ <HistorySessionPicker
+ open={showHistoryPicker}
+ onClose={handleCloseHistoryPicker}
+ onApply={handleApplyHistorySessions}
/>
- <HeaderActionButton
- compact={headerCompact}
- onClick={toggleActivityPanel}
- active={activityPanelOpen}
- icon={PanelRight}
- label={t("Activity")}
- title={t("Session activity")}
+ <QuestionBankPicker
+ open={showQuestionBankPicker}
+ onClose={handleCloseQuestionBankPicker}
+ onApply={handleApplyQuestionEntries}
/>
- <HeaderActionButton
- compact={headerCompact}
- onClick={toggleViewerPanel}
- active={viewerPanelOpen}
- icon={BookOpen}
- label={t("Viewer")}
- title={t("Open viewer")}
+ <SkillsPicker
+ open={showSkillsPicker}
+ initialAuto={skillsAutoMode}
+ initialSkills={selectedSkills}
+ onClose={handleCloseSkillsPicker}
+ onApply={handleApplySkillsSelection}
/>
- </div>
- </div>
- <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("What would you like to learn?")}
- </h1>
- <p className="mt-4 text-[15px] text-[var(--muted-foreground)]">
- {t("Ask anything — I'm here to help you understand.")}
- </p>
- </div>
- </div>
- ) : (
- <div
- ref={messagesContainerRef}
- data-chat-scroll-root="true"
- onScroll={handleMessagesScroll}
- 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: "48px",
- WebkitMaskImage: maskImage,
- maskImage,
- };
- })()
- : undefined
+ <MemoryPicker
+ open={showMemoryPicker}
+ initialFiles={selectedMemoryFiles}
+ onClose={handleCloseMemoryPicker}
+ onApply={handleApplyMemoryFiles}
+ />
+ <SaveToNotebookModal
+ open={showSaveModal}
+ payload={chatSavePayload}
+ messages={chatSaveMessages}
+ onClose={handleCloseSaveModal}
+ />
+ <FilePreviewDrawer
+ open={previewSource !== null}
+ source={previewSource}
+ onClose={handleClosePreview}
+ />
+ <SessionActivityPanel
+ open={
+ activityPanelOpen && previewSource === null && !viewerPanelOpen
}
- >
- <ChatMessageList
- messages={state.messages}
- isStreaming={state.isStreaming}
- sessionId={state.sessionId}
- language={state.language}
- onAnswerNow={handleAnswerNow}
- onCopyAssistantMessage={copyAssistantMessage}
- onRegenerateMessage={handleRegenerateMessage}
- onConfirmOutline={handleConfirmOutline}
- onPreviewAttachment={handlePreviewMessageAttachment}
- onDeleteTurn={deleteTurn}
- selectedBranches={state.selectedBranches}
- onEditMessage={editMessage}
- onSwitchBranch={switchBranch}
- />
- <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={toolMenuOpen}
- spaceMenuOpen={spaceMenuOpen}
- kbMenuOpen={kbMenuOpen}
- hasMessages={hasMessages}
- attachments={attachments}
- attachmentError={attachmentError}
- activeCap={activeCap}
- visibleTools={visibleTools}
- selectedTools={selectedTools}
- knowledgeBases={knowledgeBases}
- llmOptions={llmOptions}
- activeLLMDefault={activeLLMDefault}
- llmSelection={state.llmSelection}
- llmOptionsLoading={llmOptionsLoading}
- llmOptionsError={llmOptionsError}
- selectedBookReferences={selectedBookReferences}
- selectedNotebookRecords={selectedNotebookRecords}
- selectedHistorySessions={selectedHistorySessions}
- selectedQuestionEntries={selectedQuestionEntries}
- notebookReferenceGroups={notebookReferenceGroups}
- selectedSkills={selectedSkills}
- skillsAutoMode={skillsAutoMode}
- selectedMemoryFiles={selectedMemoryFiles}
- selectedKnowledgeBases={state.knowledgeBases}
- isStreaming={state.isStreaming}
- isResearchMode={isResearchMode}
- isMathAnimatorMode={isMathAnimatorMode}
- isVisualizeMode={isVisualizeMode}
- 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}
- onSetKbMenuOpen={setKbMenuOpen}
- onToggleAutoCap={noopToggleAutoCap}
- onToggleKB={handleToggleKB}
- onSelectLLM={setLLMSelection}
- onSelectNotebookPicker={handleSelectNotebookPicker}
- onSelectBookPicker={handleSelectBookPicker}
- onSelectHistoryPicker={handleSelectHistoryPicker}
- onSelectQuestionBankPicker={handleSelectQuestionBankPicker}
- onSelectSkillsPicker={handleSelectSkillsPicker}
- onSelectMemoryPicker={handleSelectMemoryPicker}
- onToggleTool={toggleTool}
- onToggleSkill={handleToggleSkill}
- onSetSkillsAuto={handleSetSkillsAuto}
- onToggleMemoryFile={handleToggleMemoryFile}
- onToggleResearchSource={toggleResearchSource}
- onSend={handleSend}
- onRemoveAttachment={removeAttachment}
- onPreviewAttachment={handlePreviewPendingAttachment}
- onRemoveHistory={handleRemoveHistory}
- onRemoveBookReference={handleRemoveBookReference}
- onRemoveNotebook={handleRemoveNotebook}
- onRemoveQuestion={handleRemoveQuestion}
- onDragEnter={handleDragEnter}
- onDragLeave={handleDragLeave}
- onDragOver={handleDragOver}
- onDrop={handleDrop}
- onPaste={handlePaste}
- onAddFiles={handleAddFiles}
- onSelectCapability={handleSelectCapability}
- onCancelStreaming={cancelStreamingTurn}
- />
- </div>
- <NotebookRecordPicker
- open={showNotebookPicker}
- onClose={handleCloseNotebookPicker}
- onApply={handleApplyNotebookRecords}
- />
- <BookReferencePicker
- open={showBookPicker}
- initialReferences={selectedBookReferences}
- onClose={handleCloseBookPicker}
- onApply={handleApplyBookReferences}
- />
- <HistorySessionPicker
- open={showHistoryPicker}
- onClose={handleCloseHistoryPicker}
- onApply={handleApplyHistorySessions}
- />
- <QuestionBankPicker
- open={showQuestionBankPicker}
- onClose={handleCloseQuestionBankPicker}
- onApply={handleApplyQuestionEntries}
- />
- <SkillsPicker
- open={showSkillsPicker}
- initialAuto={skillsAutoMode}
- initialSkills={selectedSkills}
- onClose={handleCloseSkillsPicker}
- onApply={handleApplySkillsSelection}
- />
- <MemoryPicker
- open={showMemoryPicker}
- initialFiles={selectedMemoryFiles}
- onClose={handleCloseMemoryPicker}
- onApply={handleApplyMemoryFiles}
- />
- <SaveToNotebookModal
- open={showSaveModal}
- payload={chatSavePayload}
- messages={chatSaveMessages}
- onClose={handleCloseSaveModal}
- />
- <FilePreviewDrawer
- open={previewSource !== null}
- 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>
+ activity={sessionActivity}
+ onOpenAttachment={handlePreviewMessageAttachment}
+ configSection={capabilityConfigSection}
+ />
+ <SessionViewerPanel
+ ref={viewerPanelRef}
+ open={viewerPanelOpen && previewSource === null}
+ sessionId={state.sessionId}
+ onClose={() => setViewerOpen(false)}
+ onAutoOpen={() => setViewerOpen(true)}
+ />
+ </div>
+ </GeogebraTabProvider>
+ </QuizFollowupProvider>
);
}
+/**
+ * Bridges the SessionViewerPanel's imperative ``openQuizFollowupTab`` into
+ * the QuizFollowupController so descendants (QuizViewer) can call
+ * ``controller.openFollowupTab(...)`` without prop-drilling the panel ref
+ * through several layers of components.
+ */
+function QuizFollowupBridge({
+ viewerPanelRef,
+}: {
+ viewerPanelRef: React.MutableRefObject<SessionViewerPanelHandle | null>;
+}) {
+ const controller = useQuizFollowupController();
+ useEffect(() => {
+ controller.setOpenTabHandler((ctx) => {
+ viewerPanelRef.current?.openQuizFollowupTab(ctx);
+ });
+ return () => controller.setOpenTabHandler(null);
+ }, [controller, viewerPanelRef]);
+ return null;
+}
+
+/**
+ * Same shape as QuizFollowupBridge, for the GeoGebra-tab opener exposed
+ * to in-message CTAs (the ``ggbscript`` markdown fence becomes a card
+ * that calls ``controller.openTab(...)`` here).
+ */
+function GeogebraTabBridge({
+ viewerPanelRef,
+}: {
+ viewerPanelRef: React.MutableRefObject<SessionViewerPanelHandle | null>;
+}) {
+ const controller = useGeogebraTabOpener();
+ useEffect(() => {
+ if (!controller) return;
+ controller.setOpenHandler((payload) => {
+ viewerPanelRef.current?.openGeogebraTab(payload);
+ });
+ return () => controller.setOpenHandler(null);
+ }, [controller, viewerPanelRef]);
+ return null;
+}
+
/**
* Header action button that auto-collapses to icon-only when the chat
* column gets squeezed (Viewer panel open, narrow viewport, etc.). The
diff --git a/web/app/(workspace)/co-learn/[[...sessionId]]/page.tsx b/web/app/(workspace)/co-learn/[[...sessionId]]/page.tsx
deleted file mode 100644
index 30dea7875..000000000
--- a/web/app/(workspace)/co-learn/[[...sessionId]]/page.tsx
+++ /dev/null
@@ -1,756 +0,0 @@
-"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/(workspace)/co-writer/[docId]/page.tsx b/web/app/(workspace)/co-writer/[docId]/page.tsx
index 5ee5eea64..85d840e9e 100644
--- a/web/app/(workspace)/co-writer/[docId]/page.tsx
+++ b/web/app/(workspace)/co-writer/[docId]/page.tsx
@@ -972,11 +972,11 @@ export default function CoWriterPage() {
);
if (!response.ok) {
throw new Error(
- (await response.text()) || "Failed to edit selected text.",
+ (await response.text()) || t("Failed to edit selected text."),
);
}
if (!response.body) {
- throw new Error("Streaming response body is missing.");
+ throw new Error(t("Streaming response body is missing."));
}
const reader = response.body.getReader();
@@ -1007,7 +1007,7 @@ export default function CoWriterPage() {
}
if (eventName === "error") {
throw new Error(
- String(payload?.detail || "Failed to edit selected text."),
+ String(payload?.detail || t("Failed to edit selected text.")),
);
}
};
@@ -1029,13 +1029,15 @@ export default function CoWriterPage() {
processSseChunk(buffer.trim());
}
if (finalResult === undefined) {
- throw new Error("Did not receive a final edit result.");
+ throw new Error(t("Did not receive a final edit result."));
}
const editedText = finalResult.edited_text ?? "";
if (markdown !== selectedRange.snapshot) {
throw new Error(
- "The draft changed before AI edit finished. Please reselect the text and try again.",
+ t(
+ "The draft changed before AI edit finished. Please reselect the text and try again.",
+ ),
);
}
@@ -1046,7 +1048,7 @@ export default function CoWriterPage() {
return;
}
setError(
- err instanceof Error ? err.message : "Failed to edit selected text.",
+ err instanceof Error ? err.message : t("Failed to edit selected text."),
);
} finally {
selectionRequestAbortRef.current = null;
@@ -1086,7 +1088,7 @@ export default function CoWriterPage() {
});
const data = await response.json();
if (!response.ok)
- throw new Error(data?.detail || "Failed to edit document.");
+ throw new Error(data?.detail || t("Failed to edit document."));
pushUndo(markdown);
setMarkdown(data.edited_text || "");
setStatus(
@@ -1096,7 +1098,9 @@ export default function CoWriterPage() {
);
setIsEditModalOpen(false);
} catch (err) {
- setError(err instanceof Error ? err.message : "Failed to edit document.");
+ setError(
+ err instanceof Error ? err.message : t("Failed to edit document."),
+ );
} finally {
setIsEditing(false);
}
@@ -1114,13 +1118,13 @@ export default function CoWriterPage() {
});
const data = await response.json();
if (!response.ok)
- throw new Error(data?.detail || "Failed to auto-mark document.");
+ throw new Error(data?.detail || t("Failed to auto-mark document."));
pushUndo(markdown);
setMarkdown(data.marked_text || "");
setStatus(t("Applied auto-mark annotations."));
} catch (err) {
setError(
- err instanceof Error ? err.message : "Failed to auto-mark document.",
+ err instanceof Error ? err.message : t("Failed to auto-mark document."),
);
} finally {
setIsAutoMarking(false);
@@ -2233,7 +2237,7 @@ export default function CoWriterPage() {
{/* ── AI Edit modal ── */}
{isEditModalOpen && (
<div
- className="fixed inset-0 z-50 flex items-center justify-center bg-black/30 backdrop-blur-sm"
+ className="fixed inset-0 z-50 flex items-center justify-center bg-[var(--overlay)] backdrop-blur-sm"
onClick={(e) => {
if (e.target === e.currentTarget) setIsEditModalOpen(false);
}}
@@ -2344,7 +2348,7 @@ export default function CoWriterPage() {
{confirmActionCopy && (
<div
- className="fixed inset-0 z-50 flex items-center justify-center bg-black/30 px-4 backdrop-blur-sm"
+ className="fixed inset-0 z-50 flex items-center justify-center bg-[var(--overlay)] px-4 backdrop-blur-sm"
onClick={(e) => {
if (e.target === e.currentTarget) setPendingConfirmAction(null);
}}
diff --git a/web/app/(workspace)/playground/page.tsx b/web/app/(workspace)/playground/page.tsx
index 9ebfce0b6..e8d40b1c4 100644
--- a/web/app/(workspace)/playground/page.tsx
+++ b/web/app/(workspace)/playground/page.tsx
@@ -49,7 +49,6 @@ import {
normalizeResearchConfig,
validateResearchConfig,
type DeepResearchFormConfig,
- type ResearchSource,
} from "@/lib/research-types";
/* ------------------------------------------------------------------ */
@@ -74,16 +73,6 @@ const TOOL_LABELS: Record<string, string> = {
paper_search: "Arxiv Search",
};
-const RESEARCH_SOURCE_OPTIONS: Array<{
- name: ResearchSource;
- label: string;
- icon: LucideIcon;
-}> = [
- { name: "kb", label: "Knowledge Base", icon: Database },
- { name: "web", label: "Web", icon: Globe },
- { name: "papers", label: "Papers", icon: FileSearch },
-];
-
const CAPABILITY_ICONS: Record<string, LucideIcon> = {
chat: MessageSquare,
deep_solve: BrainCircuit,
@@ -1245,10 +1234,7 @@ function DeepResearchTester({
body: JSON.stringify({
content,
tools: enabledTools,
- knowledge_bases:
- config.sources.includes("kb") && knowledgeBase
- ? [knowledgeBase]
- : [],
+ knowledge_bases: knowledgeBase ? [knowledgeBase] : [],
language: i18n.language,
config: buildResearchWSConfig(config),
}),
@@ -1346,15 +1332,6 @@ function DeepResearchTester({
}
};
- const toggleSource = (source: ResearchSource) => {
- onConfigChange({
- ...config,
- sources: config.sources.includes(source)
- ? config.sources.filter((item) => item !== source)
- : [...config.sources, source],
- });
- };
-
return (
<div className="space-y-4">
<ResearchConfigPanel
@@ -1364,37 +1341,6 @@ function DeepResearchTester({
onChange={onConfigChange}
onToggleCollapsed={() => {}}
/>
- <div className="rounded-xl border border-[var(--border)] bg-[var(--background)] p-3">
- <div className="mb-2 text-[12px] font-medium text-[var(--foreground)]">
- {t("Sources")}
- </div>
- <div className="flex flex-wrap gap-2">
- {RESEARCH_SOURCE_OPTIONS.map((source) => {
- const active = config.sources.includes(source.name);
- const Icon = source.icon;
- return (
- <button
- key={source.name}
- type="button"
- onClick={() => toggleSource(source.name)}
- className={`inline-flex h-[32px] items-center gap-1.5 rounded-full px-3 text-[12px] font-medium transition-[background-color,color,box-shadow] ${
- active
- ? "bg-[var(--muted)] text-[var(--foreground)] shadow-[0_1px_2px_rgba(15,23,42,0.05)] ring-1 ring-[var(--border)]/55"
- : "text-[var(--muted-foreground)]/75 hover:bg-[var(--muted)]/55 hover:text-[var(--foreground)]"
- }`}
- >
- <Icon size={13} strokeWidth={1.7} />
- {t(source.label)}
- </button>
- );
- })}
- </div>
- <div className="mt-2 text-[11px] text-[var(--muted-foreground)]">
- {config.sources.length
- ? t("Selected sources will be queried during research.")
- : t("No source selected: the run will use llm-only research.")}
- </div>
- </div>
<div className="rounded-xl border border-[var(--border)] bg-[var(--background)] p-3">
<textarea
value={input}
diff --git a/web/app/globals.css b/web/app/globals.css
index 89b70c650..e857b12fc 100644
--- a/web/app/globals.css
+++ b/web/app/globals.css
@@ -3,29 +3,48 @@
@tailwind utilities;
@layer base {
+ /* ────────────────────────────────────────────────────────────────────────
+ Theme palettes — four families that intentionally pair on two axes:
+ • Cream (:root) and Dark (.dark) → warm family, terracotta accent
+ • Snow (.theme-snow) and Glass (.theme-glass) → cool family,
+ blue and purple accents respectively
+ Tokens that every theme must publish:
+ --background, --foreground, --card / --popover (+ their -foreground),
+ --primary (+ -foreground), --secondary, --muted (+ -foreground),
+ --accent (+ -foreground), --destructive (+ -foreground),
+ --border, --input, --ring,
+ --overlay → scrim color for modal backdrops / picker shells
+ (replaces hardcoded bg-black/40 in components)
+ ──────────────────────────────────────────────────────────────────────── */
+
+ /* Cream — warm parchment default. Honest about its yellow-cream
+ warmth (was previously labelled "Light" but the palette is closer
+ to cream/linen than to neutral white). Terracotta primary. */
:root {
color-scheme: light;
- --background: #faf9f6;
- --foreground: #1f1d1b;
+ --background: #faf6ec;
+ --foreground: #1c1816;
--card: #ffffff;
- --card-foreground: #1f1d1b;
+ --card-foreground: #1c1816;
--popover: #ffffff;
- --popover-foreground: #1f1d1b;
+ --popover-foreground: #1c1816;
--primary: #b0501e;
--primary-foreground: #ffffff;
- --secondary: #ece7dd;
- --secondary-foreground: #1f1d1b;
- --muted: #ece7dd;
- --muted-foreground: #6b655f;
- --accent: #ece7dd;
- --accent-foreground: #1f1d1b;
+ --secondary: #f1ebdb;
+ --secondary-foreground: #1c1816;
+ --muted: #ede5d2;
+ --muted-foreground: #6d645a;
+ --accent: #ebe2cd;
+ --accent-foreground: #1c1816;
--destructive: #c53a2c;
--destructive-foreground: #ffffff;
- --border: #dbd4c8;
- --input: #dbd4c8;
+ --border: #d9ccb2;
+ --input: #d9ccb2;
--ring: #b0501e;
+ --overlay: rgba(28, 24, 22, 0.42);
}
+ /* Dark — warm near-black, same terracotta family as Cream. */
.dark {
color-scheme: dark;
--background: #1a1918;
@@ -47,54 +66,70 @@
--border: #3a3634;
--input: #3a3634;
--ring: #d4734b;
+ --overlay: rgba(0, 0, 0, 0.6);
}
+ /* Snow — crisp cool blue-tinted light. A royal-blue primary replaces
+ the warm terracotta so the cool background and accent finally
+ agree, and a subtle vertical gradient on <body> breaks the
+ "flat dull paper" feel of a single slate-50 wash. */
.theme-snow {
color-scheme: light;
- --background: #f8fafc;
- --foreground: #0f172a;
+ --background: #eef3fa;
+ --foreground: #0e1a2e;
--card: #ffffff;
- --card-foreground: #0f172a;
+ --card-foreground: #0e1a2e;
--popover: #ffffff;
- --popover-foreground: #0f172a;
- --primary: #b0501e;
+ --popover-foreground: #0e1a2e;
+ --primary: #1d4ed8;
--primary-foreground: #ffffff;
- --secondary: #e8eef5;
- --secondary-foreground: #0f172a;
- --muted: #e8eef5;
- --muted-foreground: #5a6b82;
- --accent: #e8eef5;
- --accent-foreground: #0f172a;
+ --secondary: #dde7f3;
+ --secondary-foreground: #0e1a2e;
+ --muted: #dce6f2;
+ --muted-foreground: #4d5d77;
+ --accent: #dde7f3;
+ --accent-foreground: #0e1a2e;
--destructive: #c7281f;
--destructive-foreground: #ffffff;
- --border: #cbd5e1;
- --input: #cbd5e1;
- --ring: #b0501e;
+ --border: #c2d0e2;
+ --input: #c2d0e2;
+ --ring: #1d4ed8;
+ --overlay: rgba(15, 23, 42, 0.42);
+ }
+
+ .theme-snow body {
+ /* Gentle top-to-bottom blue shift — barely perceptible but
+ enough to feel "atmospheric" rather than monotone. */
+ background: linear-gradient(180deg, #f2f6fb 0%, #e4ecf6 100%);
+ background-attachment: fixed;
}
+ /* Glass — translucent purple panels on near-black. Slightly brighter
+ primary so the accent reads against the radial gradient. */
.theme-glass {
color-scheme: dark;
- --background: #111111;
+ --background: #0e0d1a;
--foreground: #ffffff;
- --card: rgba(255, 255, 255, 0.05);
+ --card: rgba(255, 255, 255, 0.06);
--card-foreground: #ffffff;
--popover: rgba(24, 22, 36, 0.92);
--popover-foreground: #ffffff;
- --primary: #9d50bb;
+ --primary: #a855f7;
--primary-foreground: #ffffff;
- --secondary: rgba(255, 255, 255, 0.03);
+ --secondary: rgba(255, 255, 255, 0.04);
--secondary-foreground: #eeeeee;
- --muted: rgba(255, 255, 255, 0.05);
- --muted-foreground: #aaaaaa;
- --accent: rgba(255, 255, 255, 0.1);
+ --muted: rgba(255, 255, 255, 0.06);
+ --muted-foreground: #b5b5c7;
+ --accent: rgba(255, 255, 255, 0.12);
--accent-foreground: #ffffff;
- --border: rgba(255, 255, 255, 0.1);
- --input: rgba(255, 255, 255, 0.05);
- --ring: #6e48aa;
+ --border: rgba(255, 255, 255, 0.12);
+ --input: rgba(255, 255, 255, 0.06);
+ --ring: #a855f7;
+ --overlay: rgba(0, 0, 0, 0.55);
}
.theme-glass body {
- background: radial-gradient(circle at 50% 50%, #1a1a2e 0%, #0f0f1a 100%);
+ background: radial-gradient(circle at 50% 50%, #1a1a2e 0%, #0d0d1a 100%);
background-attachment: fixed;
}
diff --git a/web/components/SessionList.tsx b/web/components/SessionList.tsx
index 9bb80151f..d26f457ab 100644
--- a/web/components/SessionList.tsx
+++ b/web/components/SessionList.tsx
@@ -98,10 +98,18 @@ export default function SessionList({
const [editingId, setEditingId] = useState<string | null>(null);
const [draftTitle, setDraftTitle] = useState("");
- // The group-key tokens are stable across locales; the translated labels
- // (and their ordering) are built once per language change. Memoizing on
- // i18n.language so the labels recompute when the user flips the language
- // switcher.
+ // The sentinel the backend writes when a session is created and not
+ // yet renamed by the LLM title generator. We swap it for a localized
+ // "New chat" string with a breathing animation so the sidebar shows
+ // something "alive" while the title is being generated in the
+ // background instead of a literal English sentinel.
+ const isPlaceholderTitle = (raw: string | null | undefined): boolean => {
+ const value = (raw ?? "").trim();
+ return value === "" || value === "New conversation";
+ };
+ const placeholderLabel = t("New chat");
+
+ // The group-key tokens stay stable; only the translated labels change.
const groupLabels = useMemo<Record<DayGroupKey, string>>(
() => ({
today: t("Today"),
@@ -109,7 +117,7 @@ export default function SessionList({
last_7_days: t("Last 7 days"),
earlier: t("Earlier"),
}),
- [t, i18n.language],
+ [t],
);
const grouped = useMemo(() => {
@@ -231,11 +239,17 @@ export default function SessionList({
onClick={(event) => event.stopPropagation()}
className="min-w-0 flex-1 rounded border border-[var(--border)] bg-[var(--background)] px-1.5 py-px text-[12px] text-[var(--foreground)] outline-none focus:ring-1 focus:ring-[var(--primary)]/40"
/>
+ ) : isPlaceholderTitle(session.title) ? (
+ <span
+ className={`dt-breathing-text min-w-0 flex-1 truncate text-[13px] italic text-[var(--muted-foreground)] ${active ? "font-medium" : ""}`}
+ >
+ {placeholderLabel}
+ </span>
) : (
<span
className={`min-w-0 flex-1 truncate text-[13px] ${active ? "font-medium" : ""}`}
>
- {session.title || "Untitled chat"}
+ {session.title}
</span>
)}
<div className="flex shrink-0 items-center gap-px opacity-0 transition-opacity group-hover:opacity-100">
@@ -337,13 +351,23 @@ export default function SessionList({
/>
) : (
<div className="flex items-center">
- <span
- className={`line-clamp-1 min-w-0 flex-1 text-[12px] leading-snug ${
- active ? "font-medium" : "font-normal"
- }`}
- >
- {session.title || "Untitled chat"}
- </span>
+ {isPlaceholderTitle(session.title) ? (
+ <span
+ className={`dt-breathing-text line-clamp-1 min-w-0 flex-1 text-[12px] italic leading-snug text-[var(--muted-foreground)] ${
+ active ? "font-medium" : "font-normal"
+ }`}
+ >
+ {placeholderLabel}
+ </span>
+ ) : (
+ <span
+ className={`line-clamp-1 min-w-0 flex-1 text-[12px] leading-snug ${
+ active ? "font-medium" : "font-normal"
+ }`}
+ >
+ {session.title}
+ </span>
+ )}
<StatusIndicator status={session.status} />
</div>
)}
diff --git a/web/components/chat/BookReferencePicker.tsx b/web/components/chat/BookReferencePicker.tsx
index 282614d61..74137f9e6 100644
--- a/web/components/chat/BookReferencePicker.tsx
+++ b/web/components/chat/BookReferencePicker.tsx
@@ -69,6 +69,8 @@ export default function BookReferencePicker({
useEffect(() => {
if (!open) return;
let mounted = true;
+ // Re-seed selection each time the picker opens.
+ // eslint-disable-next-line react-hooks/set-state-in-effect
setSelected(initialReferences);
setLoadingBooks(true);
void bookApi
@@ -92,6 +94,8 @@ export default function BookReferencePicker({
useEffect(() => {
if (!open || !activeBookId || details[activeBookId]) return;
let mounted = true;
+ // Show detail loading before the async book lookup resolves.
+ // eslint-disable-next-line react-hooks/set-state-in-effect
setLoadingDetail(true);
void bookApi
.get(activeBookId)
diff --git a/web/components/chat/home/CapabilityConfigCard.tsx b/web/components/chat/home/CapabilityConfigCard.tsx
index fd4e3b726..7e90d145b 100644
--- a/web/components/chat/home/CapabilityConfigCard.tsx
+++ b/web/components/chat/home/CapabilityConfigCard.tsx
@@ -109,7 +109,7 @@ function CapabilityConfigCardInner({
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"
+ : "bg-[var(--primary)] text-[var(--primary-foreground)] shadow-[0_2px_6px_color-mix(in_srgb,var(--primary)_28%,transparent)] hover:shadow-[0_4px_10px_color-mix(in_srgb,var(--primary)_40%,transparent)] disabled:bg-[var(--muted-foreground)]/15 disabled:text-[var(--muted-foreground)]/40 disabled:shadow-none"
}`}
>
{confirmed ? t("Confirmed") : t("Confirm")}
diff --git a/web/components/chat/home/ChatComposer.tsx b/web/components/chat/home/ChatComposer.tsx
index f3475be82..5c2d461c1 100644
--- a/web/components/chat/home/ChatComposer.tsx
+++ b/web/components/chat/home/ChatComposer.tsx
@@ -15,11 +15,8 @@ import {
AtSign,
ChevronDown,
Database,
- Layers,
Paperclip,
- Sparkles,
Square,
- Wrench,
X,
type LucideIcon,
} from "lucide-react";
@@ -35,7 +32,6 @@ import type { SelectedQuestionEntry } from "@/components/chat/QuestionBankPicker
import type { SelectedRecord } from "@/lib/notebook-selection-types";
import type { LLMSelection } from "@/lib/unified-ws";
import type { LLMOption } from "@/lib/llm-options";
-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";
@@ -73,24 +69,10 @@ interface CapabilityDef {
allowedTools: string[];
}
-interface ToolDef {
- name: string;
- label: string;
- icon: LucideIcon;
-}
-
-interface ResearchSourceDef {
- name: ResearchSource;
- label: string;
- icon: LucideIcon;
-}
-
export default memo(function ChatComposer({
composerRef,
capMenuRef,
capBtnRef,
- toolMenuRef,
- toolBtnRef,
spaceMenuRef,
spaceBtnRef,
kbMenuRef,
@@ -98,15 +80,12 @@ export default memo(function ChatComposer({
dragCounter,
dragging,
capMenuOpen,
- toolMenuOpen,
spaceMenuOpen,
kbMenuOpen,
hasMessages,
attachments,
attachmentError,
activeCap,
- visibleTools,
- selectedTools,
knowledgeBases,
llmOptions,
activeLLMDefault,
@@ -123,22 +102,14 @@ export default memo(function ChatComposer({
selectedMemoryFiles,
selectedKnowledgeBases,
isStreaming,
- isResearchMode,
- isMathAnimatorMode,
isVisualizeMode,
- isAutoMode,
- autoEnabledCaps,
- researchConfigSources,
capabilityNeedsConfig,
capabilityConfigConfirmed,
onRequestConfigConfirm,
capabilities,
- researchSources,
onSetCapMenuOpen,
- onSetToolMenuOpen,
onSetSpaceMenuOpen,
onSetKbMenuOpen,
- onToggleAutoCap,
onToggleKB,
onSelectLLM,
onSelectNotebookPicker,
@@ -147,11 +118,9 @@ export default memo(function ChatComposer({
onSelectQuestionBankPicker,
onSelectSkillsPicker,
onSelectMemoryPicker,
- onToggleTool,
onToggleSkill,
onSetSkillsAuto,
onToggleMemoryFile,
- onToggleResearchSource,
onSend,
onRemoveAttachment,
onPreviewAttachment,
@@ -167,12 +136,12 @@ export default memo(function ChatComposer({
onAddFiles,
onSelectCapability,
onCancelStreaming,
+ prefillInputRef,
+ inputPlaceholder,
}: {
composerRef: RefObject<HTMLDivElement | null>;
capMenuRef: RefObject<HTMLDivElement | null>;
capBtnRef: RefObject<HTMLButtonElement | null>;
- toolMenuRef: RefObject<HTMLDivElement | null>;
- toolBtnRef: RefObject<HTMLButtonElement | null>;
spaceMenuRef: RefObject<HTMLDivElement | null>;
spaceBtnRef: RefObject<HTMLButtonElement | null>;
kbMenuRef: RefObject<HTMLDivElement | null>;
@@ -180,15 +149,12 @@ export default memo(function ChatComposer({
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>;
knowledgeBases: KnowledgeBase[];
llmOptions: LLMOption[];
activeLLMDefault: LLMSelection | null;
@@ -209,20 +175,11 @@ export default memo(function ChatComposer({
selectedMemoryFiles: SpaceMemoryFile[];
selectedKnowledgeBases: string[];
isStreaming: boolean;
- isResearchMode: boolean;
- isMathAnimatorMode: boolean;
isVisualizeMode: 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`.
+ * True when the active capability (e.g. Quiz / Visualize / Research)
+ * requires explicit configuration before sending. When true, `canSend`
+ * is gated on `capabilityConfigConfirmed`.
*/
capabilityNeedsConfig: boolean;
capabilityConfigConfirmed: boolean;
@@ -233,12 +190,9 @@ export default memo(function ChatComposer({
*/
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;
onSetKbMenuOpen: (open: boolean | ((prev: boolean) => boolean)) => void;
- onToggleAutoCap: (cap: string) => void;
onToggleKB: (name: string) => void;
onSelectLLM: (selection: LLMSelection | null) => void;
onSelectNotebookPicker: () => void;
@@ -247,11 +201,9 @@ export default memo(function ChatComposer({
onSelectQuestionBankPicker: () => void;
onSelectSkillsPicker: () => void;
onSelectMemoryPicker: () => void;
- onToggleTool: (tool: ToolDef["name"]) => void;
onToggleSkill: (skill: string) => void;
onSetSkillsAuto: (auto: boolean) => void;
onToggleMemoryFile: (file: SpaceMemoryFile) => void;
- onToggleResearchSource: (source: ResearchSource) => void;
onSend: (content: string) => void;
onRemoveAttachment: (index: number) => void;
onPreviewAttachment?: (index: number) => void;
@@ -267,6 +219,15 @@ export default memo(function ChatComposer({
onAddFiles: (files: File[]) => void;
onSelectCapability: (value: string) => void;
onCancelStreaming: () => void;
+ /**
+ * Optional ref the composer writes its ``prefillInput`` function into
+ * once mounted, so the message-list side (specifically
+ * ``AskUserOptions`` chips) can drop a string into the textarea
+ * without owning the composer's imperative handle directly.
+ */
+ prefillInputRef?: React.MutableRefObject<((text: string) => void) | null>;
+ /** Override the composer placeholder (e.g. quiz follow-up). */
+ inputPlaceholder?: string;
}) {
const { t } = useTranslation();
const CapIcon = activeCap.icon;
@@ -276,6 +237,16 @@ export default memo(function ChatComposer({
const inputHandleRef = useRef<ComposerInputHandle>(null);
const fileInputRef = useRef<HTMLInputElement>(null);
+ useEffect(() => {
+ if (!prefillInputRef) return;
+ prefillInputRef.current = (text: string) => {
+ inputHandleRef.current?.setValue(text);
+ };
+ return () => {
+ if (prefillInputRef) prefillInputRef.current = null;
+ };
+ }, [prefillInputRef]);
+
// 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
@@ -347,8 +318,7 @@ export default memo(function ChatComposer({
// 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 isConfigBlocked = capabilityNeedsConfig && !capabilityConfigConfirmed;
const canSend =
(hasContent || hasReferences) && !isStreaming && !isConfigBlocked;
@@ -387,7 +357,10 @@ export default memo(function ChatComposer({
return (
<div
ref={composerRef}
- className={`relative z-20 mx-auto w-full shrink-0 pb-5 ${hasMessages ? "pt-1" : ""}`}
+ className={`relative z-20 mx-auto w-full shrink-0 pb-5 ${hasMessages ? "pt-1 max-w-[960px]" : "max-w-[720px]"}`}
+ style={{
+ transition: "max-width 650ms cubic-bezier(0.16, 1, 0.3, 1)",
+ }}
>
{hasMessages && (
<div className="pointer-events-none absolute inset-x-0 top-0 h-6 bg-gradient-to-b from-transparent to-[var(--background)]/72" />
@@ -395,10 +368,10 @@ export default memo(function ChatComposer({
<div className="relative">
<div
- className={`relative rounded-2xl border bg-[var(--card)] shadow-[0_1px_8px_rgba(0,0,0,0.03)] transition-colors ${
+ className={`relative rounded-[26px] border bg-[var(--card)] shadow-[0_1px_2px_rgba(0,0,0,0.025),0_10px_28px_-10px_rgba(0,0,0,0.08)] transition-colors ${
dragging
? "border-[var(--primary)] bg-[var(--primary)]/[0.03]"
- : "border-[var(--border)]"
+ : "border-[var(--border)]/55"
}`}
onDragEnter={onDragEnter}
onDragLeave={onDragLeave}
@@ -407,7 +380,7 @@ export default memo(function ChatComposer({
data-drag-counter={dragCounter.current}
>
{dragging && (
- <div className="pointer-events-none absolute inset-0 z-10 flex items-center justify-center rounded-2xl border-2 border-dashed border-[var(--primary)]/50 bg-[var(--primary)]/[0.04]">
+ <div className="pointer-events-none absolute inset-0 z-10 flex items-center justify-center rounded-[26px] border-2 border-dashed border-[var(--primary)]/50 bg-[var(--primary)]/[0.04]">
<div className="flex flex-col items-center gap-1 text-[var(--primary)]">
<Paperclip size={22} strokeWidth={1.6} />
<span className="text-[13px] font-medium">
@@ -454,7 +427,6 @@ export default memo(function ChatComposer({
<ComposerInput
ref={inputHandleRef}
textareaRef={textareaRef}
- isMathAnimatorMode={isMathAnimatorMode}
isVisualizeMode={isVisualizeMode}
canSendEmpty={hasReferences}
onSend={doSend}
@@ -467,6 +439,8 @@ export default memo(function ChatComposer({
onSelectQuestionBankPicker={onSelectQuestionBankPicker}
onSelectSkillsPicker={onSelectSkillsPicker}
onSelectMemoryPicker={onSelectMemoryPicker}
+ placeholder={inputPlaceholder}
+ minHeight={hasMessages ? 28 : 88}
/>
{!!attachments.length && (
@@ -612,22 +586,9 @@ export default memo(function ChatComposer({
}`}
>
<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>
- )}
- </>
+ <CapIcon size={15} strokeWidth={1.7} className="shrink-0" />
+ {composerCompact ? null : (
+ <span className="truncate">{t(activeCap.label)}</span>
)}
</span>
<ChevronDown
@@ -642,216 +603,43 @@ export default memo(function ChatComposer({
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>
+ {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>
- {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 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)]" />
+ ) : null}
+ </button>
+ );
+ })}
</div>
)}
</div>
<div className="flex min-w-0 flex-1 items-center gap-1">
- {isResearchMode ? (
- <div className="relative flex items-center gap-0.5">
- <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} />
- {composerCompact ? null : t("Sources")}
- <ChevronDown
- size={10}
- className={`transition-transform ${toolMenuOpen ? "rotate-180" : ""}`}
- />
- </button>
- {researchConfigSources.length > 0 && (
- <div className="flex items-center gap-[3px] overflow-hidden">
- {researchSources
- .filter((rs) =>
- researchConfigSources.includes(rs.name),
- )
- .map((rs, i) => (
- <span
- key={rs.name}
- className="shrink-0 text-[10px] text-[var(--muted-foreground)]/35"
- >
- {i > 0 && (
- <span className="text-[12px] leading-none">
- ·
- </span>
- )}
- {t(rs.label)}
- </span>
- ))}
- </div>
- )}
- {toolMenuOpen && (
- <div
- ref={toolMenuRef}
- 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 = researchConfigSources.includes(
- source.name,
- );
- const Icon = source.icon;
- return (
- <button
- key={source.name}
- onClick={() =>
- onToggleResearchSource(source.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`}
- >
- <Icon size={13} strokeWidth={1.7} />
- <span className="flex-1 font-medium">
- {t(source.label)}
- </span>
- {active && (
- <div className="h-1.5 w-1.5 rounded-full bg-[var(--primary)]" />
- )}
- </button>
- );
- })}
- </div>
- )}
- </div>
- ) : visibleTools.length > 0 ? (
- <div className="relative flex items-center gap-0.5">
- <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)]"
- >
- <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>
- {toolMenuOpen && (
- <div
- ref={toolMenuRef}
- 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"
- >
- {visibleTools.map((tool) => {
- const active = selectedTools.has(tool.name);
- const Icon = tool.icon;
- return (
- <button
- key={tool.name}
- onClick={() => onToggleTool(tool.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`}
- >
- <Icon size={13} strokeWidth={1.7} />
- <span className="flex-1 font-medium">
- {t(tool.label)}
- </span>
- {active && (
- <div className="h-1.5 w-1.5 rounded-full bg-[var(--primary)]" />
- )}
- </button>
- );
- })}
- </div>
- )}
- </div>
- ) : null}
-
<button
type="button"
onClick={handlePickFiles}
@@ -863,7 +651,7 @@ export default memo(function ChatComposer({
<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)]">
+ <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-[var(--primary-foreground)] shadow-[0_1px_3px_color-mix(in_srgb,var(--primary)_35%,transparent)] ring-[1.5px] ring-[var(--card)]">
{attachments.length}
</span>
)}
@@ -891,7 +679,7 @@ export default memo(function ChatComposer({
<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)]">
+ <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-[var(--primary-foreground)] shadow-[0_1px_3px_color-mix(in_srgb,var(--primary)_35%,transparent)] ring-[1.5px] ring-[var(--card)]">
{selectedKnowledgeBases.length}
</span>
)}
@@ -946,7 +734,7 @@ export default memo(function ChatComposer({
<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)]">
+ <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-[var(--primary-foreground)] shadow-[0_1px_3px_color-mix(in_srgb,var(--primary)_35%,transparent)] ring-[1.5px] ring-[var(--card)]">
{spaceSelectionCount}
</span>
)}
@@ -995,7 +783,7 @@ export default memo(function ChatComposer({
<button
type="button"
onClick={onCancelStreaming}
- className="group relative inline-flex h-[29px] w-[29px] shrink-0 items-center justify-center rounded-full bg-[var(--primary)] text-white shadow-[0_4px_12px_color-mix(in_srgb,var(--primary)_18%,transparent)] transition-[background-color,box-shadow] hover:bg-[var(--primary)]/90 hover:shadow-[0_6px_16px_color-mix(in_srgb,var(--primary)_28%,transparent)]"
+ className="group relative inline-flex h-[29px] w-[29px] shrink-0 items-center justify-center rounded-full bg-[var(--primary)] text-[var(--primary-foreground)] shadow-[0_4px_12px_color-mix(in_srgb,var(--primary)_18%,transparent)] transition-[background-color,box-shadow] hover:bg-[var(--primary)]/90 hover:shadow-[0_6px_16px_color-mix(in_srgb,var(--primary)_28%,transparent)]"
aria-label={t("Stop generating")}
title={t("Stop generating")}
>
@@ -1021,9 +809,7 @@ export default memo(function ChatComposer({
<button
type="button"
onClick={handleManualSend}
- disabled={
- !(hasContent || hasReferences) || isStreaming
- }
+ disabled={!(hasContent || hasReferences) || isStreaming}
title={
isConfigBlocked
? t("Confirm settings on the right to send.")
@@ -1032,8 +818,8 @@ export default memo(function ChatComposer({
aria-disabled={!canSend}
className={`rounded-full p-[7px] shadow-[0_4px_12px_color-mix(in_srgb,var(--primary)_15%,transparent)] transition-[transform,opacity,box-shadow] disabled:opacity-25 disabled:shadow-none ${
isConfigBlocked
- ? "bg-[var(--muted-foreground)]/30 text-white hover:bg-[var(--muted-foreground)]/45"
- : "bg-[var(--primary)] text-white hover:shadow-[0_6px_16px_color-mix(in_srgb,var(--primary)_22%,transparent)]"
+ ? "bg-[var(--muted-foreground)]/30 text-[var(--primary-foreground)] hover:bg-[var(--muted-foreground)]/45"
+ : "bg-[var(--primary)] text-[var(--primary-foreground)] hover:shadow-[0_6px_16px_color-mix(in_srgb,var(--primary)_22%,transparent)]"
}`}
aria-label={t("Send")}
>
diff --git a/web/components/chat/home/ChatMessages.tsx b/web/components/chat/home/ChatMessages.tsx
index 9b0aedcb3..27194f2cb 100644
--- a/web/components/chat/home/ChatMessages.tsx
+++ b/web/components/chat/home/ChatMessages.tsx
@@ -1,10 +1,11 @@
"use client";
import dynamic from "next/dynamic";
-import { memo, useCallback, useMemo, useState } from "react";
+import { memo, useCallback, useEffect, useMemo, useRef, useState } from "react";
import {
BookOpen,
Brain,
+ Check,
ChevronLeft,
ChevronRight,
ClipboardList,
@@ -30,17 +31,21 @@ import type {
import { apiUrl } from "@/lib/api";
import { docIconFor } from "@/lib/doc-attachments";
import { extractMathAnimatorResult } from "@/lib/math-animator-types";
-import { extractQuizQuestions } from "@/lib/quiz-types";
+import {
+ extractQuizQuestions,
+ extractStreamingQuizQuestions,
+} from "@/lib/quiz-types";
import { extractVisualizeResult } from "@/lib/visualize-types";
import type { StreamEvent } from "@/lib/unified-ws";
import { hasVisibleMarkdownContent } from "@/lib/markdown-display";
import type { SelectedBookReference } from "@/lib/book-references";
-import {
- buildVisiblePath,
- type SiblingInfo,
-} from "@/lib/message-branches";
+import { buildVisiblePath, type SiblingInfo } from "@/lib/message-branches";
import type { SpaceMemoryFile } from "@/lib/space-items";
-import AutoModeAssistantMessage from "./AutoModeAssistantMessage";
+import {
+ AskUserOptions,
+ extractAskUserPayload,
+ extractMessageSegments,
+} from "./AskUserOptions";
import { TraceSurface } from "./TracePanels";
const MathAnimatorViewer = dynamic(
@@ -114,24 +119,39 @@ const AssistantMessage = memo(function AssistantMessage({
language,
onConfirmOutline,
onAnswerNow,
- onRetry,
- onSwitchToManual,
+ onSubmitUserReply,
+ researchRequestSnapshot,
}: {
msg: { content: string; capability?: string; events?: StreamEvent[] };
isStreaming?: boolean;
outlineStatus?: "editing" | "researching" | "done";
sessionId?: string | null;
language?: string;
+ researchRequestSnapshot?: MessageRequestSnapshot | null;
onConfirmOutline?: (
outline: Array<{ title: string; overview: string }>,
topic: string,
researchConfig?: Record<string, unknown> | null,
+ requestSnapshot?: MessageRequestSnapshot | null,
) => void;
onAnswerNow?: () => void;
- onRetry?: () => void;
- onSwitchToManual?: () => void;
+ /**
+ * Submit a reply for a turn that is paused on ``ask_user``. Wired
+ * through from the page so the card's option-buttons / free-text
+ * input can deliver the user's selection back to the backend over
+ * the unified WebSocket. Triggers a same-turn resume (no new user
+ * bubble). Accepts either a flat string (legacy single-question) or
+ * a structured object with per-question ``answers`` (v2 path).
+ */
+ onSubmitUserReply?: (
+ reply:
+ | string
+ | {
+ text?: string;
+ answers?: Array<{ questionId: string; text: string }>;
+ },
+ ) => void;
}) {
- const isAutoTurn = msg.capability === "auto";
const events = useMemo(() => msg.events ?? [], [msg.events]);
const resultEvent = useMemo(
() => msg.events?.find((event) => event.type === "result") ?? null,
@@ -156,9 +176,14 @@ const AssistantMessage = memo(function AssistantMessage({
}, [msg.capability, resultEvent]);
const quizQuestions = useMemo(() => {
- if (msg.capability !== "deep_question" || !resultEvent) return null;
- return extractQuizQuestions(resultEvent.metadata);
- }, [msg.capability, resultEvent]);
+ if (msg.capability !== "deep_question") return null;
+ // Once the final result event lands, it's authoritative — it carries
+ // the canonical summary.results[]. Until then, accumulate questions
+ // from the live ``quiz_question_emitted`` content events so the
+ // QuizViewer can render each card the moment it's generated.
+ if (resultEvent) return extractQuizQuestions(resultEvent.metadata);
+ return extractStreamingQuizQuestions(msg.events ?? []);
+ }, [msg.capability, msg.events, resultEvent]);
const mathAnimatorResult = useMemo(() => {
if (msg.capability !== "math_animator" || !resultEvent) return null;
@@ -170,30 +195,37 @@ 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}
- />
- </>
- );
- }
+ // Detect the ``ask_user`` terminator payload: when the assistant turn
+ // ended via the ``ask_user`` tool, this is the question the user is
+ // expected to answer next. Render option chips below the message.
+ const askUserPayload = useMemo(
+ () => extractAskUserPayload(msg.events),
+ [msg.events],
+ );
+
+ // Interleaved segments for the default chat surface — text emitted
+ // before the ask_user call renders above the card; text emitted by
+ // the resumed iteration renders below it. Only walked when this
+ // message will actually render through the default branch (the
+ // research / quiz / animator / visualize branches have their own
+ // layout and pin the card elsewhere).
+ const useInlineAskUserSegments =
+ !outlinePreview &&
+ !mathAnimatorResult &&
+ !visualizeResult &&
+ !(quizQuestions && quizQuestions.length > 0);
+ const messageSegments = useMemo(
+ () => (useInlineAskUserSegments ? extractMessageSegments(msg.events) : []),
+ [useInlineAskUserSegments, msg.events],
+ );
+ const hasInlineAskUser =
+ useInlineAskUserSegments &&
+ messageSegments.some((seg) => seg.kind === "ask_user");
+
+ const researchInProgress =
+ outlineStatus === "researching" || outlineStatus === "done";
+ const showResearchBody =
+ Boolean(outlinePreview) && researchInProgress && Boolean(msg.content);
return (
<>
@@ -206,31 +238,101 @@ const AssistantMessage = memo(function AssistantMessage({
<AnswerNowRow onAnswerNow={onAnswerNow} />
) : null}
{outlinePreview && outlinePreview.sub_topics.length > 0 ? (
- <ResearchOutlineEditor
- outline={outlinePreview.sub_topics}
- topic={outlinePreview.topic}
- onConfirm={(items) =>
- onConfirmOutline?.(
- items,
- outlinePreview.topic,
- outlinePreview.research_config,
- )
- }
- status={outlineStatus}
- />
+ <>
+ {/* Layout for the merged research bubble:
+ 1. trace cards (above, via TraceSurface)
+ 2. ask_user Q&A summary (collapsible once research starts)
+ 3. Outline editor (auto-collapses once locked)
+ 4. Final report body (only after research is underway)
+ The Q&A intentionally sits ABOVE the outline so the user
+ sees the path that produced the outline before the outline
+ itself. */}
+ {askUserPayload ? (
+ <AskUserOptions
+ data={askUserPayload}
+ onSubmit={(reply) => {
+ if (!onSubmitUserReply) return;
+ onSubmitUserReply(reply);
+ }}
+ collapsible={researchInProgress}
+ defaultCollapsed={researchInProgress}
+ />
+ ) : null}
+ <ResearchOutlineEditor
+ outline={outlinePreview.sub_topics}
+ topic={outlinePreview.topic}
+ onConfirm={(items) =>
+ onConfirmOutline?.(
+ items,
+ outlinePreview.topic,
+ outlinePreview.research_config,
+ researchRequestSnapshot,
+ )
+ }
+ status={outlineStatus}
+ />
+ {showResearchBody ? (
+ <AssistantResponse content={msg.content} />
+ ) : null}
+ </>
) : mathAnimatorResult ? (
<MathAnimatorViewer result={mathAnimatorResult} />
) : visualizeResult ? (
<VisualizationViewer result={visualizeResult} />
) : quizQuestions && quizQuestions.length > 0 ? (
- <QuizViewer
- questions={quizQuestions}
- sessionId={sessionId}
- language={language}
- />
+ <>
+ {/* Phase 1's FINISH preface (the "I researched X, now let me
+ quiz you on Y" sentence the user watched stream in) rides
+ along ABOVE the quiz card. Without this, the streamed text
+ vanishes from the bubble the moment the first card appears
+ because the branch above is mutually exclusive with
+ <AssistantResponse>. The body is already free of the
+ per-question markdown — the pipeline trims that out of
+ ``msg.content`` since the QuizViewer renders the cards
+ themselves. */}
+ {msg.content ? <AssistantResponse content={msg.content} /> : null}
+ <QuizViewer
+ questions={quizQuestions}
+ sessionId={sessionId}
+ turnId={resultEvent?.turn_id ?? null}
+ language={language}
+ />
+ </>
+ ) : hasInlineAskUser ? (
+ // Default chat surface with one or more ask_user calls: render
+ // text and cards in the exact order they were streamed, so the
+ // pre-ask_user narration sits above the card and the resumed
+ // iteration's text sits below.
+ messageSegments.map((seg) =>
+ seg.kind === "text" ? (
+ <AssistantResponse key={seg.key} content={seg.text} />
+ ) : (
+ <AskUserOptions
+ key={seg.key}
+ data={seg.data}
+ onSubmit={(reply) => {
+ if (!onSubmitUserReply) return;
+ onSubmitUserReply(reply);
+ }}
+ />
+ ),
+ )
) : (
<AssistantResponse content={msg.content} />
)}
+ {/* Non-default branches (quiz, math animator, visualize) keep
+ ask_user below the body. The default branch inlines the card
+ via ``messageSegments``; the research branch renders its own
+ card above the outline editor — both skip this fallback. */}
+ {!outlinePreview && !hasInlineAskUser && askUserPayload ? (
+ <AskUserOptions
+ data={askUserPayload}
+ onSubmit={(reply) => {
+ if (!onSubmitUserReply) return;
+ onSubmitUserReply(reply);
+ }}
+ />
+ ) : null}
</>
);
});
@@ -342,6 +444,52 @@ function RoughActionButton({
);
}
+function CopyActionButton({
+ content,
+ onCopy,
+}: {
+ content: string;
+ onCopy: (content: string) => void | Promise<void>;
+}) {
+ const { t } = useTranslation();
+ const [copied, setCopied] = useState(false);
+ const timerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
+
+ useEffect(() => {
+ return () => {
+ if (timerRef.current) clearTimeout(timerRef.current);
+ };
+ }, []);
+
+ const handleClick = useCallback(() => {
+ void Promise.resolve(onCopy(content)).then(() => {
+ setCopied(true);
+ if (timerRef.current) clearTimeout(timerRef.current);
+ timerRef.current = setTimeout(() => setCopied(false), 1600);
+ });
+ }, [content, onCopy]);
+
+ return (
+ <button
+ type="button"
+ onClick={handleClick}
+ aria-live="polite"
+ className={`inline-flex items-center gap-1 px-0.5 py-0.5 text-[11px] transition-colors ${
+ copied
+ ? "text-[var(--primary)]"
+ : "text-[var(--muted-foreground)] hover:text-[var(--foreground)]"
+ }`}
+ >
+ {copied ? (
+ <Check size={11} strokeWidth={2} />
+ ) : (
+ <Copy size={11} strokeWidth={1.5} />
+ )}
+ <span>{copied ? t("Copied") : t("Copy")}</span>
+ </button>
+ );
+}
+
function BranchNavigator({
info,
onSwitch,
@@ -580,86 +728,86 @@ const UserMessage = memo(function UserMessage({
</div>
</div>
) : (
- <div className="rounded-2xl bg-[var(--secondary)] px-4 py-2.5 text-[14px] leading-relaxed text-[var(--foreground)] shadow-sm">
- {(() => {
- const snap = msg.requestSnapshot;
- const hasNotebook = Boolean(snap?.notebookReferences?.length);
- const hasBooks = Boolean(snap?.bookReferences?.length);
- const hasHistory = Boolean(snap?.historyReferences?.length);
- const hasQuestions = Boolean(
- snap?.questionNotebookReferences?.length,
- );
- const hasSkills = Boolean(snap?.skills?.length);
- const hasMemory = Boolean(snap?.memoryReferences?.length);
- if (
- !hasNotebook &&
- !hasBooks &&
- !hasHistory &&
- !hasQuestions &&
- !hasSkills &&
- !hasMemory
- )
- return null;
- return (
- <div className="mb-2 flex flex-wrap gap-1.5">
- {snap?.notebookReferences?.map((ref) => (
- <span
- key={ref.notebook_id}
- className="inline-flex items-center gap-1.5 rounded-md border border-[var(--border)] bg-[var(--background)]/60 px-2 py-1 text-[11px] font-medium text-[var(--muted-foreground)]"
- >
- <BookOpen size={11} strokeWidth={1.8} />
- {t("Notebook")} · {ref.record_ids.length} {t("records")}
- </span>
- ))}
- {snap?.bookReferences?.map((ref) => (
- <span
- key={ref.book_id}
- className="inline-flex items-center gap-1.5 rounded-md border border-[var(--border)] bg-[var(--background)]/60 px-2 py-1 text-[11px] font-medium text-[var(--muted-foreground)]"
- >
- <BookOpen size={11} strokeWidth={1.8} />
- {t("Book")} · {ref.page_ids.length} {t("chapters")}
- </span>
- ))}
- {snap?.historyReferences?.map((sid) => (
- <span
- key={sid}
- className="inline-flex items-center gap-1.5 rounded-md border border-[var(--border)] bg-[var(--background)]/60 px-2 py-1 text-[11px] font-medium text-[var(--muted-foreground)]"
- >
- <MessageSquare size={11} strokeWidth={1.8} />
- {t("Chat History")}
- </span>
- ))}
- {hasQuestions && (
- <span className="inline-flex items-center gap-1.5 rounded-md border border-[var(--border)] bg-[var(--background)]/60 px-2 py-1 text-[11px] font-medium text-[var(--muted-foreground)]">
- <ClipboardList size={11} strokeWidth={1.8} />
- {t("Question Bank")} ·{" "}
- {snap?.questionNotebookReferences?.length} {t("items")}
- </span>
- )}
- {snap?.skills?.map((skill) => (
- <span
- key={skill}
- className="inline-flex items-center gap-1.5 rounded-md border border-[var(--border)] bg-[var(--background)]/60 px-2 py-1 text-[11px] font-medium text-[var(--muted-foreground)]"
- >
- <Wand2 size={11} strokeWidth={1.8} />
- {skill === "auto" ? t("Skills Auto") : skill}
- </span>
- ))}
- {snap?.memoryReferences?.map((file) => (
- <span
- key={file}
- className="inline-flex items-center gap-1.5 rounded-md border border-[var(--border)] bg-[var(--background)]/60 px-2 py-1 text-[11px] font-medium text-[var(--muted-foreground)]"
- >
- <Brain size={11} strokeWidth={1.8} />
- {t("Memory")} ·{" "}
- {file === "summary" ? t("Summary") : t("Profile")}
- </span>
- ))}
- </div>
- );
- })()}
- <div className="whitespace-pre-wrap">{msg.content}</div>
- </div>
+ <div className="rounded-2xl bg-[var(--secondary)] px-4 py-2.5 text-[14px] leading-relaxed text-[var(--foreground)] shadow-sm">
+ {(() => {
+ const snap = msg.requestSnapshot;
+ const hasNotebook = Boolean(snap?.notebookReferences?.length);
+ const hasBooks = Boolean(snap?.bookReferences?.length);
+ const hasHistory = Boolean(snap?.historyReferences?.length);
+ const hasQuestions = Boolean(
+ snap?.questionNotebookReferences?.length,
+ );
+ const hasSkills = Boolean(snap?.skills?.length);
+ const hasMemory = Boolean(snap?.memoryReferences?.length);
+ if (
+ !hasNotebook &&
+ !hasBooks &&
+ !hasHistory &&
+ !hasQuestions &&
+ !hasSkills &&
+ !hasMemory
+ )
+ return null;
+ return (
+ <div className="mb-2 flex flex-wrap gap-1.5">
+ {snap?.notebookReferences?.map((ref) => (
+ <span
+ key={ref.notebook_id}
+ className="inline-flex items-center gap-1.5 rounded-md border border-[var(--border)] bg-[var(--background)]/60 px-2 py-1 text-[11px] font-medium text-[var(--muted-foreground)]"
+ >
+ <BookOpen size={11} strokeWidth={1.8} />
+ {t("Notebook")} · {ref.record_ids.length} {t("records")}
+ </span>
+ ))}
+ {snap?.bookReferences?.map((ref) => (
+ <span
+ key={ref.book_id}
+ className="inline-flex items-center gap-1.5 rounded-md border border-[var(--border)] bg-[var(--background)]/60 px-2 py-1 text-[11px] font-medium text-[var(--muted-foreground)]"
+ >
+ <BookOpen size={11} strokeWidth={1.8} />
+ {t("Book")} · {ref.page_ids.length} {t("chapters")}
+ </span>
+ ))}
+ {snap?.historyReferences?.map((sid) => (
+ <span
+ key={sid}
+ className="inline-flex items-center gap-1.5 rounded-md border border-[var(--border)] bg-[var(--background)]/60 px-2 py-1 text-[11px] font-medium text-[var(--muted-foreground)]"
+ >
+ <MessageSquare size={11} strokeWidth={1.8} />
+ {t("Chat History")}
+ </span>
+ ))}
+ {hasQuestions && (
+ <span className="inline-flex items-center gap-1.5 rounded-md border border-[var(--border)] bg-[var(--background)]/60 px-2 py-1 text-[11px] font-medium text-[var(--muted-foreground)]">
+ <ClipboardList size={11} strokeWidth={1.8} />
+ {t("Question Bank")} ·{" "}
+ {snap?.questionNotebookReferences?.length} {t("items")}
+ </span>
+ )}
+ {snap?.skills?.map((skill) => (
+ <span
+ key={skill}
+ className="inline-flex items-center gap-1.5 rounded-md border border-[var(--border)] bg-[var(--background)]/60 px-2 py-1 text-[11px] font-medium text-[var(--muted-foreground)]"
+ >
+ <Wand2 size={11} strokeWidth={1.8} />
+ {skill === "auto" ? t("Skills Auto") : skill}
+ </span>
+ ))}
+ {snap?.memoryReferences?.map((file) => (
+ <span
+ key={file}
+ className="inline-flex items-center gap-1.5 rounded-md border border-[var(--border)] bg-[var(--background)]/60 px-2 py-1 text-[11px] font-medium text-[var(--muted-foreground)]"
+ >
+ <Brain size={11} strokeWidth={1.8} />
+ {t("Memory")} ·{" "}
+ {file === "summary" ? t("Summary") : t("Profile")}
+ </span>
+ ))}
+ </div>
+ );
+ })()}
+ <div className="whitespace-pre-wrap">{msg.content}</div>
+ </div>
)}
{!editing && (onCopy || canEdit || siblingInfo) && msg.content && (
<div className="flex h-5 items-center justify-end gap-2 opacity-0 transition-opacity group-hover:opacity-100 focus-within:opacity-100">
@@ -672,11 +820,7 @@ const UserMessage = memo(function UserMessage({
/>
)}
{onCopy && (
- <RoughActionButton
- icon={Copy}
- label={t("Copy")}
- onClick={() => void onCopy(msg.content)}
- />
+ <CopyActionButton content={msg.content} onCopy={onCopy} />
)}
{canEdit && (
<RoughActionButton
@@ -880,11 +1024,11 @@ export const ChatMessageList = memo(function ChatMessageList({
onRegenerateMessage,
onConfirmOutline,
onPreviewAttachment,
- onSwitchToManualMode,
onDeleteTurn,
selectedBranches,
onEditMessage,
onSwitchBranch,
+ onSubmitUserReply,
}: {
messages: ChatMessageItem[];
isStreaming: boolean;
@@ -900,17 +1044,30 @@ export const ChatMessageList = memo(function ChatMessageList({
outline: Array<{ title: string; overview: string }>,
topic: string,
researchConfig?: Record<string, unknown> | null,
+ requestSnapshot?: MessageRequestSnapshot | 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;
onDeleteTurn?: (messageId: number) => void;
/** Edit-branching: selected sibling at each branch point. */
selectedBranches?: Record<string, number>;
onEditMessage?: (messageId: number, newContent: string) => void;
onSwitchBranch?: (parentMessageId: number | null, childId: number) => void;
+ /**
+ * Deliver an ``ask_user`` reply back to the backend so the agentic
+ * loop resumes on the same turn. Forwarded into each
+ * ``AssistantMessage`` so the card UI rendered alongside the paused
+ * assistant bubble can submit selections / free-form text. Accepts
+ * either a string (legacy) or a structured object with per-question
+ * ``answers`` (v2).
+ */
+ onSubmitUserReply?: (
+ reply:
+ | string
+ | {
+ text?: string;
+ answers?: Array<{ questionId: string; text: string }>;
+ },
+ ) => void;
}) {
const { t } = useTranslation();
// Visible path: when no branching has happened the result is identical
@@ -921,6 +1078,58 @@ export const ChatMessageList = memo(function ChatMessageList({
() => buildVisiblePath(messages, selectedBranches),
[messages, selectedBranches],
);
+
+ // Deep-research two-turn merge.
+ //
+ // The capability runs in two BE turns: turn-1 emits rephrase +
+ // decompose + an outline-preview result; turn-2 (after the user
+ // confirms the outline) emits the research blocks + the final
+ // report. The user wants both turns to live in ONE assistant
+ // bubble so the rephrase trace, the Q&A summary, the (collapsed)
+ // outline editor, and the research / reporting traces are all
+ // visually contiguous instead of split across two bubbles.
+ //
+ // For each parent (outline-preview) msg with a followup
+ // deep_research msg, we synthesise a merged msg with:
+ //
+ // * events — parent.events ++ followup.events (preserving order
+ // so TraceSurface's call_id grouping keeps working).
+ // * content — followup.content (the report). The parent's
+ // rephrase-FINISH content is already represented inside the
+ // rephrase trace card, so concatenating again would duplicate
+ // the preface above the report.
+ //
+ // The followup is dropped from the visible row list so only the
+ // merged bubble renders.
+ const deepResearchMergeMap = useMemo(() => {
+ const map = new Map<
+ number,
+ { mergedEvents: StreamEvent[]; mergedContent: string }
+ >();
+ const followupIndices = new Set<number>();
+ for (let i = 0; i < visibleMessages.length; i++) {
+ const msg = visibleMessages[i];
+ if (msg.role !== "assistant" || msg.capability !== "deep_research")
+ continue;
+ const resultEv = msg.events?.find((e) => e.type === "result");
+ const meta = resultEv?.metadata as Record<string, unknown> | undefined;
+ if (!meta?.outline_preview) continue;
+ const followupIdx = visibleMessages
+ .slice(i + 1)
+ .findIndex(
+ (m) => m.role === "assistant" && m.capability === "deep_research",
+ );
+ if (followupIdx === -1) continue;
+ const absoluteFollowupIdx = i + 1 + followupIdx;
+ const followup = visibleMessages[absoluteFollowupIdx];
+ const mergedEvents = [...(msg.events ?? []), ...(followup.events ?? [])];
+ const mergedContent = followup.content || msg.content;
+ map.set(i, { mergedEvents, mergedContent });
+ followupIndices.add(absoluteFollowupIdx);
+ }
+ return { mergedByParent: map, followupIndices };
+ }, [visibleMessages]);
+
const outlineStatusByIndex = useMemo(() => {
const map = new Map<number, "editing" | "researching" | "done">();
for (let i = 0; i < visibleMessages.length; i++) {
@@ -930,24 +1139,22 @@ export const ChatMessageList = memo(function ChatMessageList({
const resultEv = msg.events?.find((e) => e.type === "result");
const meta = resultEv?.metadata as Record<string, unknown> | undefined;
if (!meta?.outline_preview) continue;
- const hasFollowup = visibleMessages
+ const followup = visibleMessages
.slice(i + 1)
- .some(
+ .find(
(m) => m.role === "assistant" && m.capability === "deep_research",
);
- if (hasFollowup) {
- const followup = visibleMessages
- .slice(i + 1)
- .find(
- (m) => m.role === "assistant" && m.capability === "deep_research",
- );
- const followupResult = followup?.events?.find(
+ if (followup) {
+ const followupResult = followup.events?.find(
(e) => e.type === "result",
);
map.set(i, followupResult ? "done" : "researching");
- } else if (isStreaming) {
- map.set(i, "researching");
} else {
+ // The first deep_research turn only plans/rephrases/decomposes and
+ // returns an outline preview. While that turn is still flushing
+ // post-result events, the outline must already be editable; only the
+ // hidden follow-up turn created by "Start Research" means research is
+ // actually underway.
map.set(i, "editing");
}
}
@@ -960,11 +1167,28 @@ export const ChatMessageList = memo(function ChatMessageList({
// addition to the hydration-time filter in UnifiedChatContext.
return visibleMessages
.map((msg, index) => ({ msg, originalIndex: index }))
- .filter(({ msg }) => msg.role !== "system")
+ .filter(({ msg, originalIndex }) => {
+ if (msg.role === "system") return false;
+ // Drop deep_research followup msgs — their events were merged
+ // into the parent (outline-preview) bubble.
+ if (deepResearchMergeMap.followupIndices.has(originalIndex))
+ return false;
+ return true;
+ })
.map(({ msg, originalIndex }) => {
- if (msg.role === "user") {
+ // Splice in the merged event stream when this row owns a
+ // deep_research two-turn pair.
+ const merged = deepResearchMergeMap.mergedByParent.get(originalIndex);
+ const effectiveMsg: ChatMessageItem = merged
+ ? {
+ ...msg,
+ events: merged.mergedEvents,
+ content: merged.mergedContent,
+ }
+ : msg;
+ if (effectiveMsg.role === "user") {
return {
- msg,
+ msg: effectiveMsg,
originalIndex,
pairedUserMessage: null as ChatMessageItem | null,
};
@@ -973,16 +1197,17 @@ export const ChatMessageList = memo(function ChatMessageList({
[...visibleMessages.slice(0, originalIndex)]
.reverse()
.find((previous) => previous.role === "user") ?? null;
- return { msg, originalIndex, pairedUserMessage };
+ return { msg: effectiveMsg, originalIndex, pairedUserMessage };
});
- }, [visibleMessages]);
+ }, [visibleMessages, deepResearchMergeMap]);
- const lastAssistantIndex = useMemo(() => {
- for (let idx = visibleMessages.length - 1; idx >= 0; idx -= 1) {
- if (visibleMessages[idx].role === "assistant") return idx;
+ const lastRenderedAssistantIndex = useMemo(() => {
+ for (let idx = messageRows.length - 1; idx >= 0; idx -= 1) {
+ if (messageRows[idx].msg.role === "assistant")
+ return messageRows[idx].originalIndex;
}
return -1;
- }, [visibleMessages]);
+ }, [messageRows]);
return (
<>
@@ -1007,10 +1232,10 @@ export const ChatMessageList = memo(function ChatMessageList({
}
const isActiveAssistant =
- isStreaming && i === visibleMessages.length - 1;
+ isStreaming && i === lastRenderedAssistantIndex;
const msgDone = !isActiveAssistant;
const showActions = msgDone && hasVisibleMarkdownContent(msg.content);
- const isLastAssistant = i === lastAssistantIndex;
+ const isLastAssistant = i === lastRenderedAssistantIndex;
const showRegenerate =
showActions &&
!isStreaming &&
@@ -1027,8 +1252,18 @@ export const ChatMessageList = memo(function ChatMessageList({
// The "Answer now" affordance lives inside the trace panel for the
// currently-streaming assistant turn. We hand the panel a thin
// closure so it does not need to know about MessageRequestSnapshot.
+ // Only enabled for the bare ``chat`` capability — solve / quiz /
+ // research run structured pipelines whose intermediate trace does
+ // not synthesize cleanly via the chat fast-path.
+ const capability =
+ pairedUserMessage?.requestSnapshot?.capability ??
+ pairedUserMessage?.capability ??
+ "";
+ const answerNowAllowed = !capability || capability === "chat";
const handleTraceAnswerNow =
- isActiveAssistant && pairedUserMessage?.requestSnapshot
+ isActiveAssistant &&
+ pairedUserMessage?.requestSnapshot &&
+ answerNowAllowed
? () =>
onAnswerNow(pairedUserMessage.requestSnapshot, {
content: msg.content,
@@ -1064,18 +1299,19 @@ export const ChatMessageList = memo(function ChatMessageList({
language={language}
onConfirmOutline={onConfirmOutline}
onAnswerNow={handleTraceAnswerNow}
- onRetry={onRegenerateMessage}
- onSwitchToManual={onSwitchToManualMode}
+ onSubmitUserReply={onSubmitUserReply}
+ researchRequestSnapshot={
+ pairedUserMessage?.requestSnapshot ?? null
+ }
/>
{(showActions || costSummary || showDelete) && (
<div className="mt-2 flex items-center">
{(showActions || showDelete) && (
<div className="flex items-center gap-2">
{showActions && (
- <RoughActionButton
- icon={Copy}
- label={t("Copy")}
- onClick={() => void onCopyAssistantMessage(msg.content)}
+ <CopyActionButton
+ content={msg.content}
+ onCopy={onCopyAssistantMessage}
/>
)}
{showActions && showRegenerate && (
diff --git a/web/components/chat/home/ComposerInput.tsx b/web/components/chat/home/ComposerInput.tsx
index 6094fc37d..6a894ac8d 100644
--- a/web/components/chat/home/ComposerInput.tsx
+++ b/web/components/chat/home/ComposerInput.tsx
@@ -19,7 +19,6 @@ import { useAutoSizedTextarea } from "@/lib/use-auto-sized-textarea";
interface ComposerInputProps {
textareaRef: RefObject<HTMLTextAreaElement | null>;
- isMathAnimatorMode: boolean;
isVisualizeMode: boolean;
// When true, parent has attachments/references queued and will accept a
// send even if the text body is empty. Without this, Enter would silently
@@ -35,11 +34,29 @@ interface ComposerInputProps {
onSelectQuestionBankPicker: () => void;
onSelectSkillsPicker: () => void;
onSelectMemoryPicker: () => void;
+ /**
+ * Override the default placeholder. When unset, falls back to the
+ * main chat ("How can I help you today?") / visualize defaults.
+ */
+ placeholder?: string;
+ /**
+ * Minimum textarea height in pixels. The auto-sized hook grows the
+ * textarea past this as the user types. Bumped on the empty-state
+ * composer so the resting box looks inviting rather than crammed.
+ */
+ minHeight?: number;
}
export interface ComposerInputHandle {
clear: () => void;
getValue: () => string;
+ /**
+ * Programmatically replace the textarea contents (used by the
+ * ``AskUserOptions`` chip click handler — picks an option, prefills
+ * the composer, leaves it to the user to edit/send rather than
+ * auto-firing the message).
+ */
+ setValue: (value: string) => void;
}
export function shouldOpenAtPopup(value: string, cursorPos: number): boolean {
@@ -55,7 +72,6 @@ export const ComposerInput = memo(
forwardRef<ComposerInputHandle, ComposerInputProps>(function ComposerInput(
{
textareaRef,
- isMathAnimatorMode,
isVisualizeMode,
canSendEmpty,
onSend,
@@ -68,6 +84,8 @@ export const ComposerInput = memo(
onSelectQuestionBankPicker,
onSelectSkillsPicker,
onSelectMemoryPicker,
+ placeholder,
+ minHeight = 28,
},
ref,
) {
@@ -96,11 +114,25 @@ export const ComposerInput = memo(
onInputChange("");
},
getValue: () => inputRef.current,
+ setValue: (value: string) => {
+ const text = value ?? "";
+ setInputBoth(text);
+ onInputChange(text);
+ // Focus + move caret to the end so the user can immediately
+ // edit or press Enter to send.
+ const el = textareaRef.current;
+ if (el) {
+ requestAnimationFrame(() => {
+ el.focus();
+ el.setSelectionRange(text.length, text.length);
+ });
+ }
+ },
}),
- [setInputBoth, onInputChange],
+ [setInputBoth, onInputChange, textareaRef],
);
- useAutoSizedTextarea(textareaRef, input, { min: 28, max: 200 });
+ useAutoSizedTextarea(textareaRef, input, { min: minHeight, max: 200 });
const handleInputChange = useCallback(
(e: React.ChangeEvent<HTMLTextAreaElement>) => {
@@ -248,14 +280,15 @@ export const ComposerInput = memo(
maxLength={32000}
suppressHydrationWarning
placeholder={
- isMathAnimatorMode
- ? t("Describe the math animation or storyboard you want...")
- : isVisualizeMode
- ? t("Describe the chart or diagram you want to visualize...")
- : t("How can I help you today?")
+ placeholder ??
+ (isVisualizeMode
+ ? t(
+ "Describe the chart, diagram, or animation you want to visualize...",
+ )
+ : t("How can I help you today?"))
}
className="w-full resize-none overflow-hidden bg-transparent text-[15px] leading-relaxed text-[var(--foreground)] outline-none placeholder:text-[var(--muted-foreground)]"
- style={{ transition: "height 0.15s ease-out", minHeight: 28 }}
+ style={{ transition: "height 0.15s ease-out" }}
/>
</div>
);
diff --git a/web/components/chat/home/SessionActivityPanel.tsx b/web/components/chat/home/SessionActivityPanel.tsx
index 7232766fc..f9b0c1c6a 100644
--- a/web/components/chat/home/SessionActivityPanel.tsx
+++ b/web/components/chat/home/SessionActivityPanel.tsx
@@ -15,12 +15,7 @@
* for tools/KBs/Space/attachments that never showed up in this session.
*/
-import {
- memo,
- useEffect,
- useState,
- type ReactNode,
-} from "react";
+import { memo, useEffect, useState, type ReactNode } from "react";
import Link from "next/link";
import {
AtSign,
@@ -334,7 +329,7 @@ const SPACE_CATEGORIES: Record<string, SpaceCategoryDef> = {
},
memory: {
key: "memory",
- href: "/space/memory",
+ href: "/memory",
label: "Memory",
icon: Brain,
},
@@ -461,11 +456,7 @@ function ActivityBody({
return (
<div className="space-y-2.5">
{tools.length > 0 ? (
- <SectionCard
- icon={Wrench}
- title={t("Tools used")}
- count={tools.length}
- >
+ <SectionCard icon={Wrench} title={t("Tools used")} count={tools.length}>
<ul className="space-y-0.5 p-1.5">
{tools.map((tool) => (
<li
diff --git a/web/components/chat/home/SessionViewerPanel.tsx b/web/components/chat/home/SessionViewerPanel.tsx
index 3fd740318..b1e1011ee 100644
--- a/web/components/chat/home/SessionViewerPanel.tsx
+++ b/web/components/chat/home/SessionViewerPanel.tsx
@@ -27,10 +27,12 @@ import dynamic from "next/dynamic";
import {
AlertCircle,
ArrowRight,
+ Compass,
ExternalLink,
FileUp,
Globe,
Loader2,
+ MessageSquarePlus,
Paperclip,
X,
} from "lucide-react";
@@ -40,17 +42,37 @@ import {
resolveSourceUrl,
type FilePreviewSource,
} from "@/components/chat/preview/previewerFor";
+import QuizFollowupTabBody from "@/components/quiz/QuizFollowupTabBody";
+import type { QuizFollowupTabContext } from "@/context/QuizFollowupContext";
+import type { GeogebraTabPayload } from "@/context/GeogebraTabContext";
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 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 Geogebra = dynamic(() => import("@/components/Geogebra"), {
+ ssr: false,
+});
const ANIM_MS = 220;
@@ -60,11 +82,27 @@ const ANIM_MS = 220;
type ViewerTab =
| { kind: "file"; id: string; label: string; source: FilePreviewSource }
- | { kind: "web"; id: string; label: string; url: string };
+ | { kind: "web"; id: string; label: string; url: string }
+ | {
+ kind: "quiz-followup";
+ id: string;
+ label: string;
+ context: QuizFollowupTabContext;
+ }
+ | {
+ kind: "geogebra";
+ id: string;
+ label: string;
+ script: string;
+ };
export interface SessionViewerPanelHandle {
openFileTab(a: MessageAttachment): void;
openWebTab(url: string): void;
+ /** Opens (or focuses) the follow-up chat tab for a quiz question. */
+ openQuizFollowupTab(context: QuizFollowupTabContext): void;
+ /** Opens (or focuses) an interactive GeoGebra applet tab. */
+ openGeogebraTab(payload: GeogebraTabPayload): void;
}
interface SessionViewerPanelProps {
@@ -82,6 +120,14 @@ function webTabIdFor(url: string): string {
return `web:${url}`;
}
+function quizFollowupTabIdFor(questionKey: string): string {
+ return `quiz-followup:${questionKey}`;
+}
+
+function geogebraTabIdFor(payloadId: string): string {
+ return `geogebra:${payloadId}`;
+}
+
function hostnameFor(url: string): string {
try {
return new URL(url).hostname.replace(/^www\./, "");
@@ -172,10 +218,82 @@ function SessionViewerPanelInner(
[onAutoOpen],
);
+ const openQuizFollowupTab = useCallback(
+ (context: QuizFollowupTabContext) => {
+ setTabs((prev) => {
+ const id = quizFollowupTabIdFor(context.questionKey);
+ const existingIdx = prev.findIndex((tab) => tab.id === id);
+ // When the tab already exists, refresh its pinned context (answer
+ // text, judgment, etc.) since the learner may have updated it
+ // since the tab was first opened.
+ if (existingIdx >= 0) {
+ const refreshed: ViewerTab = {
+ kind: "quiz-followup",
+ id,
+ label: context.tabLabel,
+ context,
+ };
+ const next = [...prev];
+ next[existingIdx] = refreshed;
+ setActiveTabId(id);
+ return next;
+ }
+ const next: ViewerTab = {
+ kind: "quiz-followup",
+ id,
+ label: context.tabLabel,
+ context,
+ };
+ setActiveTabId(id);
+ return [...prev, next];
+ });
+ onAutoOpen();
+ },
+ [onAutoOpen],
+ );
+
+ const openGeogebraTab = useCallback(
+ (payload: GeogebraTabPayload) => {
+ setTabs((prev) => {
+ const id = geogebraTabIdFor(payload.id);
+ const existingIdx = prev.findIndex((tab) => tab.id === id);
+ if (existingIdx >= 0) {
+ // Refresh the script in case the assistant produced an updated
+ // version under the same payload id (e.g. a refined figure).
+ const refreshed: ViewerTab = {
+ kind: "geogebra",
+ id,
+ label: payload.title || "GeoGebra",
+ script: payload.script,
+ };
+ const next = [...prev];
+ next[existingIdx] = refreshed;
+ setActiveTabId(id);
+ return next;
+ }
+ const next: ViewerTab = {
+ kind: "geogebra",
+ id,
+ label: payload.title || "GeoGebra",
+ script: payload.script,
+ };
+ setActiveTabId(id);
+ return [...prev, next];
+ });
+ onAutoOpen();
+ },
+ [onAutoOpen],
+ );
+
useImperativeHandle(
ref,
- () => ({ openFileTab, openWebTab }),
- [openFileTab, openWebTab],
+ () => ({
+ openFileTab,
+ openWebTab,
+ openQuizFollowupTab,
+ openGeogebraTab,
+ }),
+ [openFileTab, openWebTab, openQuizFollowupTab, openGeogebraTab],
);
const closeTab = useCallback(
@@ -257,7 +375,14 @@ function SessionViewerPanelInner(
{activeTab?.kind === "file" ? (
<FileTabBody source={activeTab.source} />
) : activeTab?.kind === "web" ? (
- <WebTabBody url={activeTab.url} />
+ <WebTabBody key={activeTab.url} url={activeTab.url} />
+ ) : activeTab?.kind === "quiz-followup" ? (
+ <QuizFollowupTabBody
+ key={activeTab.context.questionKey}
+ context={activeTab.context}
+ />
+ ) : activeTab?.kind === "geogebra" ? (
+ <GeogebraTabBody key={activeTab.id} script={activeTab.script} />
) : (
<ViewerLanding
onOpenWebTab={openWebTab}
@@ -302,34 +427,44 @@ function TabBar({
<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;
+ const Icon =
+ tab.kind === "web"
+ ? Globe
+ : tab.kind === "quiz-followup"
+ ? MessageSquarePlus
+ : tab.kind === "geogebra"
+ ? Compass
+ : Paperclip;
return (
- <button
+ <div
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 ${
+ className={`group inline-flex max-w-[180px] shrink-0 items-center rounded-t-md 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}
+ <button
+ type="button"
+ onClick={() => onSelect(tab.id)}
+ className="inline-flex min-w-0 flex-1 items-center gap-1.5 py-1.5 pl-2.5 pr-1 text-left"
+ >
+ <Icon size={11} strokeWidth={1.9} className="shrink-0" />
+ <span className="truncate">{tab.label}</span>
+ </button>
+ <button
+ type="button"
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"
+ className="mr-1 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>
+ </button>
+ </div>
);
})}
</div>
@@ -413,7 +548,7 @@ function ViewerLanding({
<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"
+ className="inline-flex shrink-0 items-center gap-1 rounded-full bg-[var(--primary)] px-3 py-1 text-[11px] font-medium text-[var(--primary-foreground)] transition-opacity disabled:opacity-30"
aria-label={t("Open URL")}
>
<ArrowRight size={11} strokeWidth={2.2} />
@@ -452,10 +587,7 @@ function ViewerLanding({
function FileTabBody({ source }: { source: FilePreviewSource }) {
const { t } = useTranslation();
- const previewUrl = useMemo(
- () => resolveSourceUrl(source, apiUrl),
- [source],
- );
+ const previewUrl = useMemo(() => resolveSourceUrl(source, apiUrl), [source]);
const kind = previewKindFor(source);
const filename = source.filename || t("Attachment");
const spec = docIconFor(filename);
@@ -583,11 +715,9 @@ function WebTabBody({ url }: { url: string }) {
}, [url]);
useEffect(() => {
- setLoaded(false);
- setTimedOut(false);
const timer = window.setTimeout(() => setTimedOut(true), 4500);
return () => window.clearTimeout(timer);
- }, [url]);
+ }, []);
const blocked = timedOut && !loaded;
@@ -614,7 +744,7 @@ function WebTabBody({ url }: { url: string }) {
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"
+ ? "bg-[var(--primary)] text-[var(--primary-foreground)] hover:bg-[var(--primary)]/90"
: "border border-[var(--border)]/55 text-[var(--muted-foreground)] hover:border-[var(--primary)]/35 hover:text-[var(--primary)]"
}`}
>
@@ -636,9 +766,7 @@ function WebTabBody({ url }: { url: string }) {
size={12}
strokeWidth={1.9}
className={`mt-[1px] shrink-0 ${
- blocked
- ? "text-[var(--primary)]"
- : "text-[var(--muted-foreground)]"
+ blocked ? "text-[var(--primary)]" : "text-[var(--muted-foreground)]"
}`}
/>
<span>
@@ -676,3 +804,26 @@ function WebTabBody({ url }: { url: string }) {
</div>
);
}
+
+/* ------------------------------------------------------------------ */
+/* Geogebra tab body */
+/* ------------------------------------------------------------------ */
+
+/**
+ * Renders an interactive GeoGebra applet for a ggbscript payload. The
+ * heavy lifting (deployggb.js load + applet mount + evalCommand loop)
+ * lives in the shared ``Geogebra`` component; this body just gives it
+ * the right size and chrome inside the tab.
+ */
+function GeogebraTabBody({ script }: { script: string }) {
+ return (
+ <div className="h-full w-full overflow-auto bg-[var(--card)] p-3">
+ <Geogebra
+ script={script}
+ width={560}
+ height={520}
+ className="m-0 border-0 bg-transparent"
+ />
+ </div>
+ );
+}
diff --git a/web/components/chat/home/SimpleComposerInput.tsx b/web/components/chat/home/SimpleComposerInput.tsx
index e893ede21..4d829a058 100644
--- a/web/components/chat/home/SimpleComposerInput.tsx
+++ b/web/components/chat/home/SimpleComposerInput.tsx
@@ -1,12 +1,6 @@
"use client";
-import {
- memo,
- useCallback,
- useRef,
- useState,
- type RefObject,
-} from "react";
+import { memo, useCallback, useRef, useState, type RefObject } from "react";
import { useTranslation } from "react-i18next";
import { shouldSubmitOnEnter } from "@/lib/composer-keyboard";
import { useAutoSizedTextarea } from "@/lib/use-auto-sized-textarea";
diff --git a/web/components/chat/home/TracePanels.tsx b/web/components/chat/home/TracePanels.tsx
index ccad24c7c..9e7bba4c2 100644
--- a/web/components/chat/home/TracePanels.tsx
+++ b/web/components/chat/home/TracePanels.tsx
@@ -20,10 +20,7 @@ import {
} from "lucide-react";
import { useTranslation } from "react-i18next";
import MarkdownRenderer from "@/components/common/MarkdownRenderer";
-import {
- formatTurnDuration,
- getTurnDurationSeconds,
-} from "@/lib/trace-timing";
+import { formatTurnDuration, getTurnDurationSeconds } from "@/lib/trace-timing";
import type { StreamEvent } from "@/lib/unified-ws";
type TraceMetadata = {
@@ -44,10 +41,25 @@ type TraceMetadata = {
round?: number;
query?: string;
tool_name?: string;
+ block_id?: string;
trace_layer?: string;
output_mode?: string;
quality?: string;
sources?: Array<Record<string, unknown>>;
+ // Set by deep_question's QuestionPipeline on per-question content events
+ // (call_kind="quiz_question_emitted"). 0-based; display as 1-based.
+ question_index?: number;
+ total_questions?: number;
+ qa_pair?: Record<string, unknown>;
+ // Set by deep_research so the top-level trace row can show the active
+ // research/reporting sub-state instead of generic reasoning/tool labels.
+ research_status_key?: string;
+ topic_index?: number | string;
+ topic_title?: string;
+ report_part?: string;
+ section_index?: number | string;
+ section_count?: number | string;
+ section_title?: string;
};
type ResearchStageId = "understand" | "decompose" | "evidence" | "result";
@@ -200,8 +212,21 @@ function getTraceHeader(
title = t("Plan");
} else if (role === "observe" || kind === "llm_observation") {
title = t("Observe");
+ } else if (role === "quiz_question" || kind === "quiz_question_emitted") {
+ // Each quiz question gets its own sub-trace card; index is 0-based in
+ // metadata, so display as 1-based for the user.
+ const idx = Number(meta.question_index);
+ title = Number.isFinite(idx)
+ ? t("Question {{n}}", { n: idx + 1 })
+ : t("Question");
} else if (role === "response" || kind === "llm_final_response") {
title = t("Response");
+ } else if (role === "reflection" || kind === "tool_result_reflection") {
+ // Tool Summarizer sub-trace (Phase 1 of the question pipeline). The
+ // top-level status row carries the verbose "DeepTutor Reflecting…"
+ // wording; the sub-trace just labels itself "Reflecting" so the card
+ // header stays short.
+ title = t("Reflecting");
} else if (role === "thought" || kind === "llm_reasoning") {
title = t("Thought");
} else if (kind === "llm_generation") {
@@ -239,15 +264,81 @@ function getTraceText(
return textEvents.map((event) => event.content).join("");
}
+// Long string values in tool args are almost always base64 payloads
+// (image bytes, file blobs) the LLM never typed itself — they were
+// server-injected by the chat pipeline. Pretty-printing the raw value
+// fills the trace with megabytes of noise, so we elide anything past
+// this many characters down to a short summary.
+const TRACE_ARGS_MAX_STRING_CHARS = 200;
+
+function elideLongStrings(value: unknown): unknown {
+ if (typeof value === "string") {
+ if (value.length > TRACE_ARGS_MAX_STRING_CHARS) {
+ const head = value.slice(0, 40);
+ return `${head}… <${value.length.toLocaleString()} chars elided>`;
+ }
+ return value;
+ }
+ if (Array.isArray(value)) {
+ return value.map(elideLongStrings);
+ }
+ if (value && typeof value === "object") {
+ const out: Record<string, unknown> = {};
+ for (const [k, v] of Object.entries(value as Record<string, unknown>)) {
+ out[k] = elideLongStrings(v);
+ }
+ return out;
+ }
+ return value;
+}
+
function formatTraceArgs(args: unknown) {
if (args == null) return "";
try {
- return JSON.stringify(args, null, 2);
+ return JSON.stringify(elideLongStrings(args), null, 2);
} catch {
return String(args);
}
}
+/**
+ * Per-tool nice rendering for ``tool_call`` args. Some tools (notably
+ * ``ask_user``) have args that are large structured payloads which the
+ * UI also renders as a dedicated card below the trace — dumping the raw
+ * JSON twice is just noise. Returning ``null`` falls back to the
+ * generic JSON ``<pre>`` block.
+ */
+function renderNiceToolArgs(
+ toolName: string | undefined,
+ rawArgs: unknown,
+): ReactNode | null {
+ if (toolName !== "ask_user" || !rawArgs || typeof rawArgs !== "object") {
+ return null;
+ }
+ const obj = rawArgs as Record<string, unknown>;
+ const questions = Array.isArray(obj.questions)
+ ? (obj.questions as Array<Record<string, unknown>>)
+ : [];
+ if (questions.length === 0) return null;
+ return (
+ <ul className="ml-3 mt-0.5 space-y-0.5 text-[10.5px] leading-[1.5] not-italic">
+ {questions.map((q, idx) => {
+ const prompt = String(q.prompt ?? q.question ?? "").trim();
+ if (!prompt) return null;
+ return (
+ <li
+ key={idx}
+ className="flex items-start gap-1.5 text-[var(--muted-foreground)]"
+ >
+ <span className="shrink-0 tabular-nums opacity-50">{idx + 1}.</span>
+ <span className="min-w-0 flex-1">{prompt}</span>
+ </li>
+ );
+ })}
+ </ul>
+ );
+}
+
/* ------------------------------------------------------------------ */
/* Display-item grouping (step-level) */
/* ------------------------------------------------------------------ */
@@ -472,11 +563,20 @@ function TraceRowBody({
<div className="space-y-0.5">
{toolEvents.map((event, idx) => {
if (event.type === "tool_call") {
- const formattedArgs = formatTraceArgs(event.metadata?.args);
+ const toolName =
+ (event.metadata?.tool as string | undefined) ?? undefined;
+ const niceArgs = renderNiceToolArgs(
+ toolName,
+ event.metadata?.args,
+ );
+ const formattedArgs = niceArgs
+ ? ""
+ : formatTraceArgs(event.metadata?.args);
return (
<div key={`${callId}-tool-call-${idx}`}>
<span className="opacity-50">→ </span>
<span>{event.content}</span>
+ {niceArgs ?? null}
{formattedArgs && (
<pre className="ml-3 mt-0.5 whitespace-pre-wrap break-words rounded-md bg-[var(--muted)] px-2 py-1 font-mono text-[10px] not-italic leading-[1.5] text-[var(--muted-foreground)]">
{formattedArgs}
@@ -544,11 +644,20 @@ function TraceRowBody({
<div className="space-y-0.5">
{toolEvents.map((event, idx) => {
if (event.type === "tool_call") {
- const formattedArgs = formatTraceArgs(event.metadata?.args);
+ const toolName =
+ (event.metadata?.tool as string | undefined) ?? undefined;
+ const niceArgs = renderNiceToolArgs(
+ toolName,
+ event.metadata?.args,
+ );
+ const formattedArgs = niceArgs
+ ? ""
+ : formatTraceArgs(event.metadata?.args);
return (
<div key={`${callId}-tool-call-${idx}`}>
<span className="opacity-50">→ </span>
<span>{event.content}</span>
+ {niceArgs ?? null}
{formattedArgs && (
<pre className="ml-3 mt-0.5 whitespace-pre-wrap break-words rounded-md bg-[var(--muted)] px-2 py-1 font-mono text-[10px] not-italic leading-[1.5] text-[var(--muted-foreground)]">
{formattedArgs}
@@ -668,7 +777,7 @@ export function CallTracePanel({
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
+ // own framing, pass ``nested`` to skip
// the card wrapper so we don't end up with card-in-card visuals.
nested?: boolean;
}) {
@@ -1184,13 +1293,32 @@ function RespondedMark(props: MarkProps) {
);
}
-type StreamingMode = "reasoning" | "tool_using" | "responding" | "responded";
+type StreamingMode =
+ | "reasoning"
+ | "tool_using"
+ | "responding"
+ | "responded"
+ | "planning"
+ | "drafting"
+ | "exploring"
+ | "quizzing"
+ | "reflecting";
/**
- * 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.
+ * Picks the status label shown above the trace card.
+ *
+ * We scan in reverse so each round's latest signal wins — a tool result
+ * mid-iteration flips the label back to reasoning, a planning chunk
+ * arriving after a tool flips it to planning, etc. Per-mode mapping:
+ *
+ * ``llm_planning`` chunks → planning (solve plan / replan / pre-retrieve)
+ * ``tool_call`` event → tool_using (any explicit tool call)
+ * ``llm_final_response``
+ * stage=``writing`` → responding (solve synthesize, also chat default)
+ * stage=``reasoning`` → drafting (solve per-step FINISH)
+ * ``llm_reasoning`` chunks → reasoning (THINK / chat default)
+ *
+ * Falls back to ``reasoning`` while events are still warming up.
*/
function detectStreamingMode(
events: StreamEvent[],
@@ -1198,15 +1326,132 @@ function detectStreamingMode(
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";
+ const meta = (event.metadata ?? {}) as Record<string, unknown>;
+ const callKind = String(meta.call_kind ?? "");
+
+ if (event.type === "tool_call") {
+ // Tool calls inherit the active stage so the top-level status stays
+ // coherent (e.g., a rag call during explore reads as "Exploring",
+ // not generic "Tool Calling").
+ if (event.stage === "exploring") return "exploring";
+ if (event.stage === "quizzing") return "quizzing";
+ return "tool_using";
+ }
+ if (event.type === "tool_result") {
+ // Tool finished — keep scanning for the iteration's actual mode.
+ continue;
+ }
+ // Quiz pipeline emits one ``quiz_question_emitted`` content event per
+ // question with the structured qa_pair in metadata — that's the signal
+ // the quizzing phase is active.
+ if (callKind === "quiz_question_emitted") return "quizzing";
+ // Question pipeline's Tool Summarizer (Phase 1 reflection over a raw
+ // tool result) streams chunks under ``call_kind="tool_result_reflection"``.
+ // While those chunks are arriving — and until the next reasoning / tool
+ // event flips the mode again — the top-level status row reads
+ // "DeepTutor Reflecting…".
+ if (callKind === "tool_result_reflection") return "reflecting";
+ if (event.type === "content" && callKind === "llm_final_response") {
+ // Explore's FINISH streams into the chat bubble while the
+ // ``exploring`` stage is still open; keep the top-level title on
+ // "DeepTutor Exploring…" until the bus moves on.
+ if (event.stage === "exploring") return "exploring";
+ if (event.stage === "writing") return "responding";
+ if (event.stage === "reasoning") return "drafting";
+ return "responding";
+ }
+ if (callKind === "llm_planning") return "planning";
+ if (event.type === "thinking" && callKind === "llm_reasoning") {
+ if (event.stage === "exploring") return "exploring";
+ if (event.stage === "quizzing") return "quizzing";
+ return "reasoning";
+ }
}
+ if (hasFinalContent) return "responding";
return "reasoning";
}
+function parsePositiveInt(value: unknown): number | null {
+ if (typeof value === "number" && Number.isFinite(value) && value > 0) {
+ return Math.floor(value);
+ }
+ if (typeof value === "string") {
+ const parsed = Number.parseInt(value, 10);
+ if (Number.isFinite(parsed) && parsed > 0) return parsed;
+ }
+ return null;
+}
+
+function getResearchTopicIndex(meta: TraceMetadata): number | null {
+ const explicit = parsePositiveInt(meta.topic_index);
+ if (explicit) return explicit;
+
+ const searchable = [meta.block_id, meta.call_id, meta.trace_id]
+ .map((value) => String(value || ""))
+ .join(" ");
+ const match = /\bblock_(\d+)\b/.exec(searchable);
+ return match ? parsePositiveInt(match[1]) : null;
+}
+
+function getDeepResearchStatusLabel(
+ events: StreamEvent[],
+ t: (key: string, opts?: Record<string, unknown>) => string,
+ isStreaming: boolean,
+) {
+ if (!isStreaming) return null;
+
+ for (let idx = events.length - 1; idx >= 0; idx -= 1) {
+ const event = events[idx];
+ if (event.source !== "deep_research") continue;
+
+ const meta = getTraceMeta(event);
+ const key = String(meta.research_status_key || "");
+
+ if (key === "decompose_target" || event.stage === "decomposing") {
+ return t("Decomposing Target");
+ }
+
+ if (key === "research_topic" || event.stage === "researching") {
+ const topicIndex = getResearchTopicIndex(meta);
+ return topicIndex
+ ? t("Researching Topic #{{n}}", { n: topicIndex })
+ : t("Researching Topic");
+ }
+
+ if (key === "report_intro") return t("Reporting Intro");
+ if (key === "report_outline") return t("Reporting Outline");
+ if (key === "report_conclusion") return t("Reporting Conclusion");
+ if (key === "report_section") {
+ const sectionIndex = parsePositiveInt(meta.section_index);
+ return sectionIndex
+ ? t("Reporting Section #{{n}}", { n: sectionIndex })
+ : t("Reporting Section");
+ }
+
+ if (event.stage === "reporting") {
+ const label = String(meta.label || "").toLowerCase();
+ if (label.includes("intro") || label.includes("引言")) {
+ return t("Reporting Intro");
+ }
+ if (label.includes("conclusion") || label.includes("结论")) {
+ return t("Reporting Conclusion");
+ }
+ if (label.includes("section") || label.includes("章节")) {
+ const sectionIndex = parsePositiveInt(meta.section_index);
+ return sectionIndex
+ ? t("Reporting Section #{{n}}", { n: sectionIndex })
+ : t("Reporting Section");
+ }
+ return t("Reporting");
+ }
+ }
+
+ return null;
+}
+
export function StreamingStatus({
events,
isStreaming,
@@ -1247,13 +1492,24 @@ export function StreamingStatus({
);
const label =
- mode === "tool_using"
- ? t("Tool using…")
- : mode === "responding"
- ? t("DeepTutor responding…")
- : mode === "responded"
- ? t("DeepTutor responded.")
- : t("DeepTutor reasoning…");
+ getDeepResearchStatusLabel(events, t, Boolean(isStreaming)) ??
+ (mode === "tool_using"
+ ? t("Tool Calling…")
+ : mode === "planning"
+ ? t("DeepTutor Planning…")
+ : mode === "drafting"
+ ? t("DeepTutor Drafting…")
+ : mode === "responding"
+ ? t("DeepTutor Responding…")
+ : mode === "exploring"
+ ? t("DeepTutor Exploring…")
+ : mode === "quizzing"
+ ? t("DeepTutor Quizzing…")
+ : mode === "reflecting"
+ ? t("DeepTutor Reflecting…")
+ : mode === "responded"
+ ? t("DeepTutor responded.")
+ : t("DeepTutor Reasoning…"));
// Single turn-level clock. Ticks every second while the turn is in
// flight and freezes on the final elapsed time once the answer ends —
@@ -1279,7 +1535,7 @@ export function StreamingStatus({
const Mark =
mode === "tool_using"
? ToolMark
- : mode === "responding"
+ : mode === "responding" || mode === "drafting"
? RespondingMark
: mode === "responded"
? RespondedMark
@@ -1310,17 +1566,14 @@ export function StreamingStatus({
</>
);
- // role="status" + aria-live="polite" surfaces mode transitions
- // (reasoning → tool using → responding → responded) to screen readers
- // without barging in on the user. aria-atomic="false" so only the changed
- // label is announced rather than the whole row each tick.
+ // aria-live="polite" surfaces mode transitions to screen readers without
+ // barging in on the user.
if (collapsible && onToggle) {
return (
<button
type="button"
onClick={onToggle}
aria-expanded={expanded ? "true" : "false"}
- role="status"
aria-live="polite"
aria-atomic="false"
className={`mb-3 -ml-1 flex items-center gap-2.5 rounded-md px-1 py-0.5 text-[14px] font-semibold leading-none transition-colors hover:bg-[var(--muted)]/40 ${textColor}`}
diff --git a/web/components/chat/space/ChatSpaceMenu.tsx b/web/components/chat/space/ChatSpaceMenu.tsx
index 190e8ebdc..0862a5103 100644
--- a/web/components/chat/space/ChatSpaceMenu.tsx
+++ b/web/components/chat/space/ChatSpaceMenu.tsx
@@ -149,9 +149,7 @@ export default memo(function ChatSpaceMenu({
type="button"
role={isMention ? "option" : undefined}
aria-selected={isMention ? isActive : undefined}
- onMouseEnter={
- isMention ? () => setActiveIdx(idx) : undefined
- }
+ onMouseEnter={isMention ? () => setActiveIdx(idx) : undefined}
onClick={() => onSelectItem(key as SelectableSpaceKey)}
className={`flex w-full items-center gap-2.5 text-left transition-colors ${
isActive ? "bg-[var(--muted)]/60" : "hover:bg-[var(--muted)]/40"
diff --git a/web/components/common/Modal.tsx b/web/components/common/Modal.tsx
index abf245f8f..79912149c 100644
--- a/web/components/common/Modal.tsx
+++ b/web/components/common/Modal.tsx
@@ -130,7 +130,7 @@ export default function Modal({
// mousedown rather than click so dragging out of an input doesn't
// accidentally close on mouseup.
onMouseDown={handleBackdropMouseDown}
- className="fixed inset-0 bg-black/40 backdrop-blur-sm flex items-center justify-center z-50 animate-in fade-in"
+ className="fixed inset-0 bg-[var(--overlay)] backdrop-blur-sm flex items-center justify-center z-50 animate-in fade-in"
>
<div
ref={dialogRef}
diff --git a/web/components/common/PickerShell.tsx b/web/components/common/PickerShell.tsx
index c2ded8387..ae40b8245 100644
--- a/web/components/common/PickerShell.tsx
+++ b/web/components/common/PickerShell.tsx
@@ -53,9 +53,9 @@ export interface PickerShellProps {
*/
className?: string;
/**
- * Override the default `bg-black/40` backdrop. Pass any opacity / blur /
- * tint combo. Useful for pickers that want a frosted-glass look or a
- * lighter scrim.
+ * Override the default `bg-[var(--overlay)]` backdrop (a theme-aware scrim:
+ * warm/cool tint matches the active palette). Pass any opacity / blur /
+ * tint combo for pickers that want a frosted-glass look or a lighter scrim.
*/
backdropClass?: string;
}
@@ -72,7 +72,7 @@ export default function PickerShell({
zIndex = 85,
align = "center",
className,
- backdropClass = "bg-black/40",
+ backdropClass = "bg-[var(--overlay)]",
}: PickerShellProps) {
const dialogRef = useRef<HTMLDivElement>(null);
const previouslyFocusedRef = useRef<HTMLElement | null>(null);
diff --git a/web/components/common/RichMarkdownRenderer.tsx b/web/components/common/RichMarkdownRenderer.tsx
index 250745c10..42ac7a4cd 100644
--- a/web/components/common/RichMarkdownRenderer.tsx
+++ b/web/components/common/RichMarkdownRenderer.tsx
@@ -8,6 +8,7 @@ import { useTranslation } from "react-i18next";
import "katex/dist/katex.min.css";
import { processMarkdownContent } from "@/lib/latex";
import {
+ citationAnchorIdFor,
escapeUnknownHtmlTagsForDisplay,
normalizeMarkdownForDisplay,
} from "@/lib/markdown-display";
@@ -32,6 +33,11 @@ const LazyCodeBlock = dynamic(() => import("./RichCodeBlock"), {
loading: () => null,
});
+const GeogebraOpenCTA = dynamic(
+ () => import("@/components/common/GeogebraOpenCTA"),
+ { ssr: false, loading: () => null },
+);
+
type PluginBundle = {
remarkMath?: unknown;
rehypeKatex?: unknown;
@@ -103,6 +109,35 @@ function sourceLineAttr(node: any): { "data-source-line"?: number } {
return {};
}
+// Scrolls only the nearest scrollable ancestor instead of every scrollable
+// ancestor up to the viewport. Using `Element.scrollIntoView` here walks the
+// ancestor chain and can shift outer panes that happen to be scrollable
+// (e.g. when the preview container sits inside a flex layout that briefly
+// gains scroll height), which manifests as the whole page jumping after a
+// citation click.
+function scrollAnchorIntoView(target: HTMLElement): void {
+ let container: HTMLElement | null = target.parentElement;
+ while (container) {
+ const style = window.getComputedStyle(container);
+ const overflowY = style.overflowY;
+ if (
+ (overflowY === "auto" || overflowY === "scroll") &&
+ container.scrollHeight > container.clientHeight
+ ) {
+ break;
+ }
+ container = container.parentElement;
+ }
+ if (!container) {
+ target.scrollIntoView({ block: "start", behavior: "smooth" });
+ return;
+ }
+ const containerRect = container.getBoundingClientRect();
+ const targetRect = target.getBoundingClientRect();
+ const top = targetRect.top - containerRect.top + container.scrollTop;
+ container.scrollTo({ top, behavior: "smooth" });
+}
+
export default function RichMarkdownRenderer({
content,
className = "",
@@ -437,6 +472,29 @@ export default function RichMarkdownRenderer({
);
}
+ if (lang === "ggbscript" && enableCode) {
+ // Backend emits ```ggbscript[page_id;title]. We don't render the
+ // applet inline anymore — the chat answer stays text-only and we
+ // surface a CTA card. Clicking it opens (or focuses) a GeoGebra
+ // tab inside the right-hand SessionViewerPanel where the user can
+ // interact with the figure without the chat scroll fighting it.
+ const metaMatch = /language-ggbscript\[([^;\]]*)(?:;([^\]]*))?\]/.exec(
+ blockClassName || "",
+ );
+ const ggbPayloadId = metaMatch?.[1]?.trim() || undefined;
+ const ggbTitle = metaMatch?.[2]?.trim() || undefined;
+ return (
+ <div {...lineProps}>
+ <GeogebraOpenCTA
+ script={raw}
+ payloadId={ggbPayloadId}
+ title={ggbTitle}
+ className={gap}
+ />
+ </div>
+ );
+ }
+
// Route every multi-line block through the rich code block so the
// indented (no-language) variant still gets a polished, consistent
// theme instead of the washed-out fallback panel.
@@ -485,10 +543,22 @@ export default function RichMarkdownRenderer({
if (isCitation) {
const label = extractText(children);
const ids = label.split(/\s*,\s*/);
- const scrollToRef = (event: React.MouseEvent) => {
+ const scrollToRef = (event: React.MouseEvent, id?: string) => {
event.preventDefault();
- const target = document.getElementById("references");
- target?.scrollIntoView({ block: "start", behavior: "smooth" });
+ const hashTarget =
+ id && citationAnchorIdFor(id)
+ ? citationAnchorIdFor(id)
+ : href?.startsWith("#")
+ ? decodeURIComponent(href.slice(1))
+ : "references";
+ const target =
+ document.getElementById(hashTarget || "") ??
+ document.getElementById("references");
+ const parentDetails = target?.closest("details");
+ if (parentDetails instanceof HTMLDetailsElement) {
+ parentDetails.open = true;
+ }
+ if (target) scrollAnchorIntoView(target);
};
return (
<span
@@ -501,12 +571,13 @@ export default function RichMarkdownRenderer({
const prefix = prefixMatch?.[1] ?? "";
const num =
prefix && prefixMatch ? id.slice(prefixMatch[0].length) : id;
+ const citationAnchor = citationAnchorIdFor(id);
return (
<React.Fragment key={id}>
{idx > 0 && ", "}
<a
- href={href}
- onClick={scrollToRef}
+ href={citationAnchor ? `#${citationAnchor}` : href}
+ onClick={(event) => scrollToRef(event, id)}
className="cursor-pointer text-[var(--primary)] no-underline transition-colors hover:text-[var(--primary)]/70 hover:underline"
>
{prefix ? (
@@ -540,7 +611,7 @@ export default function RichMarkdownRenderer({
event.preventDefault();
const targetId = decodeURIComponent(href.slice(1));
const target = document.getElementById(targetId);
- target?.scrollIntoView({ block: "start", behavior: "smooth" });
+ if (target) scrollAnchorIntoView(target);
}}
className="text-[var(--primary)] underline decoration-[var(--primary)]/40 underline-offset-2 transition-colors hover:decoration-[var(--primary)]"
{...props}
diff --git a/web/components/common/SimpleMarkdownRenderer.tsx b/web/components/common/SimpleMarkdownRenderer.tsx
index b4786cb81..03f3e76be 100644
--- a/web/components/common/SimpleMarkdownRenderer.tsx
+++ b/web/components/common/SimpleMarkdownRenderer.tsx
@@ -3,7 +3,10 @@
import React, { useMemo } from "react";
import ReactMarkdown from "react-markdown";
import remarkGfm from "remark-gfm";
-import { normalizeMarkdownForDisplay } from "@/lib/markdown-display";
+import {
+ citationAnchorIdFor,
+ normalizeMarkdownForDisplay,
+} from "@/lib/markdown-display";
import type { MarkdownRendererProps } from "./MarkdownRenderer";
function extractText(children: React.ReactNode): string {
@@ -345,9 +348,21 @@ export default function SimpleMarkdownRenderer({
if (isCitation) {
const label = extractText(children);
const ids = label.split(/\s*,\s*/);
- const scrollToRef = (event: React.MouseEvent) => {
+ const scrollToRef = (event: React.MouseEvent, id?: string) => {
event.preventDefault();
- const target = document.getElementById("references");
+ const hashTarget =
+ id && citationAnchorIdFor(id)
+ ? citationAnchorIdFor(id)
+ : href?.startsWith("#")
+ ? decodeURIComponent(href.slice(1))
+ : "references";
+ const target =
+ document.getElementById(hashTarget || "") ??
+ document.getElementById("references");
+ const parentDetails = target?.closest("details");
+ if (parentDetails instanceof HTMLDetailsElement) {
+ parentDetails.open = true;
+ }
target?.scrollIntoView({ block: "start", behavior: "smooth" });
};
return (
@@ -361,12 +376,13 @@ export default function SimpleMarkdownRenderer({
const prefix = prefixMatch?.[1] ?? "";
const num =
prefix && prefixMatch ? id.slice(prefixMatch[0].length) : id;
+ const citationAnchor = citationAnchorIdFor(id);
return (
<React.Fragment key={id}>
{idx > 0 && ", "}
<a
- href={href}
- onClick={scrollToRef}
+ href={citationAnchor ? `#${citationAnchor}` : href}
+ onClick={(event) => scrollToRef(event, id)}
className="cursor-pointer text-[var(--primary)] no-underline transition-colors hover:text-[var(--primary)]/70 hover:underline"
>
{prefix ? (
diff --git a/web/components/common/ToastViewport.tsx b/web/components/common/ToastViewport.tsx
index bc567eb78..8356fc8d8 100644
--- a/web/components/common/ToastViewport.tsx
+++ b/web/components/common/ToastViewport.tsx
@@ -2,10 +2,7 @@
import { X } from "lucide-react";
import { useEffect, useState } from "react";
-import {
- subscribeNotifications,
- type Notification,
-} from "@/lib/notifications";
+import { subscribeNotifications, type Notification } from "@/lib/notifications";
/**
* Renders the toast stack in the bottom-right. Mounted once at the
diff --git a/web/components/notebook/SaveToNotebookModal.tsx b/web/components/notebook/SaveToNotebookModal.tsx
index 75d16f555..1e510be33 100644
--- a/web/components/notebook/SaveToNotebookModal.tsx
+++ b/web/components/notebook/SaveToNotebookModal.tsx
@@ -321,7 +321,7 @@ export default function SaveToNotebookModal({
);
if (!response.ok || !response.body) {
- throw new Error("Failed to save to notebook.");
+ throw new Error(t("Failed to save to notebook."));
}
const reader = response.body.getReader();
@@ -347,7 +347,7 @@ export default function SaveToNotebookModal({
setSummaryPreview(finalSummary);
} else if (type === "error") {
throw new Error(
- String(event.payload.detail || "Failed to save to notebook."),
+ String(event.payload.detail || t("Failed to save to notebook.")),
);
} else if (type === "result") {
const summary = String(event.payload.summary || finalSummary);
@@ -360,11 +360,11 @@ export default function SaveToNotebookModal({
}
}
- throw new Error("Notebook save stream ended unexpectedly.");
+ throw new Error(t("Notebook save stream ended unexpectedly."));
} catch (err) {
if (controller.signal.aborted) return;
setError(
- err instanceof Error ? err.message : "Failed to save to notebook.",
+ err instanceof Error ? err.message : t("Failed to save to notebook."),
);
setIsLoading(false);
}
diff --git a/web/components/research/ResearchOutlineEditor.tsx b/web/components/research/ResearchOutlineEditor.tsx
index 6391caf6b..f3d5fd2e5 100644
--- a/web/components/research/ResearchOutlineEditor.tsx
+++ b/web/components/research/ResearchOutlineEditor.tsx
@@ -1,7 +1,14 @@
"use client";
-import { useCallback, useState } from "react";
-import { Plus, Play, Trash2, Loader2, CheckCircle2 } from "lucide-react";
+import { useCallback, useEffect, useRef, useState } from "react";
+import {
+ ChevronDown,
+ Plus,
+ Play,
+ Trash2,
+ Loader2,
+ CheckCircle2,
+} from "lucide-react";
import { useTranslation } from "react-i18next";
import type { OutlineItem } from "@/lib/research-types";
@@ -23,12 +30,27 @@ export default function ResearchOutlineEditor({
const { t } = useTranslation();
const [items, setItems] = useState<OutlineItem[]>(initialOutline);
const [localConfirmed, setLocalConfirmed] = useState(false);
+ // Auto-collapse once the research is underway / done, but let the user
+ // re-expand by clicking the summary header. While editing, stays open.
+ // ``userToggled`` latches on the first user click so subsequent
+ // status-change re-renders don't keep slamming the card closed.
+ const [collapsed, setCollapsed] = useState(false);
+ const userToggledRef = useRef(false);
const locked =
externalStatus === "researching" ||
externalStatus === "done" ||
localConfirmed;
+ useEffect(() => {
+ if (locked && !userToggledRef.current) setCollapsed(true);
+ }, [locked]);
+
+ const toggleCollapsed = useCallback(() => {
+ userToggledRef.current = true;
+ setCollapsed((c) => !c);
+ }, []);
+
const updateItem = useCallback(
(index: number, field: keyof OutlineItem, value: string) => {
setItems((prev) =>
@@ -68,13 +90,39 @@ export default function ResearchOutlineEditor({
const StatusIcon = externalStatus === "done" ? CheckCircle2 : Loader2;
+ const headerClickable = locked;
+
return (
<div className="my-2 rounded-lg border border-[var(--border)]/30 bg-[var(--background)] shadow-sm">
- <div className="border-b border-[var(--border)]/20 px-4 py-2.5">
+ <button
+ type="button"
+ disabled={!headerClickable}
+ onClick={headerClickable ? toggleCollapsed : undefined}
+ className={`block w-full text-left ${collapsed ? "" : "border-b border-[var(--border)]/20"} px-4 py-2 ${
+ headerClickable
+ ? "cursor-pointer transition-colors hover:bg-[var(--muted-foreground)]/[0.025]"
+ : "cursor-default"
+ }`}
+ >
<div className="flex items-center justify-between">
- <h3 className="text-[13px] font-semibold text-[var(--foreground)]">
- {t("Research Outline")}
- </h3>
+ <div className="flex items-center gap-1.5">
+ {headerClickable && (
+ <ChevronDown
+ size={12}
+ className={`shrink-0 text-[var(--muted-foreground)]/50 transition-transform ${
+ collapsed ? "-rotate-90" : ""
+ }`}
+ />
+ )}
+ <h3 className="text-[13px] font-semibold text-[var(--foreground)]">
+ {t("Research Outline")}
+ </h3>
+ {collapsed && validItems.length > 0 && (
+ <span className="text-[11px] text-[var(--muted-foreground)]/45">
+ · {validItems.length} {t("sub-topics")}
+ </span>
+ )}
+ </div>
{statusLabel && (
<span className="flex items-center gap-1.5 text-[11px] text-[var(--muted-foreground)]/60">
<StatusIcon
@@ -85,89 +133,97 @@ export default function ResearchOutlineEditor({
</span>
)}
</div>
- {!locked && (
+ {!locked && !collapsed && (
<p className="mt-0.5 text-[11px] text-[var(--muted-foreground)]/60">
Review and edit the sub-topics below, then start the research. You
can also type in the chat to regenerate the outline.
</p>
)}
- </div>
-
- <div className="space-y-0 divide-y divide-[var(--border)]/15">
- {validItems.map((item, index) => (
- <div
- key={index}
- className="group flex items-start gap-2 px-3 py-2.5 transition-colors hover:bg-[var(--muted-foreground)]/[0.02]"
- >
- <span className="mt-1.5 w-4 shrink-0 text-center text-[11px] font-medium tabular-nums text-[var(--muted-foreground)]/30">
- {index + 1}
- </span>
- <div className="min-w-0 flex-1 space-y-1">
- {locked ? (
- <>
- <div className="text-[12px] font-medium text-[var(--foreground)]">
- {item.title}
- </div>
- {item.overview && (
- <div className="text-[11px] leading-relaxed text-[var(--muted-foreground)]/70">
- {item.overview}
- </div>
+ </button>
+ {!collapsed && (
+ <>
+ <div className="space-y-0 divide-y divide-[var(--border)]/15">
+ {validItems.map((item, index) => (
+ <div
+ key={index}
+ className="group flex items-start gap-2 px-3 py-1.5 transition-colors hover:bg-[var(--muted-foreground)]/[0.02]"
+ >
+ <span className="mt-[3px] w-4 shrink-0 text-center text-[11px] font-medium tabular-nums leading-tight text-[var(--muted-foreground)]/30">
+ {index + 1}
+ </span>
+ <div className="min-w-0 flex-1 space-y-0.5">
+ {locked ? (
+ <>
+ <div className="text-[12px] font-medium leading-snug text-[var(--foreground)]">
+ {item.title}
+ </div>
+ {item.overview && (
+ <div className="text-[11px] leading-snug text-[var(--muted-foreground)]/70">
+ {item.overview}
+ </div>
+ )}
+ </>
+ ) : (
+ <>
+ <input
+ type="text"
+ value={item.title ?? ""}
+ onChange={(e) =>
+ updateItem(index, "title", e.target.value)
+ }
+ placeholder={t("Sub-topic title...")}
+ className="w-full bg-transparent text-[12px] font-medium leading-snug text-[var(--foreground)] outline-none placeholder:text-[var(--muted-foreground)]/30"
+ />
+ <textarea
+ value={item.overview ?? ""}
+ onChange={(e) =>
+ updateItem(index, "overview", e.target.value)
+ }
+ placeholder={t("Research direction and focus...")}
+ rows={1}
+ className="w-full resize-none bg-transparent text-[11px] leading-snug text-[var(--muted-foreground)]/70 outline-none placeholder:text-[var(--muted-foreground)]/25"
+ style={
+ { fieldSizing: "content" } as React.CSSProperties
+ }
+ />
+ </>
)}
- </>
- ) : (
- <>
- <input
- type="text"
- value={item.title ?? ""}
- onChange={(e) => updateItem(index, "title", e.target.value)}
- placeholder={t("Sub-topic title...")}
- className="w-full bg-transparent text-[12px] font-medium text-[var(--foreground)] outline-none placeholder:text-[var(--muted-foreground)]/30"
- />
- <textarea
- value={item.overview ?? ""}
- onChange={(e) =>
- updateItem(index, "overview", e.target.value)
- }
- placeholder={t("Research direction and focus...")}
- rows={2}
- className="w-full resize-none bg-transparent text-[11px] leading-relaxed text-[var(--muted-foreground)]/70 outline-none placeholder:text-[var(--muted-foreground)]/25"
- />
- </>
- )}
- </div>
- {!locked && items.length > 1 && (
+ </div>
+ {!locked && items.length > 1 && (
+ <button
+ type="button"
+ onClick={() => removeItem(index)}
+ className="mt-0.5 shrink-0 rounded p-0.5 text-[var(--muted-foreground)]/20 opacity-0 transition-all hover:bg-red-500/10 hover:text-red-500/60 group-hover:opacity-100"
+ >
+ <Trash2 size={12} />
+ </button>
+ )}
+ </div>
+ ))}
+ </div>
+
+ {!locked && (
+ <div className="flex items-center justify-between border-t border-[var(--border)]/20 px-4 py-2">
<button
type="button"
- onClick={() => removeItem(index)}
- className="mt-1 shrink-0 rounded p-0.5 text-[var(--muted-foreground)]/20 opacity-0 transition-all hover:bg-red-500/10 hover:text-red-500/60 group-hover:opacity-100"
+ onClick={addItem}
+ className="flex items-center gap-1 rounded-md px-2 py-1 text-[11px] text-[var(--muted-foreground)]/50 transition-colors hover:bg-[var(--muted-foreground)]/5 hover:text-[var(--muted-foreground)]/70"
>
- <Trash2 size={12} />
+ <Plus size={12} />
+ {t("Add sub-topic")}
</button>
- )}
- </div>
- ))}
- </div>
-
- {!locked && (
- <div className="flex items-center justify-between border-t border-[var(--border)]/20 px-4 py-2">
- <button
- type="button"
- onClick={addItem}
- className="flex items-center gap-1 rounded-md px-2 py-1 text-[11px] text-[var(--muted-foreground)]/50 transition-colors hover:bg-[var(--muted-foreground)]/5 hover:text-[var(--muted-foreground)]/70"
- >
- <Plus size={12} />
- {t("Add sub-topic")}
- </button>
- <button
- type="button"
- onClick={handleConfirm}
- disabled={items.every((i) => !i.title.trim())}
- className="flex items-center gap-1.5 rounded-lg bg-[var(--primary)] px-3 py-1.5 text-[11px] font-medium text-[var(--primary-foreground)] transition-all hover:opacity-90 disabled:opacity-40"
- >
- <Play size={11} />
- {t("Start Research")}
- </button>
- </div>
+ <button
+ type="button"
+ onClick={handleConfirm}
+ disabled={items.every((i) => !i.title.trim())}
+ className="flex items-center gap-1.5 rounded-lg bg-[var(--primary)] px-3 py-1.5 text-[11px] font-medium text-[var(--primary-foreground)] transition-all hover:opacity-90 disabled:opacity-40"
+ >
+ <Play size={11} />
+ {t("Start Research")}
+ </button>
+ </div>
+ )}
+ </>
)}
</div>
);
diff --git a/web/components/sidebar/BookRecent.tsx b/web/components/sidebar/BookRecent.tsx
index 2540fdfa2..6c373d04e 100644
--- a/web/components/sidebar/BookRecent.tsx
+++ b/web/components/sidebar/BookRecent.tsx
@@ -80,10 +80,7 @@ export function BookRecent({ collapsed = false, limit = 4 }: BookRecentProps) {
{book.title || "Untitled book"}
</span>
<span className="shrink-0 text-[10px] tabular-nums text-[var(--muted-foreground)]/40">
- {formatRelativeTime(
- Number(book.updated_at) || 0,
- i18n.language,
- )}
+ {formatRelativeTime(Number(book.updated_at) || 0, i18n.language)}
</span>
</Link>
);
diff --git a/web/components/sidebar/CoWriterRecent.tsx b/web/components/sidebar/CoWriterRecent.tsx
index 3c4a9bb38..00512330b 100644
--- a/web/components/sidebar/CoWriterRecent.tsx
+++ b/web/components/sidebar/CoWriterRecent.tsx
@@ -2,7 +2,7 @@
import Link from "next/link";
import { usePathname } from "next/navigation";
-import { useCallback, useEffect, useRef, useState } from "react";
+import { useEffect, useState } from "react";
import { useTranslation } from "react-i18next";
import {
listCoWriterDocuments,
@@ -23,27 +23,33 @@ export function CoWriterRecent({
const { i18n } = useTranslation();
const [docs, setDocs] = useState<CoWriterDocumentSummary[]>([]);
const pathname = usePathname();
- const limitRef = useRef(limit);
- limitRef.current = limit;
-
- const refresh = useCallback(async () => {
- try {
- const items = await listCoWriterDocuments();
- setDocs(items.slice(0, limitRef.current));
- } catch {
- /* ignore */
- }
- }, []);
useEffect(() => {
- void refresh();
- }, [refresh, pathname]);
+ let active = true;
+ void listCoWriterDocuments()
+ .then((items) => {
+ if (active) setDocs(items.slice(0, limit));
+ })
+ .catch(() => {});
+ return () => {
+ active = false;
+ };
+ }, [limit, pathname]);
useEffect(() => {
- return subscribeCoWriterChanges(() => {
- void refresh();
+ let active = true;
+ const unsubscribe = subscribeCoWriterChanges(() => {
+ void listCoWriterDocuments()
+ .then((items) => {
+ if (active) setDocs(items.slice(0, limit));
+ })
+ .catch(() => {});
});
- }, [refresh]);
+ return () => {
+ active = false;
+ unsubscribe();
+ };
+ }, [limit]);
if (docs.length === 0) return null;
@@ -62,10 +68,7 @@ export function CoWriterRecent({
{doc.title || "Untitled draft"}
</span>
<span className="shrink-0 text-[10px] tabular-nums text-[var(--muted-foreground)]/40">
- {formatRelativeTime(
- Number(doc.updated_at) || 0,
- i18n.language,
- )}
+ {formatRelativeTime(Number(doc.updated_at) || 0, i18n.language)}
</span>
</Link>
))}
diff --git a/web/components/sidebar/SidebarShell.tsx b/web/components/sidebar/SidebarShell.tsx
index 547f8c073..2b10d304a 100644
--- a/web/components/sidebar/SidebarShell.tsx
+++ b/web/components/sidebar/SidebarShell.tsx
@@ -8,6 +8,7 @@ import { useAppShell } from "@/context/AppShellContext";
import {
BookOpen,
Bot,
+ Brain,
Github,
LayoutGrid,
Library,
@@ -17,12 +18,10 @@ 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";
@@ -42,12 +41,6 @@ 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",
@@ -73,6 +66,12 @@ const PRIMARY_NAV: NavEntry[] = [
icon: LayoutGrid,
tooltipKey: "Space tooltip",
},
+ {
+ href: "/memory",
+ label: "Memory",
+ icon: Brain,
+ tooltipKey: "Memory tooltip",
+ },
];
const SECONDARY_NAV: NavEntry[] = [
@@ -276,11 +275,8 @@ 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 === sessionsOwnerHref &&
+ item.href === "/chat" &&
showSessions &&
onSelectSession &&
onRenameSession &&
diff --git a/web/components/sidebar/UtilitySidebar.tsx b/web/components/sidebar/UtilitySidebar.tsx
index 908ac54ba..921c8083c 100644
--- a/web/components/sidebar/UtilitySidebar.tsx
+++ b/web/components/sidebar/UtilitySidebar.tsx
@@ -1,7 +1,7 @@
"use client";
-import { useCallback, useEffect, useMemo, useRef, useState } from "react";
-import { usePathname, useRouter } from "next/navigation";
+import { useCallback, useEffect, useRef, useState } from "react";
+import { useRouter } from "next/navigation";
import { useTranslation } from "react-i18next";
import { SidebarShell } from "@/components/sidebar/SidebarShell";
import { LogoutButton } from "@/components/auth/LogoutButton";
@@ -13,13 +13,10 @@ 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);
@@ -30,35 +27,30 @@ export default function UtilitySidebar() {
setLoadingSessions(true);
}
try {
- setSessions(
- await listSessions(50, 0, { force: true, kind: surface.kind }),
- );
+ setSessions(await listSessions(50, 0, { force: true }));
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, surface.kind]);
+ }, [refreshSessions]);
const handleNewChat = useCallback(() => {
setActiveSessionId(null);
- router.push(surface.basePath);
- }, [router, setActiveSessionId, surface.basePath]);
+ router.push("/chat");
+ }, [router, setActiveSessionId]);
const handleSelectSession = useCallback(
async (sessionId: string) => {
setActiveSessionId(sessionId);
- router.push(`${surface.basePath}/${sessionId}`);
+ router.push(`/chat/${sessionId}`);
},
- [router, setActiveSessionId, surface.basePath],
+ [router, setActiveSessionId],
);
const handleRenameSession = useCallback(
diff --git a/web/components/sidebar/WorkspaceSidebar.tsx b/web/components/sidebar/WorkspaceSidebar.tsx
index 5d254dc14..393db9819 100644
--- a/web/components/sidebar/WorkspaceSidebar.tsx
+++ b/web/components/sidebar/WorkspaceSidebar.tsx
@@ -1,7 +1,7 @@
"use client";
-import { useCallback, useEffect, useMemo, useRef, useState } from "react";
-import { usePathname, useRouter } from "next/navigation";
+import { useCallback, useEffect, useRef, useState } from "react";
+import { useRouter } from "next/navigation";
import { useTranslation } from "react-i18next";
import { SidebarShell } from "@/components/sidebar/SidebarShell";
import { LogoutButton } from "@/components/auth/LogoutButton";
@@ -13,13 +13,10 @@ 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,
@@ -35,23 +32,23 @@ export default function WorkspaceSidebar() {
setLoadingSessions(true);
}
try {
- setSessions(
- await listSessions(50, 0, { force: true, kind: surface.kind }),
- );
+ setSessions(await listSessions(50, 0, { force: true }));
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.
+ // First mount shows the skeleton; subsequent refreshes triggered by
+ // ``sidebarRefreshToken`` (STREAM_END, server-side session bind,
+ // turn deletion) silently swap in the new list. Resetting the ref
+ // each refresh briefly re-renders the loading skeleton, which the
+ // user perceives as a flicker on every message send / Answer Now.
useEffect(() => {
- hasLoadedSessionsRef.current = false;
void refreshSessions();
- }, [refreshSessions, sidebarRefreshToken, surface.kind]);
+ }, [refreshSessions, sidebarRefreshToken]);
const orderedSessions = sessions
.map((session, index) => {
@@ -77,14 +74,14 @@ export default function WorkspaceSidebar() {
const handleNewChat = () => {
newSession();
- router.push(surface.basePath);
+ router.push("/chat");
};
const handleSelectSession = useCallback(
async (sessionId: string) => {
- router.push(`${surface.basePath}/${sessionId}`);
+ router.push(`/chat/${sessionId}`);
},
- [router, surface.basePath],
+ [router],
);
const handleRenameSession = useCallback(
@@ -114,10 +111,10 @@ export default function WorkspaceSidebar() {
);
if (selectedSessionId === sessionId) {
newSession();
- router.push(surface.basePath);
+ router.push("/chat");
}
},
- [newSession, router, selectedSessionId, surface.basePath, t],
+ [newSession, router, selectedSessionId, t],
);
return (
diff --git a/web/components/space/ChatHistorySection.tsx b/web/components/space/ChatHistorySection.tsx
index 52af6d287..720bc83c6 100644
--- a/web/components/space/ChatHistorySection.tsx
+++ b/web/components/space/ChatHistorySection.tsx
@@ -19,29 +19,23 @@ 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.
+ * Sessions list for chat history. Reopened sessions always route back to
+ * the main chat surface.
*/
export interface ChatHistorySectionProps {
- kind?: SurfaceKind;
icon?: LucideIcon;
title?: string;
description?: string;
}
export default function ChatHistorySection({
- kind = "chat",
icon,
title,
description,
}: ChatHistorySectionProps = {}) {
- const basePath = SURFACES[kind].basePath;
+ const basePath = "/chat";
const { t } = useTranslation();
const router = useRouter();
const { activeSessionId, setActiveSessionId } = useAppShell();
@@ -49,17 +43,14 @@ 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, kind }));
- } finally {
- setLoading(false);
- }
- },
- [kind],
- );
+ const load = useCallback(async (force = false) => {
+ setLoading(true);
+ try {
+ setSessions(await listSessions(200, 0, { force }));
+ } finally {
+ setLoading(false);
+ }
+ }, []);
useEffect(() => {
void load(true);
diff --git a/web/components/space/SkillsSection.tsx b/web/components/space/SkillsSection.tsx
index 9f718d141..05bc7b9f3 100644
--- a/web/components/space/SkillsSection.tsx
+++ b/web/components/space/SkillsSection.tsx
@@ -610,7 +610,7 @@ export default function SkillsSection() {
{/* Editor modal */}
{editor && (
<div
- className="fixed inset-0 z-50 flex items-center justify-center bg-black/40 p-4"
+ className="fixed inset-0 z-50 flex items-center justify-center bg-[var(--overlay)] p-4"
role="dialog"
aria-modal="true"
>
diff --git a/web/context/AppShellContext.tsx b/web/context/AppShellContext.tsx
index 1b02cdfbd..08d3ebc01 100644
--- a/web/context/AppShellContext.tsx
+++ b/web/context/AppShellContext.tsx
@@ -58,6 +58,8 @@ export function AppShellProvider({ children }: { children: React.ReactNode }) {
const [sidebarCollapsed, setSidebarCollapsedState] = useState<boolean>(false);
useEffect(() => {
+ // Hydrate client-only preferences after SSR-safe first render.
+ // eslint-disable-next-line react-hooks/set-state-in-effect
setLanguageState(readStoredLanguage());
setSidebarCollapsedState(readStoredSidebarCollapsed());
}, []);
diff --git a/web/context/UnifiedChatContext.tsx b/web/context/UnifiedChatContext.tsx
index f9ec319fd..1b764f467 100644
--- a/web/context/UnifiedChatContext.tsx
+++ b/web/context/UnifiedChatContext.tsx
@@ -23,12 +23,14 @@ import {
getSession,
deleteMessage,
updateBranchSelection,
+ updateSessionTitle,
type SessionMessage,
} from "@/lib/session-api";
import { normalizeMarkdownForDisplay } from "@/lib/markdown-display";
import { normalizeMessageContent } from "@/lib/message-content";
import { buildVisiblePath, tipMessageId } from "@/lib/message-branches";
import { shouldAppendEventContent } from "@/lib/stream";
+import { hasPendingAskUserInMessages } from "@/lib/ask-user-state";
import { notify } from "@/lib/notifications";
import i18n from "i18next";
import {
@@ -72,15 +74,11 @@ export interface SendMessageOptions {
* sibling under this parent rather than appended to the session tail.
* ``null`` means "explicitly attach to the session root". */
parentMessageId?: number | null;
- // Surface that originated the turn. The backend stamps this onto the
- // session row when ``ensure_session`` first creates it, then it never
- // changes. Callers from /co-learn must pass ``"co_learn"`` so the auto
- // routing surface doesn't leak into /chat's history.
- kind?: import("@/lib/unified-ws").SessionKind;
}
export interface ChatState {
sessionId: string | null;
+ sessionTitle: string;
enabledTools: string[];
activeCapability: string | null;
knowledgeBases: string[];
@@ -195,6 +193,7 @@ type Action =
type: "LOAD_SESSION";
key: string;
sessionId: string;
+ title?: string;
messages: MessageItem[];
activeTurnId?: string | null;
status?: SessionRuntimeStatus;
@@ -205,6 +204,7 @@ type Action =
language?: string;
selectedBranches?: Record<string, number>;
}
+ | { type: "SET_SESSION_TITLE"; key: string; title: string }
| { type: "DELETE_TURN"; key: string; messageId: number }
| { type: "NEW_SESSION"; key: string }
| {
@@ -217,7 +217,8 @@ type Action =
type: "REPLACE_SELECTED_BRANCHES";
key: string;
selectedBranches: Record<string, number>;
- };
+ }
+ | { type: "BUMP_SIDEBAR_REFRESH" };
function createSessionEntry(
key: string,
@@ -226,6 +227,7 @@ function createSessionEntry(
return {
key,
sessionId,
+ sessionTitle: "",
enabledTools: [],
activeCapability: null,
knowledgeBases: [],
@@ -266,6 +268,15 @@ function updateSelectedSession(
};
}
+function isSameTurnEvent(a: StreamEvent, b: StreamEvent): boolean {
+ const aSeq = Number(a.seq || 0);
+ const bSeq = Number(b.seq || 0);
+ if (aSeq <= 0 || bSeq <= 0 || aSeq !== bSeq) return false;
+ const aTurn = a.turn_id || "";
+ const bTurn = b.turn_id || "";
+ return Boolean(aTurn && bTurn && aTurn === bTurn);
+}
+
function reducer(state: ProviderState, action: Action): ProviderState {
switch (action.type) {
case "SET_TOOLS":
@@ -425,6 +436,13 @@ function reducer(state: ProviderState, action: Action): ProviderState {
});
last = msgs[msgs.length - 1];
}
+ if (
+ (last?.events || []).some((event) =>
+ isSameTurnEvent(event, action.event),
+ )
+ ) {
+ return state;
+ }
const events = [...(last?.events || []), action.event];
let content = last?.content || "";
if (shouldAppendEventContent(action.event))
@@ -487,6 +505,7 @@ function reducer(state: ProviderState, action: Action): ProviderState {
...current,
key: targetKey,
sessionId: action.sessionId,
+ sessionTitle: current.sessionTitle || existing?.sessionTitle || "",
activeTurnId: action.turnId || current.activeTurnId,
status: current.isStreaming ? "running" : current.status,
updatedAt: Date.now(),
@@ -515,6 +534,8 @@ function reducer(state: ProviderState, action: Action): ProviderState {
...existing,
key: action.key,
sessionId: action.sessionId,
+ sessionTitle:
+ action.title !== undefined ? action.title : existing.sessionTitle,
enabledTools: action.tools ?? existing.enabledTools,
activeCapability:
action.capability !== undefined
@@ -538,6 +559,22 @@ function reducer(state: ProviderState, action: Action): ProviderState {
},
};
}
+ case "SET_SESSION_TITLE": {
+ const session = state.sessions[action.key];
+ if (!session) return state;
+ return {
+ ...state,
+ sessions: {
+ ...state.sessions,
+ [action.key]: {
+ ...session,
+ sessionTitle: action.title,
+ updatedAt: Date.now(),
+ },
+ },
+ sidebarRefreshToken: state.sidebarRefreshToken + 1,
+ };
+ }
case "SET_SELECTED_BRANCH": {
const session = state.sessions[action.key];
if (!session) return state;
@@ -607,6 +644,11 @@ function reducer(state: ProviderState, action: Action): ProviderState {
sidebarRefreshToken: state.sidebarRefreshToken + 1,
};
}
+ case "BUMP_SIDEBAR_REFRESH":
+ return {
+ ...state,
+ sidebarRefreshToken: state.sidebarRefreshToken + 1,
+ };
case "NEW_SESSION": {
const MAX_CACHED_SESSIONS = 20;
let nextSessions = {
@@ -638,6 +680,11 @@ const initialState: ProviderState = {
sidebarRefreshToken: 0,
};
+// Grace window between the orchestrator's ``done`` event and the actual
+// WS disconnect. Keeps the connection alive long enough for post-turn
+// pushes like the LLM-generated ``session_meta`` title update to land.
+const POST_DONE_DISCONNECT_DELAY_MS = 15_000;
+
interface ChatContextValue {
state: ChatState;
setTools: (tools: string[]) => void;
@@ -657,6 +704,24 @@ interface ChatContextValue {
memoryReferences?: MemoryReferencePayload,
) => void;
cancelStreamingTurn: () => void;
+ /**
+ * Deliver the user's reply for a turn that is paused on an
+ * ``ask_user`` tool call. Sends the reply via the unified WS so the
+ * backend can substitute it into the matching ``role=tool`` message
+ * and resume the agentic loop on the **same** turn. No-op when the
+ * active session has no live turn waiting on input.
+ *
+ * Accepts a plain string (legacy single-question reply) or a
+ * structured object with ``answers`` (v2 multi-question reply).
+ */
+ submitUserReply: (
+ reply:
+ | string
+ | {
+ text?: string;
+ answers?: Array<{ questionId: string; text: string }>;
+ },
+ ) => void;
regenerateLastMessage: () => void;
deleteTurn: (messageId: number) => Promise<void>;
/** Re-send a user message under a new branch (sibling of the original).
@@ -666,6 +731,7 @@ interface ChatContextValue {
editMessage: (messageId: number, newContent: string) => Promise<void>;
/** Switch which sibling is currently visible at a branch point. */
switchBranch: (parentMessageId: number | null, childId: number) => void;
+ renameSessionTitle: (title: string) => Promise<void>;
newSession: () => void;
loadSession: (sessionId: string) => Promise<void>;
selectedSessionId: string | null;
@@ -918,6 +984,26 @@ export function UnifiedChatProvider({
}
return;
}
+ if (event.type === "session_meta") {
+ // Post-turn metadata push (currently only used for the
+ // LLM-generated session title). The backend writes the new
+ // title to its store *before* sending this event. Update the
+ // active header immediately and bump the sidebar so history
+ // rows refresh to the generated title without a flicker.
+ const title = String(
+ (event.metadata as { title?: string } | undefined)?.title || "",
+ ).trim();
+ if (title) {
+ dispatch({
+ type: "SET_SESSION_TITLE",
+ key: effectiveKey,
+ title,
+ });
+ } else {
+ dispatch({ type: "BUMP_SIDEBAR_REFRESH" });
+ }
+ return;
+ }
if (event.type === "done") {
const status = String(
(event.metadata as { status?: string } | undefined)?.status ||
@@ -931,16 +1017,25 @@ export function UnifiedChatProvider({
});
pendingRegenerateRef.current.delete(effectiveKey);
const runner = runnersRef.current.get(effectiveKey);
- runner?.client.disconnect();
- runnersRef.current.delete(effectiveKey);
+ // Hold the WS open briefly so post-turn ``session_meta`` events
+ // (e.g. the LLM-generated title for the first user/assistant
+ // pair) can still reach us. The backend generates the title
+ // before its finally block sends the subscriber sentinel, but
+ // the title model can take a couple of seconds — disconnecting
+ // synchronously on ``done`` would race that publish.
+ if (runner) {
+ runnersRef.current.delete(effectiveKey);
+ window.setTimeout(() => {
+ runner.client.disconnect();
+ }, POST_DONE_DISCONNECT_DELAY_MS);
+ }
// Reconcile optimistic client-side message ids with the
// server's real ids after the turn finishes. Without this the
// Edit button (which needs a real id to attach the new branch
// under) and branch navigation (which keys off real ids) would
// stay disabled until the user navigates away and back.
if (status === "completed") {
- const finishedSession =
- stateRef.current.sessions[effectiveKey];
+ const finishedSession = stateRef.current.sessions[effectiveKey];
const sessionId = finishedSession?.sessionId;
if (sessionId) {
loadSessionRef.current?.(sessionId).catch(() => {
@@ -1011,6 +1106,14 @@ export function UnifiedChatProvider({
() => {
const session = stateRef.current.sessions[record.key];
if (session?.isStreaming) {
+ if (
+ hasPendingAskUserInMessages(
+ session.messages,
+ session.activeTurnId,
+ )
+ ) {
+ return;
+ }
dispatch({
type: "STREAM_END",
key: record.key,
@@ -1030,6 +1133,10 @@ export function UnifiedChatProvider({
),
};
runnersRef.current.set(key, record);
+ const session = stateRef.current.sessions[key];
+ if (session?.activeTurnId) {
+ record.client.setResumeState(session.activeTurnId, session.lastSeq);
+ }
record.client.connect();
return record;
},
@@ -1076,6 +1183,7 @@ export function UnifiedChatProvider({
type: "LOAD_SESSION",
key: session.session_id || session.id,
sessionId: session.session_id || session.id,
+ title: session.title || "",
messages: hydrateMessages(session.messages ?? []),
activeTurnId: activeTurn?.turn_id || activeTurn?.id || null,
status:
@@ -1162,6 +1270,11 @@ export function UnifiedChatProvider({
const current = stateRef.current;
for (const [key, session] of Object.entries(current.sessions)) {
if (!session.isStreaming) continue;
+ if (
+ hasPendingAskUserInMessages(session.messages, session.activeTurnId)
+ ) {
+ continue;
+ }
if (Date.now() - session.updatedAt <= IDLE_TIMEOUT_MS) continue;
dispatch({
@@ -1234,20 +1347,46 @@ export function UnifiedChatProvider({
replaySnapshot?.memoryReferences ?? memoryReferences;
const effectiveBookReferences =
replaySnapshot?.bookReferences ?? options?.bookReferences;
+ const effectiveAttachments =
+ replaySnapshot?.attachments?.map((a) => ({
+ type: a.type,
+ filename: a.filename,
+ base64: a.base64,
+ url: a.url,
+ mime_type: a.mime_type,
+ })) ?? msgAttachments;
+ const effectiveConfig = config ?? replaySnapshot?.config;
+ const effectiveNotebookReferences =
+ replaySnapshot?.notebookReferences ?? notebookReferences;
+ const effectiveHistoryReferences =
+ replaySnapshot?.historyReferences ?? historyReferences;
+ const effectiveQuestionNotebookReferences =
+ replaySnapshot?.questionNotebookReferences ??
+ questionNotebookReferences;
const requestSnapshot: MessageRequestSnapshot = replaySnapshot ?? {
content,
capability: effectiveCapability,
enabledTools: [...effectiveTools],
knowledgeBases: [...effectiveKnowledgeBases],
language: effectiveLanguage,
- ...(msgAttachments?.length ? { attachments: msgAttachments } : {}),
- ...(config && Object.keys(config).length > 0 ? { config } : {}),
- ...(notebookReferences?.length ? { notebookReferences } : {}),
- ...(historyReferences?.length
- ? { historyReferences: [...historyReferences] }
+ ...(effectiveAttachments?.length
+ ? { attachments: effectiveAttachments }
+ : {}),
+ ...(effectiveConfig && Object.keys(effectiveConfig).length > 0
+ ? { config: effectiveConfig }
+ : {}),
+ ...(effectiveNotebookReferences?.length
+ ? { notebookReferences: effectiveNotebookReferences }
: {}),
- ...(questionNotebookReferences?.length
- ? { questionNotebookReferences: [...questionNotebookReferences] }
+ ...(effectiveHistoryReferences?.length
+ ? { historyReferences: [...effectiveHistoryReferences] }
+ : {}),
+ ...(effectiveQuestionNotebookReferences?.length
+ ? {
+ questionNotebookReferences: [
+ ...effectiveQuestionNotebookReferences,
+ ],
+ }
: {}),
...(effectiveBookReferences?.length
? { bookReferences: effectiveBookReferences }
@@ -1287,16 +1426,16 @@ export function UnifiedChatProvider({
key,
content,
capability: effectiveCapability,
- attachments: msgAttachments,
+ attachments: effectiveAttachments,
requestSnapshot,
parentMessageId: localParentId,
});
}
dispatch({ type: "STREAM_START", key });
- const effectiveConfig =
+ const effectiveTurnConfig =
options?.persistUserMessage === false
- ? { ...(config || {}), _persist_user_message: false }
- : config;
+ ? { ...(effectiveConfig || {}), _persist_user_message: false }
+ : effectiveConfig;
sendThroughRunner(key, {
type: "start_turn",
content,
@@ -1304,17 +1443,18 @@ export function UnifiedChatProvider({
capability: effectiveCapability,
knowledge_bases: effectiveKnowledgeBases,
session_id: session.sessionId,
- ...(options?.kind ? { kind: options.kind } : {}),
- attachments,
+ attachments: effectiveAttachments,
language: effectiveLanguage,
- ...(notebookReferences?.length
- ? { notebook_references: notebookReferences }
+ ...(effectiveNotebookReferences?.length
+ ? { notebook_references: effectiveNotebookReferences }
: {}),
- ...(historyReferences?.length
- ? { history_references: historyReferences }
+ ...(effectiveHistoryReferences?.length
+ ? { history_references: effectiveHistoryReferences }
: {}),
- ...(questionNotebookReferences?.length
- ? { question_notebook_references: questionNotebookReferences }
+ ...(effectiveQuestionNotebookReferences?.length
+ ? {
+ question_notebook_references: effectiveQuestionNotebookReferences,
+ }
: {}),
...(effectiveBookReferences?.length
? { book_references: effectiveBookReferences }
@@ -1326,8 +1466,8 @@ export function UnifiedChatProvider({
...(effectiveLLMSelection
? { llm_selection: effectiveLLMSelection }
: {}),
- ...(effectiveConfig && Object.keys(effectiveConfig).length > 0
- ? { config: effectiveConfig }
+ ...(effectiveTurnConfig && Object.keys(effectiveTurnConfig).length > 0
+ ? { config: effectiveTurnConfig }
: {}),
// Send ``parent_message_id`` only when we have a real (positive)
// server id to chain under, or when the caller explicitly pinned
@@ -1359,6 +1499,44 @@ export function UnifiedChatProvider({
dispatch({ type: "STREAM_END", key, status: "cancelled" });
}, []);
+ const submitUserReply = useCallback(
+ (
+ reply:
+ | string
+ | {
+ text?: string;
+ answers?: Array<{ questionId: string; text: string }>;
+ },
+ ) => {
+ const currentState = stateRef.current;
+ const key = currentState.selectedKey;
+ if (!key) return;
+ const session = currentState.sessions[key];
+ const turnId = session?.activeTurnId;
+ const pendingAskUser = session
+ ? hasPendingAskUserInMessages(session.messages, turnId)
+ : false;
+ // Only meaningful while a turn is live. A paused ask_user turn can be
+ // silent long enough for the socket to reconnect, so allow submission
+ // whenever the unresolved card and active turn id are still present.
+ if (!session || !turnId || (!session.isStreaming && !pendingAskUser)) {
+ return;
+ }
+ const message: import("@/lib/unified-ws").SubmitUserReplyMessage = {
+ type: "submit_user_reply",
+ turn_id: turnId,
+ };
+ if (typeof reply === "string") {
+ message.text = reply;
+ } else {
+ if (typeof reply.text === "string") message.text = reply.text;
+ if (Array.isArray(reply.answers)) message.answers = reply.answers;
+ }
+ sendThroughRunner(key, message);
+ },
+ [sendThroughRunner],
+ );
+
const regenerateLastMessage = useCallback(() => {
const currentState = stateRef.current;
const key = currentState.selectedKey;
@@ -1394,6 +1572,7 @@ export function UnifiedChatProvider({
const current = ensureSelectedSession(state);
return {
sessionId: current.sessionId,
+ sessionTitle: current.sessionTitle,
enabledTools: current.enabledTools,
activeCapability: current.activeCapability,
knowledgeBases: current.knowledgeBases,
@@ -1440,6 +1619,23 @@ export function UnifiedChatProvider({
dispatch({ type: "SET_LANGUAGE", lang });
}, []);
+ const renameSessionTitle = useCallback(async (title: string) => {
+ const trimmed = title.trim();
+ if (!trimmed) return;
+ const currentState = stateRef.current;
+ const key = currentState.selectedKey;
+ if (!key) return;
+ const session = currentState.sessions[key];
+ const sessionId = session?.sessionId;
+ if (!sessionId) return;
+ const updated = await updateSessionTitle(sessionId, trimmed);
+ dispatch({
+ type: "SET_SESSION_TITLE",
+ key,
+ title: updated.title || trimmed,
+ });
+ }, []);
+
const newSession = useCallback(() => {
dispatch({ type: "NEW_SESSION", key: makeDraftKey() });
}, [makeDraftKey]);
@@ -1509,7 +1705,8 @@ export function UnifiedChatProvider({
if (!key) return;
const session = currentState.sessions[key];
if (!session) return;
- const parentKey = parentMessageId == null ? "null" : String(parentMessageId);
+ const parentKey =
+ parentMessageId == null ? "null" : String(parentMessageId);
dispatch({
type: "SET_SELECTED_BRANCH",
key,
@@ -1580,10 +1777,12 @@ export function UnifiedChatProvider({
setLanguage,
sendMessage,
cancelStreamingTurn,
+ submitUserReply,
regenerateLastMessage,
deleteTurn,
editMessage,
switchBranch,
+ renameSessionTitle,
newSession,
loadSession,
selectedSessionId: derivedState.sessionId,
@@ -1599,10 +1798,12 @@ export function UnifiedChatProvider({
setLanguage,
sendMessage,
cancelStreamingTurn,
+ submitUserReply,
regenerateLastMessage,
deleteTurn,
editMessage,
switchBranch,
+ renameSessionTitle,
newSession,
loadSession,
sessionStatuses,
diff --git a/web/features/multi-user/components/GrantEditor.tsx b/web/features/multi-user/components/GrantEditor.tsx
index 32354ced7..6b81ada5d 100644
--- a/web/features/multi-user/components/GrantEditor.tsx
+++ b/web/features/multi-user/components/GrantEditor.tsx
@@ -45,9 +45,6 @@ export function GrantEditor({ userId }: { userId: string }) {
useEffect(() => {
let cancelled = false;
- setLoading(true);
- setSaveState("idle");
- setMessage("");
Promise.all([fetchAdminResources(), fetchUserGrant(userId)])
.then(([nextResources, nextGrant]) => {
if (cancelled) return;
diff --git a/web/hooks/useKnowledgeProgress.ts b/web/hooks/useKnowledgeProgress.ts
index 30f62bd98..d9dbd9a34 100644
--- a/web/hooks/useKnowledgeProgress.ts
+++ b/web/hooks/useKnowledgeProgress.ts
@@ -143,6 +143,7 @@ export function useKnowledgeProgress(options?: UseKnowledgeProgressOptions) {
const source = new EventSource(
apiUrl(`/api/v1/knowledge/tasks/${encodeURIComponent(taskId)}/stream`),
+ { withCredentials: true },
);
sourcesRef.current[kbName] = source;
diff --git a/web/i18n/I18nProvider.tsx b/web/i18n/I18nProvider.tsx
index 13bafb022..bc5decd2f 100644
--- a/web/i18n/I18nProvider.tsx
+++ b/web/i18n/I18nProvider.tsx
@@ -3,7 +3,12 @@
import { useEffect } from "react";
import i18n from "i18next";
-import { initI18n, normalizeLanguage, type AppLanguage } from "./init";
+import {
+ ensureLanguage,
+ initI18n,
+ normalizeLanguage,
+ type AppLanguage,
+} from "./init";
// Initialize i18next at module load (before any React render) so that the
// `init()` call — which fires `initialized` / `languageChanged` events that
@@ -22,15 +27,19 @@ export function I18nProvider({
children: React.ReactNode;
}) {
useEffect(() => {
+ let cancelled = false;
const nextLang = normalizeLanguage(language);
- if (i18n.language !== nextLang) {
- i18n.changeLanguage(nextLang);
- }
-
- // Keep <html lang="..."> in sync for accessibility & Intl defaults
- if (typeof document !== "undefined") {
+ void ensureLanguage(nextLang).then(() => {
+ if (cancelled) return;
+ if (i18n.language !== nextLang) {
+ i18n.changeLanguage(nextLang);
+ }
+ // Keep <html lang="..."> in sync for accessibility & Intl defaults.
document.documentElement.lang = nextLang;
- }
+ });
+ return () => {
+ cancelled = true;
+ };
}, [language]);
return children;
diff --git a/web/i18n/init.ts b/web/i18n/init.ts
index f57a314a4..7509c6489 100644
--- a/web/i18n/init.ts
+++ b/web/i18n/init.ts
@@ -2,7 +2,6 @@ import i18n, { type Resource } from "i18next";
import { initReactI18next } from "react-i18next";
import enApp from "@/locales/en/app.json";
-import zhApp from "@/locales/zh/app.json";
export type AppLanguage = "en" | "zh";
@@ -20,7 +19,6 @@ export function initI18n(language?: unknown) {
const resources: Resource = {
en: { app: enApp },
- zh: { app: zhApp },
};
i18n.use(initReactI18next).init({
@@ -42,3 +40,11 @@ export function initI18n(language?: unknown) {
_initialized = true;
return i18n;
}
+
+export async function ensureLanguage(language: AppLanguage) {
+ if (i18n.hasResourceBundle(language, "app")) return;
+ if (language === "zh") {
+ const zhApp = (await import("@/locales/zh/app.json")).default;
+ i18n.addResourceBundle("zh", "app", zhApp, true, true);
+ }
+}
diff --git a/web/lib/api.ts b/web/lib/api.ts
index da65b8dc2..23a8d9b31 100644
--- a/web/lib/api.ts
+++ b/web/lib/api.ts
@@ -1,22 +1,36 @@
// API configuration and utility functions
-// Get API base URL injected by the launcher from data/user/settings/system.json.
-export const API_BASE_URL =
- process.env.NEXT_PUBLIC_API_BASE ||
- (() => {
+// The Docker image and the `deeptutor start` launcher both build the Next.js
+// bundle with this literal placeholder and substitute it at container/process
+// start. If a deployment serves bundles where the substitution silently
+// failed (read-only fs, missing tool, etc.), every API call would target a
+// broken URL and the Settings page would render blank with no clue why.
+// Treating the placeholder as "not configured" surfaces the failure mode
+// instead of letting fetches die quietly.
+const API_BASE_PLACEHOLDER = "__NEXT_PUBLIC_API_BASE_PLACEHOLDER__";
+
+function resolveBuildTimeApiBase(): string {
+ const raw = process.env.NEXT_PUBLIC_API_BASE;
+ if (!raw || raw === API_BASE_PLACEHOLDER) {
if (typeof window !== "undefined") {
- console.error("NEXT_PUBLIC_API_BASE is not set.");
console.error(
- "Please configure data/user/settings/system.json and restart the application.",
+ raw === API_BASE_PLACEHOLDER
+ ? "NEXT_PUBLIC_API_BASE placeholder was not substituted at startup."
+ : "NEXT_PUBLIC_API_BASE is not set.",
);
console.error(
- "Run python scripts/start_tour.py to rebuild your local setup if needed.",
+ "Please configure data/user/settings/system.json and restart the application.",
);
}
throw new Error(
"NEXT_PUBLIC_API_BASE is not configured. Please update data/user/settings/system.json and restart.",
);
- })();
+ }
+ return raw;
+}
+
+// Get API base URL injected by the launcher from data/user/settings/system.json.
+export const API_BASE_URL = resolveBuildTimeApiBase();
// Hostnames that always refer to the local machine. When the build-time base
// URL points to one of these, but the page is opened from a non-local origin,
diff --git a/web/lib/co-writer-api.ts b/web/lib/co-writer-api.ts
index 3e1fda9b4..182ba1dd3 100644
--- a/web/lib/co-writer-api.ts
+++ b/web/lib/co-writer-api.ts
@@ -31,7 +31,9 @@ async function jsonOrThrow<T>(res: Response): Promise<T> {
export async function listCoWriterDocuments(): Promise<
CoWriterDocumentSummary[]
> {
- const res = await apiFetch(apiUrl(`${BASE}/documents`), { cache: "no-store" });
+ const res = await apiFetch(apiUrl(`${BASE}/documents`), {
+ cache: "no-store",
+ });
const data = await jsonOrThrow<{ documents: CoWriterDocumentSummary[] }>(res);
return Array.isArray(data?.documents) ? data.documents : [];
}
diff --git a/web/lib/iframe-html.ts b/web/lib/iframe-html.ts
index 503830abe..9492525ce 100644
--- a/web/lib/iframe-html.ts
+++ b/web/lib/iframe-html.ts
@@ -2,8 +2,8 @@
* Helpers for rendering AI-generated HTML inside a sandboxed `<iframe>`:
* - {@link injectKaTeX} ensures the page can render `$...$` / `$$...$$`
* even if the model didn't include KaTeX itself.
- * - {@link sanitizeIframeHtml} strips bare `<script>` blocks (except the
- * KaTeX init shim) and any inline event handlers / `javascript:` URLs.
+ * - {@link sanitizeIframeHtml} strips navigation escapes while leaving
+ * interactive scripts isolated by the caller's sandboxed iframe.
*
* These were originally written for the (now-deprecated) Guided Learning
* page; the visualize capability now reuses them for `render_mode=html`.
@@ -17,7 +17,6 @@ const KATEX_RESOURCES = [
"/script>",
].join("\n ");
-// eslint-disable-next-line no-template-curly-in-string
const KATEX_INIT_SCRIPT =
"<script data-katex-init>" +
'document.addEventListener("DOMContentLoaded",function(){var t=0,i=setInterval(function(){if(typeof renderMathInElement==="function"){clearInterval(i);try{renderMathInElement(document.body,{delimiters:[{left:"$$",right:"$$",display:true},{left:"$",right:"$",display:false},{left:"\\\\(",right:"\\\\)",display:false},{left:"\\\\[",right:"\\\\]",display:true}],throwOnError:false})}catch(e){console.error("[KaTeX] Error:",e)}}else if(++t>50){clearInterval(i);console.warn("[KaTeX] Timeout")}},100)});' +
diff --git a/web/lib/markdown-display.ts b/web/lib/markdown-display.ts
index 7c6ad0ab3..34c93c7d9 100644
--- a/web/lib/markdown-display.ts
+++ b/web/lib/markdown-display.ts
@@ -99,62 +99,18 @@ const ALLOWED_HTML_TAGS = new Set<string>([
"caption",
"col",
"colgroup",
- // media
+ // passive media
"img",
"video",
"audio",
"source",
"picture",
"track",
- "iframe",
- "canvas",
- "embed",
- "object",
- "param",
- "map",
- "area",
- // disclosure / forms (we keep these even if they are usually stripped)
+ // disclosure / lightweight status
"details",
"summary",
"progress",
"meter",
- "input",
- "textarea",
- "select",
- "button",
- "label",
- "fieldset",
- "legend",
- "form",
- "option",
- "optgroup",
- "datalist",
- "output",
- // svg
- "svg",
- "g",
- "path",
- "rect",
- "circle",
- "ellipse",
- "line",
- "polyline",
- "polygon",
- "text",
- "tspan",
- "use",
- "defs",
- "lineargradient",
- "radialgradient",
- "stop",
- "marker",
- "pattern",
- "mask",
- "clippath",
- "symbol",
- "title",
- "desc",
- "foreignobject",
// mathml
"math",
"mi",
@@ -184,6 +140,29 @@ const FENCED_CODE_BLOCK_REGEX = /```[\s\S]*?```/g;
const INLINE_CODE_SPAN_REGEX = /`[^`\n]*`/g;
const PROTECTED_SPAN_REGEX = /```[\s\S]*?```|`[^`\n]*`/g;
const PROTECTED_PLACEHOLDER_REGEX = /\u0000PROTECTED_(\d+)\u0000/g;
+const HTML_ATTR_VALUE = /(?:"[^"]*"|'[^']*'|[^\s"'=<>`]+)/.source;
+const HTML_EVENT_ATTR_REGEX = new RegExp(
+ String.raw`\s+on[a-z]+\s*=\s*${HTML_ATTR_VALUE}`,
+ "gi",
+);
+const HTML_STYLE_ATTR_REGEX = new RegExp(
+ String.raw`\s+style\s*=\s*${HTML_ATTR_VALUE}`,
+ "gi",
+);
+const HTML_SRCDOC_ATTR_REGEX = new RegExp(
+ String.raw`\s+srcdoc\s*=\s*${HTML_ATTR_VALUE}`,
+ "gi",
+);
+const HTML_UNSAFE_URL_ATTR_REGEX =
+ /\s+(href|src|xlink:href|formaction)\s*=\s*(?:"\s*(?:javascript:|data:text\/html|data:image\/svg\+xml)[^"]*"|'\s*(?:javascript:|data:text\/html|data:image\/svg\+xml)[^']*'|(?:javascript:|data:text\/html|data:image\/svg\+xml)[^\s"'=<>`]+)/gi;
+
+function sanitizeAllowedHtmlTag(tag: string): string {
+ return tag
+ .replace(HTML_EVENT_ATTR_REGEX, "")
+ .replace(HTML_STYLE_ATTR_REGEX, "")
+ .replace(HTML_SRCDOC_ATTR_REGEX, "")
+ .replace(HTML_UNSAFE_URL_ATTR_REGEX, "");
+}
function escapeUnknownHtmlTags(content: string): string {
if (!content || (!content.includes("<") && !content.includes(">"))) {
@@ -196,7 +175,7 @@ function escapeUnknownHtmlTags(content: string): string {
});
const escaped = masked.replace(HTML_LIKE_TAG_REGEX, (match, name: string) => {
const lower = String(name).toLowerCase();
- if (ALLOWED_HTML_TAGS.has(lower)) return match;
+ if (ALLOWED_HTML_TAGS.has(lower)) return sanitizeAllowedHtmlTag(match);
// Already wrapped in backticks (would happen if the source already
// protected a similar token earlier in the string).
return `\`${match}\``;
@@ -314,7 +293,8 @@ function removeEmptyHtmlTables(content: string): string {
const PREFIXED_CIT = String.raw`(?:web|rag|code|src)-\d+`;
const NUMERIC_CIT = String.raw`\d+`;
-const SINGLE_CIT = `(?:${PREFIXED_CIT}|${NUMERIC_CIT})`;
+const RESEARCH_CIT = String.raw`(?:CIT-\d+-\d+|PLAN-\d+)`;
+const SINGLE_CIT = `(?:${PREFIXED_CIT}|${NUMERIC_CIT}|${RESEARCH_CIT})`;
const MULTI_CIT = `${SINGLE_CIT}(?:\\s*,\\s*${SINGLE_CIT})*`;
const INLINE_CITATION_REGEX = new RegExp(
@@ -330,13 +310,26 @@ const ESCAPED_CITATION_LINK_REGEX = new RegExp(
String.raw`]\)`,
"g",
);
+const EXISTING_RESEARCH_CITATION_LINK_REGEX = new RegExp(
+ String.raw`\[(${RESEARCH_CIT})\]\(#(ref-[a-z0-9_-]+)\s+["` +
+ "\u201c" +
+ String.raw`]citation["` +
+ "\u201d" +
+ String.raw`]\)`,
+ "gi",
+);
+const REFERENCE_LIST_START_REGEX =
+ /^##\s+(References|参考文献|参考资料)|<details\b[^>]*\bid=["']references["'][^>]*>/im;
+const REFERENCE_LIST_DATA_ID_REGEX =
+ /data-citation-id=["'](CIT-\d+-\d+|PLAN-\d+)["']/gi;
+const RESEARCH_CITATION_ID_TEXT_REGEX = /\b(CIT-\d+-\d+|PLAN-\d+)\b/gi;
function unwrapBacktickedCitations(content: string): string {
return content.replace(
new RegExp(
"`(\\[" +
MULTI_CIT +
- '\\](?:\\s*\\(#references\\s+["\\u201c]citation["\\u201d]\\))?)`',
+ '\\](?:\\s*\\(#(?:references|ref-[a-z0-9_-]+)\\s+["\\u201c]citation["\\u201d]\\))?)`',
"g",
),
"$1",
@@ -344,38 +337,110 @@ function unwrapBacktickedCitations(content: string): string {
}
function linkifyCitations(content: string): string {
- const refSectionIdx = content.search(/^##\s+(References|参考文献)/m);
+ const citationNumbers = buildResearchCitationNumberMap(content);
+ const refSectionIdx = content.search(REFERENCE_LIST_START_REGEX);
const body = refSectionIdx >= 0 ? content.slice(0, refSectionIdx) : content;
const tail = refSectionIdx >= 0 ? content.slice(refSectionIdx) : "";
// Normalize existing citation links that may have escaped brackets or smart quotes
- let linked = body.replace(
- ESCAPED_CITATION_LINK_REGEX,
- (_match, id: string) => `[${id.trim()}](#references "citation")`,
+ let linked = body.replace(ESCAPED_CITATION_LINK_REGEX, (_match, id: string) =>
+ formatCitationLinks(id.trim(), citationNumbers),
+ );
+
+ linked = linked.replace(
+ EXISTING_RESEARCH_CITATION_LINK_REGEX,
+ (_match, id: string) => formatCitationLinks(id.trim(), citationNumbers),
);
// Convert bare [web-1] / [rag-1] / [1] / [1, 3] references to a single citation link
linked = linked.replace(INLINE_CITATION_REGEX, (_match, refs: string) => {
- return `[${refs.trim()}](#references "citation")`;
+ return formatCitationLinks(refs, citationNumbers);
});
// Handle escaped bare citations like \[web-1\] or \[1\] that linkifyCitations missed
linked = linked.replace(
new RegExp(String.raw`\\\[(${MULTI_CIT})\\\](?!\s*\()`, "g"),
(_match, refs: string) => {
- return `[${refs.trim()}](#references "citation")`;
+ return formatCitationLinks(refs, citationNumbers);
},
);
// Remove stray space before trailing punctuation after citations
linked = linked.replace(
- /(\(#references\s+"citation"\))\s+([.。,,;:!?])/g,
+ /(\(#(?:references|ref-[a-z0-9_-]+)\s+"citation"\))\s+([.。,,;:!?])/gi,
"$1$2",
);
return linked + tail;
}
+export function citationAnchorIdFor(id: string): string | null {
+ const normalized = String(id || "").trim();
+ if (!/^(?:CIT-\d+-\d+|PLAN-\d+)$/i.test(normalized)) return null;
+ return `ref-${normalized.toLowerCase().replace(/[^a-z0-9_-]+/g, "-")}`;
+}
+
+export function citationHrefForId(id: string): string {
+ const anchor = citationAnchorIdFor(id);
+ return anchor ? `#${anchor}` : "#references";
+}
+
+function citationHrefForRefs(refs: string): string {
+ const ids = String(refs || "")
+ .split(/\s*,\s*/)
+ .map((id) => id.trim())
+ .filter(Boolean);
+ return ids.length === 1 ? citationHrefForId(ids[0]) : "#references";
+}
+
+function isResearchCitationId(id: string): boolean {
+ return /^(?:CIT-\d+-\d+|PLAN-\d+)$/i.test(String(id || "").trim());
+}
+
+function buildResearchCitationNumberMap(content: string): Map<string, number> {
+ const map = new Map<string, number>();
+ const refSectionIdx = content.search(REFERENCE_LIST_START_REGEX);
+ const scan = refSectionIdx >= 0 ? content.slice(refSectionIdx) : content;
+
+ const add = (id: string) => {
+ const normalized = String(id || "").trim();
+ if (!isResearchCitationId(normalized) || map.has(normalized)) return;
+ map.set(normalized, map.size + 1);
+ };
+
+ for (const match of scan.matchAll(REFERENCE_LIST_DATA_ID_REGEX)) {
+ add(match[1] || "");
+ }
+ if (map.size === 0) {
+ for (const match of scan.matchAll(RESEARCH_CITATION_ID_TEXT_REGEX)) {
+ add(match[1] || "");
+ }
+ }
+ return map;
+}
+
+function formatCitationLinks(
+ refs: string,
+ citationNumbers: Map<string, number>,
+): string {
+ const ids = String(refs || "")
+ .split(/\s*,\s*/)
+ .map((id) => id.trim())
+ .filter(Boolean);
+ if (!ids.length) return `[${refs}](#references "citation")`;
+ if (ids.every(isResearchCitationId)) {
+ return ids
+ .map((id) => {
+ const number = citationNumbers.get(id) ?? Number.NaN;
+ const label = Number.isFinite(number) ? String(number) : id;
+ return `[${label}](${citationHrefForId(id)} "citation")`;
+ })
+ .join("");
+ }
+ const label = ids.join(", ");
+ return `[${label}](${citationHrefForRefs(label)} "citation")`;
+}
+
function maskProtectedSpans(
content: string,
regex: RegExp,
diff --git a/web/lib/notebook-api.ts b/web/lib/notebook-api.ts
index beff27be0..818e4c076 100644
--- a/web/lib/notebook-api.ts
+++ b/web/lib/notebook-api.ts
@@ -119,10 +119,18 @@ export async function deleteNotebookRecord(
// ── Question notebook (quiz entries + categories) ─────────────────
+export interface NotebookAnswerImage {
+ id: string;
+ url: string;
+ filename: string;
+ mime_type: string;
+}
+
export interface NotebookEntry {
id: number;
session_id: string;
session_title: string;
+ turn_id: string;
question_id: string;
question: string;
question_type: string;
@@ -131,9 +139,12 @@ export interface NotebookEntry {
explanation: string;
difficulty: string;
user_answer: string;
+ user_answer_images?: NotebookAnswerImage[];
is_correct: boolean;
bookmarked: boolean;
followup_session_id: string;
+ /** Latest AI-judge text for this entry; empty when never run. */
+ ai_judgment?: string;
created_at: number;
updated_at: number;
categories?: NotebookCategory[];
@@ -201,11 +212,13 @@ export async function getNotebookEntry(
export async function lookupNotebookEntry(
sessionId: string,
questionId: string,
+ turnId?: string | null,
): Promise<NotebookEntry | null> {
const params = new URLSearchParams({
session_id: sessionId,
question_id: questionId,
});
+ if (turnId) params.set("turn_id", turnId);
const response = await apiFetch(
apiUrl(`/api/v1/question-notebook/entries/lookup/by-question?${params}`),
);
@@ -215,7 +228,11 @@ export async function lookupNotebookEntry(
export async function updateNotebookEntry(
entryId: number,
- updates: { bookmarked?: boolean; followup_session_id?: string },
+ updates: {
+ bookmarked?: boolean;
+ followup_session_id?: string;
+ ai_judgment?: string;
+ },
): Promise<void> {
const response = await apiFetch(
apiUrl(`/api/v1/question-notebook/entries/${entryId}`),
@@ -228,8 +245,19 @@ export async function updateNotebookEntry(
await expectJson<{ updated: boolean }>(response);
}
+export interface NotebookAnswerImageUpload {
+ id?: string;
+ /** Base64 (no ``data:`` prefix) for a freshly-picked image. */
+ base64?: string;
+ /** Existing AttachmentStore URL for an already-persisted image. */
+ url?: string;
+ filename: string;
+ mime_type: string;
+}
+
export async function upsertNotebookEntry(data: {
session_id: string;
+ turn_id?: string;
question_id: string;
question: string;
question_type?: string;
@@ -238,6 +266,11 @@ export async function upsertNotebookEntry(data: {
explanation?: string;
difficulty?: string;
user_answer?: string;
+ /**
+ * Optional list of images attached to the learner's answer. Omit to
+ * leave any stored images untouched; pass an empty array to clear them.
+ */
+ user_answer_images?: NotebookAnswerImageUpload[];
is_correct?: boolean;
}): Promise<NotebookEntry> {
const response = await apiFetch(
@@ -299,18 +332,24 @@ export async function removeEntryFromCategory(
// ── Categories ──────────────────────────────────────────────────
export async function listCategories(): Promise<NotebookCategory[]> {
- const response = await apiFetch(apiUrl("/api/v1/question-notebook/categories"), {
- cache: "no-store",
- });
+ const response = await apiFetch(
+ apiUrl("/api/v1/question-notebook/categories"),
+ {
+ cache: "no-store",
+ },
+ );
return expectJson<NotebookCategory[]>(response);
}
export async function createCategory(name: string): Promise<NotebookCategory> {
- const response = await apiFetch(apiUrl("/api/v1/question-notebook/categories"), {
- method: "POST",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({ name }),
- });
+ const response = await apiFetch(
+ apiUrl("/api/v1/question-notebook/categories"),
+ {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ name }),
+ },
+ );
return expectJson<NotebookCategory>(response);
}
diff --git a/web/lib/research-types.ts b/web/lib/research-types.ts
index b39c8bd35..7c9328715 100644
--- a/web/lib/research-types.ts
+++ b/web/lib/research-types.ts
@@ -5,7 +5,6 @@ export type ResearchMode =
| "comparison"
| "learning_path";
export type ResearchDepth = "" | "quick" | "standard" | "deep" | "manual";
-export type ResearchSource = "kb" | "web" | "papers";
export interface OutlineItem {
title: string;
@@ -15,7 +14,6 @@ export interface OutlineItem {
export interface DeepResearchFormConfig {
mode: ResearchMode;
depth: ResearchDepth;
- sources: ResearchSource[];
manual_subtopics?: number;
manual_max_iterations?: number;
confirmed_outline?: OutlineItem[];
@@ -30,7 +28,6 @@ export function createEmptyResearchConfig(): DeepResearchFormConfig {
return {
mode: "",
depth: "",
- sources: [],
};
}
@@ -53,12 +50,6 @@ export function normalizeResearchConfig(
raw?.depth === "manual"
? raw.depth
: empty.depth,
- sources: Array.isArray(raw?.sources)
- ? raw.sources.filter(
- (source): source is ResearchSource =>
- source === "kb" || source === "web" || source === "papers",
- )
- : empty.sources,
};
}
@@ -89,7 +80,6 @@ export function buildResearchWSConfig(
const result: Record<string, unknown> = {
mode: cfg.mode,
depth: cfg.depth,
- sources: [...cfg.sources],
};
if (cfg.depth === "manual") {
@@ -128,11 +118,8 @@ export function summarizeResearchConfig(
const validation = validateResearchConfig(cfg);
const tr = translate ?? ((s: string) => s);
if (!validation.valid) return tr("Incomplete settings");
- const sourceSummary = cfg.sources.length
- ? cfg.sources.join("+")
- : tr("llm-only");
const modeLabel =
RESEARCH_MODE_LABELS[cfg.mode] ?? cfg.mode.replace("_", " ");
const depthLabel = RESEARCH_DEPTH_LABELS[cfg.depth] ?? cfg.depth;
- return [tr(modeLabel), tr(depthLabel), sourceSummary].join(" · ");
+ return [tr(modeLabel), tr(depthLabel)].join(" · ");
}
diff --git a/web/lib/session-api.ts b/web/lib/session-api.ts
index b8c2a2e8e..69f4e69a9 100644
--- a/web/lib/session-api.ts
+++ b/web/lib/session-api.ts
@@ -1,6 +1,5 @@
import { apiFetch, 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 {
@@ -42,8 +41,6 @@ export interface SessionSummary {
| "cancelled"
| "rejected";
active_turn_id?: string;
- /** Originating surface — see ``SurfaceKind`` in lib/session-surfaces. */
- kind?: SurfaceKind;
preferences?: {
capability?: string;
tools?: string[];
@@ -128,18 +125,14 @@ async function expectJson<T>(response: Response): Promise<T> {
export async function listSessions(
limit = 50,
offset = 0,
- options?: { force?: boolean; kind?: SurfaceKind | null },
+ options?: { force?: boolean },
): 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:${kindKey}:${limit}:${offset}`,
+ `sessions:${limit}:${offset}`,
async () => {
const response = await apiFetch(
apiUrl(`/api/v1/sessions?${qs.toString()}`),
@@ -189,13 +182,14 @@ export async function deleteSession(sessionId: string): Promise<void> {
export async function recordQuizResults(
sessionId: string,
answers: QuizResultItem[],
+ turnId?: string | null,
): Promise<void> {
const response = await apiFetch(
apiUrl(`/api/v1/sessions/${sessionId}/quiz-results`),
{
method: "POST",
headers: { "Content-Type": "application/json" },
- body: JSON.stringify({ answers }),
+ body: JSON.stringify({ answers, turn_id: turnId || "" }),
},
);
await expectJson<{ recorded: boolean }>(response);
diff --git a/web/lib/session-surfaces.ts b/web/lib/session-surfaces.ts
deleted file mode 100644
index 5ea33657d..000000000
--- a/web/lib/session-surfaces.ts
+++ /dev/null
@@ -1,55 +0,0 @@
-/**
- * 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 fc0297329..6facdc217 100644
--- a/web/lib/space-items.ts
+++ b/web/lib/space-items.ts
@@ -1,22 +1,18 @@
"use client";
import {
- Brain,
ClipboardList,
History,
NotebookPen,
- Sparkles,
Wand2,
type LucideIcon,
} from "lucide-react";
export type SpaceItemKey =
| "chat_history"
- | "co_learn_history"
| "notebooks"
| "question_bank"
- | "skills"
- | "memory";
+ | "skills";
export type SpaceMemoryFile = "summary" | "profile";
@@ -36,13 +32,6 @@ 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",
@@ -65,11 +54,4 @@ export const SPACE_ITEMS: SpaceItem[] = [
description: "Behavior playbooks that guide chat responses.",
icon: Wand2,
},
- {
- key: "memory",
- href: "/space/memory",
- label: "Memory",
- description: "Long-form memory the assistant carries across sessions.",
- icon: Brain,
- },
];
diff --git a/web/lib/unified-ws.ts b/web/lib/unified-ws.ts
index ce5520154..59421ce95 100644
--- a/web/lib/unified-ws.ts
+++ b/web/lib/unified-ws.ts
@@ -11,7 +11,6 @@
*/
import { wsUrl } from "./api";
-import type { SurfaceKind } from "./session-surfaces";
// ---- StreamEvent types (mirror Python StreamEventType) ----
@@ -28,6 +27,7 @@ export type StreamEventType =
| "result"
| "error"
| "session"
+ | "session_meta"
| "done";
export interface StreamEvent {
@@ -49,14 +49,6 @@ 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;
@@ -64,7 +56,6 @@ export interface StartTurnMessage {
capability?: string | null;
knowledge_bases?: string[];
session_id?: string | null;
- kind?: SessionKind;
attachments?: {
type: string;
url?: string;
@@ -127,6 +118,23 @@ export interface RegenerateMessage {
overrides?: Record<string, unknown>;
}
+/**
+ * Deliver the user's answer for an ``ask_user`` paused turn so the
+ * agentic loop can resume on the same turn. The user's reply is
+ * substituted into the matching ``role=tool`` message body before the
+ * next LLM iteration runs.
+ *
+ * Either ``text`` (legacy single-question shape) or ``answers``
+ * (v2 multi-question shape) must be provided. When both are present
+ * the backend prefers ``answers``.
+ */
+export interface SubmitUserReplyMessage {
+ type: "submit_user_reply";
+ turn_id: string;
+ text?: string;
+ answers?: Array<{ questionId: string; text: string }>;
+}
+
export type ChatMessage =
| StartTurnMessage
| SubscribeTurnMessage
@@ -134,7 +142,8 @@ export type ChatMessage =
| ResumeTurnMessage
| UnsubscribeMessage
| CancelTurnMessage
- | RegenerateMessage;
+ | RegenerateMessage
+ | SubmitUserReplyMessage;
// ---- Connection manager ----
diff --git a/web/locales/en/app.json b/web/locales/en/app.json
index 3c69a8595..c31348b94 100644
--- a/web/locales/en/app.json
+++ b/web/locales/en/app.json
@@ -151,6 +151,7 @@
"Search": "Search",
"Snow": "Snow",
"Light": "Light",
+ "Cream": "Cream",
"Dark": "Dark",
"Glass": "Glass",
"Configure your AI services and preferences": "Configure your AI services and preferences",
@@ -1111,16 +1112,28 @@
"Development build": "Development build",
"Run Tour": "Run Tour",
"Tour": "Tour",
- "settingsTour.llm.title": "1 / 5 — LLM",
- "settingsTour.llm.desc": "Pick the active LLM profile, endpoint, and model used for chat and reasoning.",
- "settingsTour.embedding.title": "2 / 5 — Embedding",
- "settingsTour.embedding.desc": "Configure the embedding provider and model used for knowledge retrieval.",
- "settingsTour.search.title": "3 / 5 — Search",
- "settingsTour.search.desc": "Set an optional web-search provider and any related network settings.",
- "settingsTour.saveTest.title": "4 / 5 — Save & Test",
- "settingsTour.saveTest.desc": "After editing, click Save Draft to persist your changes to the catalog. Then open Diagnostics below and Run Test to verify the connection works.",
- "settingsTour.apply.title": "5 / 5 — Apply",
- "settingsTour.apply.desc": "Once the test passes, click Apply to activate the selected runtime configuration immediately.",
+ "settingsTour.appearance.title": "settingsTour.appearance.title",
+ "settingsTour.appearance.desc": "settingsTour.appearance.desc",
+ "settingsTour.status.title": "settingsTour.status.title",
+ "settingsTour.status.desc": "settingsTour.status.desc",
+ "settingsTour.llm.title": "LLM",
+ "settingsTour.llm.desc": "Manage LLM profiles — provider, endpoint, and model. The active model powers chat and most agent reasoning.",
+ "settingsTour.embedding.title": "Embedding",
+ "settingsTour.embedding.desc": "Configure the embedding provider and dimensions used for retrieval and knowledge-base ingestion.",
+ "settingsTour.search.title": "Search",
+ "settingsTour.search.desc": "Pick the web-search provider and tune proxy / request settings.",
+ "settingsTour.capabilities.title": "Capabilities",
+ "settingsTour.capabilities.desc": "Tune per-capability LLM params and runtime caps for every capability surfaced in chat (chat / solve / question / research / …).",
+ "settingsTour.memory.title": "Memory",
+ "settingsTour.memory.desc": "Tune the memory consolidator: chunking, LLM budgets, dedup, and reference policies.",
+ "settingsTour.mcp.title": "MCP servers",
+ "settingsTour.mcp.desc": "Connect external MCP (Model Context Protocol) servers to expose more tools to the agent (coming soon).",
+ "settingsTour.tools.title": "settingsTour.tools.title",
+ "settingsTour.tools.desc": "settingsTour.tools.desc",
+ "settingsTour.apply.title": "Save & Apply",
+ "settingsTour.apply.desc": "Save Draft persists your changes; Apply activates them right away. Both controls live in the top toolbar, always within reach.",
+ "Step {{current}} of {{total}}": "Step {{current}} of {{total}}",
+ "Back": "Back",
"settings.configNote": "Save Draft persists all profiles to model_catalog.json, which DeepTutor reads at runtime. Apply activates the selected profile and refreshes runtime clients. You can keep multiple profiles in the catalog and switch between them anytime.",
"Unsupported file type": "Unsupported file type",
"No extension": "No extension",
@@ -1143,7 +1156,6 @@
"Latest activity": "Latest activity",
"Live pipeline": "Live pipeline",
"Action required": "Action required",
- "Step {{current}} of {{total}}": "Step {{current}} of {{total}}",
"Waiting for live progress...": "Waiting for live progress...",
"Once a knowledge base is ready, it stays clean here as a reusable resource instead of showing stale completion banners.": "Once a knowledge base is ready, it stays clean here as a reusable resource instead of showing stale completion banners.",
"This file exceeds the maximum size of {{size}}.": "This file exceeds the maximum size of {{size}}.",
@@ -1643,5 +1655,378 @@
"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."
+ "Confirm settings on the right to send.": "Confirm settings on the right to send.",
+ "Provider connection": "Provider connection",
+ "Delete “{{name}}”": "Delete “{{name}}”",
+ "Permanently remove the currently selected profile.": "Permanently remove the currently selected profile.",
+ "Extra (optional)": "Extra (optional)",
+ "API version and extra request headers": "API version and extra request headers",
+ "API version and proxy": "API version and proxy",
+ "Rename model": "Rename model",
+ "Rename profile": "Rename profile",
+ "Detected context window written to draft": "Detected context window written to draft",
+ "Detected value matches your current setting": "Detected value matches your current setting",
+ "Concept Question": "Concept Question",
+ "Fill in the Blank": "Fill in the Blank",
+ "Short Answer": "Short Answer",
+ "Essay": "Essay",
+ "Type Mix": "Type Mix",
+ "Decrease": "Decrease",
+ "Increase": "Increase",
+ "True": "True",
+ "False": "False",
+ "AI Judge": "AI Judge",
+ "AI Judgment": "AI Judgment",
+ "Back to question": "Back to question",
+ "No answer recorded.": "No answer recorded.",
+ "Ask anything about this question, your answer, or the AI judgment.": "Ask anything about this question, your answer, or the AI judgment.",
+ "Attach image": "Attach image",
+ "Judging...": "Judging...",
+ "Re-judge": "Re-judge",
+ "Attach an image as your answer": "Attach an image as your answer",
+ "Add another image": "Add another image",
+ "Replace image": "Replace image",
+ "Remove image": "Remove image",
+ "AI judge failed. Please retry.": "AI judge failed. Please retry.",
+ "AI judge connection closed unexpectedly.": "AI judge connection closed unexpectedly.",
+ "Switch user-toggleable tools on or off. Locked tools are mounted automatically when the chat agent needs them.": "Switch user-toggleable tools on or off. Locked tools are mounted automatically when the chat agent needs them.",
+ "Always on": "Always on",
+ "Auto-mounted by the agent when needed. Not user-toggleable.": "Auto-mounted by the agent when needed. Not user-toggleable.",
+ "Failed to save": "Failed to save",
+ "On": "On",
+ "Off": "Off",
+ "Tune the app, configure model services, and inspect built-in tools.": "Tune the app, configure model services, and inspect built-in tools.",
+ "Appearance": "Appearance",
+ "Tune the visual theme and interface language. Changes apply immediately and are stored in your account.": "Tune the visual theme and interface language. Changes apply immediately and are stored in your account.",
+ "Pick the colour palette you prefer.": "Pick the colour palette you prefer.",
+ "Pick the colour palette and interface style. Each tile previews the theme it applies.": "Pick the colour palette and interface style. Each tile previews the theme it applies.",
+ "Snow is the warm default; Light is a cool blue-grey; Dark mirrors Snow's accent on a warm near-black; Glass adds translucent panels on pure black.": "Snow is the warm default; Light is a cool blue-grey; Dark mirrors Snow's accent on a warm near-black; Glass adds translucent panels on pure black.",
+ "Cream is a warm, paper-like default with a terracotta accent. Snow is its cool, blue-tinted sibling with a royal-blue accent. Dark keeps Cream's warmth on near-black. Glass adds translucent purple panels on a deep gradient.": "Cream is a warm, paper-like default with a terracotta accent. Snow is its cool, blue-tinted sibling with a royal-blue accent. Dark keeps Cream's warmth on near-black. Glass adds translucent purple panels on a deep gradient.",
+ "Snow keeps things minimal; Glass adds translucent panels. Dark mode follows the same accent palette.": "Snow keeps things minimal; Glass adds translucent panels. Dark mode follows the same accent palette.",
+ "Choose the interface language.": "Choose the interface language.",
+ "Interface language": "Interface language",
+ "Affects the UI only. Model output language is controlled by your prompt.": "Affects the UI only. Model output language is controlled by your prompt.",
+ "Runtime status for backend and configured services.": "Runtime status for backend and configured services.",
+ "Live state of the backend and the model services your configuration applies to.": "Live state of the backend and the model services your configuration applies to.",
+ "Status reflects the runtime values after the last Apply. Draft changes only take effect once applied.": "Status reflects the runtime values after the last Apply. Draft changes only take effect once applied.",
+ "Built-in tools the chat agent can invoke.": "Built-in tools the chat agent can invoke.",
+ "Built-in tools the chat agent can invoke. Each shows its description, parameters, and prompt hints in your current language.": "Built-in tools the chat agent can invoke. Each shows its description, parameters, and prompt hints in your current language.",
+ "Failed to load tools": "Failed to load tools",
+ "When to use": "When to use",
+ "Input format": "Input format",
+ "Guideline": "Guideline",
+ "optional": "optional",
+ "MCP servers": "MCP servers",
+ "External MCP servers (coming soon).": "External MCP servers (coming soon).",
+ "Connect external MCP (Model Context Protocol) servers to extend the agent's capabilities.": "Connect external MCP (Model Context Protocol) servers to extend the agent's capabilities.",
+ "MCP server support is coming soon": "MCP server support is coming soon",
+ "We're working on a way to register and authenticate MCP servers from this page so the chat agent can call tools they expose. Until then, this section is reserved as a placeholder.": "We're working on a way to register and authenticate MCP servers from this page so the chat agent can call tools they expose. Until then, this section is reserved as a placeholder.",
+ "Language model providers and active profile.": "Language model providers and active profile.",
+ "Configure language model profiles. The active model is used for chat and most agent reasoning.": "Configure language model profiles. The active model is used for chat and most agent reasoning.",
+ "Embedding model providers and dimensions.": "Embedding model providers and dimensions.",
+ "Configure embedding model profiles. Used by retrieval and knowledge-base ingestion.": "Configure embedding model profiles. Used by retrieval and knowledge-base ingestion.",
+ "Web search providers.": "Web search providers.",
+ "Configure web search providers. Used by the web_search tool and any agent step that hits the open web.": "Configure web search providers. Used by the web_search tool and any agent step that hits the open web.",
+ "{{count}} profiles": "{{count}} profiles",
+ "Memory tooltip": "Memory tooltip",
+ "Browse L1 trace for this surface": "Browse L1 trace for this surface",
+ "L1 trace · {{surface}}": "L1 trace · {{surface}}",
+ "{{count}} events": "{{count}} events",
+ "Clear focus": "Clear focus",
+ "No trace events recorded yet.": "No trace events recorded yet.",
+ "L1 · Raw traces": "L1 · Raw traces",
+ "L2 · Per-surface": "L2 · Per-surface",
+ "L3 · Cross-surface": "L3 · Cross-surface",
+ "Every L1 trace event, click to jump to the source.": "Every L1 trace event, click to jump to the source.",
+ "Per-surface summaries consolidated from L1.": "Per-surface summaries consolidated from L1.",
+ "Cross-surface knowledge consolidated from L2.": "Cross-surface knowledge consolidated from L2.",
+ "All surfaces": "All surfaces",
+ "Clear all L1 trace for {{surface}}": "Clear all L1 trace for {{surface}}",
+ "Open in {{label}}": "Open in {{label}}",
+ "Workspace coverage": "Workspace coverage",
+ "{{n}} items in workspace not yet in trace": "{{n}} items in workspace not yet in trace",
+ "All discoverable items already traced": "All discoverable items already traced",
+ "Backfill {{n}}": "Backfill {{n}}",
+ "L1 mirrors your workspace, L2 summarises per-surface content, L3 is cross-surface knowledge.": "L1 mirrors your workspace, L2 summarises per-surface content, L3 is cross-surface knowledge.",
+ "L1 · Workspace": "L1 · Workspace",
+ "Live snapshot of your workspace — one entry per real artifact.": "Live snapshot of your workspace — one entry per real artifact.",
+ "Re-scan workspace and record any changes": "Re-scan workspace and record any changes",
+ "Refreshed: {{n}} changes": "Refreshed: {{n}} changes",
+ "Refreshed: no changes": "Refreshed: no changes",
+ "Snapshot": "Snapshot",
+ "Changes": "Changes",
+ "Queries": "Queries",
+ "{{n}} entities": "{{n}} entities",
+ "last refresh {{ts}}": "last refresh {{ts}}",
+ "Nothing in workspace yet.": "Nothing in workspace yet.",
+ "No changes recorded yet. Run Refresh to capture the baseline.": "No changes recorded yet. Run Refresh to capture the baseline.",
+ "{{n}} pending": "{{n}} pending",
+ "Workspace changed since last refresh. Click Refresh to commit these to the changes log.": "Workspace changed since last refresh. Click Refresh to commit these to the changes log.",
+ "Pending — {{n}} change(s) since last refresh": "Pending — {{n}} change(s) since last refresh",
+ "Pending — not yet committed to changes log": "Pending — not yet committed to changes log",
+ "Click Refresh to commit": "Click Refresh to commit",
+ "new": "new",
+ "modified": "modified",
+ "removed": "removed",
+ "No RAG queries recorded yet.": "No RAG queries recorded yet.",
+ "Empty. Click Update to consolidate from the current snapshot.": "Empty. Click Update to consolidate from the current snapshot.",
+ "Per-surface summaries consolidated from L1 content.": "Per-surface summaries consolidated from L1 content.",
+ "Tool Calling…": "Tool Calling…",
+ "DeepTutor Planning…": "DeepTutor Planning…",
+ "DeepTutor Drafting…": "DeepTutor Drafting…",
+ "DeepTutor Responding…": "DeepTutor Responding…",
+ "DeepTutor Reasoning…": "DeepTutor Reasoning…",
+ "DeepTutor responded.": "DeepTutor responded.",
+ "DeepTutor Exploring…": "DeepTutor Exploring…",
+ "DeepTutor Quizzing…": "DeepTutor Quizzing…",
+ "DeepTutor Reflecting…": "DeepTutor Reflecting…",
+ "Decomposing Target": "Decomposing Target",
+ "Researching Topic": "Researching Topic",
+ "Researching Topic #{{n}}": "Researching Topic #{{n}}",
+ "Reporting Outline": "Reporting Outline",
+ "Reporting Intro": "Reporting Intro",
+ "Reporting Section": "Reporting Section",
+ "Reporting Section #{{n}}": "Reporting Section #{{n}}",
+ "Reporting Conclusion": "Reporting Conclusion",
+ "Reflecting": "Reflecting",
+ "Everything DeepTutor remembers about you, organised across three layers. Click into any layer to inspect or curate it.": "Everything DeepTutor remembers about you, organised across three layers. Click into any layer to inspect or curate it.",
+ "Memory settings": "Memory settings",
+ "L1 · Workspace mirror": "L1 · Workspace mirror",
+ "L2 · Per-surface summaries": "L2 · Per-surface summaries",
+ "L3 · Cross-surface knowledge": "L3 · Cross-surface knowledge",
+ "Live": "Live",
+ "Curated": "Curated",
+ "entities tracked": "entities tracked",
+ "Snapshot of your live workspace across {{n}} surfaces. Refresh to record changes.": "Snapshot of your live workspace across {{n}} surfaces. Refresh to record changes.",
+ "facts across {{n}} surfaces": "facts across {{n}} surfaces",
+ "Surface-specific facts extracted by the consolidator. Run Update / Audit / Dedup per doc.": "Surface-specific facts extracted by the consolidator. Run Update / Audit / Dedup per doc.",
+ "propositions across {{n}} slots": "propositions across {{n}} slots",
+ "Cross-surface synthesis: profile, recent timeline, knowledge scope. Hedged claims with L2 evidence.": "Cross-surface synthesis: profile, recent timeline, knowledge scope. Hedged claims with L2 evidence.",
+ "See all three layers at once — L3 synthesis at the centre, L2 facts in the middle, L1 traces on the outside. Hover any node for a preview.": "See all three layers at once — L3 synthesis at the centre, L2 facts in the middle, L1 traces on the outside. Hover any node for a preview.",
+ "Pick a surface to open its workbench. Each L2 doc has Update / Audit / Dedup modes.": "Pick a surface to open its workbench. Each L2 doc has Update / Audit / Dedup modes.",
+ "{{n}} facts captured": "{{n}} facts captured",
+ "Not built yet": "Not built yet",
+ "Open workbench": "Open workbench",
+ "Cross-surface synthesis: profile, recent timeline, knowledge scope. Each slot has its own workbench.": "Cross-surface synthesis: profile, recent timeline, knowledge scope. Each slot has its own workbench.",
+ "A rolling timeline across all surfaces, last 1–4 weeks.": "A rolling timeline across all surfaces, last 1–4 weeks.",
+ "Durable identity, learning style, knowledge level — only multi-surface evidence.": "Durable identity, learning style, knowledge level — only multi-surface evidence.",
+ "Concepts you've engaged with, tagged familiar / practicing / unsure.": "Concepts you've engaged with, tagged familiar / practicing / unsure.",
+ "{{n}} propositions": "{{n}} propositions",
+ "Surface-specific facts about the user. Update extracts new facts; Audit checks vs raw evidence; Dedup tidies.": "Surface-specific facts about the user. Update extracts new facts; Audit checks vs raw evidence; Dedup tidies.",
+ "Cross-surface synthesis. Hedged claims with L2 evidence.": "Cross-surface synthesis. Hedged claims with L2 evidence.",
+ "Edit raw": "Edit raw",
+ "Rendered": "Rendered",
+ "Line numbers": "Line numbers",
+ "Empty. Click Update to extract facts from your traces.": "Empty. Click Update to extract facts from your traces.",
+ "Update memory": "Update memory",
+ "Extract facts from new traces since last update. Append-only.": "Extract facts from new traces since last update. Append-only.",
+ "LLM budget (rounds)": "LLM budget (rounds)",
+ "Audit memory": "Audit memory",
+ "Check existing facts against full raw evidence. Line-level edits.": "Check existing facts against full raw evidence. Line-level edits.",
+ "Dedup": "Dedup",
+ "Iteratively merge duplicates & rewrite muddled entries.": "Iteratively merge duplicates & rewrite muddled entries.",
+ "Adjust defaults in": "Adjust defaults in",
+ "Run progress": "Run progress",
+ "Tune the chunk-based consolidator: how many LLM rounds per Update / Audit / Dedup, how aggressively to chunk, and how strictly to validate references.": "Tune the chunk-based consolidator: how many LLM rounds per Update / Audit / Dedup, how aggressively to chunk, and how strictly to validate references.",
+ "Update mode": "Update mode",
+ "Default LLM rounds for chunk-based incremental fact extraction. Per-doc overrides live in the workbench.": "Default LLM rounds for chunk-based incremental fact extraction. Per-doc overrides live in the workbench.",
+ "L2 budget (per surface)": "L2 budget (per surface)",
+ "L3 budget (per slot)": "L3 budget (per slot)",
+ "Maximum chunks the chunker emits for an L2 update.": "Maximum chunks the chunker emits for an L2 update.",
+ "Maximum chunks for an L3 update across the 7 L2 docs.": "Maximum chunks for an L3 update across the 7 L2 docs.",
+ "Audit mode": "Audit mode",
+ "Default LLM rounds for line-level edits against raw evidence.": "Default LLM rounds for line-level edits against raw evidence.",
+ "Iterative dedup over the full doc. Stops early when an iteration emits zero edits.": "Iterative dedup over the full doc. Stops early when an iteration emits zero edits.",
+ "Run dedup automatically after Update": "Run dedup automatically after Update",
+ "Chunking": "Chunking",
+ "Lower-level knobs that shape how content is split.": "Lower-level knobs that shape how content is split.",
+ "Overlap ratio": "Overlap ratio",
+ "Fraction of chunk size carried into the next chunk. 0–0.5.": "Fraction of chunk size carried into the next chunk. 0–0.5.",
+ "Boundary": "Boundary",
+ "Where the chunker prefers to cut.": "Where the chunker prefers to cut.",
+ "Paragraph": "Paragraph",
+ "Sentence": "Sentence",
+ "Min chunk chars": "Min chunk chars",
+ "Max chunk chars": "Max chunk chars",
+ "Floor for individual chunk size.": "Floor for individual chunk size.",
+ "Ceiling for individual chunk size.": "Ceiling for individual chunk size.",
+ "References": "References",
+ "How strictly facts must cite the chunk they were extracted from.": "How strictly facts must cite the chunk they were extracted from.",
+ "Require ref on every fact": "Require ref on every fact",
+ "Drops facts that come back without a ref.": "Drops facts that come back without a ref.",
+ "Drop invalid refs (vs reject the whole fact)": "Drop invalid refs (vs reject the whole fact)",
+ "On: keep the fact, drop only out-of-pool refs. Off: any bad ref rejects the fact.": "On: keep the fact, drop only out-of-pool refs. Off: any bad ref rejects the fact.",
+ "Run": "Run",
+ "Failed to save to notebook.": "Failed to save to notebook.",
+ "Notebook save stream ended unexpectedly.": "Notebook save stream ended unexpectedly.",
+ "Failed to edit selected text.": "Failed to edit selected text.",
+ "Streaming response body is missing.": "Streaming response body is missing.",
+ "Did not receive a final edit result.": "Did not receive a final edit result.",
+ "The draft changed before AI edit finished. Please reselect the text and try again.": "The draft changed before AI edit finished. Please reselect the text and try again.",
+ "Failed to edit document.": "Failed to edit document.",
+ "Failed to auto-mark document.": "Failed to auto-mark document.",
+ "Failed to save capability settings (HTTP {{status}})": "Failed to save capability settings (HTTP {{status}})",
+ "Backend returned an unexpected payload after save.": "Backend returned an unexpected payload after save.",
+ "Knowledge base": "Knowledge base",
+ "Co-writer": "Co-writer",
+ "Recent summary": "Recent summary",
+ "User profile": "User profile",
+ "Knowledge scope": "Knowledge scope",
+ "Failed to load capability settings (HTTP {{status}}). Make sure the backend is running the latest build — the /api/v1/capabilities/settings endpoint was added in this release.": "Failed to load capability settings (HTTP {{status}}). Make sure the backend is running the latest build — the /api/v1/capabilities/settings endpoint was added in this release.",
+ "The backend returned an unexpected payload for /api/v1/capabilities/settings. Restart the backend to pick up the latest schema.": "The backend returned an unexpected payload for /api/v1/capabilities/settings. Restart the backend to pick up the latest schema.",
+ "Failed to load capability settings.": "Failed to load capability settings.",
+ "Preparing {{service}} diagnostics...": "Preparing {{service}} diagnostics...",
+ "Could not start diagnostics.": "Could not start diagnostics.",
+ "Diagnostics stream disconnected.": "Diagnostics stream disconnected.",
+ "System status unavailable.": "System status unavailable.",
+ "System status unavailable: {{message}}": "System status unavailable: {{message}}",
+ "http://127.0.0.1:7890 (optional)": "http://127.0.0.1:7890 (optional)",
+ "stream failed": "stream failed",
+ "start failed": "start failed",
+ "start failed: {{status}}": "start failed: {{status}}",
+ "undo failed": "undo failed",
+ "undo failed: {{status}}": "undo failed: {{status}}",
+ "reset failed: {{status}}": "reset failed: {{status}}",
+ "unknown error": "unknown error",
+ "Answer-now (max tokens)": "Answer-now (max tokens)",
+ "Budget for the user-forced short-circuit response.": "Budget for the user-forced short-circuit response.",
+ "Cap on the THINK / TOOL inner loop within a single plan step.": "Cap on the THINK / TOOL inner loop within a single plan step.",
+ "Cap on the explore loop before planning.": "Cap on the explore loop before planning.",
+ "Couldn't load capability settings": "Couldn't load capability settings",
+ "Deep question (quiz) generation pipeline.": "Deep question (quiz) generation pipeline.",
+ "Deep research pipeline. Iteration count is controlled per request via the depth selector (quick / standard / deep / manual) in the chat input, not here.": "Deep research pipeline. Iteration count is controlled per request via the depth selector (quick / standard / deep / manual) in the chat input, not here.",
+ "Deep solve pipeline: chained THINK / TOOL / FINISH / REPLAN loop.": "Deep solve pipeline: chained THINK / TOOL / FINISH / REPLAN loop.",
+ "Explore max iterations": "Explore max iterations",
+ "Hard cap on chat loop iterations per turn.": "Hard cap on chat loop iterations per turn.",
+ "How far back paper search will scan.": "How far back paper search will scan.",
+ "How many times the planner may revise the plan within one turn.": "How many times the planner may revise the plan within one turn.",
+ "Manim animation / image generation pipeline.": "Manim animation / image generation pipeline.",
+ "Math animator": "Math animator",
+ "Max iterations": "Max iterations",
+ "Max iterations per step": "Max iterations per step",
+ "Max replans": "Max replans",
+ "Max tokens": "Max tokens",
+ "Paper search years limit": "Paper search years limit",
+ "Per-capability LLM parameters and runtime knobs. Values are persisted to data/user/settings/agents.yaml (LLM params) and data/user/settings/main.yaml (runtime knobs).": "Per-capability LLM parameters and runtime knobs. Values are persisted to data/user/settings/agents.yaml (LLM params) and data/user/settings/main.yaml (runtime knobs).",
+ "Per-iteration budget for the chat LLM call (which emits THINK / TOOL / FINISH labels in a single stream).": "Per-iteration budget for the chat LLM call (which emits THINK / TOOL / FINISH labels in a single stream).",
+ "Per-tool wall-clock timeout for the researching phase.": "Per-tool wall-clock timeout for the researching phase.",
+ "Sampling temperature shared across every chat stage.": "Sampling temperature shared across every chat stage.",
+ "Selection edit / inline rewrite agent.": "Selection edit / inline rewrite agent.",
+ "Summarize long tool outputs to keep the prompt budget low.": "Summarize long tool outputs to keep the prompt budget low.",
+ "Temperature": "Temperature",
+ "The agentic chat loop. Stage budgets cap max_tokens per stage; lower the intermediate stages on small-context models.": "The agentic chat loop. Stage budgets cap max_tokens per stage; lower the intermediate stages on small-context models.",
+ "Tool max retries": "Tool max retries",
+ "Tool summarizer (max tokens)": "Tool summarizer (max tokens)",
+ "Tool summarizer enabled": "Tool summarizer enabled",
+ "Tool timeout (s)": "Tool timeout (s)",
+ "Clear trace": "Clear trace",
+ "Default model": "Default model",
+ "Edit applied": "Edit applied",
+ "Edit rejected": "Edit rejected",
+ "Facts extracted": "Facts extracted",
+ "LLM workspace": "LLM workspace",
+ "Markdown updated": "Markdown updated",
+ "Pick a mode and click Run. The LLM trace — system prompt, user prompt, response — appears here, turn by turn.": "Pick a mode and click Run. The LLM trace — system prompt, user prompt, response — appears here, turn by turn.",
+ "Ref dropped": "Ref dropped",
+ "Reset failed: {{msg}}": "Reset failed: {{msg}}",
+ "Reset memory (delete md + seen-id state)": "Reset memory (delete md + seen-id state)",
+ "Reset will delete the current memory file AND its seen-id state. The next Update will re-ingest every L1 entity from scratch. Continue?": "Reset will delete the current memory file AND its seen-id state. The next Update will re-ingest every L1 entity from scratch. Continue?",
+ "Run ended": "Run ended",
+ "Run started": "Run started",
+ "Streaming…": "Streaming…",
+ "System prompt": "System prompt",
+ "Traces loaded": "Traces loaded",
+ "Undo applied": "Undo applied",
+ "Undo last memory edit": "Undo last memory edit",
+ "User prompt": "User prompt",
+ "Working…": "Working…",
+ "(skipped)": "(skipped)",
+ "All questions answered.": "All questions answered.",
+ "Next question": "Next question",
+ "Other — write your own reply…": "Other — write your own reply…",
+ "Other: {{text}}": "Other: {{text}}",
+ "Pick an option or type your own to continue.": "Pick an option or type your own to continue.",
+ "Please answer to continue.": "Please answer to continue.",
+ "Previous question": "Previous question",
+ "Sending your answers…": "Sending your answers…",
+ "Submit answers": "Submit answers",
+ "Type your reply…": "Type your reply…",
+ "Unanswered questions will be submitted as skipped.": "Unanswered questions will be submitted as skipped.",
+ "Your answers": "Your answers",
+ "{{count}} questions — tap a tab to switch.": "{{count}} questions — tap a tab to switch.",
+ "Close tab": "Close tab",
+ "Close viewer": "Close viewer",
+ "Loading {{host}}…": "Loading {{host}}…",
+ "Many sites refuse to embed for security reasons. If the page below stays blank, use “Open in browser”.": "Many sites refuse to embed for security reasons. If the page below stays blank, use “Open in browser”.",
+ "Open URL": "Open URL",
+ "Open a local file": "Open a local file",
+ "Open in browser": "Open in browser",
+ "Paste a URL or open a local file. Attachments from chat will also land here.": "Paste a URL or open a local file. Attachments from chat will also land here.",
+ "This site looks like it refused to embed (its security headers block iframes). Use “Open in browser” to view it in a real tab.": "This site looks like it refused to embed (its security headers block iframes). Use “Open in browser” to view it in a real tab.",
+ "https://example.com": "https://example.com",
+ "Pick a document to view or update": "Pick a document to view or update",
+ "Preferences are written when you explicitly tell the chat assistant your preferences (style, language, format).": "Preferences are written when you explicitly tell the chat assistant your preferences (style, language, format).",
+ "Preferences is written by the chat assistant, not consolidated.": "Preferences is written by the chat assistant, not consolidated.",
+ "Stored at memory/backup/{{name}}. v2 starts fresh — interact with DeepTutor and click Update on each doc to build memory.": "Stored at memory/backup/{{name}}. v2 starts fresh — interact with DeepTutor and click Update on each doc to build memory.",
+ "Update progress": "Update progress",
+ "Your v1 memory was archived": "Your v1 memory was archived",
+ "not built": "not built",
+ "Click to rename session": "Click to rename session",
+ "Open viewer": "Open viewer",
+ "Rename failed": "Rename failed",
+ "Session activity": "Session activity",
+ "Session title": "Session title",
+ "Start a conversation to rename": "Start a conversation to rename",
+ "As you chat, the tools, references and attachments you use will appear here.": "As you chat, the tools, references and attachments you use will appear here.",
+ "Question #{{n}}": "Question #{{n}}",
+ "Tools used": "Tools used",
+ "{{n}} page(s)": "{{n}} page(s)",
+ "Merge automatically after Audit": "Merge automatically after Audit",
+ "Merge automatically after Dedup": "Merge automatically after Dedup",
+ "Merge automatically after Update": "Merge automatically after Update",
+ "Merge footnotes": "Merge footnotes",
+ "No-LLM consolidation: collapse duplicate ref rows into one footnote each, then renumber. Idempotent, safe to run any time.": "No-LLM consolidation: collapse duplicate ref rows into one footnote each, then renumber. Idempotent, safe to run any time.",
+ "Click to open an interactive GeoGebra canvas in the side viewer.": "Click to open an interactive GeoGebra canvas in the side viewer.",
+ "GeoGebra figure": "GeoGebra figure",
+ "GeoGebra viewer is not available in this surface": "GeoGebra viewer is not available in this surface",
+ "Interactive GeoGebra figure": "Interactive GeoGebra figure",
+ "Embedding requests are sent to this URL exactly; DeepTutor does not append /embeddings or /api/embed at request time.": "Embedding requests are sent to this URL exactly; DeepTutor does not append /embeddings or /api/embed at request time.",
+ "Endpoint URL": "Endpoint URL",
+ "Model endpoints are assigned by your administrator. You can still personalize theme and language here.": "Model endpoints are assigned by your administrator. You can still personalize theme and language here.",
+ "Waiting for test run...": "Waiting for test run...",
+ "Browse, rename, delete, and reopen previous conversations from your learning space.": "Browse, rename, delete, and reopen previous conversations from your learning space.",
+ "Delete this chat?": "Delete this chat?",
+ "Search chat history...": "Search chat history...",
+ "Attach knowledge bases": "Attach knowledge bases",
+ "No knowledge bases available": "No knowledge bases available",
+ "Could not load settings from the backend.": "Could not load settings from the backend.",
+ "Verify the backend is running and NEXT_PUBLIC_API_BASE points to a reachable host. For Docker, see data/user/settings/system.json.": "Verify the backend is running and NEXT_PUBLIC_API_BASE points to a reachable host. For Docker, see data/user/settings/system.json.",
+ "Delete this turn?": "Delete this turn?",
+ "Skills Auto": "Skills Auto",
+ "Failed to load GeoGebra": "Failed to load GeoGebra",
+ "Loading GeoGebra...": "Loading GeoGebra...",
+ "HTML visualization": "HTML visualization",
+ "SVG visualization": "SVG visualization",
+ "Assigned by admin": "Assigned by admin",
+ "Assigned knowledge bases are read-only": "Assigned knowledge bases are read-only",
+ "Describe the chart, diagram, or animation you want to visualize...": "Describe the chart, diagram, or animation you want to visualize...",
+ "sub-topics": "sub-topics",
+ "{{count}} round": "{{count}} round",
+ "Memory graph": "Memory graph",
+ "L3 synthesis at the centre, L2 facts in the middle ring, L1 traces on the outside.": "L3 synthesis at the centre, L2 facts in the middle ring, L1 traces on the outside.",
+ "Composing memory graph…": "Composing memory graph…",
+ "Zoom in": "Zoom in",
+ "Zoom out": "Zoom out",
+ "Fit": "Fit",
+ "Per-surface": "Per-surface",
+ "Raw traces": "Raw traces",
+ "Recent": "Recent",
+ "facts": "facts",
+ "traces": "traces",
+ "synthesis": "synthesis",
+ "L3 · synthesis": "L3 · synthesis",
+ "L2 · curated": "L2 · curated",
+ "L1 · raw trace": "L1 · raw trace",
+ "Click to lock · open in workbench": "Click to lock · open in workbench",
+ "Hover a node to preview the memory. Click to lock the highlight and trace its references inward (L1 → L2 → L3) or outward.": "Hover a node to preview the memory. Click to lock the highlight and trace its references inward (L1 → L2 → L3) or outward."
}
diff --git a/web/locales/zh/app.json b/web/locales/zh/app.json
index 095ed8514..3dc92024f 100644
--- a/web/locales/zh/app.json
+++ b/web/locales/zh/app.json
@@ -149,8 +149,9 @@
"Embedding": "嵌入模型",
"TTS": "TTS",
"Search": "搜索",
- "Snow": "雪白",
+ "Snow": "雪色",
"Light": "浅色",
+ "Cream": "奶油",
"Dark": "深色",
"Glass": "琉璃",
"Configure your AI services and preferences": "配置你的 AI 服务与偏好",
@@ -701,8 +702,12 @@
"Backend": "后端",
"Emb": "向量",
"Profile": "配置文件",
+ "Profiles": "配置",
+ "Provider connection": "提供商连接",
"No endpoint": "未设置端点",
- "Delete profile": "删除配置文件",
+ "Delete profile": "删除当前配置文件",
+ "Delete “{{name}}”": "删除 “{{name}}”",
+ "Permanently remove the currently selected profile.": "永久删除当前选中的配置文件。",
"Provider Hint / Binding": "提供商提示 / 绑定",
"Select provider...": "选择提供商...",
"Perplexity requires API key. It will fail hard without credentials.": "Perplexity 需要 API 密钥,缺少凭证将无法使用。",
@@ -711,12 +716,21 @@
"Unsupported provider. Use brave/tavily/jina/searxng/duckduckgo/perplexity.": "不受支持的提供商。请使用 brave/tavily/jina/searxng/duckduckgo/perplexity。",
"API Version": "API 版本",
"Proxy": "代理",
+ "Extra (optional)": "Extra(可选)",
+ "API version and extra request headers": "API 版本和额外请求头",
+ "API version and proxy": "API 版本和代理",
"Extra Headers (JSON)": "额外请求头 (JSON)",
"Models": "模型列表",
"Label": "标签",
"Model ID": "模型 ID",
+ "Rename model": "重命名模型",
+ "Rename profile": "重命名配置文件",
+ "Double-click to rename": "双击重命名",
"Context Window": "上下文窗口",
- "Detected at": "识别时间",
+ "Source": "来源",
+ "Detected": "检测到",
+ "Detected context window written to draft": "检测到的上下文窗口已写入草稿",
+ "Detected value matches your current setting": "检测值与当前设置一致",
"Unset": "未设置",
"Known": "内置识别",
"Detected from the provider during the latest LLM test and saved into model_catalog.json.": "已在最近一次 LLM 测试中从提供商识别出上下文窗口,并写入 model_catalog.json。",
@@ -728,7 +742,6 @@
"Send dimensions": "发送 dimensions 参数",
"Some embedding models (e.g. Qwen text-embedding-v4) reject the `dimensions` request param. Turn this off if your provider returns HTTP 400.": "部分 embedding 模型(如 Qwen text-embedding-v4)不支持 `dimensions` 请求参数。若你的服务返回 HTTP 400,请关闭此开关。",
"Source: detected from API probe": "来源:API 测试检测",
- "Detected": "检测到",
"Use this": "使用该值",
"Auto (probe on next test)": "自动(下次测试时检测)",
"Custom…": "自定义…",
@@ -744,7 +757,6 @@
"TutorBot Agents": "TutorBot 代理",
"Manage your in-process TutorBot instances": "管理正在运行的 TutorBot 实例",
"Bots": "机器人",
- "Profiles": "配置",
"Souls": "灵魂",
"New Bot": "新建机器人",
"Create TutorBot": "创建 TutorBot",
@@ -821,7 +833,6 @@
"Running tools and preparing the final edit...": "正在运行工具并准备最终编辑…",
"Full Draft AI Edit": "全文 AI 编辑",
"Describe how you want the text edited...": "描述你想如何编辑文本…",
- "Source": "来源",
"None": "无",
"Select...": "选择…",
"Auto Mark": "自动批注",
@@ -887,7 +898,14 @@
"Tool result": "工具结果",
"Auto": "自动",
"Coding": "编程题",
- "Preference": "偏好",
+ "Concept Question": "概念题",
+ "Fill in the Blank": "填空题",
+ "Short Answer": "简答题",
+ "Essay": "论述题",
+ "types": "种类型",
+ "Type Mix": "题型分配",
+ "Decrease": "减少",
+ "Increase": "增加",
"Max Questions": "最大题目数",
"Or": "或",
"You": "你",
@@ -898,7 +916,6 @@
"Run Research": "开始研究",
"Code Execution": "代码执行",
"default": "默认",
- "Extra constraints, style, focus areas...": "额外约束、风格、重点方向…",
"Try": "试试",
"No conversations yet": "暂无对话",
"Save title": "保存标题",
@@ -953,12 +970,29 @@
"Ask a follow-up question about this item...": "就此题提出追问…",
"Mimic Paper": "仿真试卷",
"Upload PDF": "上传 PDF",
- "Extra constraints...": "额外约束…",
"Check Answer": "检查答案",
+ "True": "对",
+ "False": "错",
"Correct": "正确",
"Incorrect": "错误",
"Retry": "重试",
"Reference Answer": "参考答案",
+ "AI Judge": "AI 评判",
+ "AI Judgment": "AI 评判",
+ "Follow-up": "追问对话",
+ "Back to question": "返回题目",
+ "Your Answer": "你的答案",
+ "No answer recorded.": "暂无文字作答。",
+ "Ask anything about this question, your answer, or the AI judgment.": "对这道题、你的作答或 AI 评判进行任何提问…",
+ "Attach image": "上传图片",
+ "Judging...": "评判中…",
+ "Re-judge": "重新评判",
+ "Attach an image as your answer": "上传图片作答",
+ "Add another image": "继续添加图片",
+ "Replace image": "更换图片",
+ "Remove image": "移除图片",
+ "AI judge failed. Please retry.": "AI 评判失败,请重试。",
+ "AI judge connection closed unexpectedly.": "AI 评判连接意外断开。",
"Previous": "上一题",
"Write your code here...": "在此输入代码…",
"Type your answer...": "在此输入答案…",
@@ -999,9 +1033,7 @@
"Remove from category": "从分类中移除",
"No entries yet": "暂无题目",
"Questions from your quizzes will appear here.": "测验中的题目将汇总到此处。",
- "Your Answer": "你的答案",
"From session": "来自会话",
- "Follow-up": "追问对话",
"Bookmark": "收藏",
"Remove Bookmark": "取消收藏",
"Add to Category": "添加到分类",
@@ -1106,21 +1138,72 @@
"Copy": "复制",
"Regenerate": "重新生成",
"Latest release": "最新版本",
- "Up to date": "已是最新",
+ "Up to date": "已最新",
"Update available": "有新版本",
"Development build": "开发构建",
"Run Tour": "运行引导",
"Tour": "引导",
- "settingsTour.llm.title": "1 / 5 — LLM",
- "settingsTour.llm.desc": "在这里选择当前生效的 LLM 配置、接口地址和模型。",
- "settingsTour.embedding.title": "2 / 5 — Embedding",
- "settingsTour.embedding.desc": "在这里配置用于知识检索的 Embedding 提供商和模型。",
- "settingsTour.search.title": "3 / 5 — Search",
- "settingsTour.search.desc": "在这里设置可选的联网搜索提供商以及相关网络参数。",
- "settingsTour.saveTest.title": "4 / 5 — 保存与测试",
- "settingsTour.saveTest.desc": "编辑完成后,点击 Save Draft 将更改保存到配置目录。然后展开下方的 Diagnostics 面板,点击 Run Test 验证连接是否正常。",
- "settingsTour.apply.title": "5 / 5 — 应用",
- "settingsTour.apply.desc": "测试通过后,点击 Apply 激活当前选中的运行时配置,DeepTutor 会立即使用新的配置。",
+ "settingsTour.appearance.title": "外观",
+ "settingsTour.appearance.desc": "选择视觉主题和界面语言,改动立即生效。",
+ "settingsTour.status.title": "状态",
+ "settingsTour.status.desc": "一眼查看后端和各项服务的运行状态。草稿与运行时不一致时会显示 Pending。",
+ "settingsTour.llm.title": "LLM",
+ "settingsTour.llm.desc": "管理 LLM 配置文件——提供商、接口地址和可用模型。当前激活的模型用于聊天和大部分 agent 推理。",
+ "settingsTour.embedding.title": "嵌入模型",
+ "settingsTour.embedding.desc": "配置用于检索和知识库入库的 Embedding 提供商与维度。",
+ "settingsTour.search.title": "搜索",
+ "settingsTour.search.desc": "选择联网搜索提供商,配置代理与请求参数。",
+ "settingsTour.capabilities.title": "能力",
+ "settingsTour.capabilities.desc": "调整聊天页每个能力(聊天/解题/测验/研究等)的 LLM 参数和运行时上限。",
+ "settingsTour.memory.title": "记忆",
+ "settingsTour.memory.desc": "调整记忆整理流程:分块、LLM 预算、去重和引用策略。",
+ "settingsTour.mcp.title": "MCP 服务器",
+ "settingsTour.mcp.desc": "接入外部 MCP(Model Context Protocol)服务器,扩展 agent 可用的工具(即将上线)。",
+ "settingsTour.tools.title": "工具",
+ "settingsTour.tools.desc": "在此开关用户可自选的工具;锁定工具会在 chat agent 需要时自动挂载。",
+ "Step {{current}} of {{total}}": "第 {{current}} / {{total}} 步",
+ "Back": "上一步",
+ "Switch user-toggleable tools on or off. Locked tools are mounted automatically when the chat agent needs them.": "在此开关用户可自选的工具;锁定工具会在 chat agent 需要时自动挂载。",
+ "Always on": "始终启用",
+ "Auto-mounted by the agent when needed. Not user-toggleable.": "由 agent 在需要时自动挂载,用户无需手动开关。",
+ "Failed to save": "保存失败",
+ "On": "已启用",
+ "Off": "已关闭",
+ "settingsTour.apply.title": "保存与应用",
+ "settingsTour.apply.desc": "改完之后,「保存草稿」只暂存修改;「应用」会立即激活。两个按钮一直钉在顶部工具栏,随时可达。",
+ "Tune the app, configure model services, and inspect built-in tools.": "调整外观、配置模型服务、查看内置工具。",
+ "Appearance": "外观",
+ "Tune the visual theme and interface language. Changes apply immediately and are stored in your account.": "调整视觉主题和界面语言。改动立即生效并保存到你的账号。",
+ "Pick the colour palette you prefer.": "选择你喜欢的配色。",
+ "Pick the colour palette and interface style. Each tile previews the theme it applies.": "选择配色和界面风格。每个卡片预览对应主题的实际效果。",
+ "Snow is the warm default; Light is a cool blue-grey; Dark mirrors Snow's accent on a warm near-black; Glass adds translucent panels on pure black.": "Snow 是温润的默认配色;Light 偏冷蓝灰;Dark 在暖近黑底上沿用 Snow 的点缀色;Glass 在纯黑底上叠加半透明面板。",
+ "Cream is a warm, paper-like default with a terracotta accent. Snow is its cool, blue-tinted sibling with a royal-blue accent. Dark keeps Cream's warmth on near-black. Glass adds translucent purple panels on a deep gradient.": "奶油是温润如纸的默认主题,点缀暖陶橙;雪色是它清冷蓝调的姊妹版,点缀宝蓝;深色在近黑底上延续奶油的暖意;琉璃在深紫渐变底色上叠加半透明面板。",
+ "Snow keeps things minimal; Glass adds translucent panels. Dark mode follows the same accent palette.": "Snow 最简洁;Glass 加入半透明面板;Dark 沿用同一套点缀色。",
+ "Choose the interface language.": "选择界面语言。",
+ "Interface language": "界面语言",
+ "Affects the UI only. Model output language is controlled by your prompt.": "只影响界面文案,模型输出语言由你的提示词控制。",
+ "Runtime status for backend and configured services.": "后端与各模型服务的运行状态。",
+ "Live state of the backend and the model services your configuration applies to.": "后端和当前配置生效的模型服务的实时状态。",
+ "Status reflects the runtime values after the last Apply. Draft changes only take effect once applied.": "状态反映上一次 Apply 之后的运行时数值。草稿改动需要 Apply 才会生效。",
+ "Built-in tools the chat agent can invoke.": "聊天 agent 可调用的内置工具。",
+ "Built-in tools the chat agent can invoke. Each shows its description, parameters, and prompt hints in your current language.": "聊天 agent 可调用的内置工具。每个工具列出当前语言下的描述、参数和提示。",
+ "Failed to load tools": "加载工具列表失败",
+ "When to use": "何时使用",
+ "Input format": "输入格式",
+ "Guideline": "使用指引",
+ "optional": "可选",
+ "MCP servers": "MCP 服务器",
+ "External MCP servers (coming soon).": "外部 MCP 服务器(即将上线)。",
+ "Connect external MCP (Model Context Protocol) servers to extend the agent's capabilities.": "接入外部 MCP(Model Context Protocol)服务器,扩展 agent 的能力。",
+ "MCP server support is coming soon": "MCP 服务器支持即将上线",
+ "We're working on a way to register and authenticate MCP servers from this page so the chat agent can call tools they expose. Until then, this section is reserved as a placeholder.": "我们正在为这里加上注册和鉴权 MCP 服务器的能力,让聊天 agent 可以调用它们暴露的工具。在那之前,这里只是占位。",
+ "Language model providers and active profile.": "语言模型供应商和当前激活的配置。",
+ "Configure language model profiles. The active model is used for chat and most agent reasoning.": "配置语言模型。当前激活的模型用于聊天和大多数 agent 推理。",
+ "Embedding model providers and dimensions.": "嵌入模型供应商和维度。",
+ "Configure embedding model profiles. Used by retrieval and knowledge-base ingestion.": "配置嵌入模型。用于检索和知识库入库。",
+ "Web search providers.": "网络搜索供应商。",
+ "Configure web search providers. Used by the web_search tool and any agent step that hits the open web.": "配置网络搜索供应商。web_search 工具和任何访问公开网络的 agent 步骤都会用到。",
+ "{{count}} profiles": "{{count}} 个配置文件",
"settings.configNote": "Save Draft 会将所有配置保存到 model_catalog.json,DeepTutor 运行时会从该文件读取配置。Apply 会激活当前选中的配置并刷新运行时客户端。你可以保存多套配置,随时切换。",
"Unsupported file type": "不支持的文件类型",
"No extension": "无扩展名",
@@ -1134,7 +1217,6 @@
"Supported formats": "支持的格式",
"Maximum file size: {{size}}": "单个文件最大:{{size}}",
"PDF limit: {{size}}": "PDF 限制:{{size}}",
- "types": "种类型",
"Click to browse supported documents": "点击选择受支持的文档",
"This knowledge base needs reindex before it can accept new files.": "这个知识库需要先重新索引,之后才能接收新文件。",
"The last processing run failed.": "上一次处理失败了。",
@@ -1143,7 +1225,6 @@
"Latest activity": "最新动态",
"Live pipeline": "实时流水线",
"Action required": "需要处理",
- "Step {{current}} of {{total}}": "第 {{current}} / {{total}} 步",
"Waiting for live progress...": "正在等待实时进度…",
"Once a knowledge base is ready, it stays clean here as a reusable resource instead of showing stale completion banners.": "知识库初始化完成后,这里会把它当作可复用资源展示,而不是一直保留陈旧的完成提示。",
"This file exceeds the maximum size of {{size}}.": "该文件超过了 {{size}} 的大小限制。",
@@ -1329,7 +1410,6 @@
"Back to documents": "返回文档列表",
"Document not found": "未找到文档",
"Document title": "文档标题",
- "Double-click to rename": "双击重命名",
"Loading document…": "正在加载文档…",
"Saved": "已保存",
"Saving…": "正在保存…",
@@ -1635,6 +1715,49 @@
"Book tooltip": "生成交互式 AI 书籍。",
"Knowledge tooltip": "管理文档与教学人设。",
"Space tooltip": "你的个人学习空间。",
+ "Memory tooltip": "助手跨会话保留的长期记忆。",
+ "Browse L1 trace for this surface": "浏览该面的 L1 原始事件",
+ "L1 trace · {{surface}}": "L1 原始事件 · {{surface}}",
+ "{{count}} events": "{{count}} 条事件",
+ "Clear focus": "取消高亮",
+ "No trace events recorded yet.": "尚未记录任何原始事件。",
+ "L1 · Raw traces": "L1 · 原始事件",
+ "L2 · Per-surface": "L2 · 各模块摘要",
+ "L3 · Cross-surface": "L3 · 跨模块知识",
+ "Every L1 trace event, click to jump to the source.": "全部 L1 原始事件,点击直接跳到对应功能。",
+ "Per-surface summaries consolidated from L1.": "由 L1 归纳出的各模块摘要。",
+ "Cross-surface knowledge consolidated from L2.": "由 L2 跨模块归纳的整体认知。",
+ "All surfaces": "全部模块",
+ "Clear all L1 trace for {{surface}}": "清空 {{surface}} 模块的 L1 原始事件",
+ "Open in {{label}}": "在 {{label}} 中打开",
+ "Workspace coverage": "Workspace 覆盖度",
+ "{{n}} items in workspace not yet in trace": "Workspace 中还有 {{n}} 项未进入 trace",
+ "All discoverable items already traced": "Workspace 中所有可识别项已被 trace",
+ "Backfill {{n}}": "回填 {{n}} 项",
+ "L1 mirrors your workspace, L2 summarises per-surface content, L3 is cross-surface knowledge.": "L1 直接映射你的 workspace,L2 是各模块的内容摘要,L3 是跨模块知识。",
+ "L1 · Workspace": "L1 · Workspace",
+ "Live snapshot of your workspace — one entry per real artifact.": "Workspace 的实时快照——每条对应一个真实产物。",
+ "Re-scan workspace and record any changes": "重新扫描 workspace 并记录变更",
+ "Refreshed: {{n}} changes": "已刷新:{{n}} 项变更",
+ "Refreshed: no changes": "已刷新:无变更",
+ "Snapshot": "快照",
+ "Changes": "变更",
+ "Queries": "查询",
+ "{{n}} entities": "{{n}} 条实体",
+ "last refresh {{ts}}": "上次刷新 {{ts}}",
+ "Nothing in workspace yet.": "Workspace 里暂时没有内容。",
+ "No changes recorded yet. Run Refresh to capture the baseline.": "尚无变更记录。点击 Refresh 建立基线。",
+ "{{n}} pending": "{{n}} 个待提交",
+ "Workspace changed since last refresh. Click Refresh to commit these to the changes log.": "上次刷新之后 workspace 有变化,点击 Refresh 把这些变化提交到变更日志。",
+ "Pending — {{n}} change(s) since last refresh": "待提交 — 上次刷新后有 {{n}} 个变化",
+ "Pending — not yet committed to changes log": "待提交 — 尚未写入变更日志",
+ "Click Refresh to commit": "点击 Refresh 提交",
+ "new": "新增",
+ "modified": "已修改",
+ "removed": "已删除",
+ "No RAG queries recorded yet.": "尚未记录任何 RAG 查询。",
+ "Empty. Click Update to consolidate from the current snapshot.": "暂无内容。点 Update 基于当前快照生成摘要。",
+ "Per-surface summaries consolidated from L1 content.": "基于 L1 内容归纳出的各模块摘要。",
"Quiz settings": "测验设置",
"Animator settings": "动画设置",
"Visualize settings": "可视化设置",
@@ -1643,5 +1766,265 @@
"Confirmed": "已确认",
"Edit any field to update settings.": "修改任意字段即可更新设置。",
"Confirm settings to enable sending.": "确认设置后即可发送。",
- "Confirm settings on the right to send.": "请先在右侧确认设置后再发送。"
+ "Confirm settings on the right to send.": "请先在右侧确认设置后再发送。",
+ "Tool Calling…": "调用工具中…",
+ "DeepTutor Planning…": "DeepTutor 规划中…",
+ "DeepTutor Drafting…": "DeepTutor 撰写中…",
+ "DeepTutor Responding…": "DeepTutor 回答中…",
+ "DeepTutor Reasoning…": "DeepTutor 推理中…",
+ "DeepTutor responded.": "DeepTutor 已回答。",
+ "DeepTutor Exploring…": "DeepTutor 探索中…",
+ "DeepTutor Quizzing…": "DeepTutor 出题中…",
+ "DeepTutor Reflecting…": "DeepTutor 反思中…",
+ "Decomposing Target": "Decomposing Target",
+ "Researching Topic": "Researching Topic",
+ "Researching Topic #{{n}}": "Researching Topic #{{n}}",
+ "Reporting Outline": "Reporting Outline",
+ "Reporting Intro": "Reporting Intro",
+ "Reporting Section": "Reporting Section",
+ "Reporting Section #{{n}}": "Reporting Section #{{n}}",
+ "Reporting Conclusion": "Reporting Conclusion",
+ "Reflecting": "反思",
+ "Everything DeepTutor remembers about you, organised across three layers. Click into any layer to inspect or curate it.": "DeepTutor 关于你的全部记忆,分为三层组织。点击任何一层进入查看或整理。",
+ "Memory settings": "记忆设置",
+ "L1 · Workspace mirror": "L1 · 工作区镜像",
+ "L2 · Per-surface summaries": "L2 · 各模块摘要",
+ "L3 · Cross-surface knowledge": "L3 · 跨模块知识",
+ "Live": "实时",
+ "Curated": "整理后",
+ "entities tracked": "条 workspace 实体",
+ "Snapshot of your live workspace across {{n}} surfaces. Refresh to record changes.": "对你 {{n}} 个 surface 工作区的快照。点击 Refresh 记录变化。",
+ "facts across {{n}} surfaces": "条事实,共 {{n}} 个 surface",
+ "Surface-specific facts extracted by the consolidator. Run Update / Audit / Dedup per doc.": "由 consolidator 抽取的、每个 surface 的事实。每个文档支持 更新 / 检查 / 去重。",
+ "propositions across {{n}} slots": "条命题,共 {{n}} 个 slot",
+ "Cross-surface synthesis: profile, recent timeline, knowledge scope. Hedged claims with L2 evidence.": "跨 surface 综合:用户画像、近期时间线、知识 scope。每条判断都有 L2 证据。",
+ "See all three layers at once — L3 synthesis at the centre, L2 facts in the middle, L1 traces on the outside. Hover any node for a preview.": "一次查看全部三层 —— 中心为 L3 综合,中圈为 L2 事实,外圈为 L1 原始事件。悬停任意节点可预览。",
+ "Pick a surface to open its workbench. Each L2 doc has Update / Audit / Dedup modes.": "选择一个 surface 进入工作台。每个 L2 文档支持更新 / 检查 / 去重三种模式。",
+ "{{n}} facts captured": "已记录 {{n}} 条事实",
+ "Not built yet": "尚未构建",
+ "Open workbench": "进入工作台",
+ "Cross-surface synthesis: profile, recent timeline, knowledge scope. Each slot has its own workbench.": "跨 surface 综合:用户画像、近期时间线、知识 scope。每个 slot 都有独立工作台。",
+ "A rolling timeline across all surfaces, last 1–4 weeks.": "跨所有 surface 的近 1-4 周滚动时间线。",
+ "Durable identity, learning style, knowledge level — only multi-surface evidence.": "持久的身份、学习风格、知识水平 — 仅接受多 surface 证据。",
+ "Concepts you've engaged with, tagged familiar / practicing / unsure.": "你接触过的概念,含 熟悉 / 练习中 / 不确定 标签。",
+ "{{n}} propositions": "{{n}} 条命题",
+ "Surface-specific facts about the user. Update extracts new facts; Audit checks vs raw evidence; Dedup tidies.": "关于用户的、surface 特定的事实。更新抽取新事实;检查对照原始证据;去重整理冗余。",
+ "Cross-surface synthesis. Hedged claims with L2 evidence.": "跨 surface 综合。每条判断都有 L2 证据。",
+ "Edit raw": "编辑原文",
+ "Rendered": "渲染视图",
+ "Line numbers": "带行号",
+ "Empty. Click Update to extract facts from your traces.": "空。点击 更新 从原始 trace 中抽取事实。",
+ "Update memory": "更新记忆",
+ "Extract facts from new traces since last update. Append-only.": "抽取自上次更新以来新增 trace 中的事实。增量追加。",
+ "LLM budget (rounds)": "LLM 预算(轮数)",
+ "Audit memory": "检查记忆",
+ "Check existing facts against full raw evidence. Line-level edits.": "对照完整原始证据检查已有事实。行级编辑。",
+ "Dedup": "去重",
+ "Iteratively merge duplicates & rewrite muddled entries.": "迭代式合并重复、改写混乱条目。",
+ "Adjust defaults in": "默认值可在",
+ "Run progress": "执行进度",
+ "Tune the chunk-based consolidator: how many LLM rounds per Update / Audit / Dedup, how aggressively to chunk, and how strictly to validate references.": "调整基于分块的 consolidator:每个模式 LLM 调用轮数、分块强度、引用校验严格程度。",
+ "Update mode": "更新模式",
+ "Default LLM rounds for chunk-based incremental fact extraction. Per-doc overrides live in the workbench.": "增量抽取事实时默认的 LLM 轮数。工作台可单文档覆盖。",
+ "L2 budget (per surface)": "L2 预算(每个 surface)",
+ "L3 budget (per slot)": "L3 预算(每个 slot)",
+ "Maximum chunks the chunker emits for an L2 update.": "L2 更新时分块器最多产生的 chunk 数。",
+ "Maximum chunks for an L3 update across the 7 L2 docs.": "L3 更新时跨 7 个 L2 文档的最大 chunk 数。",
+ "Audit mode": "检查模式",
+ "Default LLM rounds for line-level edits against raw evidence.": "对照原始证据做行级编辑时的默认 LLM 轮数。",
+ "Iterative dedup over the full doc. Stops early when an iteration emits zero edits.": "对整个文档迭代去重。某轮无任何编辑时提前停止。",
+ "Run dedup automatically after Update": "更新后自动跑去重",
+ "Chunking": "分块",
+ "Lower-level knobs that shape how content is split.": "底层旋钮:控制内容如何切分。",
+ "Overlap ratio": "重叠比例",
+ "Fraction of chunk size carried into the next chunk. 0–0.5.": "相邻 chunk 的字符重叠比例,0–0.5。",
+ "Boundary": "切分边界",
+ "Where the chunker prefers to cut.": "分块器倾向于在哪里切。",
+ "Paragraph": "段落",
+ "Sentence": "句子",
+ "Min chunk chars": "Chunk 最小字符数",
+ "Max chunk chars": "Chunk 最大字符数",
+ "Floor for individual chunk size.": "单个 chunk 字符数下限。",
+ "Ceiling for individual chunk size.": "单个 chunk 字符数上限。",
+ "References": "引用",
+ "How strictly facts must cite the chunk they were extracted from.": "事实必须如何严格地引用其所在 chunk。",
+ "Require ref on every fact": "每条事实必须有 ref",
+ "Drops facts that come back without a ref.": "丢弃没有 ref 的事实。",
+ "Drop invalid refs (vs reject the whole fact)": "丢弃无效 ref(vs 拒绝整条事实)",
+ "On: keep the fact, drop only out-of-pool refs. Off: any bad ref rejects the fact.": "开启:保留事实,只丢弃 chunk 范围之外的 ref。关闭:任何无效 ref 都会拒绝整条事实。",
+ "Run": "运行",
+ "Preference": "偏好设置",
+ "Extra constraints, style, focus areas...": "额外约束、风格、关注点...",
+ "Failed to save to notebook.": "保存到 Notebook 失败。",
+ "Notebook save stream ended unexpectedly.": "Notebook 保存流意外中断。",
+ "Failed to edit selected text.": "编辑选中文本失败。",
+ "Streaming response body is missing.": "流式响应体缺失。",
+ "Did not receive a final edit result.": "未接收到最终的编辑结果。",
+ "The draft changed before AI edit finished. Please reselect the text and try again.": "在 AI 编辑完成前草稿已发生变化。请重新选择文本并重试。",
+ "Failed to edit document.": "编辑文档失败。",
+ "Failed to auto-mark document.": "自动标注文档失败。",
+ "Failed to save capability settings (HTTP {{status}})": "保存能力设置失败(HTTP {{status}})",
+ "Backend returned an unexpected payload after save.": "保存后后端返回了意外的数据格式。",
+ "Knowledge base": "知识库",
+ "Co-writer": "Co-writer",
+ "Recent summary": "近期总结",
+ "User profile": "用户画像",
+ "Knowledge scope": "知识 Scope",
+ "Failed to load capability settings (HTTP {{status}}). Make sure the backend is running the latest build — the /api/v1/capabilities/settings endpoint was added in this release.": "加载能力设置失败 (HTTP {{status}})。请确认后端已运行最新版本——/api/v1/capabilities/settings 接口是在本次发布中新增的。",
+ "The backend returned an unexpected payload for /api/v1/capabilities/settings. Restart the backend to pick up the latest schema.": "后端为 /api/v1/capabilities/settings 返回了意外的数据格式。请重启后端以加载最新 schema。",
+ "Failed to load capability settings.": "加载能力设置失败。",
+ "Preparing {{service}} diagnostics...": "正在准备 {{service}} 诊断...",
+ "Could not start diagnostics.": "无法启动诊断。",
+ "Diagnostics stream disconnected.": "诊断流已断开。",
+ "System status unavailable.": "系统状态不可用。",
+ "System status unavailable: {{message}}": "系统状态不可用:{{message}}",
+ "http://127.0.0.1:7890 (optional)": "http://127.0.0.1:7890(可选)",
+ "stream failed": "流传输失败",
+ "start failed": "启动失败",
+ "start failed: {{status}}": "启动失败:{{status}}",
+ "undo failed": "撤销失败",
+ "undo failed: {{status}}": "撤销失败:{{status}}",
+ "reset failed: {{status}}": "重置失败:{{status}}",
+ "unknown error": "未知错误",
+ "Answer-now (max tokens)": "立即回答(最大 token 数)",
+ "Budget for the user-forced short-circuit response.": "用户强制短路响应的 token 预算。",
+ "Cap on the THINK / TOOL inner loop within a single plan step.": "单个计划步骤内 THINK / TOOL 内循环的上限。",
+ "Cap on the explore loop before planning.": "规划前探索循环的上限。",
+ "Couldn't load capability settings": "无法加载能力设置",
+ "Deep question (quiz) generation pipeline.": "Deep Question(出题)生成流水线。",
+ "Deep research pipeline. Iteration count is controlled per request via the depth selector (quick / standard / deep / manual) in the chat input, not here.": "Deep Research 流水线。迭代次数按请求由聊天输入框中的深度选择器(快速 / 标准 / 深度 / 手动)控制,不在此处设置。",
+ "Deep solve pipeline: chained THINK / TOOL / FINISH / REPLAN loop.": "Deep Solve 流水线:链式 THINK / TOOL / FINISH / REPLAN 循环。",
+ "Explore max iterations": "探索阶段最大迭代次数",
+ "Hard cap on chat loop iterations per turn.": "单轮聊天循环迭代次数的硬上限。",
+ "How far back paper search will scan.": "论文搜索回溯多少年。",
+ "How many times the planner may revise the plan within one turn.": "单轮内规划器可以修订计划的次数。",
+ "Manim animation / image generation pipeline.": "Manim 动画 / 图像生成流水线。",
+ "Math animator": "数学动画",
+ "Max iterations": "最大迭代次数",
+ "Max iterations per step": "每步最大迭代次数",
+ "Max replans": "最大重新规划次数",
+ "Max tokens": "最大 token 数",
+ "Paper search years limit": "论文搜索年限",
+ "Per-capability LLM parameters and runtime knobs. Values are persisted to data/user/settings/agents.yaml (LLM params) and data/user/settings/main.yaml (runtime knobs).": "每个能力的 LLM 参数和运行时旋钮。配置会持久化到 data/user/settings/agents.yaml(LLM 参数)和 data/user/settings/main.yaml(运行时旋钮)。",
+ "Per-iteration budget for the chat LLM call (which emits THINK / TOOL / FINISH labels in a single stream).": "聊天 LLM 调用的每次迭代 token 预算(在单一流中输出 THINK / TOOL / FINISH 标签)。",
+ "Per-tool wall-clock timeout for the researching phase.": "研究阶段每个工具的实际耗时超时上限。",
+ "Sampling temperature shared across every chat stage.": "所有聊天阶段共享的采样温度。",
+ "Selection edit / inline rewrite agent.": "选区编辑 / 行内改写 Agent。",
+ "Summarize long tool outputs to keep the prompt budget low.": "对过长的工具输出进行摘要以控制 prompt 预算。",
+ "Temperature": "温度",
+ "The agentic chat loop. Stage budgets cap max_tokens per stage; lower the intermediate stages on small-context models.": "Agentic 聊天循环。Stage budgets 限定每个阶段的 max_tokens;在小上下文模型上调低中间阶段。",
+ "Tool max retries": "工具最大重试次数",
+ "Tool summarizer (max tokens)": "工具摘要器(最大 token 数)",
+ "Tool summarizer enabled": "启用工具摘要器",
+ "Tool timeout (s)": "工具超时(秒)",
+ "Clear trace": "清空轨迹",
+ "Default model": "默认模型",
+ "Edit applied": "编辑已应用",
+ "Edit rejected": "编辑已拒绝",
+ "Facts extracted": "已抽取的事实",
+ "LLM workspace": "LLM 工作区",
+ "Markdown updated": "Markdown 已更新",
+ "Pick a mode and click Run. The LLM trace — system prompt, user prompt, response — appears here, turn by turn.": "选择一个模式并点击「运行」。LLM 轨迹(system prompt、user prompt、response)将按轮次显示在此处。",
+ "Ref dropped": "Ref 已丢弃",
+ "Reset failed: {{msg}}": "重置失败:{{msg}}",
+ "Reset memory (delete md + seen-id state)": "重置记忆(删除 md + seen-id 状态)",
+ "Reset will delete the current memory file AND its seen-id state. The next Update will re-ingest every L1 entity from scratch. Continue?": "重置将删除当前记忆文件以及 seen-id 状态。下次「更新」会从零重新摄取所有 L1 实体。是否继续?",
+ "Run ended": "运行已结束",
+ "Run started": "运行已启动",
+ "Streaming…": "流式传输中…",
+ "System prompt": "System prompt",
+ "Traces loaded": "轨迹已加载",
+ "Undo applied": "撤销已应用",
+ "Undo last memory edit": "撤销上一次记忆编辑",
+ "User prompt": "User prompt",
+ "Working…": "处理中…",
+ "(skipped)": "(已跳过)",
+ "All questions answered.": "所有问题已回答。",
+ "Next question": "下一题",
+ "Other — write your own reply…": "其他 — 自定义回复…",
+ "Other: {{text}}": "其他:{{text}}",
+ "Pick an option or type your own to continue.": "选择一个选项或输入自定义回复以继续。",
+ "Please answer to continue.": "请作答以继续。",
+ "Previous question": "上一题",
+ "Sending your answers…": "正在发送回答…",
+ "Submit answers": "提交回答",
+ "Type your reply…": "输入回复…",
+ "Unanswered questions will be submitted as skipped.": "未回答的问题将作为「已跳过」提交。",
+ "Your answers": "你的回答",
+ "{{count}} questions — tap a tab to switch.": "{{count}} 个问题 — 点击标签切换。",
+ "Close tab": "关闭标签页",
+ "Close viewer": "关闭查看器",
+ "Loading {{host}}…": "正在加载 {{host}}…",
+ "Many sites refuse to embed for security reasons. If the page below stays blank, use “Open in browser”.": "出于安全原因,许多网站拒绝嵌入。如果下方页面保持空白,请使用「在浏览器中打开」。",
+ "Open URL": "打开 URL",
+ "Open a local file": "打开本地文件",
+ "Open in browser": "在浏览器中打开",
+ "Paste a URL or open a local file. Attachments from chat will also land here.": "粘贴 URL 或打开本地文件。聊天中的附件也会在此处打开。",
+ "This site looks like it refused to embed (its security headers block iframes). Use “Open in browser” to view it in a real tab.": "该网站似乎拒绝了嵌入(其安全头阻止了 iframe)。请使用「在浏览器中打开」在真实标签页中查看。",
+ "https://example.com": "https://example.com",
+ "Pick a document to view or update": "选择一个文档以查看或更新",
+ "Preferences are written when you explicitly tell the chat assistant your preferences (style, language, format).": "当你向聊天助手明确告知偏好(风格、语言、格式)时,偏好才会被写入。",
+ "Preferences is written by the chat assistant, not consolidated.": "偏好由聊天助手写入,不经过 consolidate。",
+ "Stored at memory/backup/{{name}}. v2 starts fresh — interact with DeepTutor and click Update on each doc to build memory.": "已存储到 memory/backup/{{name}}。v2 从零开始 — 与 DeepTutor 交互,并对每个文档点击「更新」以构建记忆。",
+ "Update progress": "更新进度",
+ "Your v1 memory was archived": "你的 v1 记忆已归档",
+ "not built": "未构建",
+ "Click to rename session": "点击重命名会话",
+ "Open viewer": "打开查看器",
+ "Rename failed": "重命名失败",
+ "Session activity": "会话活动",
+ "Session title": "会话标题",
+ "Start a conversation to rename": "开始对话后即可重命名",
+ "As you chat, the tools, references and attachments you use will appear here.": "随着你聊天,使用过的工具、引用和附件会显示在这里。",
+ "Question #{{n}}": "第 {{n}} 题",
+ "Tools used": "使用的工具",
+ "{{n}} page(s)": "共 {{n}} 页",
+ "Merge automatically after Audit": "Audit 后自动合并",
+ "Merge automatically after Dedup": "Dedup 后自动合并",
+ "Merge automatically after Update": "Update 后自动合并",
+ "Merge footnotes": "合并脚注",
+ "No-LLM consolidation: collapse duplicate ref rows into one footnote each, then renumber. Idempotent, safe to run any time.": "无需 LLM 的整理:将重复的 ref 行合并为一个脚注后重新编号。幂等操作,任意时刻可安全运行。",
+ "Click to open an interactive GeoGebra canvas in the side viewer.": "点击在侧边查看器中打开交互式 GeoGebra 画布。",
+ "GeoGebra figure": "GeoGebra 图形",
+ "GeoGebra viewer is not available in this surface": "此界面不支持 GeoGebra 查看器",
+ "Interactive GeoGebra figure": "交互式 GeoGebra 图形",
+ "Embedding requests are sent to this URL exactly; DeepTutor does not append /embeddings or /api/embed at request time.": "向量化请求会直接发送到此 URL;DeepTutor 不会在请求时追加 /embeddings 或 /api/embed。",
+ "Endpoint URL": "端点 URL",
+ "Model endpoints are assigned by your administrator. You can still personalize theme and language here.": "模型端点由管理员分配。你仍可在此处自定义主题和语言。",
+ "Waiting for test run...": "等待测试运行...",
+ "Browse, rename, delete, and reopen previous conversations from your learning space.": "浏览、重命名、删除并重新打开学习空间中的历史对话。",
+ "Delete this chat?": "删除此对话?",
+ "Search chat history...": "搜索历史对话...",
+ "Attach knowledge bases": "附加知识库",
+ "No knowledge bases available": "暂无可用的知识库",
+ "Could not load settings from the backend.": "无法从后端加载设置。",
+ "Verify the backend is running and NEXT_PUBLIC_API_BASE points to a reachable host. For Docker, see data/user/settings/system.json.": "请确认后端正在运行,且 NEXT_PUBLIC_API_BASE 指向可访问的主机。Docker 部署请参考 data/user/settings/system.json。",
+ "Delete this turn?": "删除此轮对话?",
+ "Skills Auto": "Skills Auto",
+ "Failed to load GeoGebra": "加载 GeoGebra 失败",
+ "Loading GeoGebra...": "正在加载 GeoGebra...",
+ "HTML visualization": "HTML 可视化",
+ "SVG visualization": "SVG 可视化",
+ "Assigned by admin": "由管理员分配",
+ "Assigned knowledge bases are read-only": "管理员分配的知识库为只读",
+ "Describe the chart, diagram, or animation you want to visualize...": "描述你想可视化的图表、示意图或动画...",
+ "sub-topics": "子主题",
+ "{{count}} round": "{{count}} 轮",
+ "Memory graph": "记忆图谱",
+ "L3 synthesis at the centre, L2 facts in the middle ring, L1 traces on the outside.": "中心为 L3 综合,中圈为 L2 事实,外圈为 L1 原始事件。",
+ "Composing memory graph…": "正在构建记忆图谱…",
+ "Zoom in": "放大",
+ "Zoom out": "缩小",
+ "Fit": "适配",
+ "Per-surface": "各模块",
+ "Raw traces": "原始事件",
+ "Recent": "近期",
+ "facts": "条事实",
+ "traces": "条事件",
+ "synthesis": "综合",
+ "L3 · synthesis": "L3 · 综合",
+ "L2 · curated": "L2 · 已归纳",
+ "L1 · raw trace": "L1 · 原始事件",
+ "Click to lock · open in workbench": "点击锁定 · 在工作台中打开",
+ "Hover a node to preview the memory. Click to lock the highlight and trace its references inward (L1 → L2 → L3) or outward.": "悬停节点可预览记忆。点击可锁定高亮,并追踪其向内(L1 → L2 → L3)或向外的引用关系。"
}
diff --git a/web/scripts/route_budgets.mjs b/web/scripts/route_budgets.mjs
index 5df2beb63..c51c4cb03 100644
--- a/web/scripts/route_budgets.mjs
+++ b/web/scripts/route_budgets.mjs
@@ -80,6 +80,7 @@ for (const manifestFile of manifestFiles) {
if (!rootShellSize && rootLayoutFiles.length > 0) {
rootShellSize = sumChunkSizes(rootLayoutFiles);
}
+ const rootLayoutChunks = new Set(rootLayoutFiles);
const routeEntryKey = Object.keys(entryFiles).find(
(key) => key.startsWith("[project]/app/") && key.endsWith("/page") && !key.includes("/layout"),
@@ -88,7 +89,9 @@ for (const manifestFile of manifestFiles) {
continue;
}
- const chunkPaths = entryFiles[routeEntryKey] || [];
+ const chunkPaths = (entryFiles[routeEntryKey] || []).filter(
+ (chunkPath) => !rootLayoutChunks.has(chunkPath),
+ );
routeRows.push({
route,
sizeBytes: sumChunkSizes(chunkPaths),
@@ -98,7 +101,7 @@ for (const manifestFile of manifestFiles) {
let hasFailure = false;
-console.log("Route budgets:");
+console.log("Route budgets (excluding root shell):");
for (const row of routeRows) {
const sizeKb = Math.round(row.sizeBytes / 1024);
const budget = ROUTE_BUDGETS_KB[row.route];
diff --git a/web/tests/markdown-display.test.ts b/web/tests/markdown-display.test.ts
index 7d4259f14..c67c28c12 100644
--- a/web/tests/markdown-display.test.ts
+++ b/web/tests/markdown-display.test.ts
@@ -39,6 +39,30 @@ test("normalizeMarkdownForDisplay linkifies bare citations in prose", () => {
);
});
+test("normalizeMarkdownForDisplay links research citations to exact references", () => {
+ assert.equal(
+ normalizeMarkdownForDisplay(
+ "Agentic loops [CIT-1-01] and plans [PLAN-01].",
+ ),
+ 'Agentic loops [1](#ref-cit-1-01 "citation") and plans [2](#ref-plan-01 "citation").',
+ );
+});
+
+test("normalizeMarkdownForDisplay numbers research citations from reference list order", () => {
+ const refs =
+ '<details id="references" open><summary>参考资料</summary><ol>' +
+ '<li id="ref-cit-1-01" data-citation-id="CIT-1-01">' +
+ "<strong>[1]</strong> <code>CIT-1-01</code> A</li>" +
+ '<li id="ref-cit-2-01" data-citation-id="CIT-2-01">' +
+ "<strong>[2]</strong> <code>CIT-2-01</code> B</li>" +
+ "</ol></details>";
+ const input = `First [CIT-2-01], then [CIT-1-01].\n\n${refs}`;
+ assert.equal(
+ normalizeMarkdownForDisplay(input),
+ `First [2](#ref-cit-2-01 "citation"), then [1](#ref-cit-1-01 "citation").\n\n${refs}`,
+ );
+});
+
test("normalizeMarkdownForDisplay keeps array indexes inside fenced code", () => {
const input = "```js\nconst item = values[0];\n```";
assert.equal(normalizeMarkdownForDisplay(input), input);
@@ -56,6 +80,22 @@ test("normalizeMarkdownForDisplay unwraps explicit citation code spans outside c
);
});
+test("normalizeMarkdownForDisplay unwraps research citation code spans", () => {
+ assert.equal(
+ normalizeMarkdownForDisplay("See `[CIT-1-01]` for details."),
+ 'See [1](#ref-cit-1-01 "citation") for details.',
+ );
+});
+
+test("normalizeMarkdownForDisplay does not linkify research reference list ids", () => {
+ const input =
+ '<details id="references" open><summary>参考资料</summary><ol>' +
+ '<li id="ref-cit-1-01" data-citation-id="CIT-1-01">' +
+ "<strong>[1]</strong> <code>CIT-1-01</code> Web Search: q</li>" +
+ "</ol></details>";
+ assert.equal(normalizeMarkdownForDisplay(input), input);
+});
+
test("escapeUnknownHtmlTagsForDisplay escapes LLM pseudo tags", () => {
const input = "Before\n<think>internal scratchpad</think>\nAfter";
assert.equal(
@@ -75,6 +115,20 @@ test("escapeUnknownHtmlTagsForDisplay keeps allowed html tags", () => {
assert.equal(escapeUnknownHtmlTagsForDisplay(input), input);
});
+test("escapeUnknownHtmlTagsForDisplay escapes active html containers", () => {
+ const input = '<iframe src="https://example.com"></iframe>';
+ assert.equal(
+ escapeUnknownHtmlTagsForDisplay(input),
+ '`<iframe src="https://example.com">``</iframe>`',
+ );
+});
+
+test("escapeUnknownHtmlTagsForDisplay strips unsafe html attributes", () => {
+ const input =
+ '<a href="javascript:alert(1)" onclick="alert(2)" style="color:red">link</a>';
+ assert.equal(escapeUnknownHtmlTagsForDisplay(input), "<a>link</a>");
+});
+
test("hasVisibleMarkdownContent rejects empty raw-html placeholders", () => {
assert.equal(
hasVisibleMarkdownContent("<details><summary></summary></details>"),