DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.
Python ai-agentsai-tutorclawbotcli-tooldeepresearchinteractive-learninglearningmulti-agent-systemsrag
refactor: remove litellm dependency, align provider architecture
Bingxi Zhao (Frank)5960fbc0f7a7
diff --git a/deeptutor/agents/research/utils/token_tracker.py b/deeptutor/agents/research/utils/token_tracker.pyindex 6909e8d55..49a013509 100644--- a/deeptutor/agents/research/utils/token_tracker.py+++ b/deeptutor/agents/research/utils/token_tracker.py@@ -18,15 +18,7 @@ except ImportError:TIKTOKEN_AVAILABLE = Falsetiktoken = None # type: ignore-# Try importing litellm (optional)-try:- import litellm # type: ignore- from litellm import token_counter # type: ignore-- LITELLM_AVAILABLE = True-except ImportError:- LITELLM_AVAILABLE = False- litellm = None # type: ignore+LITELLM_AVAILABLE = False# Model pricing table (USD per 1K tokens)MODEL_PRICING = {@@ -63,11 +55,13 @@ def count_tokens_with_tiktoken(text: str, model_name: str) -> int:def count_tokens_with_litellm(messages: list[dict], model_name: str) -> dict[str, int]:- if not LITELLM_AVAILABLE:+ """Count tokens from messages using tiktoken (litellm removed)."""+ if not TIKTOKEN_AVAILABLE:return {"prompt_tokens": 0, "completion_tokens": 0, "total_tokens": 0}try:- token_count = token_counter(model=model_name, messages=messages) # type: ignore- return {"prompt_tokens": token_count, "completion_tokens": 0, "total_tokens": token_count}+ text = "\n".join(str(m.get("content", "")) for m in messages)+ count = count_tokens_with_tiktoken(text, model_name)+ return {"prompt_tokens": count, "completion_tokens": 0, "total_tokens": count}except Exception:return {"prompt_tokens": 0, "completion_tokens": 0, "total_tokens": 0}@@ -80,17 +74,6 @@ def get_model_pricing(model_name: str) -> dict[str, float]:for key, val in MODEL_PRICING.items():if key in lower or lower in key:return val- # litellm query- if LITELLM_AVAILABLE:- try:- info = litellm.get_model_info(model=model_name) # type: ignore- if info and "input_cost_per_token" in info:- return {- "input": info.get("input_cost_per_token", 0) * 1000,- "output": info.get("output_cost_per_token", 0) * 1000,- }- except Exception:- passreturn MODEL_PRICING["gpt-4o-mini"]diff --git a/deeptutor/agents/solve/utils/token_tracker.py b/deeptutor/agents/solve/utils/token_tracker.pyindex 8188217a2..ae6ca65c7 100644--- a/deeptutor/agents/solve/utils/token_tracker.py+++ b/deeptutor/agents/solve/utils/token_tracker.py@@ -18,15 +18,7 @@ except ImportError:TIKTOKEN_AVAILABLE = Falsetiktoken = None-# Try importing litellm (optional advanced library)-try:- import litellm- from litellm import token_counter-- LITELLM_AVAILABLE = True-except ImportError:- LITELLM_AVAILABLE = False- litellm = None+LITELLM_AVAILABLE = False# Model pricing table (price per 1K tokens, unit: USD)@@ -103,56 +95,20 @@ def count_tokens_with_tiktoken(text: str, model_name: str) -> int:def count_tokens_with_litellm(messages: list[dict], model_name: str) -> dict[str, int]:- """- Calculate token count using litellm (if available)-- Args:- messages: Message list- model_name: Model name-- Returns:- {'prompt_tokens': int, 'completion_tokens': int, 'total_tokens': int}- """- if not LITELLM_AVAILABLE:+ """Count tokens from messages using tiktoken (litellm removed)."""+ if not TIKTOKEN_AVAILABLE:return {"prompt_tokens": 0, "completion_tokens": 0, "total_tokens": 0}-try:- # Use litellm's token_counter- token_count = token_counter(model=model_name, messages=messages)- return {- "prompt_tokens": token_count,- "completion_tokens": 0, # litellm only counts prompt tokens- "total_tokens": token_count,- }+ text = "\n".join(str(m.get("content", "")) for m in messages)+ count = count_tokens_with_tiktoken(text, model_name)+ return {"prompt_tokens": count, "completion_tokens": 0, "total_tokens": count}except Exception:return {"prompt_tokens": 0, "completion_tokens": 0, "total_tokens": 0}def calculate_cost_with_litellm(model: str, prompt_tokens: int, completion_tokens: int) -> float:- """- Calculate cost using litellm (more accurate if available)-- Args:- model: Model name- prompt_tokens: Input tokens- completion_tokens: Output tokens-- Returns:- Cost (USD)- """- if not LITELLM_AVAILABLE:- # Fall back to manual calculation- return calculate_cost(model, prompt_tokens, completion_tokens)-- try:- # Use litellm's completion_cost function- cost = litellm.completion_cost(- model=model, prompt_tokens=prompt_tokens, completion_tokens=completion_tokens- )- return cost- except Exception:- # If failed, fall back to manual calculation- return calculate_cost(model, prompt_tokens, completion_tokens)+ """Calculate cost using built-in pricing table."""+ return calculate_cost(model, prompt_tokens, completion_tokens)def get_model_pricing(model_name: str) -> dict[str, float]:@@ -175,20 +131,6 @@ def get_model_pricing(model_name: str) -> dict[str, float]:if key.lower() in model_lower or model_lower in key.lower():return pricing- # If using litellm, try to get price from litellm- if LITELLM_AVAILABLE:- try:- # litellm has built-in pricing table- model_info = litellm.get_model_info(model=model_name)- if model_info and "input_cost_per_token" in model_info:- return {- "input": model_info.get("input_cost_per_token", 0) * 1000,- "output": model_info.get("output_cost_per_token", 0) * 1000,- }- except Exception:- pass-- # Default price (use gpt-4o-mini as conservative estimate)return MODEL_PRICING.get("gpt-4o-mini", {"input": 0.00015, "output": 0.0006})diff --git a/deeptutor/api/routers/settings.py b/deeptutor/api/routers/settings.pyindex 73e835c86..23a26ff7c 100644--- a/deeptutor/api/routers/settings.py+++ b/deeptutor/api/routers/settings.py@@ -96,9 +96,32 @@ def save_ui_settings(settings: dict[str, Any]) -> None:json.dump(settings, handle, ensure_ascii=False, indent=2)+def _provider_choices() -> dict[str, list[dict[str, str]]]:+ """Build dropdown options for provider selection, keyed by service type."""+ from deeptutor.services.provider_registry import PROVIDERS++ llm = sorted(+ [{"value": s.name, "label": s.label, "base_url": s.default_api_base} for s in PROVIDERS],+ key=lambda p: p["label"].lower(),+ )+ search = [+ {"value": "brave", "label": "Brave", "base_url": ""},+ {"value": "tavily", "label": "Tavily", "base_url": ""},+ {"value": "jina", "label": "Jina", "base_url": ""},+ {"value": "searxng", "label": "SearXNG", "base_url": ""},+ {"value": "duckduckgo", "label": "DuckDuckGo", "base_url": ""},+ {"value": "perplexity", "label": "Perplexity", "base_url": ""},+ ]+ return {"llm": llm, "embedding": llm, "search": search}++@router.get("")async def get_settings():- return {"ui": load_ui_settings(), "catalog": get_model_catalog_service().load()}+ return {+ "ui": load_ui_settings(),+ "catalog": get_model_catalog_service().load(),+ "providers": _provider_choices(),+ }@router.get("/catalog")diff --git a/deeptutor/services/llm/executors.py b/deeptutor/services/llm/executors.pyindex 4add109be..f2c8b9675 100644--- a/deeptutor/services/llm/executors.py+++ b/deeptutor/services/llm/executors.py@@ -1,13 +1,16 @@-"""Provider-backed LLM executors (LiteLLM + direct OpenAI/Azure)."""+"""Provider-backed LLM executors (openai + anthropic SDKs, no litellm)."""from __future__ import annotations-from collections.abc import AsyncGeneratorimport os+import uuid+from collections.abc import AsyncGeneratorfrom typing import Any+from openai import AsyncOpenAI+from deeptutor.logging import get_logger-from deeptutor.services.llm.provider_registry import find_by_name, normalize_model_for_litellm+from deeptutor.services.llm.provider_registry import find_by_name, strip_provider_prefixfrom .config import get_token_limit_kwargsfrom .utils import extract_response_content@@ -29,7 +32,7 @@ def _build_messages(]-def _setup_litellm_env(provider_name: str, api_key: str | None, api_base: str | None) -> None:+def _setup_provider_env(provider_name: str, api_key: str | None, api_base: str | None) -> None:spec = find_by_name(provider_name)if not spec or not api_key:return@@ -41,15 +44,24 @@ def _setup_litellm_env(provider_name: str, api_key: str | None, api_base: str |os.environ.setdefault(env_name, resolved)-def litellm_available() -> bool:- try:- import litellm # noqa: F401- except Exception:- return False- return True+def _resolve_model_and_base(+ provider_name: str,+ model: str,+ api_key: str | None,+ base_url: str | None,+) -> tuple[str, str | None, str | None]:+ """Resolve the actual model name, base_url, and api_key for the provider.++ Returns (resolved_model, effective_base_url, effective_api_key).+ """+ spec = find_by_name(provider_name)+ resolved_model = strip_provider_prefix(model, spec) if spec else model+ effective_base = base_url or (spec.default_api_base if spec else None) or None+ effective_key = api_key+ return resolved_model, effective_base, effective_key-async def litellm_complete(+async def sdk_complete(*,prompt: str,system_prompt: str,@@ -63,11 +75,26 @@ async def litellm_complete(reasoning_effort: str | None = None,**kwargs: object,) -> str:- from litellm import acompletion+ """Non-streaming completion using the openai SDK."""+ _setup_provider_env(provider_name, api_key, base_url)+ resolved_model, effective_base, effective_key = _resolve_model_and_base(+ provider_name, model, api_key, base_url,+ )++ default_headers: dict[str, str] = {"x-session-affinity": uuid.uuid4().hex}+ if extra_headers:+ default_headers.update(extra_headers)++ client = AsyncOpenAI(+ api_key=effective_key or "no-key",+ base_url=effective_base,+ default_headers=default_headers,+ max_retries=0,+ )++ max_tokens_val = int(kwargs.pop("max_tokens", 4096))+ temperature_val = float(kwargs.pop("temperature", 0.7))- _setup_litellm_env(provider_name, api_key, base_url)- spec = find_by_name(provider_name)- resolved_model = normalize_model_for_litellm(model, spec)payload: dict[str, Any] = {"model": resolved_model,"messages": _build_messages(@@ -75,24 +102,17 @@ async def litellm_complete(system_prompt=system_prompt,messages=messages,),- "max_tokens": int(kwargs.pop("max_tokens", 4096)),- "temperature": float(kwargs.pop("temperature", 0.7)),- "drop_params": True,+ "temperature": temperature_val,}- payload.update(get_token_limit_kwargs(model, int(payload["max_tokens"])))- if api_key:- payload["api_key"] = api_key- if base_url:- payload["api_base"] = base_url- if api_version:- payload["api_version"] = api_version- if extra_headers:- payload["extra_headers"] = extra_headers++ token_kwargs = get_token_limit_kwargs(resolved_model, max_tokens_val)+ payload.update(token_kwargs)+if reasoning_effort:payload["reasoning_effort"] = reasoning_effortpayload.update(kwargs)- response = await acompletion(**payload)+ response = await client.chat.completions.create(**payload)choices = getattr(response, "choices", None) or []if not choices:return ""@@ -102,7 +122,7 @@ async def litellm_complete(return extract_response_content(message)-async def litellm_stream(+async def sdk_stream(*,prompt: str,system_prompt: str,@@ -116,11 +136,26 @@ async def litellm_stream(reasoning_effort: str | None = None,**kwargs: object,) -> AsyncGenerator[str, None]:- from litellm import acompletion+ """Streaming completion using the openai SDK."""+ _setup_provider_env(provider_name, api_key, base_url)+ resolved_model, effective_base, effective_key = _resolve_model_and_base(+ provider_name, model, api_key, base_url,+ )++ default_headers: dict[str, str] = {"x-session-affinity": uuid.uuid4().hex}+ if extra_headers:+ default_headers.update(extra_headers)++ client = AsyncOpenAI(+ api_key=effective_key or "no-key",+ base_url=effective_base,+ default_headers=default_headers,+ max_retries=0,+ )++ max_tokens_val = int(kwargs.pop("max_tokens", 4096))+ temperature_val = float(kwargs.pop("temperature", 0.7))- _setup_litellm_env(provider_name, api_key, base_url)- spec = find_by_name(provider_name)- resolved_model = normalize_model_for_litellm(model, spec)payload: dict[str, Any] = {"model": resolved_model,"messages": _build_messages(@@ -128,25 +163,18 @@ async def litellm_stream(system_prompt=system_prompt,messages=messages,),- "max_tokens": int(kwargs.pop("max_tokens", 4096)),- "temperature": float(kwargs.pop("temperature", 0.7)),- "drop_params": True,+ "temperature": temperature_val,"stream": True,}- payload.update(get_token_limit_kwargs(model, int(payload["max_tokens"])))- if api_key:- payload["api_key"] = api_key- if base_url:- payload["api_base"] = base_url- if api_version:- payload["api_version"] = api_version- if extra_headers:- payload["extra_headers"] = extra_headers++ token_kwargs = get_token_limit_kwargs(resolved_model, max_tokens_val)+ payload.update(token_kwargs)+if reasoning_effort:payload["reasoning_effort"] = reasoning_effortpayload.update(kwargs)- stream_response = await acompletion(**payload)+ stream_response = await client.chat.completions.create(**payload)async for chunk in stream_response:choices = getattr(chunk, "choices", None) or []if not choices:@@ -157,12 +185,9 @@ async def litellm_stream(delta = choice.get("delta")if delta is None:continue- # Skip stop-chunks where content is explicitly None (avoids- # extract_response_content converting the delta repr to string).raw_content = getattr(delta, "content", None) if not isinstance(delta, dict) else delta.get("content")if raw_content is None:continuecontent = extract_response_content(delta)if content:yield content-diff --git a/deeptutor/services/llm/factory.py b/deeptutor/services/llm/factory.pyindex b3a175ff5..8b8fd85af 100644--- a/deeptutor/services/llm/factory.py+++ b/deeptutor/services/llm/factory.py@@ -55,9 +55,8 @@ from .exceptions import (LLMTimeoutError,)from .executors import (- litellm_available,- litellm_complete,- litellm_stream,+ sdk_complete,+ sdk_stream,)from .utils import is_local_llm_server@@ -263,13 +262,13 @@ async def complete("openai_codex requires OAuth login in CLI. ""Run `deeptutor provider login openai-codex` first.")- if provider_mode == "oauth" and not litellm_available():+ if provider_mode == "oauth":raise LLMConfigError(- f"{provider_name} requires litellm + OAuth session. "- "Install provider deps and run `deeptutor provider login ...`."+ f"{provider_name} requires OAuth session. "+ "Run `deeptutor provider login ...` first.")- if provider_mode != "direct" and litellm_available():- return await litellm_complete(+ if provider_mode != "direct":+ return await sdk_complete(prompt=prompt_value,system_prompt=system_prompt_value,provider_name=provider_name,@@ -392,14 +391,14 @@ async def stream("openai_codex requires OAuth login in CLI. ""Run `deeptutor provider login openai-codex` first.")- if provider_mode == "oauth" and not litellm_available():+ if provider_mode == "oauth":raise LLMConfigError(- f"{provider_name} requires litellm + OAuth session. "- "Install provider deps and run `deeptutor provider login ...`."+ f"{provider_name} requires OAuth session. "+ "Run `deeptutor provider login ...` first.")- if provider_mode != "direct" and litellm_available():- async for chunk in litellm_stream(+ if provider_mode != "direct":+ async for chunk in sdk_stream(prompt=prompt,system_prompt=system_prompt,provider_name=provider_name,diff --git a/deeptutor/services/provider_registry.py b/deeptutor/services/provider_registry.pyindex 11e6bf2a3..ca5bcf735 100644--- a/deeptutor/services/provider_registry.py+++ b/deeptutor/services/provider_registry.py@@ -1,4 +1,11 @@-"""Nanobot-style provider registry for DeepTutor LLM routing."""+"""Provider registry for DeepTutor LLM routing.++Single source of truth for provider metadata. Adding a new provider:+ 1. Add a ProviderSpec to PROVIDERS below.+ Done. Env vars, config matching, status display all derive from here.++Order matters — it controls match priority and fallback. Gateways first.+"""from __future__ import annotations@@ -8,14 +15,22 @@ from typing import Any@dataclass(frozen=True)class ProviderSpec:- """Single provider metadata entry."""+ """Single provider metadata entry.++ Placeholders in env_extras values:+ {api_key} — the user's API key+ {api_base} — api_base from config, or this spec's default_api_base+ """name: strkeywords: tuple[str, ...]env_key: strdisplay_name: str = ""- litellm_prefix: str = ""- skip_prefixes: tuple[str, ...] = ()++ # Which provider implementation to use:+ # "openai_compat" | "anthropic" | "azure_openai" | "openai_codex" | "github_copilot"+ backend: str = "openai_compat"+env_extras: tuple[tuple[str, str], ...] = ()is_gateway: bool = Falseis_local: bool = False@@ -23,6 +38,8 @@ class ProviderSpec:detect_by_base_keyword: str = ""default_api_base: str = ""strip_model_prefix: bool = False+ supports_max_completion_tokens: bool = False+ supports_prompt_caching: bool = Falsemodel_overrides: tuple[tuple[str, dict[str, Any]], ...] = ()is_oauth: bool = Falseis_direct: bool = False@@ -73,12 +90,18 @@ def canonical_provider_name(name: str | None) -> str | None:return PROVIDER_ALIASES.get(key, key)+# ---------------------------------------------------------------------------+# PROVIDERS — the registry. Order = priority.+# ---------------------------------------------------------------------------+PROVIDERS: tuple[ProviderSpec, ...] = (+ # === Direct (user supplies everything, no auto-detection) ===============ProviderSpec(name="custom",keywords=(),env_key="",display_name="Custom",+ backend="openai_compat",is_direct=True,),ProviderSpec(@@ -86,25 +109,28 @@ PROVIDERS: tuple[ProviderSpec, ...] = (keywords=("azure", "azure_openai"),env_key="",display_name="Azure OpenAI",+ backend="azure_openai",is_direct=True,),+ # === Gateways (detected by api_key / api_base, route any model) ========ProviderSpec(name="openrouter",keywords=("openrouter",),env_key="OPENROUTER_API_KEY",display_name="OpenRouter",- litellm_prefix="openrouter",+ backend="openai_compat",is_gateway=True,detect_by_key_prefix="sk-or-",detect_by_base_keyword="openrouter",default_api_base="https://openrouter.ai/api/v1",+ supports_prompt_caching=True,),ProviderSpec(name="aihubmix",keywords=("aihubmix",),env_key="OPENAI_API_KEY",display_name="AiHubMix",- litellm_prefix="openai",+ backend="openai_compat",is_gateway=True,detect_by_base_keyword="aihubmix",default_api_base="https://aihubmix.com/v1",@@ -115,7 +141,7 @@ PROVIDERS: tuple[ProviderSpec, ...] = (keywords=("siliconflow",),env_key="OPENAI_API_KEY",display_name="SiliconFlow",- litellm_prefix="openai",+ backend="openai_compat",is_gateway=True,detect_by_base_keyword="siliconflow",default_api_base="https://api.siliconflow.cn/v1",@@ -125,7 +151,7 @@ PROVIDERS: tuple[ProviderSpec, ...] = (keywords=("volcengine", "volces", "ark"),env_key="OPENAI_API_KEY",display_name="VolcEngine",- litellm_prefix="volcengine",+ backend="openai_compat",is_gateway=True,detect_by_base_keyword="volces",default_api_base="https://ark.cn-beijing.volces.com/api/v3",@@ -135,7 +161,7 @@ PROVIDERS: tuple[ProviderSpec, ...] = (keywords=("volcengine-plan",),env_key="OPENAI_API_KEY",display_name="VolcEngine Coding Plan",- litellm_prefix="volcengine",+ backend="openai_compat",is_gateway=True,default_api_base="https://ark.cn-beijing.volces.com/api/coding/v3",strip_model_prefix=True,@@ -145,7 +171,7 @@ PROVIDERS: tuple[ProviderSpec, ...] = (keywords=("byteplus",),env_key="OPENAI_API_KEY",display_name="BytePlus",- litellm_prefix="volcengine",+ backend="openai_compat",is_gateway=True,detect_by_base_keyword="bytepluses",default_api_base="https://ark.ap-southeast.bytepluses.com/api/v3",@@ -156,30 +182,36 @@ PROVIDERS: tuple[ProviderSpec, ...] = (keywords=("byteplus-plan",),env_key="OPENAI_API_KEY",display_name="BytePlus Coding Plan",- litellm_prefix="volcengine",+ backend="openai_compat",is_gateway=True,default_api_base="https://ark.ap-southeast.bytepluses.com/api/coding/v3",strip_model_prefix=True,),+ # === Standard providers (matched by model-name keywords) ===============ProviderSpec(name="anthropic",keywords=("anthropic", "claude"),env_key="ANTHROPIC_API_KEY",display_name="Anthropic",+ backend="anthropic",default_api_base="https://api.anthropic.com/v1",+ supports_prompt_caching=True,),ProviderSpec(name="openai",keywords=("openai", "gpt"),env_key="OPENAI_API_KEY",display_name="OpenAI",+ backend="openai_compat",default_api_base="https://api.openai.com/v1",+ supports_max_completion_tokens=True,),ProviderSpec(name="openai_codex",keywords=("openai_codex", "codex"),env_key="",display_name="OpenAI Codex",+ backend="openai_codex",is_oauth=True,default_api_base="https://chatgpt.com/backend-api",),@@ -188,43 +220,42 @@ PROVIDERS: tuple[ProviderSpec, ...] = (keywords=("github_copilot", "copilot"),env_key="",display_name="GitHub Copilot",- litellm_prefix="github_copilot",- skip_prefixes=("github_copilot/",),+ backend="github_copilot",is_oauth=True,+ default_api_base="https://api.githubcopilot.com",+ strip_model_prefix=True,),ProviderSpec(name="deepseek",keywords=("deepseek",),env_key="DEEPSEEK_API_KEY",display_name="DeepSeek",- litellm_prefix="deepseek",- skip_prefixes=("deepseek/",),- default_api_base="https://api.deepseek.com/v1",+ backend="openai_compat",+ default_api_base="https://api.deepseek.com",),ProviderSpec(name="gemini",keywords=("gemini",),env_key="GEMINI_API_KEY",display_name="Gemini",- litellm_prefix="gemini",- skip_prefixes=("gemini/",),+ backend="openai_compat",+ default_api_base="https://generativelanguage.googleapis.com/v1beta/openai/",),ProviderSpec(name="zhipu",keywords=("zhipu", "glm", "zai"),env_key="ZAI_API_KEY",display_name="Zhipu AI",- litellm_prefix="zai",- skip_prefixes=("zhipu/", "zai/", "openrouter/", "hosted_vllm/"),+ backend="openai_compat",env_extras=(("ZHIPUAI_API_KEY", "{api_key}"),),+ default_api_base="https://open.bigmodel.cn/api/paas/v4",),ProviderSpec(name="dashscope",keywords=("qwen", "dashscope"),env_key="DASHSCOPE_API_KEY",display_name="DashScope",- litellm_prefix="dashscope",- skip_prefixes=("dashscope/", "openrouter/"),+ backend="openai_compat",default_api_base="https://dashscope.aliyuncs.com/compatible-mode/v1",),ProviderSpec(@@ -232,9 +263,7 @@ PROVIDERS: tuple[ProviderSpec, ...] = (keywords=("moonshot", "kimi"),env_key="MOONSHOT_API_KEY",display_name="Moonshot",- litellm_prefix="moonshot",- skip_prefixes=("moonshot/", "openrouter/"),- env_extras=(("MOONSHOT_API_BASE", "{api_base}"),),+ backend="openai_compat",default_api_base="https://api.moonshot.ai/v1",model_overrides=(("kimi-k2.5", {"temperature": 1.0}),),),@@ -243,16 +272,40 @@ PROVIDERS: tuple[ProviderSpec, ...] = (keywords=("minimax",),env_key="MINIMAX_API_KEY",display_name="MiniMax",- litellm_prefix="minimax",- skip_prefixes=("minimax/", "openrouter/"),+ backend="openai_compat",default_api_base="https://api.minimax.io/v1",),+ ProviderSpec(+ name="mistral",+ keywords=("mistral",),+ env_key="MISTRAL_API_KEY",+ display_name="Mistral",+ backend="openai_compat",+ default_api_base="https://api.mistral.ai/v1",+ ),+ ProviderSpec(+ name="stepfun",+ keywords=("stepfun", "step"),+ env_key="STEPFUN_API_KEY",+ display_name="Step Fun",+ backend="openai_compat",+ default_api_base="https://api.stepfun.com/v1",+ ),+ ProviderSpec(+ name="xiaomi_mimo",+ keywords=("xiaomi_mimo", "mimo"),+ env_key="XIAOMIMIMO_API_KEY",+ display_name="Xiaomi MIMO",+ backend="openai_compat",+ default_api_base="https://api.xiaomimimo.com/v1",+ ),+ # === Local deployment ==================================================ProviderSpec(name="vllm",keywords=("vllm",),env_key="HOSTED_VLLM_API_KEY",display_name="vLLM",- litellm_prefix="hosted_vllm",+ backend="openai_compat",is_local=True,default_api_base="http://localhost:8000/v1",),@@ -261,21 +314,38 @@ PROVIDERS: tuple[ProviderSpec, ...] = (keywords=("ollama", "nemotron"),env_key="OLLAMA_API_KEY",display_name="Ollama",- litellm_prefix="ollama_chat",- skip_prefixes=("ollama/", "ollama_chat/"),+ backend="openai_compat",is_local=True,detect_by_base_keyword="11434",default_api_base="http://localhost:11434/v1",),+ ProviderSpec(+ name="ovms",+ keywords=("openvino", "ovms"),+ env_key="",+ display_name="OpenVINO Model Server",+ backend="openai_compat",+ is_direct=True,+ is_local=True,+ default_api_base="http://localhost:8000/v3",+ ),+ # === Auxiliary ==========================================================ProviderSpec(name="groq",keywords=("groq",),env_key="GROQ_API_KEY",display_name="Groq",- litellm_prefix="groq",- skip_prefixes=("groq/",),+ backend="openai_compat",default_api_base="https://api.groq.com/openai/v1",),+ ProviderSpec(+ name="qianfan",+ keywords=("qianfan", "ernie"),+ env_key="QIANFAN_API_KEY",+ display_name="Qianfan",+ backend="openai_compat",+ default_api_base="https://qianfan.baidubce.com/v2",+ ),)@@ -329,17 +399,13 @@ def find_gateway(return None-def normalize_model_for_litellm(model: str, spec: ProviderSpec | None) -> str:- """Apply Nanobot-style model prefixing rules for LiteLLM."""+def strip_provider_prefix(model: str, spec: ProviderSpec | None) -> str:+ """Strip the provider/ prefix from a model name if applicable."""if not model or not spec:return model- resolved = model- if spec.strip_model_prefix and "/" in resolved:- resolved = resolved.split("/", 1)[1]- if spec.litellm_prefix and not any(resolved.startswith(prefix) for prefix in spec.skip_prefixes):- if not resolved.startswith(f"{spec.litellm_prefix}/"):- resolved = f"{spec.litellm_prefix}/{resolved}"- return resolved+ if spec.strip_model_prefix and "/" in model:+ return model.split("/", 1)[1]+ return model__all__ = [@@ -351,5 +417,5 @@ __all__ = ["find_by_name","find_by_model","find_gateway",- "normalize_model_for_litellm",+ "strip_provider_prefix",]diff --git a/deeptutor/tutorbot/providers/__init__.py b/deeptutor/tutorbot/providers/__init__.pyindex 07a9ead7e..992096bfd 100644--- a/deeptutor/tutorbot/providers/__init__.py+++ b/deeptutor/tutorbot/providers/__init__.py@@ -2,11 +2,18 @@from deeptutor.tutorbot.providers.base import LLMProvider, LLMResponse-__all__ = ["LLMProvider", "LLMResponse", "LiteLLMProvider"]+__all__ = ["LLMProvider", "LLMResponse", "OpenAICompatProvider", "AnthropicProvider"]def __getattr__(name: str):+ if name == "OpenAICompatProvider":+ from deeptutor.tutorbot.providers.openai_compat_provider import OpenAICompatProvider+ return OpenAICompatProvider+ if name == "AnthropicProvider":+ from deeptutor.tutorbot.providers.anthropic_provider import AnthropicProvider+ return AnthropicProvider+ # Legacy aliasif name == "LiteLLMProvider":- from deeptutor.tutorbot.providers.litellm_provider import LiteLLMProvider- return LiteLLMProvider+ from deeptutor.tutorbot.providers.openai_compat_provider import OpenAICompatProvider+ return OpenAICompatProviderraise AttributeError(f"module {__name__!r} has no attribute {name!r}")diff --git a/deeptutor/tutorbot/providers/anthropic_provider.py b/deeptutor/tutorbot/providers/anthropic_provider.pynew file mode 100644index 000000000..471838ffd--- /dev/null+++ b/deeptutor/tutorbot/providers/anthropic_provider.py@@ -0,0 +1,470 @@+"""Anthropic provider — direct SDK integration for Claude models.++Handles message format conversion (OpenAI -> Anthropic Messages API),+prompt caching, extended thinking, tool calls, and streaming.+"""++from __future__ import annotations++import asyncio+import re+import secrets+import string+from collections.abc import Awaitable, Callable+from typing import Any++import json_repair++from deeptutor.tutorbot.providers.base import LLMProvider, LLMResponse, ToolCallRequest++_ALNUM = string.ascii_letters + string.digits+++def _gen_tool_id() -> str:+ return "toolu_" + "".join(secrets.choice(_ALNUM) for _ in range(22))+++class AnthropicProvider(LLMProvider):+ """LLM provider using the native Anthropic SDK for Claude models."""++ def __init__(+ self,+ api_key: str | None = None,+ api_base: str | None = None,+ default_model: str = "claude-sonnet-4-20250514",+ extra_headers: dict[str, str] | None = None,+ ):+ super().__init__(api_key, api_base)+ self.default_model = default_model+ self.extra_headers = extra_headers or {}++ from anthropic import AsyncAnthropic++ client_kw: dict[str, Any] = {"max_retries": 0}+ if api_key:+ client_kw["api_key"] = api_key+ if api_base:+ client_kw["base_url"] = api_base+ if extra_headers:+ client_kw["default_headers"] = extra_headers+ self._client = AsyncAnthropic(**client_kw)++ @classmethod+ def _handle_error(cls, e: Exception) -> LLMResponse:+ payload = (+ getattr(e, "body", None)+ or getattr(e, "doc", None)+ or getattr(getattr(e, "response", None), "text", None)+ )+ payload_text = payload if isinstance(payload, str) else str(payload) if payload is not None else ""+ msg = f"Error: {payload_text.strip()[:500]}" if payload_text.strip() else f"Error calling LLM: {e}"+ return LLMResponse(content=msg, finish_reason="error")++ @staticmethod+ def _strip_prefix(model: str) -> str:+ if model.startswith("anthropic/"):+ return model[len("anthropic/"):]+ return model++ # ------------------------------------------------------------------+ # Message conversion: OpenAI chat format -> Anthropic Messages API+ # ------------------------------------------------------------------++ def _convert_messages(+ self, messages: list[dict[str, Any]],+ ) -> tuple[str | list[dict[str, Any]], list[dict[str, Any]]]:+ """Return ``(system, anthropic_messages)``."""+ system: str | list[dict[str, Any]] = ""+ raw: list[dict[str, Any]] = []++ for msg in messages:+ role = msg.get("role", "")+ content = msg.get("content")++ if role == "system":+ system = content if isinstance(content, (str, list)) else str(content or "")+ continue++ if role == "tool":+ block = self._tool_result_block(msg)+ if raw and raw[-1]["role"] == "user":+ prev_c = raw[-1]["content"]+ if isinstance(prev_c, list):+ prev_c.append(block)+ else:+ raw[-1]["content"] = [+ {"type": "text", "text": prev_c or ""}, block,+ ]+ else:+ raw.append({"role": "user", "content": [block]})+ continue++ if role == "assistant":+ raw.append({"role": "assistant", "content": self._assistant_blocks(msg)})+ continue++ if role == "user":+ raw.append({+ "role": "user",+ "content": self._convert_user_content(content),+ })+ continue++ return system, self._merge_consecutive(raw)++ @staticmethod+ def _tool_result_block(msg: dict[str, Any]) -> dict[str, Any]:+ content = msg.get("content")+ block: dict[str, Any] = {+ "type": "tool_result",+ "tool_use_id": msg.get("tool_call_id", ""),+ }+ if isinstance(content, (str, list)):+ block["content"] = content+ else:+ block["content"] = str(content) if content else ""+ return block++ @staticmethod+ def _assistant_blocks(msg: dict[str, Any]) -> list[dict[str, Any]]:+ blocks: list[dict[str, Any]] = []+ content = msg.get("content")++ for tb in msg.get("thinking_blocks") or []:+ if isinstance(tb, dict) and tb.get("type") == "thinking":+ blocks.append({+ "type": "thinking",+ "thinking": tb.get("thinking", ""),+ "signature": tb.get("signature", ""),+ })++ if isinstance(content, str) and content:+ blocks.append({"type": "text", "text": content})+ elif isinstance(content, list):+ for item in content:+ blocks.append(item if isinstance(item, dict) else {"type": "text", "text": str(item)})++ for tc in msg.get("tool_calls") or []:+ if not isinstance(tc, dict):+ continue+ func = tc.get("function", {})+ args = func.get("arguments", "{}")+ if isinstance(args, str):+ args = json_repair.loads(args)+ blocks.append({+ "type": "tool_use",+ "id": tc.get("id") or _gen_tool_id(),+ "name": func.get("name", ""),+ "input": args,+ })++ return blocks or [{"type": "text", "text": ""}]++ def _convert_user_content(self, content: Any) -> Any:+ if isinstance(content, str) or content is None:+ return content or "(empty)"+ if not isinstance(content, list):+ return str(content)++ result: list[dict[str, Any]] = []+ for item in content:+ if not isinstance(item, dict):+ result.append({"type": "text", "text": str(item)})+ continue+ if item.get("type") == "image_url":+ converted = self._convert_image_block(item)+ if converted:+ result.append(converted)+ continue+ result.append(item)+ return result or "(empty)"++ @staticmethod+ def _convert_image_block(block: dict[str, Any]) -> dict[str, Any] | None:+ url = (block.get("image_url") or {}).get("url", "")+ if not url:+ return None+ m = re.match(r"data:(image/\w+);base64,(.+)", url, re.DOTALL)+ if m:+ return {+ "type": "image",+ "source": {"type": "base64", "media_type": m.group(1), "data": m.group(2)},+ }+ return {+ "type": "image",+ "source": {"type": "url", "url": url},+ }++ @staticmethod+ def _merge_consecutive(msgs: list[dict[str, Any]]) -> list[dict[str, Any]]:+ """Anthropic requires alternating user/assistant roles."""+ merged: list[dict[str, Any]] = []+ for msg in msgs:+ if merged and merged[-1]["role"] == msg["role"]:+ prev_c = merged[-1]["content"]+ cur_c = msg["content"]+ if isinstance(prev_c, str):+ prev_c = [{"type": "text", "text": prev_c}]+ if isinstance(cur_c, str):+ cur_c = [{"type": "text", "text": cur_c}]+ if isinstance(cur_c, list):+ prev_c.extend(cur_c)+ merged[-1]["content"] = prev_c+ else:+ merged.append(msg)+ return merged++ # ------------------------------------------------------------------+ # Tool definition conversion+ # ------------------------------------------------------------------++ @staticmethod+ def _convert_tools(tools: list[dict[str, Any]] | None) -> list[dict[str, Any]] | None:+ if not tools:+ return None+ result = []+ for tool in tools:+ func = tool.get("function", tool)+ entry: dict[str, Any] = {+ "name": func.get("name", ""),+ "input_schema": func.get("parameters", {"type": "object", "properties": {}}),+ }+ desc = func.get("description")+ if desc:+ entry["description"] = desc+ if "cache_control" in tool:+ entry["cache_control"] = tool["cache_control"]+ result.append(entry)+ return result++ @staticmethod+ def _convert_tool_choice(+ tool_choice: str | dict[str, Any] | None,+ thinking_enabled: bool = False,+ ) -> dict[str, Any] | None:+ if thinking_enabled:+ return {"type": "auto"}+ if tool_choice is None or tool_choice == "auto":+ return {"type": "auto"}+ if tool_choice == "required":+ return {"type": "any"}+ if tool_choice == "none":+ return None+ if isinstance(tool_choice, dict):+ name = tool_choice.get("function", {}).get("name")+ if name:+ return {"type": "tool", "name": name}+ return {"type": "auto"}++ # ------------------------------------------------------------------+ # Prompt caching+ # ------------------------------------------------------------------++ @classmethod+ def _apply_cache_control(+ cls,+ system: str | list[dict[str, Any]],+ messages: list[dict[str, Any]],+ tools: list[dict[str, Any]] | None,+ ) -> tuple[str | list[dict[str, Any]], list[dict[str, Any]], list[dict[str, Any]] | None]:+ marker = {"type": "ephemeral"}++ if isinstance(system, str) and system:+ system = [{"type": "text", "text": system, "cache_control": marker}]+ elif isinstance(system, list) and system:+ system = list(system)+ system[-1] = {**system[-1], "cache_control": marker}++ new_msgs = list(messages)+ if len(new_msgs) >= 3:+ m = new_msgs[-2]+ c = m.get("content")+ if isinstance(c, str):+ new_msgs[-2] = {**m, "content": [{"type": "text", "text": c, "cache_control": marker}]}+ elif isinstance(c, list) and c:+ nc = list(c)+ nc[-1] = {**nc[-1], "cache_control": marker}+ new_msgs[-2] = {**m, "content": nc}++ new_tools = tools+ if tools:+ new_tools = list(tools)+ for idx in cls._tool_cache_marker_indices(new_tools):+ new_tools[idx] = {**new_tools[idx], "cache_control": marker}++ return system, new_msgs, new_tools++ # ------------------------------------------------------------------+ # Build API kwargs+ # ------------------------------------------------------------------++ def _build_kwargs(+ self,+ messages: list[dict[str, Any]],+ tools: list[dict[str, Any]] | None,+ model: str | None,+ max_tokens: int,+ temperature: float,+ reasoning_effort: str | None,+ tool_choice: str | dict[str, Any] | None,+ ) -> dict[str, Any]:+ model_name = self._strip_prefix(model or self.default_model)+ system, anthropic_msgs = self._convert_messages(self._sanitize_empty_content(messages))+ anthropic_tools = self._convert_tools(tools)++ system, anthropic_msgs, anthropic_tools = self._apply_cache_control(+ system, anthropic_msgs, anthropic_tools,+ )++ max_tokens = max(1, max_tokens)+ thinking_enabled = bool(reasoning_effort)++ kwargs: dict[str, Any] = {+ "model": model_name,+ "messages": anthropic_msgs,+ "max_tokens": max_tokens,+ }++ if system:+ kwargs["system"] = system++ if reasoning_effort == "adaptive":+ kwargs["thinking"] = {"type": "adaptive"}+ kwargs["temperature"] = 1.0+ elif thinking_enabled:+ budget_map = {"low": 1024, "medium": 4096, "high": max(8192, max_tokens)}+ budget = budget_map.get(reasoning_effort.lower(), 4096)+ kwargs["thinking"] = {"type": "enabled", "budget_tokens": budget}+ kwargs["max_tokens"] = max(max_tokens, budget + 4096)+ kwargs["temperature"] = 1.0+ else:+ kwargs["temperature"] = temperature++ if anthropic_tools:+ kwargs["tools"] = anthropic_tools+ tc = self._convert_tool_choice(tool_choice, thinking_enabled)+ if tc:+ kwargs["tool_choice"] = tc++ if self.extra_headers:+ kwargs["extra_headers"] = self.extra_headers++ return kwargs++ # ------------------------------------------------------------------+ # Response parsing+ # ------------------------------------------------------------------++ @staticmethod+ def _parse_response(response: Any) -> LLMResponse:+ content_parts: list[str] = []+ tool_calls: list[ToolCallRequest] = []+ thinking_blocks: list[dict[str, Any]] = []++ for block in response.content:+ if block.type == "text":+ content_parts.append(block.text)+ elif block.type == "tool_use":+ tool_calls.append(ToolCallRequest(+ id=block.id,+ name=block.name,+ arguments=block.input if isinstance(block.input, dict) else {},+ ))+ elif block.type == "thinking":+ thinking_blocks.append({+ "type": "thinking",+ "thinking": block.thinking,+ "signature": getattr(block, "signature", ""),+ })++ stop_map = {"tool_use": "tool_calls", "end_turn": "stop", "max_tokens": "length"}+ finish_reason = stop_map.get(response.stop_reason or "", response.stop_reason or "stop")++ usage: dict[str, int] = {}+ if response.usage:+ input_tokens = response.usage.input_tokens+ cache_creation = getattr(response.usage, "cache_creation_input_tokens", 0) or 0+ cache_read = getattr(response.usage, "cache_read_input_tokens", 0) or 0+ total_prompt = input_tokens + cache_creation + cache_read+ usage = {+ "prompt_tokens": total_prompt,+ "completion_tokens": response.usage.output_tokens,+ "total_tokens": total_prompt + response.usage.output_tokens,+ }++ return LLMResponse(+ content="".join(content_parts) or None,+ tool_calls=tool_calls,+ finish_reason=finish_reason,+ usage=usage,+ thinking_blocks=thinking_blocks or None,+ )++ # ------------------------------------------------------------------+ # Public API+ # ------------------------------------------------------------------++ async def chat(+ self,+ messages: list[dict[str, Any]],+ tools: list[dict[str, Any]] | None = None,+ model: str | None = None,+ max_tokens: int = 4096,+ temperature: float = 0.7,+ reasoning_effort: str | None = None,+ tool_choice: str | dict[str, Any] | None = None,+ ) -> LLMResponse:+ kwargs = self._build_kwargs(+ messages, tools, model, max_tokens, temperature,+ reasoning_effort, tool_choice,+ )+ try:+ response = await self._client.messages.create(**kwargs)+ return self._parse_response(response)+ except Exception as e:+ return self._handle_error(e)++ async def chat_stream(+ self,+ messages: list[dict[str, Any]],+ tools: list[dict[str, Any]] | None = None,+ model: str | None = None,+ max_tokens: int = 4096,+ temperature: float = 0.7,+ reasoning_effort: str | None = None,+ tool_choice: str | dict[str, Any] | None = None,+ on_content_delta: Callable[[str], Awaitable[None]] | None = None,+ ) -> LLMResponse:+ kwargs = self._build_kwargs(+ messages, tools, model, max_tokens, temperature,+ reasoning_effort, tool_choice,+ )+ idle_timeout_s = 90+ try:+ async with self._client.messages.stream(**kwargs) as stream:+ if on_content_delta:+ stream_iter = stream.text_stream.__aiter__()+ while True:+ try:+ text = await asyncio.wait_for(+ stream_iter.__anext__(),+ timeout=idle_timeout_s,+ )+ except StopAsyncIteration:+ break+ await on_content_delta(text)+ response = await asyncio.wait_for(+ stream.get_final_message(),+ timeout=idle_timeout_s,+ )+ return self._parse_response(response)+ except asyncio.TimeoutError:+ return LLMResponse(+ content=f"Error calling LLM: stream stalled for more than {idle_timeout_s} seconds",+ finish_reason="error",+ )+ except Exception as e:+ return self._handle_error(e)++ def get_default_model(self) -> str:+ return self.default_modeldiff --git a/deeptutor/tutorbot/providers/base.py b/deeptutor/tutorbot/providers/base.pyindex 114a94861..905b68d6d 100644--- a/deeptutor/tutorbot/providers/base.py+++ b/deeptutor/tutorbot/providers/base.py@@ -143,6 +143,20 @@ class LLMProvider(ABC):result.append(msg)return result+ @staticmethod+ def _tool_cache_marker_indices(tools: list[dict[str, Any]]) -> list[int]:+ """Return indices of tool definitions that should get cache_control markers.++ Heuristic: mark the last tool, and every 5th tool counting backwards,+ to balance cache granularity vs. overhead.+ """+ n = len(tools)+ if n == 0:+ return []+ if n <= 5:+ return [n - 1]+ return [i for i in range(n - 1, -1, -5)]+@staticmethoddef _sanitize_request_messages(messages: list[dict[str, Any]],diff --git a/deeptutor/tutorbot/providers/deeptutor_adapter.py b/deeptutor/tutorbot/providers/deeptutor_adapter.pyindex bbebf2d75..009852b5f 100644--- a/deeptutor/tutorbot/providers/deeptutor_adapter.py+++ b/deeptutor/tutorbot/providers/deeptutor_adapter.py@@ -2,23 +2,50 @@When TutorBot runs in-process inside the DeepTutor server, this providerreads api_key / model / base_url from DeepTutor's unified config and-delegates to the standard LiteLLMProvider, avoiding duplicate configuration.+delegates to the appropriate provider (OpenAICompat or Anthropic)."""from __future__ import annotations-from deeptutor.tutorbot.providers.litellm_provider import LiteLLMProvider+from deeptutor.tutorbot.providers.base import LLMProvider-def create_deeptutor_provider() -> LiteLLMProvider:- """Build a LiteLLMProvider pre-configured from DeepTutor's LLMConfig."""+def create_deeptutor_provider() -> LLMProvider:+ """Build a provider pre-configured from DeepTutor's LLMConfig."""from deeptutor.services.llm.config import get_llm_config+ from deeptutor.services.provider_registry import find_by_model, find_by_namecfg = get_llm_config()- return LiteLLMProvider(- api_key=cfg.api_key or None,- api_base=cfg.effective_url or cfg.base_url or None,- default_model=cfg.model,- extra_headers=cfg.extra_headers or {},- provider_name=cfg.provider_name or None,++ api_key = cfg.api_key or None+ api_base = cfg.effective_url or cfg.base_url or None+ model = cfg.model+ extra_headers = cfg.extra_headers or {}+ provider_name = cfg.provider_name or None++ spec = None+ if provider_name:+ spec = find_by_name(provider_name)+ if spec is None and model:+ spec = find_by_model(model)++ backend = spec.backend if spec else "openai_compat"++ if backend == "anthropic":+ from deeptutor.tutorbot.providers.anthropic_provider import AnthropicProvider+ return AnthropicProvider(+ api_key=api_key,+ api_base=api_base,+ default_model=model,+ extra_headers=extra_headers,+ )++ from deeptutor.tutorbot.providers.openai_compat_provider import OpenAICompatProvider+ return OpenAICompatProvider(+ api_key=api_key,+ api_base=api_base,+ default_model=model,+ extra_headers=extra_headers,+ spec=spec,+ provider_name=provider_name,)diff --git a/deeptutor/tutorbot/providers/litellm_provider.py b/deeptutor/tutorbot/providers/litellm_provider.pydeleted file mode 100644index 64ee6e9b1..000000000--- a/deeptutor/tutorbot/providers/litellm_provider.py+++ /dev/null@@ -1,353 +0,0 @@-"""LiteLLM provider implementation for multi-provider support."""--import hashlib-import os-import secrets-import string-from typing import Any--import json_repair-import litellm-from litellm import acompletion-from loguru import logger--from deeptutor.tutorbot.providers.base import LLMProvider, LLMResponse, ToolCallRequest-from deeptutor.tutorbot.providers.registry import find_by_model, find_gateway--# Standard chat-completion message keys.-_ALLOWED_MSG_KEYS = frozenset({"role", "content", "tool_calls", "tool_call_id", "name", "reasoning_content"})-_ANTHROPIC_EXTRA_KEYS = frozenset({"thinking_blocks"})-_ALNUM = string.ascii_letters + string.digits--def _short_tool_id() -> str:- """Generate a 9-char alphanumeric ID compatible with all providers (incl. Mistral)."""- return "".join(secrets.choice(_ALNUM) for _ in range(9))---class LiteLLMProvider(LLMProvider):- """- LLM provider using LiteLLM for multi-provider support.-- Supports OpenRouter, Anthropic, OpenAI, Gemini, MiniMax, and many other providers through- a unified interface. Provider-specific logic is driven by the registry- (see providers/registry.py) — no if-elif chains needed here.- """-- def __init__(- self,- api_key: str | None = None,- api_base: str | None = None,- default_model: str = "anthropic/claude-opus-4-5",- extra_headers: dict[str, str] | None = None,- provider_name: str | None = None,- ):- super().__init__(api_key, api_base)- self.default_model = default_model- self.extra_headers = extra_headers or {}-- # Detect gateway / local deployment.- # provider_name (from config key) is the primary signal;- # api_key / api_base are fallback for auto-detection.- self._gateway = find_gateway(provider_name, api_key, api_base)-- # Configure environment variables- if api_key:- self._setup_env(api_key, api_base, default_model)-- if api_base:- litellm.api_base = api_base-- # Disable LiteLLM logging noise- litellm.suppress_debug_info = True- # Drop unsupported parameters for providers (e.g., gpt-5 rejects some params)- litellm.drop_params = True-- self._langsmith_enabled = bool(os.getenv("LANGSMITH_API_KEY"))-- def _setup_env(self, api_key: str, api_base: str | None, model: str) -> None:- """Set environment variables based on detected provider."""- spec = self._gateway or find_by_model(model)- if not spec:- return- if not spec.env_key:- # OAuth/provider-only specs (for example: openai_codex)- return-- # Gateway/local overrides existing env; standard provider doesn't- if self._gateway:- os.environ[spec.env_key] = api_key- else:- os.environ.setdefault(spec.env_key, api_key)-- # Resolve env_extras placeholders:- # {api_key} → user's API key- # {api_base} → user's api_base, falling back to spec.default_api_base- effective_base = api_base or spec.default_api_base- for env_name, env_val in spec.env_extras:- resolved = env_val.replace("{api_key}", api_key)- resolved = resolved.replace("{api_base}", effective_base)- os.environ.setdefault(env_name, resolved)-- def _resolve_model(self, model: str) -> str:- """Resolve model name by applying provider/gateway prefixes."""- if self._gateway:- # Gateway mode: apply gateway prefix, skip provider-specific prefixes- prefix = self._gateway.litellm_prefix- if self._gateway.strip_model_prefix:- model = model.split("/")[-1]- if prefix and not model.startswith(f"{prefix}/"):- model = f"{prefix}/{model}"- return model-- # Standard mode: auto-prefix for known providers- spec = find_by_model(model)- if spec and spec.litellm_prefix:- model = self._canonicalize_explicit_prefix(model, spec.name, spec.litellm_prefix)- if not any(model.startswith(s) for s in spec.skip_prefixes):- model = f"{spec.litellm_prefix}/{model}"-- return model-- @staticmethod- def _canonicalize_explicit_prefix(model: str, spec_name: str, canonical_prefix: str) -> str:- """Normalize explicit provider prefixes like `github-copilot/...`."""- if "/" not in model:- return model- prefix, remainder = model.split("/", 1)- if prefix.lower().replace("-", "_") != spec_name:- return model- return f"{canonical_prefix}/{remainder}"-- def _supports_cache_control(self, model: str) -> bool:- """Return True when the provider supports cache_control on content blocks."""- if self._gateway is not None:- return self._gateway.supports_prompt_caching- spec = find_by_model(model)- return spec is not None and spec.supports_prompt_caching-- def _apply_cache_control(- self,- messages: list[dict[str, Any]],- tools: list[dict[str, Any]] | None,- ) -> tuple[list[dict[str, Any]], list[dict[str, Any]] | None]:- """Return copies of messages and tools with cache_control injected."""- new_messages = []- for msg in messages:- if msg.get("role") == "system":- content = msg["content"]- if isinstance(content, str):- new_content = [{"type": "text", "text": content, "cache_control": {"type": "ephemeral"}}]- else:- new_content = list(content)- new_content[-1] = {**new_content[-1], "cache_control": {"type": "ephemeral"}}- new_messages.append({**msg, "content": new_content})- else:- new_messages.append(msg)-- new_tools = tools- if tools:- new_tools = list(tools)- new_tools[-1] = {**new_tools[-1], "cache_control": {"type": "ephemeral"}}-- return new_messages, new_tools-- def _apply_model_overrides(self, model: str, kwargs: dict[str, Any]) -> None:- """Apply model-specific parameter overrides from the registry."""- model_lower = model.lower()- spec = find_by_model(model)- if spec:- for pattern, overrides in spec.model_overrides:- if pattern in model_lower:- kwargs.update(overrides)- return-- @staticmethod- def _extra_msg_keys(original_model: str, resolved_model: str) -> frozenset[str]:- """Return provider-specific extra keys to preserve in request messages."""- spec = find_by_model(original_model) or find_by_model(resolved_model)- if (spec and spec.name == "anthropic") or "claude" in original_model.lower() or resolved_model.startswith("anthropic/"):- return _ANTHROPIC_EXTRA_KEYS- return frozenset()-- @staticmethod- def _normalize_tool_call_id(tool_call_id: Any) -> Any:- """Normalize tool_call_id to a provider-safe 9-char alphanumeric form."""- if not isinstance(tool_call_id, str):- return tool_call_id- if len(tool_call_id) == 9 and tool_call_id.isalnum():- return tool_call_id- return hashlib.sha1(tool_call_id.encode()).hexdigest()[:9]-- @staticmethod- def _sanitize_messages(messages: list[dict[str, Any]], extra_keys: frozenset[str] = frozenset()) -> list[dict[str, Any]]:- """Strip non-standard keys and ensure assistant messages have a content key."""- allowed = _ALLOWED_MSG_KEYS | extra_keys- sanitized = LLMProvider._sanitize_request_messages(messages, allowed)- id_map: dict[str, str] = {}-- def map_id(value: Any) -> Any:- if not isinstance(value, str):- return value- return id_map.setdefault(value, LiteLLMProvider._normalize_tool_call_id(value))-- for clean in sanitized:- # Keep assistant tool_calls[].id and tool tool_call_id in sync after- # shortening, otherwise strict providers reject the broken linkage.- if isinstance(clean.get("tool_calls"), list):- normalized_tool_calls = []- for tc in clean["tool_calls"]:- if not isinstance(tc, dict):- normalized_tool_calls.append(tc)- continue- tc_clean = dict(tc)- tc_clean["id"] = map_id(tc_clean.get("id"))- normalized_tool_calls.append(tc_clean)- clean["tool_calls"] = normalized_tool_calls-- if "tool_call_id" in clean and clean["tool_call_id"]:- clean["tool_call_id"] = map_id(clean["tool_call_id"])- return sanitized-- async def chat(- self,- messages: list[dict[str, Any]],- tools: list[dict[str, Any]] | None = None,- model: str | None = None,- max_tokens: int = 4096,- temperature: float = 0.7,- reasoning_effort: str | None = None,- tool_choice: str | dict[str, Any] | None = None,- ) -> LLMResponse:- """- Send a chat completion request via LiteLLM.-- Args:- messages: List of message dicts with 'role' and 'content'.- tools: Optional list of tool definitions in OpenAI format.- model: Model identifier (e.g., 'anthropic/claude-sonnet-4-5').- max_tokens: Maximum tokens in response.- temperature: Sampling temperature.-- Returns:- LLMResponse with content and/or tool calls.- """- original_model = model or self.default_model- model = self._resolve_model(original_model)- extra_msg_keys = self._extra_msg_keys(original_model, model)-- if self._supports_cache_control(original_model):- messages, tools = self._apply_cache_control(messages, tools)-- # Clamp max_tokens to at least 1 — negative or zero values cause- # LiteLLM to reject the request with "max_tokens must be at least 1".- max_tokens = max(1, max_tokens)-- kwargs: dict[str, Any] = {- "model": model,- "messages": self._sanitize_messages(self._sanitize_empty_content(messages), extra_keys=extra_msg_keys),- "max_tokens": max_tokens,- "temperature": temperature,- }-- # Apply model-specific overrides (e.g. kimi-k2.5 temperature)- self._apply_model_overrides(model, kwargs)-- if self._langsmith_enabled:- kwargs.setdefault("callbacks", []).append("langsmith")-- # Pass api_key directly — more reliable than env vars alone- if self.api_key:- kwargs["api_key"] = self.api_key-- # Pass api_base for custom endpoints- if self.api_base:- kwargs["api_base"] = self.api_base-- # Pass extra headers (e.g. APP-Code for AiHubMix)- if self.extra_headers:- kwargs["extra_headers"] = self.extra_headers-- if reasoning_effort:- kwargs["reasoning_effort"] = reasoning_effort- kwargs["drop_params"] = True-- if tools:- kwargs["tools"] = tools- kwargs["tool_choice"] = tool_choice or "auto"-- try:- response = await acompletion(**kwargs)- return self._parse_response(response)- except Exception as e:- # Return error as content for graceful handling- return LLMResponse(- content=f"Error calling LLM: {str(e)}",- finish_reason="error",- )-- def _parse_response(self, response: Any) -> LLMResponse:- """Parse LiteLLM response into our standard format."""- choice = response.choices[0]- message = choice.message- content = message.content- finish_reason = choice.finish_reason-- # Some providers (e.g. GitHub Copilot) split content and tool_calls- # across multiple choices. Merge them so tool_calls are not lost.- raw_tool_calls = []- for ch in response.choices:- msg = ch.message- if hasattr(msg, "tool_calls") and msg.tool_calls:- raw_tool_calls.extend(msg.tool_calls)- if ch.finish_reason in ("tool_calls", "stop"):- finish_reason = ch.finish_reason- if not content and msg.content:- content = msg.content-- if len(response.choices) > 1:- logger.debug("LiteLLM response has {} choices, merged {} tool_calls",- len(response.choices), len(raw_tool_calls))-- tool_calls = []- for tc in raw_tool_calls:- # Parse arguments from JSON string if needed- args = tc.function.arguments- if isinstance(args, str):- args = json_repair.loads(args)-- provider_specific_fields = getattr(tc, "provider_specific_fields", None) or None- function_provider_specific_fields = (- getattr(tc.function, "provider_specific_fields", None) or None- )-- tool_calls.append(ToolCallRequest(- id=_short_tool_id(),- name=tc.function.name,- arguments=args,- provider_specific_fields=provider_specific_fields,- function_provider_specific_fields=function_provider_specific_fields,- ))-- usage = {}- if hasattr(response, "usage") and response.usage:- usage = {- "prompt_tokens": response.usage.prompt_tokens,- "completion_tokens": response.usage.completion_tokens,- "total_tokens": response.usage.total_tokens,- }-- reasoning_content = getattr(message, "reasoning_content", None) or None- thinking_blocks = getattr(message, "thinking_blocks", None) or None-- return LLMResponse(- content=content,- tool_calls=tool_calls,- finish_reason=finish_reason or "stop",- usage=usage,- reasoning_content=reasoning_content,- thinking_blocks=thinking_blocks,- )-- def get_default_model(self) -> str:- """Get the default model."""- return self.default_modeldiff --git a/deeptutor/tutorbot/providers/openai_compat_provider.py b/deeptutor/tutorbot/providers/openai_compat_provider.pynew file mode 100644index 000000000..4706fc578--- /dev/null+++ b/deeptutor/tutorbot/providers/openai_compat_provider.py@@ -0,0 +1,551 @@+"""OpenAI-compatible provider for all non-Anthropic LLM APIs.++Uses the official ``openai.AsyncOpenAI`` SDK to talk to any OpenAI-compatible+endpoint (OpenAI, DeepSeek, Gemini, Moonshot, MiniMax, gateways, local, etc.).+"""++from __future__ import annotations++import asyncio+import hashlib+import secrets+import string+import uuid+from collections.abc import Awaitable, Callable+from typing import TYPE_CHECKING, Any++import json_repair+from openai import AsyncOpenAI++from deeptutor.tutorbot.providers.base import LLMProvider, LLMResponse, ToolCallRequest++if TYPE_CHECKING:+ from deeptutor.tutorbot.providers.registry import ProviderSpec++_ALLOWED_MSG_KEYS = frozenset({+ "role", "content", "tool_calls", "tool_call_id", "name",+ "reasoning_content", "extra_content",+})+_ALNUM = string.ascii_letters + string.digits++_DEFAULT_OPENROUTER_HEADERS = {+ "HTTP-Referer": "https://github.com/HKUDS/DeepTutor",+ "X-OpenRouter-Title": "DeepTutor",+}+++def _short_tool_id() -> str:+ """9-char alphanumeric ID compatible with all providers (incl. Mistral)."""+ return "".join(secrets.choice(_ALNUM) for _ in range(9))+++def _get(obj: Any, key: str) -> Any:+ if isinstance(obj, dict):+ return obj.get(key)+ return getattr(obj, key, None)+++def _coerce_dict(value: Any) -> dict[str, Any] | None:+ if value is None:+ return None+ if isinstance(value, dict):+ return value if value else None+ model_dump = getattr(value, "model_dump", None)+ if callable(model_dump):+ dumped = model_dump()+ if isinstance(dumped, dict) and dumped:+ return dumped+ return None+++def _uses_openrouter(spec: "ProviderSpec | None", api_base: str | None) -> bool:+ if spec and spec.name == "openrouter":+ return True+ return bool(api_base and "openrouter" in api_base.lower())+++class OpenAICompatProvider(LLMProvider):+ """Unified provider for all OpenAI-compatible APIs.++ Receives a resolved ``ProviderSpec`` from the caller — no internal+ registry lookups needed.+ """++ def __init__(+ self,+ api_key: str | None = None,+ api_base: str | None = None,+ default_model: str = "gpt-4o",+ extra_headers: dict[str, str] | None = None,+ spec: ProviderSpec | None = None,+ provider_name: str | None = None,+ ):+ super().__init__(api_key, api_base)+ self.default_model = default_model+ self.extra_headers = extra_headers or {}+ self._spec = spec+ self._provider_name = provider_name++ if api_key and spec and spec.env_key:+ self._setup_env(api_key, api_base)++ effective_base = api_base or (spec.default_api_base if spec else None) or None+ default_headers: dict[str, str] = {"x-session-affinity": uuid.uuid4().hex}+ if _uses_openrouter(spec, effective_base):+ default_headers.update(_DEFAULT_OPENROUTER_HEADERS)+ if extra_headers:+ default_headers.update(extra_headers)++ self._client = AsyncOpenAI(+ api_key=api_key or "no-key",+ base_url=effective_base,+ default_headers=default_headers,+ max_retries=0,+ )++ def _setup_env(self, api_key: str, api_base: str | None) -> None:+ import os++ spec = self._spec+ if not spec or not spec.env_key:+ return+ if spec.is_gateway:+ os.environ[spec.env_key] = api_key+ else:+ os.environ.setdefault(spec.env_key, api_key)+ effective_base = api_base or spec.default_api_base+ for env_name, env_val in spec.env_extras:+ resolved = env_val.replace("{api_key}", api_key).replace("{api_base}", effective_base or "")+ os.environ.setdefault(env_name, resolved)++ # ------------------------------------------------------------------+ # Prompt caching+ # ------------------------------------------------------------------++ @classmethod+ def _apply_cache_control(+ cls,+ messages: list[dict[str, Any]],+ tools: list[dict[str, Any]] | None,+ ) -> tuple[list[dict[str, Any]], list[dict[str, Any]] | None]:+ cache_marker = {"type": "ephemeral"}+ new_messages = list(messages)++ def _mark(msg: dict[str, Any]) -> dict[str, Any]:+ content = msg.get("content")+ if isinstance(content, str):+ return {**msg, "content": [+ {"type": "text", "text": content, "cache_control": cache_marker},+ ]}+ if isinstance(content, list) and content:+ nc = list(content)+ nc[-1] = {**nc[-1], "cache_control": cache_marker}+ return {**msg, "content": nc}+ return msg++ if new_messages and new_messages[0].get("role") == "system":+ new_messages[0] = _mark(new_messages[0])+ if len(new_messages) >= 3:+ new_messages[-2] = _mark(new_messages[-2])++ new_tools = tools+ if tools:+ new_tools = list(tools)+ for idx in cls._tool_cache_marker_indices(new_tools):+ new_tools[idx] = {**new_tools[idx], "cache_control": cache_marker}+ return new_messages, new_tools++ # ------------------------------------------------------------------+ # Message sanitization+ # ------------------------------------------------------------------++ @staticmethod+ def _normalize_tool_call_id(tool_call_id: Any) -> Any:+ if not isinstance(tool_call_id, str):+ return tool_call_id+ if len(tool_call_id) == 9 and tool_call_id.isalnum():+ return tool_call_id+ return hashlib.sha1(tool_call_id.encode()).hexdigest()[:9]++ def _sanitize_messages(self, messages: list[dict[str, Any]]) -> list[dict[str, Any]]:+ sanitized = LLMProvider._sanitize_request_messages(messages, _ALLOWED_MSG_KEYS)+ id_map: dict[str, str] = {}++ def map_id(value: Any) -> Any:+ if not isinstance(value, str):+ return value+ return id_map.setdefault(value, self._normalize_tool_call_id(value))++ for clean in sanitized:+ if isinstance(clean.get("tool_calls"), list):+ normalized = []+ for tc in clean["tool_calls"]:+ if not isinstance(tc, dict):+ normalized.append(tc)+ continue+ tc_clean = dict(tc)+ tc_clean["id"] = map_id(tc_clean.get("id"))+ normalized.append(tc_clean)+ clean["tool_calls"] = normalized+ if "tool_call_id" in clean and clean["tool_call_id"]:+ clean["tool_call_id"] = map_id(clean["tool_call_id"])+ return sanitized++ # ------------------------------------------------------------------+ # Build kwargs+ # ------------------------------------------------------------------++ @staticmethod+ def _supports_temperature(+ model_name: str,+ reasoning_effort: str | None = None,+ ) -> bool:+ if reasoning_effort and reasoning_effort.lower() != "none":+ return False+ name = model_name.lower()+ return not any(token in name for token in ("gpt-5", "o1", "o3", "o4"))++ def _build_kwargs(+ self,+ messages: list[dict[str, Any]],+ tools: list[dict[str, Any]] | None,+ model: str | None,+ max_tokens: int,+ temperature: float,+ reasoning_effort: str | None,+ tool_choice: str | dict[str, Any] | None,+ ) -> dict[str, Any]:+ model_name = model or self.default_model+ spec = self._spec++ if spec and spec.supports_prompt_caching:+ if any(model_name.lower().startswith(k) for k in ("anthropic/", "claude")):+ messages, tools = self._apply_cache_control(messages, tools)++ if spec and spec.strip_model_prefix:+ model_name = model_name.split("/")[-1]++ kwargs: dict[str, Any] = {+ "model": model_name,+ "messages": self._sanitize_messages(self._sanitize_empty_content(messages)),+ }++ if self._supports_temperature(model_name, reasoning_effort):+ kwargs["temperature"] = temperature++ if spec and getattr(spec, "supports_max_completion_tokens", False):+ kwargs["max_completion_tokens"] = max(1, max_tokens)+ else:+ kwargs["max_tokens"] = max(1, max_tokens)++ if spec:+ model_lower = model_name.lower()+ for pattern, overrides in spec.model_overrides:+ if pattern in model_lower:+ kwargs.update(overrides)+ break++ if reasoning_effort:+ kwargs["reasoning_effort"] = reasoning_effort++ if spec and reasoning_effort is not None:+ thinking_enabled = reasoning_effort.lower() != "minimal"+ extra: dict[str, Any] | None = None+ if spec.name == "dashscope":+ extra = {"enable_thinking": thinking_enabled}+ elif spec.name in (+ "volcengine", "volcengine_coding_plan",+ "byteplus", "byteplus_coding_plan",+ ):+ extra = {+ "thinking": {"type": "enabled" if thinking_enabled else "disabled"}+ }+ if extra:+ kwargs.setdefault("extra_body", {}).update(extra)++ if tools:+ kwargs["tools"] = tools+ kwargs["tool_choice"] = tool_choice or "auto"++ return kwargs++ # ------------------------------------------------------------------+ # Response parsing+ # ------------------------------------------------------------------++ @staticmethod+ def _maybe_mapping(value: Any) -> dict[str, Any] | None:+ if isinstance(value, dict):+ return value+ model_dump = getattr(value, "model_dump", None)+ if callable(model_dump):+ dumped = model_dump()+ if isinstance(dumped, dict):+ return dumped+ return None++ @classmethod+ def _extract_text_content(cls, value: Any) -> str | None:+ if value is None:+ return None+ if isinstance(value, str):+ return value+ if isinstance(value, list):+ parts: list[str] = []+ for item in value:+ item_map = cls._maybe_mapping(item)+ if item_map:+ text = item_map.get("text")+ if isinstance(text, str):+ parts.append(text)+ continue+ text = getattr(item, "text", None)+ if isinstance(text, str):+ parts.append(text)+ continue+ if isinstance(item, str):+ parts.append(item)+ return "".join(parts) or None+ return str(value)++ @classmethod+ def _extract_usage(cls, response: Any) -> dict[str, int]:+ usage_obj = None+ response_map = cls._maybe_mapping(response)+ if response_map is not None:+ usage_obj = response_map.get("usage")+ elif hasattr(response, "usage") and response.usage:+ usage_obj = response.usage++ usage_map = cls._maybe_mapping(usage_obj)+ if usage_map is not None:+ return {+ "prompt_tokens": int(usage_map.get("prompt_tokens") or 0),+ "completion_tokens": int(usage_map.get("completion_tokens") or 0),+ "total_tokens": int(usage_map.get("total_tokens") or 0),+ }+ if usage_obj:+ return {+ "prompt_tokens": getattr(usage_obj, "prompt_tokens", 0) or 0,+ "completion_tokens": getattr(usage_obj, "completion_tokens", 0) or 0,+ "total_tokens": getattr(usage_obj, "total_tokens", 0) or 0,+ }+ return {}++ def _parse(self, response: Any) -> LLMResponse:+ if isinstance(response, str):+ return LLMResponse(content=response, finish_reason="stop")++ if not response.choices:+ return LLMResponse(content="Error: API returned empty choices.", finish_reason="error")++ choice = response.choices[0]+ msg = choice.message+ content = msg.content+ finish_reason = choice.finish_reason++ raw_tool_calls: list[Any] = []+ for ch in response.choices:+ m = ch.message+ if hasattr(m, "tool_calls") and m.tool_calls:+ raw_tool_calls.extend(m.tool_calls)+ if ch.finish_reason in ("tool_calls", "stop"):+ finish_reason = ch.finish_reason+ if not content and m.content:+ content = m.content+ if not content and getattr(m, "reasoning", None):+ content = m.reasoning++ tool_calls = []+ for tc in raw_tool_calls:+ args = tc.function.arguments+ if isinstance(args, str):+ args = json_repair.loads(args)+ tool_calls.append(ToolCallRequest(+ id=_short_tool_id(),+ name=tc.function.name,+ arguments=args if isinstance(args, dict) else {},+ provider_specific_fields=getattr(tc, "provider_specific_fields", None) or None,+ function_provider_specific_fields=(+ getattr(tc.function, "provider_specific_fields", None) or None+ ),+ ))++ reasoning_content = getattr(msg, "reasoning_content", None) or None+ if not reasoning_content and getattr(msg, "reasoning", None):+ reasoning_content = msg.reasoning++ usage = self._extract_usage(response)++ return LLMResponse(+ content=content,+ tool_calls=tool_calls,+ finish_reason=finish_reason or "stop",+ usage=usage,+ reasoning_content=reasoning_content,+ )++ @classmethod+ def _parse_chunks(cls, chunks: list[Any]) -> LLMResponse:+ content_parts: list[str] = []+ reasoning_parts: list[str] = []+ tc_bufs: dict[int, dict[str, Any]] = {}+ finish_reason = "stop"+ usage: dict[str, int] = {}++ def _accum_tc(tc: Any, idx_hint: int) -> None:+ tc_index: int = _get(tc, "index") if _get(tc, "index") is not None else idx_hint+ buf = tc_bufs.setdefault(tc_index, {+ "id": "", "name": "", "arguments": "",+ })+ tc_id = _get(tc, "id")+ if tc_id:+ buf["id"] = str(tc_id)+ fn = _get(tc, "function")+ if fn is not None:+ fn_name = _get(fn, "name")+ if fn_name:+ buf["name"] = str(fn_name)+ fn_args = _get(fn, "arguments")+ if fn_args:+ buf["arguments"] += str(fn_args)++ for chunk in chunks:+ if isinstance(chunk, str):+ content_parts.append(chunk)+ continue++ if not chunk.choices:+ usage = cls._extract_usage(chunk) or usage+ continue+ choice = chunk.choices[0]+ if choice.finish_reason:+ finish_reason = choice.finish_reason+ delta = choice.delta+ if delta and delta.content:+ content_parts.append(delta.content)+ if delta:+ reasoning = getattr(delta, "reasoning_content", None)+ if not reasoning:+ reasoning = getattr(delta, "reasoning", None)+ if reasoning:+ reasoning_parts.append(reasoning)+ for tc in (delta.tool_calls or []) if delta else []:+ _accum_tc(tc, getattr(tc, "index", 0))++ return LLMResponse(+ content="".join(content_parts) or None,+ tool_calls=[+ ToolCallRequest(+ id=b["id"] or _short_tool_id(),+ name=b["name"],+ arguments=json_repair.loads(b["arguments"]) if b["arguments"] else {},+ )+ for b in tc_bufs.values()+ ],+ finish_reason=finish_reason,+ usage=usage,+ reasoning_content="".join(reasoning_parts) or None,+ )++ @staticmethod+ def _handle_error(e: Exception) -> LLMResponse:+ body = (+ getattr(e, "doc", None)+ or getattr(e, "body", None)+ or getattr(getattr(e, "response", None), "text", None)+ )+ body_text = body if isinstance(body, str) else str(body) if body is not None else ""+ msg = f"Error: {body_text.strip()[:500]}" if body_text.strip() else f"Error calling LLM: {e}"+ return LLMResponse(content=msg, finish_reason="error")++ # ------------------------------------------------------------------+ # Public API+ # ------------------------------------------------------------------++ @staticmethod+ def _is_tool_format_error(e: Exception) -> bool:+ """Detect errors caused by strict tool-argument JSON validation.++ Some endpoints (e.g. DashScope Coding Plan) reject non-streaming+ tool calls with 400 when the model produces malformed arguments.+ Streaming avoids this because the SDK accumulates tokens into a+ well-formed response.+ """+ text = str(getattr(e, "body", None) or getattr(e, "message", None) or e).lower()+ return any(kw in text for kw in (+ "function.arguments",+ "must be in json format",+ "invalid.*parameter.*function",+ ))++ async def chat(+ self,+ messages: list[dict[str, Any]],+ tools: list[dict[str, Any]] | None = None,+ model: str | None = None,+ max_tokens: int = 4096,+ temperature: float = 0.7,+ reasoning_effort: str | None = None,+ tool_choice: str | dict[str, Any] | None = None,+ ) -> LLMResponse:+ kwargs = self._build_kwargs(+ messages, tools, model, max_tokens, temperature,+ reasoning_effort, tool_choice,+ )+ try:+ return self._parse(await self._client.chat.completions.create(**kwargs))+ except Exception as e:+ if tools and self._is_tool_format_error(e):+ return await self.chat_stream(+ messages, tools, model, max_tokens, temperature,+ reasoning_effort, tool_choice,+ )+ return self._handle_error(e)++ async def chat_stream(+ self,+ messages: list[dict[str, Any]],+ tools: list[dict[str, Any]] | None = None,+ model: str | None = None,+ max_tokens: int = 4096,+ temperature: float = 0.7,+ reasoning_effort: str | None = None,+ tool_choice: str | dict[str, Any] | None = None,+ on_content_delta: Callable[[str], Awaitable[None]] | None = None,+ ) -> LLMResponse:+ kwargs = self._build_kwargs(+ messages, tools, model, max_tokens, temperature,+ reasoning_effort, tool_choice,+ )+ kwargs["stream"] = True+ kwargs["stream_options"] = {"include_usage": True}+ idle_timeout_s = 90+ try:+ stream = await self._client.chat.completions.create(**kwargs)+ chunks: list[Any] = []+ stream_iter = stream.__aiter__()+ while True:+ try:+ chunk = await asyncio.wait_for(+ stream_iter.__anext__(),+ timeout=idle_timeout_s,+ )+ except StopAsyncIteration:+ break+ chunks.append(chunk)+ if on_content_delta and chunk.choices:+ text = getattr(chunk.choices[0].delta, "content", None)+ if text:+ await on_content_delta(text)+ return self._parse_chunks(chunks)+ except asyncio.TimeoutError:+ return LLMResponse(+ content=f"Error calling LLM: stream stalled for more than {idle_timeout_s} seconds",+ finish_reason="error",+ )+ except Exception as e:+ return self._handle_error(e)++ def get_default_model(self) -> str:+ return self.default_modeldiff --git a/deeptutor/tutorbot/providers/registry.py b/deeptutor/tutorbot/providers/registry.pyindex bee6c5eb1..b4b5732ec 100644--- a/deeptutor/tutorbot/providers/registry.py+++ b/deeptutor/tutorbot/providers/registry.py@@ -3,8 +3,7 @@ Provider Registry — single source of truth for LLM provider metadata.Adding a new provider:1. Add a ProviderSpec to PROVIDERS below.- 2. Add a field to ProvidersConfig in config/schema.py.- Done. Env vars, prefixing, config matching, status display all derive from here.+ Done. Env vars, config matching, status display all derive from here.Order matters — it controls match priority and fallback. Gateways first.Every entry writes out all fields so you can copy-paste as a template.@@ -26,40 +25,53 @@ class ProviderSpec:"""# identity- name: str # config field name, e.g. "dashscope"- keywords: tuple[str, ...] # model-name keywords for matching (lowercase)- env_key: str # LiteLLM env var, e.g. "DASHSCOPE_API_KEY"- display_name: str = "" # shown in status output+ name: str+ keywords: tuple[str, ...]+ env_key: str+ display_name: str = ""- # model prefixing- litellm_prefix: str = "" # "dashscope" → model becomes "dashscope/{model}"- skip_prefixes: tuple[str, ...] = () # don't prefix if model already starts with these+ # Which provider implementation to use:+ # "openai_compat" | "anthropic" | "azure_openai" | "openai_codex" | "github_copilot"+ backend: str = "openai_compat"# extra env vars, e.g. (("ZHIPUAI_API_KEY", "{api_key}"),)env_extras: tuple[tuple[str, str], ...] = ()# gateway / local detection- is_gateway: bool = False # routes any model (OpenRouter, AiHubMix)- is_local: bool = False # local deployment (vLLM, Ollama)- detect_by_key_prefix: str = "" # match api_key prefix, e.g. "sk-or-"- detect_by_base_keyword: str = "" # match substring in api_base URL- default_api_base: str = "" # fallback base URL+ is_gateway: bool = False+ is_local: bool = False+ detect_by_key_prefix: str = ""+ detect_by_base_keyword: str = ""+ default_api_base: str = ""# gateway behavior- strip_model_prefix: bool = False # strip "provider/" before re-prefixing+ strip_model_prefix: bool = False+ supports_max_completion_tokens: bool = False# per-model param overrides, e.g. (("kimi-k2.5", {"temperature": 1.0}),)model_overrides: tuple[tuple[str, dict[str, Any]], ...] = ()# OAuth-based providers (e.g., OpenAI Codex) don't use API keys- is_oauth: bool = False # if True, uses OAuth flow instead of API key+ is_oauth: bool = False- # Direct providers bypass LiteLLM entirely (e.g., CustomProvider)+ # Direct providers skip API-key validationis_direct: bool = False# Provider supports cache_control on content blocks (e.g. Anthropic prompt caching)supports_prompt_caching: bool = False+ @property+ def mode(self) -> str:+ if self.is_oauth:+ return "oauth"+ if self.is_direct:+ return "direct"+ if self.is_gateway:+ return "gateway"+ if self.is_local:+ return "local"+ return "standard"+@propertydef label(self) -> str:return self.display_name or self.name.title()@@ -70,388 +82,256 @@ class ProviderSpec:# ---------------------------------------------------------------------------PROVIDERS: tuple[ProviderSpec, ...] = (- # === Custom (direct OpenAI-compatible endpoint, bypasses LiteLLM) ======+ # === Direct (user supplies everything) ==================================ProviderSpec(name="custom",keywords=(),env_key="",display_name="Custom",- litellm_prefix="",+ backend="openai_compat",is_direct=True,),-- # === Azure OpenAI (direct API calls with API version 2024-10-21) =====ProviderSpec(name="azure_openai",keywords=("azure", "azure-openai"),env_key="",display_name="Azure OpenAI",- litellm_prefix="",+ backend="azure_openai",is_direct=True,),- # === Gateways (detected by api_key / api_base, not model name) =========- # Gateways can route any model, so they win in fallback.- # OpenRouter: global gateway, keys start with "sk-or-"+ # === Gateways (detected by api_key / api_base, route any model) ========ProviderSpec(name="openrouter",keywords=("openrouter",),env_key="OPENROUTER_API_KEY",display_name="OpenRouter",- litellm_prefix="openrouter", # claude-3 → openrouter/claude-3- skip_prefixes=(),- env_extras=(),+ backend="openai_compat",is_gateway=True,- is_local=False,detect_by_key_prefix="sk-or-",detect_by_base_keyword="openrouter",default_api_base="https://openrouter.ai/api/v1",- strip_model_prefix=False,- model_overrides=(),supports_prompt_caching=True,),- # AiHubMix: global gateway, OpenAI-compatible interface.- # strip_model_prefix=True: it doesn't understand "anthropic/claude-3",- # so we strip to bare "claude-3" then re-prefix as "openai/claude-3".ProviderSpec(name="aihubmix",keywords=("aihubmix",),- env_key="OPENAI_API_KEY", # OpenAI-compatible+ env_key="OPENAI_API_KEY",display_name="AiHubMix",- litellm_prefix="openai", # → openai/{model}- skip_prefixes=(),- env_extras=(),+ backend="openai_compat",is_gateway=True,- is_local=False,- detect_by_key_prefix="",detect_by_base_keyword="aihubmix",default_api_base="https://aihubmix.com/v1",- strip_model_prefix=True, # anthropic/claude-3 → claude-3 → openai/claude-3- model_overrides=(),+ strip_model_prefix=True,),- # SiliconFlow (硅基流动): OpenAI-compatible gateway, model names keep org prefixProviderSpec(name="siliconflow",keywords=("siliconflow",),env_key="OPENAI_API_KEY",display_name="SiliconFlow",- litellm_prefix="openai",- skip_prefixes=(),- env_extras=(),+ backend="openai_compat",is_gateway=True,- is_local=False,- detect_by_key_prefix="",detect_by_base_keyword="siliconflow",default_api_base="https://api.siliconflow.cn/v1",- strip_model_prefix=False,- model_overrides=(),),-- # VolcEngine (火山引擎): OpenAI-compatible gateway, pay-per-use modelsProviderSpec(name="volcengine",keywords=("volcengine", "volces", "ark"),env_key="OPENAI_API_KEY",display_name="VolcEngine",- litellm_prefix="volcengine",- skip_prefixes=(),- env_extras=(),+ backend="openai_compat",is_gateway=True,- is_local=False,- detect_by_key_prefix="",detect_by_base_keyword="volces",default_api_base="https://ark.cn-beijing.volces.com/api/v3",- strip_model_prefix=False,- model_overrides=(),),-- # VolcEngine Coding Plan (火山引擎 Coding Plan): same key as volcengineProviderSpec(name="volcengine_coding_plan",keywords=("volcengine-plan",),env_key="OPENAI_API_KEY",display_name="VolcEngine Coding Plan",- litellm_prefix="volcengine",- skip_prefixes=(),- env_extras=(),+ backend="openai_compat",is_gateway=True,- is_local=False,- detect_by_key_prefix="",- detect_by_base_keyword="",default_api_base="https://ark.cn-beijing.volces.com/api/coding/v3",strip_model_prefix=True,- model_overrides=(),),-- # BytePlus: VolcEngine international, pay-per-use modelsProviderSpec(name="byteplus",keywords=("byteplus",),env_key="OPENAI_API_KEY",display_name="BytePlus",- litellm_prefix="volcengine",- skip_prefixes=(),- env_extras=(),+ backend="openai_compat",is_gateway=True,- is_local=False,- detect_by_key_prefix="",detect_by_base_keyword="bytepluses",default_api_base="https://ark.ap-southeast.bytepluses.com/api/v3",strip_model_prefix=True,- model_overrides=(),),-- # BytePlus Coding Plan: same key as byteplusProviderSpec(name="byteplus_coding_plan",keywords=("byteplus-plan",),env_key="OPENAI_API_KEY",display_name="BytePlus Coding Plan",- litellm_prefix="volcengine",- skip_prefixes=(),- env_extras=(),+ backend="openai_compat",is_gateway=True,- is_local=False,- detect_by_key_prefix="",- detect_by_base_keyword="",default_api_base="https://ark.ap-southeast.bytepluses.com/api/coding/v3",strip_model_prefix=True,- model_overrides=(),),--# === Standard providers (matched by model-name keywords) ===============- # Anthropic: LiteLLM recognizes "claude-*" natively, no prefix needed.ProviderSpec(name="anthropic",keywords=("anthropic", "claude"),env_key="ANTHROPIC_API_KEY",display_name="Anthropic",- litellm_prefix="",- skip_prefixes=(),- env_extras=(),- is_gateway=False,- is_local=False,- detect_by_key_prefix="",- detect_by_base_keyword="",- default_api_base="",- strip_model_prefix=False,- model_overrides=(),+ backend="anthropic",+ default_api_base="https://api.anthropic.com/v1",supports_prompt_caching=True,),- # OpenAI: LiteLLM recognizes "gpt-*" natively, no prefix needed.ProviderSpec(name="openai",keywords=("openai", "gpt"),env_key="OPENAI_API_KEY",display_name="OpenAI",- litellm_prefix="",- skip_prefixes=(),- env_extras=(),- is_gateway=False,- is_local=False,- detect_by_key_prefix="",- detect_by_base_keyword="",- default_api_base="",- strip_model_prefix=False,- model_overrides=(),+ backend="openai_compat",+ supports_max_completion_tokens=True,),- # OpenAI Codex: uses OAuth, not API key.ProviderSpec(name="openai_codex",keywords=("openai-codex",),- env_key="", # OAuth-based, no API key+ env_key="",display_name="OpenAI Codex",- litellm_prefix="", # Not routed through LiteLLM- skip_prefixes=(),- env_extras=(),- is_gateway=False,- is_local=False,- detect_by_key_prefix="",+ backend="openai_codex",detect_by_base_keyword="codex",default_api_base="https://chatgpt.com/backend-api",- strip_model_prefix=False,- model_overrides=(),- is_oauth=True, # OAuth-based authentication+ is_oauth=True,),- # Github Copilot: uses OAuth, not API key.ProviderSpec(name="github_copilot",keywords=("github_copilot", "copilot"),- env_key="", # OAuth-based, no API key+ env_key="",display_name="Github Copilot",- litellm_prefix="github_copilot", # github_copilot/model → github_copilot/model- skip_prefixes=("github_copilot/",),- env_extras=(),- is_gateway=False,- is_local=False,- detect_by_key_prefix="",- detect_by_base_keyword="",- default_api_base="",- strip_model_prefix=False,- model_overrides=(),- is_oauth=True, # OAuth-based authentication+ backend="github_copilot",+ default_api_base="https://api.githubcopilot.com",+ strip_model_prefix=True,+ is_oauth=True,),- # DeepSeek: needs "deepseek/" prefix for LiteLLM routing.ProviderSpec(name="deepseek",keywords=("deepseek",),env_key="DEEPSEEK_API_KEY",display_name="DeepSeek",- litellm_prefix="deepseek", # deepseek-chat → deepseek/deepseek-chat- skip_prefixes=("deepseek/",), # avoid double-prefix- env_extras=(),- is_gateway=False,- is_local=False,- detect_by_key_prefix="",- detect_by_base_keyword="",- default_api_base="",- strip_model_prefix=False,- model_overrides=(),+ backend="openai_compat",+ default_api_base="https://api.deepseek.com",),- # Gemini: needs "gemini/" prefix for LiteLLM.ProviderSpec(name="gemini",keywords=("gemini",),env_key="GEMINI_API_KEY",display_name="Gemini",- litellm_prefix="gemini", # gemini-pro → gemini/gemini-pro- skip_prefixes=("gemini/",), # avoid double-prefix- env_extras=(),- is_gateway=False,- is_local=False,- detect_by_key_prefix="",- detect_by_base_keyword="",- default_api_base="",- strip_model_prefix=False,- model_overrides=(),+ backend="openai_compat",+ default_api_base="https://generativelanguage.googleapis.com/v1beta/openai/",),- # Zhipu: LiteLLM uses "zai/" prefix.- # Also mirrors key to ZHIPUAI_API_KEY (some LiteLLM paths check that).- # skip_prefixes: don't add "zai/" when already routed via gateway.ProviderSpec(name="zhipu",keywords=("zhipu", "glm", "zai"),env_key="ZAI_API_KEY",display_name="Zhipu AI",- litellm_prefix="zai", # glm-4 → zai/glm-4- skip_prefixes=("zhipu/", "zai/", "openrouter/", "hosted_vllm/"),+ backend="openai_compat",env_extras=(("ZHIPUAI_API_KEY", "{api_key}"),),- is_gateway=False,- is_local=False,- detect_by_key_prefix="",- detect_by_base_keyword="",- default_api_base="",- strip_model_prefix=False,- model_overrides=(),+ default_api_base="https://open.bigmodel.cn/api/paas/v4",),- # DashScope: Qwen models, needs "dashscope/" prefix.ProviderSpec(name="dashscope",keywords=("qwen", "dashscope"),env_key="DASHSCOPE_API_KEY",display_name="DashScope",- litellm_prefix="dashscope", # qwen-max → dashscope/qwen-max- skip_prefixes=("dashscope/", "openrouter/"),- env_extras=(),- is_gateway=False,- is_local=False,- detect_by_key_prefix="",- detect_by_base_keyword="",- default_api_base="",- strip_model_prefix=False,- model_overrides=(),+ backend="openai_compat",+ default_api_base="https://dashscope.aliyuncs.com/compatible-mode/v1",),- # Moonshot: Kimi models, needs "moonshot/" prefix.- # LiteLLM requires MOONSHOT_API_BASE env var to find the endpoint.- # Kimi K2.5 API enforces temperature >= 1.0.ProviderSpec(name="moonshot",keywords=("moonshot", "kimi"),env_key="MOONSHOT_API_KEY",display_name="Moonshot",- litellm_prefix="moonshot", # kimi-k2.5 → moonshot/kimi-k2.5- skip_prefixes=("moonshot/", "openrouter/"),- env_extras=(("MOONSHOT_API_BASE", "{api_base}"),),- is_gateway=False,- is_local=False,- detect_by_key_prefix="",- detect_by_base_keyword="",- default_api_base="https://api.moonshot.ai/v1", # intl; use api.moonshot.cn for China- strip_model_prefix=False,+ backend="openai_compat",+ default_api_base="https://api.moonshot.ai/v1",model_overrides=(("kimi-k2.5", {"temperature": 1.0}),),),- # MiniMax: needs "minimax/" prefix for LiteLLM routing.- # Uses OpenAI-compatible API at api.minimax.io/v1.ProviderSpec(name="minimax",keywords=("minimax",),env_key="MINIMAX_API_KEY",display_name="MiniMax",- litellm_prefix="minimax", # MiniMax-M2.1 → minimax/MiniMax-M2.1- skip_prefixes=("minimax/", "openrouter/"),- env_extras=(),- is_gateway=False,- is_local=False,- detect_by_key_prefix="",- detect_by_base_keyword="",+ backend="openai_compat",default_api_base="https://api.minimax.io/v1",- strip_model_prefix=False,- model_overrides=(),),- # === Local deployment (matched by config key, NOT by api_base) =========- # vLLM / any OpenAI-compatible local server.- # Detected when config key is "vllm" (provider_name="vllm").+ ProviderSpec(+ name="mistral",+ keywords=("mistral",),+ env_key="MISTRAL_API_KEY",+ display_name="Mistral",+ backend="openai_compat",+ default_api_base="https://api.mistral.ai/v1",+ ),+ ProviderSpec(+ name="stepfun",+ keywords=("stepfun", "step"),+ env_key="STEPFUN_API_KEY",+ display_name="Step Fun",+ backend="openai_compat",+ default_api_base="https://api.stepfun.com/v1",+ ),+ ProviderSpec(+ name="xiaomi_mimo",+ keywords=("xiaomi_mimo", "mimo"),+ env_key="XIAOMIMIMO_API_KEY",+ display_name="Xiaomi MIMO",+ backend="openai_compat",+ default_api_base="https://api.xiaomimimo.com/v1",+ ),+ # === Local deployment ==================================================ProviderSpec(name="vllm",keywords=("vllm",),env_key="HOSTED_VLLM_API_KEY",display_name="vLLM/Local",- litellm_prefix="hosted_vllm", # Llama-3-8B → hosted_vllm/Llama-3-8B- skip_prefixes=(),- env_extras=(),- is_gateway=False,+ backend="openai_compat",is_local=True,- detect_by_key_prefix="",- detect_by_base_keyword="",- default_api_base="", # user must provide in config- strip_model_prefix=False,- model_overrides=(),+ default_api_base="http://localhost:8000/v1",),- # === Ollama (local, OpenAI-compatible) ===================================ProviderSpec(name="ollama",keywords=("ollama", "nemotron"),env_key="OLLAMA_API_KEY",display_name="Ollama",- litellm_prefix="ollama_chat", # model → ollama_chat/model- skip_prefixes=("ollama/", "ollama_chat/"),- env_extras=(),- is_gateway=False,+ backend="openai_compat",is_local=True,- detect_by_key_prefix="",detect_by_base_keyword="11434",- default_api_base="http://localhost:11434",- strip_model_prefix=False,- model_overrides=(),+ default_api_base="http://localhost:11434/v1",+ ),+ ProviderSpec(+ name="ovms",+ keywords=("openvino", "ovms"),+ env_key="",+ display_name="OpenVINO Model Server",+ backend="openai_compat",+ is_direct=True,+ is_local=True,+ default_api_base="http://localhost:8000/v3",),- # === Auxiliary (not a primary LLM provider) ============================- # Groq: mainly used for Whisper voice transcription, also usable for LLM.- # Needs "groq/" prefix for LiteLLM routing. Placed last — it rarely wins fallback.+ # === Auxiliary ==========================================================ProviderSpec(name="groq",keywords=("groq",),env_key="GROQ_API_KEY",display_name="Groq",- litellm_prefix="groq", # llama3-8b-8192 → groq/llama3-8b-8192- skip_prefixes=("groq/",), # avoid double-prefix- env_extras=(),- is_gateway=False,- is_local=False,- detect_by_key_prefix="",- detect_by_base_keyword="",- default_api_base="",- strip_model_prefix=False,- model_overrides=(),+ backend="openai_compat",+ default_api_base="https://api.groq.com/openai/v1",+ ),+ ProviderSpec(+ name="qianfan",+ keywords=("qianfan", "ernie"),+ env_key="QIANFAN_API_KEY",+ display_name="Qianfan",+ backend="openai_compat",+ default_api_base="https://qianfan.baidubce.com/v2",),)@@ -462,19 +342,16 @@ PROVIDERS: tuple[ProviderSpec, ...] = (def find_by_model(model: str) -> ProviderSpec | None:- """Match a standard provider by model-name keyword (case-insensitive).- Skips gateways/local — those are matched by api_key/api_base instead."""+ """Match a standard provider by model-name keyword (case-insensitive)."""model_lower = model.lower()model_normalized = model_lower.replace("-", "_")model_prefix = model_lower.split("/", 1)[0] if "/" in model_lower else ""normalized_prefix = model_prefix.replace("-", "_")std_specs = [s for s in PROVIDERS if not s.is_gateway and not s.is_local]- # Prefer explicit provider prefix — prevents `github-copilot/...codex` matching openai_codex.for spec in std_specs:if model_prefix and normalized_prefix == spec.name:return spec-for spec in std_specs:if any(kw in model_lower or kw.replace("-", "_") in model_normalized for kw in spec.keywords@@ -488,29 +365,17 @@ def find_gateway(api_key: str | None = None,api_base: str | None = None,) -> ProviderSpec | None:- """Detect gateway/local provider.-- Priority:- 1. provider_name — if it maps to a gateway/local spec, use it directly.- 2. api_key prefix — e.g. "sk-or-" → OpenRouter.- 3. api_base keyword — e.g. "aihubmix" in URL → AiHubMix.-- A standard provider with a custom api_base (e.g. DeepSeek behind a proxy)- will NOT be mistaken for vLLM — the old fallback is gone.- """- # 1. Direct match by config key+ """Detect gateway/local provider."""if provider_name:spec = find_by_name(provider_name)if spec and (spec.is_gateway or spec.is_local):return spec- # 2. Auto-detect by api_key prefix / api_base keywordfor spec in PROVIDERS:if spec.detect_by_key_prefix and api_key and api_key.startswith(spec.detect_by_key_prefix):return specif spec.detect_by_base_keyword and api_base and spec.detect_by_base_keyword in api_base:return spec-return Nonediff --git a/deeptutor_cli/provider_cmd.py b/deeptutor_cli/provider_cmd.pyindex ab8a9218f..3d2ac3ecb 100644--- a/deeptutor_cli/provider_cmd.py+++ b/deeptutor_cli/provider_cmd.py@@ -56,13 +56,18 @@ def _login_openai_codex() -> None:async def _login_github_copilot() -> None:try:- from litellm import acompletion+ from openai import AsyncOpenAIexcept ImportError:- typer.echo("litellm is not installed. Install CLI deps: pip install -r requirements/cli.txt")+ typer.echo("openai is not installed. Install CLI deps: pip install -r requirements/cli.txt")raise typer.Exit(code=1)try:- await acompletion(- model="github_copilot/gpt-4o",+ client = AsyncOpenAI(+ api_key="copilot",+ base_url="https://api.githubcopilot.com",+ max_retries=0,+ )+ await client.chat.completions.create(+ model="gpt-4o",messages=[{"role": "user", "content": "ping"}],max_tokens=1,)diff --git a/pyproject.toml b/pyproject.tomlindex e093984a4..1b608155e 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -21,7 +21,6 @@ dependencies = ["aiohttp>=3.9.4","httpx>=0.27.0","requests>=2.32.2",- "litellm>=1.79.0","ddgs>=9.9.1","nest_asyncio>=1.5.8","tenacity>=8.0.0",diff --git a/requirements/cli.txt b/requirements/cli.txtindex f1627d704..fe745fd05 100644--- a/requirements/cli.txt+++ b/requirements/cli.txt@@ -11,7 +11,6 @@ jinja2>=3.1.0# --- LLM ---openai>=1.30.0-litellm>=1.79.0tiktoken>=0.5.0# --- LLM provider SDKs ---diff --git a/web/app/(utility)/knowledge/page.tsx b/web/app/(utility)/knowledge/page.tsxindex 7d0cfab17..b38e79833 100644--- a/web/app/(utility)/knowledge/page.tsx+++ b/web/app/(utility)/knowledge/page.tsx@@ -3,6 +3,7 @@import dynamic from "next/dynamic";import { useEffect, useMemo, useRef, useState } from "react";import { useRouter } from "next/navigation";+import { useTranslation } from "react-i18next";import {ArrowRight,BookOpen,@@ -128,6 +129,7 @@ const kbIsUploadable = (kb: KnowledgeBase): boolean =>export default function KnowledgePage() {const router = useRouter();+ const { t } = useTranslation();const [tab, setTab] = useState<"knowledge" | "notebooks">("knowledge");const [knowledgeBases, setKnowledgeBases] = useState<KnowledgeBase[]>([]);const [notebooks, setNotebooks] = useState<NotebookInfo[]>([]);@@ -474,7 +476,7 @@ export default function KnowledgePage() {};const deleteKnowledgeBase = async (kbName: string) => {- if (!window.confirm(`Delete knowledge base "${kbName}"?`)) return;+ if (!window.confirm(t('Delete knowledge base "{{name}}"?', { name: kbName }))) return;await fetch(apiUrl(`/api/v1/knowledge/${kbName}`), { method: "DELETE" });invalidateKnowledgeCaches();await loadAll();@@ -523,20 +525,20 @@ export default function KnowledgePage() {};const formatTimestamp = (value?: number) => {- if (!value) return "Unknown time";+ if (!value) return t("Unknown time");return new Date(value * 1000).toLocaleString();};const getRecordBadge = (type: string) => {switch (type) {case "chat":- return { label: "Chat", color: "bg-sky-100 text-sky-700 dark:bg-sky-900/40 dark:text-sky-300", icon: MessageSquare };+ return { label: t("Chat"), color: "bg-sky-100 text-sky-700 dark:bg-sky-900/40 dark:text-sky-300", icon: MessageSquare };case "guided_learning":- return { label: "Guided Learning", color: "bg-violet-100 text-violet-700 dark:bg-violet-900/40 dark:text-violet-300", icon: GraduationCap };+ return { label: t("Guided Learning"), color: "bg-violet-100 text-violet-700 dark:bg-violet-900/40 dark:text-violet-300", icon: GraduationCap };case "co_writer":- return { label: "Co-Writer", color: "bg-amber-100 text-amber-700 dark:bg-amber-900/40 dark:text-amber-300", icon: PenLine };+ return { label: t("Co-Writer"), color: "bg-amber-100 text-amber-700 dark:bg-amber-900/40 dark:text-amber-300", icon: PenLine };case "research":- return { label: "Research", color: "bg-emerald-100 text-emerald-700 dark:bg-emerald-900/40 dark:text-emerald-300", icon: Search };+ return { label: t("Research"), color: "bg-emerald-100 text-emerald-700 dark:bg-emerald-900/40 dark:text-emerald-300", icon: Search };default:return { label: type, color: "bg-slate-100 text-slate-600 dark:bg-slate-800 dark:text-slate-400", icon: NotebookPen };}@@ -565,11 +567,11 @@ export default function KnowledgePage() {const uploadBlockedReason = useMemo(() => {if (!uploadTargetKb) return null;if (kbNeedsReindex(uploadTargetKb)) {- return "This knowledge base is in legacy index format and needs reindex before upload.";+ return t("This knowledge base is in legacy index format and needs reindex before upload.");}const status = resolveKbStatus(uploadTargetKb);if (status !== "ready") {- return `This knowledge base is currently ${status.replaceAll("_", " ")} and cannot accept uploads yet.`;+ return t("This knowledge base is currently {{status}} and cannot accept uploads yet.", { status: status.replaceAll("_", " ") });}return null;}, [uploadTargetKb]);@@ -584,17 +586,17 @@ export default function KnowledgePage() {<div className="mb-6 flex items-start justify-between gap-4"><div><h1 className="text-2xl font-bold tracking-tight text-[var(--foreground)]">- Knowledge+ {t("Knowledge")}</h1><p className="mt-1 text-[13px] text-[var(--muted-foreground)]">- Manage your knowledge bases and notebooks in one place.+ {t("Manage your knowledge bases and notebooks in one place.")}</p></div><div className="inline-flex shrink-0 rounded-lg border border-[var(--border)] bg-[var(--muted)] p-0.5">{[- { key: "knowledge", label: "Knowledge Bases", icon: Database },- { key: "notebooks", label: "Notebooks", icon: NotebookPen },+ { key: "knowledge", label: t("Knowledge Bases"), icon: Database },+ { key: "notebooks", label: t("Notebooks"), icon: NotebookPen },].map((item) => (<buttonkey={item.key}@@ -630,7 +632,7 @@ export default function KnowledgePage() {<div className="mb-4 flex items-center gap-2"><Plus size={15} className="text-[var(--muted-foreground)]" /><h2 className="text-[14px] font-semibold text-[var(--foreground)]">- Create knowledge base+ {t("Create knowledge base")}</h2></div>@@ -638,7 +640,7 @@ export default function KnowledgePage() {<inputvalue={newKbName}onChange={(event) => setNewKbName(event.target.value)}- placeholder="Knowledge base name"+ placeholder={t("Knowledge base name")}className="w-full rounded-lg border border-[var(--border)] bg-[var(--background)] px-3 py-2 text-[13px] text-[var(--foreground)] outline-none transition-colors focus:border-[var(--foreground)]/25"/>@@ -662,8 +664,10 @@ export default function KnowledgePage() {><FileUp size={15} />{newKbFiles.length- ? `${newKbFiles.length} file${newKbFiles.length > 1 ? "s" : ""} selected`- : "Choose files..."}+ ? newKbFiles.length > 1+ ? t("{n} files selected", { n: newKbFiles.length })+ : t("{n} file selected", { n: newKbFiles.length })+ : t("Choose files...")}</button><inputref={createFileRef}@@ -694,7 +698,7 @@ export default function KnowledgePage() {className="inline-flex items-center gap-1.5 rounded-lg bg-[var(--primary)] px-3.5 py-1.5 text-[13px] font-medium text-[var(--primary-foreground)] transition-opacity disabled:cursor-not-allowed disabled:opacity-40">{creating ? <Loader2 className="h-3.5 w-3.5 animate-spin" /> : <Plus size={14} />}- Create+ {t("Create")}</button>{(createProcess.taskId || createProcess.logs.length > 0 || createProcess.executing) && (@@ -708,7 +712,7 @@ export default function KnowledgePage() {<ProcessLogslogs={createProcess.logs}executing={createProcess.executing}- title="Create Process"+ title={t("Create Process")}/></div>)}@@ -726,7 +730,7 @@ export default function KnowledgePage() {<div className="mb-4 flex items-center gap-2"><Upload size={15} className="text-[var(--muted-foreground)]" /><h2 className="text-[14px] font-semibold text-[var(--foreground)]">- Upload documents+ {t("Upload documents")}</h2></div>@@ -736,14 +740,14 @@ export default function KnowledgePage() {onChange={(event) => setUploadTarget(event.target.value)}className="w-full rounded-lg border border-[var(--border)] bg-[var(--background)] px-3 py-2 text-[13px] text-[var(--foreground)] outline-none">- <option value="">Select a knowledge base</option>+ <option value="">{t("Select a knowledge base")}</option>{combinedKbs.map((kb) => {const status = resolveKbStatus(kb);const needsReindex = kbNeedsReindex(kb);const uploadable = kbIsUploadable(kb);let suffix = "";if (needsReindex) {- suffix = " (needs reindex)";+ suffix = ` (${t("needs reindex")})`;} else if (status !== "ready") {suffix = ` (${status.replaceAll("_", " ")})`;}@@ -758,7 +762,7 @@ export default function KnowledgePage() {{!hasUploadableKb && (<div className="rounded-lg border border-amber-200 bg-amber-50 px-3 py-2 text-[12px] text-amber-700 dark:border-amber-900 dark:bg-amber-950/30 dark:text-amber-300">- No ready knowledge base is available for upload. Create a new KB or reindex legacy KBs first.+ {t("No ready knowledge base is available for upload. Create a new KB or reindex legacy KBs first.")}</div>)}@@ -775,8 +779,10 @@ export default function KnowledgePage() {><FileUp size={15} />{uploadFiles.length- ? `${uploadFiles.length} file${uploadFiles.length > 1 ? "s" : ""} selected`- : "Choose files..."}+ ? uploadFiles.length > 1+ ? t("{n} files selected", { n: uploadFiles.length })+ : t("{n} file selected", { n: uploadFiles.length })+ : t("Choose files...")}</button><inputref={uploadFileRef}@@ -811,7 +817,7 @@ export default function KnowledgePage() {) : (<Upload size={14} />)}- Upload+ {t("Upload")}</button>{(uploadProcess.taskId || uploadProcess.logs.length > 0 || uploadProcess.executing) && (@@ -825,7 +831,7 @@ export default function KnowledgePage() {<ProcessLogslogs={uploadProcess.logs}executing={uploadProcess.executing}- title="Upload Process"+ title={t("Upload Process")}/></div>)}@@ -844,7 +850,7 @@ export default function KnowledgePage() {<div className="mb-4 flex items-center gap-2"><BookOpen size={15} className="text-[var(--muted-foreground)]" /><h2 className="text-[14px] font-semibold text-[var(--foreground)]">- Knowledge bases+ {t("Knowledge bases")}</h2></div>@@ -855,7 +861,7 @@ export default function KnowledgePage() {const needsReindex = kbNeedsReindex(kb);const displayStatus =needsReindex- ? "needs reindex"+ ? t("needs reindex"): status !== "ready"? status.replaceAll("_", " "): null;@@ -879,13 +885,13 @@ export default function KnowledgePage() {</h3>{kb.is_default && (<span className="inline-flex items-center gap-1 rounded-md bg-[var(--muted)] px-1.5 py-0.5 text-[10px] font-medium text-[var(--muted-foreground)]">- <Star size={10} /> Default+ <Star size={10} /> {t("Default")}</span>)}</div><div className="mt-1.5 flex flex-wrap gap-x-3 gap-y-1 text-[11px] text-[var(--muted-foreground)]">- <span>Provider: {kb.statistics?.rag_provider || "llamaindex"}</span>- <span>Documents: {kb.statistics?.raw_documents ?? 0}</span>+ <span>{t("Provider")}: {kb.statistics?.rag_provider || "llamaindex"}</span>+ <span>{t("Documents")}: {kb.statistics?.raw_documents ?? 0}</span>{displayStatus && (<spanclassName={@@ -894,7 +900,7 @@ export default function KnowledgePage() {: "capitalize"}>- Status: {displayStatus}+ {t("Status")}: {displayStatus}</span>)}</div>@@ -906,7 +912,7 @@ export default function KnowledgePage() {onClick={() => setDefaultKnowledgeBase(kb.name)}className="rounded-md border border-[var(--border)] px-2.5 py-1 text-[12px] text-[var(--foreground)] transition-colors hover:bg-[var(--muted)]">- Set default+ {t("Set default")}</button>)}<button@@ -939,7 +945,7 @@ export default function KnowledgePage() {{!combinedKbs.length && (<div className="rounded-lg border border-dashed border-[var(--border)] px-6 py-10 text-center text-[13px] text-[var(--muted-foreground)]">- No knowledge bases yet. Create one to get started.+ {t("No knowledge bases yet. Create one to get started.")}</div>)}</div>@@ -952,7 +958,7 @@ export default function KnowledgePage() {<div className="mb-4 flex items-center gap-2"><Plus size={15} className="text-[var(--muted-foreground)]" /><h2 className="text-[14px] font-semibold text-[var(--foreground)]">- Create notebook+ {t("Create notebook")}</h2></div>@@ -960,13 +966,13 @@ export default function KnowledgePage() {<inputvalue={newNotebookName}onChange={(event) => setNewNotebookName(event.target.value)}- placeholder="Notebook name"+ placeholder={t("Notebook name")}className="rounded-lg border border-[var(--border)] bg-[var(--background)] px-3 py-2 text-[13px] text-[var(--foreground)] outline-none transition-colors focus:border-[var(--foreground)]/25"/><inputvalue={newNotebookDescription}onChange={(event) => setNewNotebookDescription(event.target.value)}- placeholder="Description"+ placeholder={t("Description")}className="rounded-lg border border-[var(--border)] bg-[var(--background)] px-3 py-2 text-[13px] text-[var(--foreground)] outline-none transition-colors focus:border-[var(--foreground)]/25"/><button@@ -974,7 +980,7 @@ export default function KnowledgePage() {disabled={!newNotebookName.trim()}className="rounded-lg bg-[var(--primary)] px-3.5 py-2 text-[13px] font-medium text-[var(--primary-foreground)] disabled:cursor-not-allowed disabled:opacity-40">- Create+ {t("Create")}</button></div></section>@@ -984,7 +990,7 @@ export default function KnowledgePage() {<div className="mb-4 flex items-center gap-2"><NotebookPen size={15} className="text-[var(--muted-foreground)]" /><h2 className="text-[14px] font-semibold text-[var(--foreground)]">- Notebooks+ {t("Notebooks")}</h2></div>@@ -1017,7 +1023,7 @@ export default function KnowledgePage() {</p>)}<div className="mt-3 flex items-center justify-between text-[11px] text-[var(--muted-foreground)]">- <span>{notebook.record_count ?? 0} records</span>+ <span>{notebook.record_count ?? 0} {t("records")}</span><span>{notebook.updated_at ? formatTimestamp(notebook.updated_at) : ""}</span></div></div>@@ -1028,7 +1034,7 @@ export default function KnowledgePage() {{!notebooks.length && (<div className="rounded-xl border border-dashed border-[var(--border)] px-6 py-10 text-center text-[13px] text-[var(--muted-foreground)]">- No notebooks yet. Create one to organize outputs.+ {t("No notebooks yet. Create one to organize outputs.")}</div>)}</div>@@ -1056,7 +1062,7 @@ export default function KnowledgePage() {)}</div><span className="text-[11px] tabular-nums text-[var(--muted-foreground)]">- {selectedNotebook.records?.length || 0} records+ {selectedNotebook.records?.length || 0} {t("records")}</span></div>@@ -1070,7 +1076,7 @@ export default function KnowledgePage() {(record.type === "chat" || record.type === "guided_learning") &&Boolean(record.metadata?.session_id);const sessionLabel =- record.type === "chat" ? "Open chat session" : "Open guided learning session";+ record.type === "chat" ? t("Open chat session") : t("Open guided learning session");return (<div key={record.id} className="group">@@ -1104,7 +1110,7 @@ export default function KnowledgePage() {)}{record.type !== "chat" && record.user_query && (<div className="mb-3 flex items-baseline gap-2 text-[12px]">- <span className="shrink-0 font-medium text-[var(--muted-foreground)]">Query:</span>+ <span className="shrink-0 font-medium text-[var(--muted-foreground)]">{t("Query:")}</span><span className="text-[var(--foreground)]/70">{record.user_query}</span></div>)}@@ -1135,7 +1141,7 @@ export default function KnowledgePage() {{!selectedNotebook.records?.length && (<div className="px-6 py-12 text-center text-[13px] text-[var(--muted-foreground)]">- This notebook is empty for now.+ {t("This notebook is empty for now.")}</div>)}</div>@@ -1143,7 +1149,7 @@ export default function KnowledgePage() {</div>) : (<div className="flex min-h-[320px] items-center justify-center rounded-2xl border border-dashed border-[var(--border)] text-[13px] text-[var(--muted-foreground)]">- Select a notebook to inspect its saved records.+ {t("Select a notebook to inspect its saved records.")}</div>)}</div>diff --git a/web/app/(utility)/memory/page.tsx b/web/app/(utility)/memory/page.tsxindex f68a16955..bfca3b5bb 100644--- a/web/app/(utility)/memory/page.tsx+++ b/web/app/(utility)/memory/page.tsx@@ -3,6 +3,7 @@import dynamic from "next/dynamic";import { useCallback, useEffect, useRef, useState } from "react";import { Brain, Eraser, Loader2, RefreshCw, Save, BookOpen, User } from "lucide-react";+import { useTranslation } from "react-i18next";import { useAppShell } from "@/context/AppShellContext";import { apiUrl } from "@/lib/api";@@ -51,6 +52,7 @@ function formatUpdatedAt(value: string | null): string {}export default function MemoryPage() {+ const { t } = useTranslation();const { activeSessionId, language } = useAppShell();const [data, setData] = useState<MemoryData>(EMPTY);const [loading, setLoading] = useState(true);@@ -158,7 +160,7 @@ export default function MemoryPage() {<div className="mb-6 flex items-start justify-between"><div><h1 className="text-[24px] font-semibold tracking-tight text-[var(--foreground)]">- Memory+ {t("Memory")}</h1>{toast ? (<p className="mt-1 text-[13px] text-[var(--primary)] animate-fade-in">{toast}</p>@@ -260,7 +262,7 @@ export default function MemoryPage() {placeholder={tab.placeholder}/><p className="mt-2 text-[11px] text-[var(--muted-foreground)]/40">- Cmd+S to save · Markdown supported+ {t("Cmd+S to save · Markdown supported")}</p></div>) : editorValue.trim() ? (@@ -274,7 +276,7 @@ export default function MemoryPage() {</div><p className="text-[14px] font-medium text-[var(--foreground)]">No {tab.label.toLowerCase()} yet</p><p className="mt-1.5 max-w-xs text-[13px] text-[var(--muted-foreground)]">- Refresh from a session or write directly in the editor.+ {t("Refresh from a session or write directly in the editor.")}</p></div>)}diff --git a/web/app/(utility)/settings/page.tsx b/web/app/(utility)/settings/page.tsxindex 537ab40c8..d83dca4dc 100644--- a/web/app/(utility)/settings/page.tsx+++ b/web/app/(utility)/settings/page.tsx@@ -21,6 +21,8 @@ import {X,} from "lucide-react";+import { useTranslation } from "react-i18next";+import { writeStoredLanguage } from "@/context/AppShellContext";import { apiUrl } from "@/lib/api";import { setTheme as applyThemePreference } from "@/lib/theme";@@ -68,9 +70,12 @@ type UiSettings = {language: "en" | "zh";};+type ProviderOption = { value: string; label: string; base_url?: string };+type SettingsPayload = {ui: UiSettings;catalog: Catalog;+ providers?: Record<ServiceName, ProviderOption[]>;};type SystemStatus = {@@ -142,6 +147,9 @@ function defaultCatalog(): Catalog {const inputClass ="w-full rounded-lg border border-[var(--border)] bg-transparent px-3 py-2 text-[14px] text-[var(--foreground)] outline-none transition-colors focus:border-[var(--ring)] placeholder:text-[var(--muted-foreground)]/40";+const selectClass =+ "w-full appearance-none rounded-lg border border-[var(--border)] bg-transparent px-3 py-2 text-[14px] text-[var(--foreground)] outline-none transition-colors focus:border-[var(--ring)] cursor-pointer";+function stringifyExtraHeaders(value: CatalogProfile["extra_headers"]): string {if (!value) return "";if (typeof value === "string") return value;@@ -186,6 +194,7 @@ function SpotlightOverlay({onNext: () => void;onSkip: () => void;}) {+ const { t } = useTranslation();const [rect, setRect] = useState<DOMRect | null>(null);const guideStep = TOUR_GUIDE_STEPS[stepIndex];@@ -229,23 +238,23 @@ function SpotlightOverlay({style={{ top: tooltipTop, left: tooltipLeft }}><div className="mb-1 text-[13px] font-semibold text-[var(--foreground)]">- {guideStep.title}+ {t(guideStep.title)}</div><p className="mb-4 text-[12px] leading-relaxed text-[var(--muted-foreground)]">- {guideStep.desc}+ {t(guideStep.desc)}</p><div className="flex items-center justify-between"><buttononClick={onSkip}className="text-[12px] text-[var(--muted-foreground)]/60 transition-colors hover:text-[var(--muted-foreground)]">- Skip tour+ {t("Skip tour")}</button><buttononClick={onNext}className="inline-flex items-center gap-1 rounded-lg bg-[var(--foreground)] px-3 py-1.5 text-[12px] font-medium text-[var(--background)] transition-opacity hover:opacity-80">- {stepIndex < TOUR_GUIDE_STEPS.length - 1 ? "Next" : "Got it"}+ {stepIndex < TOUR_GUIDE_STEPS.length - 1 ? t("Next") : t("Got it")}<ChevronRight className="h-3 w-3" /></button></div>@@ -269,6 +278,7 @@ function TestResultsModal({onConfirm: () => void;onCancel: () => void;}) {+ const { t } = useTranslation();const hasCriticalFailure = results.llm === "fail" || results.embedding === "fail";const allDone = !testing && results.llm !== "pending" && results.embedding !== "pending";@@ -280,10 +290,10 @@ function TestResultsModal({};const label = (r: TourTestResult) => {- if (r === "pass") return "Passed";- if (r === "fail") return "Failed";- if (r === "skip") return "Skipped";- return "Testing...";+ if (r === "pass") return t("Passed");+ if (r === "fail") return t("Failed");+ if (r === "skip") return t("Skipped");+ return t("Testing...");};return (@@ -291,7 +301,7 @@ function TestResultsModal({<div className="w-[400px] rounded-2xl border border-[var(--border)] bg-[var(--card)] p-6 shadow-2xl"><div className="mb-5 flex items-center justify-between"><h2 className="text-[16px] font-semibold text-[var(--foreground)]">- {testing ? "Running tests..." : "Test Results"}+ {testing ? t("Running tests...") : t("Test Results")}</h2>{!testing && (<button onClick={onCancel} className="text-[var(--muted-foreground)] hover:text-[var(--foreground)]">@@ -321,7 +331,7 @@ function TestResultsModal({onClick={onCancel}className="flex-1 rounded-lg border border-[var(--border)] px-4 py-2 text-[13px] font-medium text-[var(--muted-foreground)] transition-colors hover:border-[var(--foreground)]/20 hover:text-[var(--foreground)]">- Back to editing+ {t("Back to editing")}</button><buttononClick={onConfirm}@@ -331,7 +341,7 @@ function TestResultsModal({: "bg-[var(--foreground)] text-[var(--background)]"}`}>- {hasCriticalFailure ? "Launch anyway" : "Confirm & Launch"}+ {hasCriticalFailure ? t("Launch anyway") : t("Confirm & Launch")}</button></div>)}@@ -339,7 +349,7 @@ function TestResultsModal({{testing && (<div className="flex items-center justify-center gap-2 py-2 text-[13px] text-[var(--muted-foreground)]"><Loader2 className="h-3.5 w-3.5 animate-spin" />- Please wait...+ {t("Please wait...")}</div>)}</div>@@ -352,6 +362,7 @@ function TestResultsModal({// ═══════════════════════════════════════════════════════════════════════════function SettingsPageContent() {+ const { t } = useTranslation();const searchParams = useSearchParams();const isTourMode = searchParams.get("tour") === "true";@@ -367,6 +378,7 @@ function SettingsPageContent() {const [applying, setApplying] = useState(false);const [toast, setToast] = useState<string>("");const [diagnosticsOpen, setDiagnosticsOpen] = useState(false);+ const [providers, setProviders] = useState<Record<ServiceName, ProviderOption[]>>({ llm: [], embedding: [], search: [] });const eventSourceRef = useRef<EventSource | null>(null);// Tour-specific state@@ -387,6 +399,7 @@ function SettingsPageContent() {setDraft(cloneCatalog(settingsPayload.catalog));setTheme(settingsPayload.ui.theme);setLanguage(settingsPayload.ui.language);+ if (settingsPayload.providers) setProviders(settingsPayload.providers);const statusResponse = await fetch(apiUrl("/api/v1/system/status"));const statusPayload = (await statusResponse.json()) as SystemStatus;@@ -577,7 +590,7 @@ function SettingsPageContent() {const payload = await response.json();setCatalog(payload.catalog);setDraft(cloneCatalog(payload.catalog));- setToast("Draft saved");+ setToast(t("Draft saved"));} finally {setSaving(false);}@@ -594,7 +607,7 @@ function SettingsPageContent() {const payload = await response.json();setCatalog(payload.catalog);setDraft(cloneCatalog(payload.catalog));- setToast("Applied to .env");+ setToast(t("Applied to .env"));const statusResponse = await fetch(apiUrl("/api/v1/system/status"));setStatus((await statusResponse.json()) as SystemStatus);} finally {@@ -640,7 +653,7 @@ function SettingsPageContent() {eventSourceRef.current = null;setTestRunning(null);setLogs((current) => `${current}[failed] Diagnostics stream disconnected.\n`);- setToast("Diagnostics stream disconnected");+ setToast(t("Diagnostics stream disconnected"));};} catch (error) {const message = error instanceof Error ? error.message : "Could not start diagnostics.";@@ -736,10 +749,10 @@ function SettingsPageContent() {setTourCompleted(true);setTourRedirectAt(payload.redirect_at ?? Math.floor(Date.now() / 1000) + 5);} else {- setToast("Failed to complete tour");+ setToast(t("Failed to complete tour"));}} catch {- setToast("Failed to complete tour");+ setToast(t("Failed to complete tour"));}};@@ -752,7 +765,7 @@ function SettingsPageContent() {const reopenTour = async () => {const response = await fetch(apiUrl("/api/v1/settings/tour/reopen"), { method: "POST" });const payload = (await response.json()) as { command?: string; message?: string };- setToast(payload.command ? `Run ${payload.command} in your terminal.` : payload.message || "Run python scripts/start_tour.py in your terminal.");+ setToast(payload.command ? t("Run {{command}} in your terminal.", { command: payload.command }) : payload.message || t("Run python scripts/start_tour.py in your terminal."));};// ═══════════════════════════════════════════════════════════════════════@@ -769,10 +782,10 @@ function SettingsPageContent() {<div><div className="flex items-center gap-2 text-[14px] font-semibold text-[var(--foreground)]"><Rocket className="h-4 w-4 text-[var(--primary)]" />- Setup Tour+ {t("Setup Tour")}</div><p className="mt-1 text-[13px] text-[var(--muted-foreground)]">- Configure your endpoints below, run tests, then launch DeepTutor.+ {t("Configure your endpoints below, run tests, then launch DeepTutor.")}</p></div><button@@ -782,7 +795,7 @@ function SettingsPageContent() {className="ml-4 inline-flex shrink-0 items-center gap-1.5 rounded-lg bg-[var(--foreground)] px-4 py-2 text-[13px] font-medium text-[var(--background)] transition-opacity hover:opacity-80 disabled:opacity-40">{tourTestPhase === "testing" ? <Loader2 className="h-3.5 w-3.5 animate-spin" /> : <CheckCircle2 className="h-3.5 w-3.5" />}- Complete & Launch+ {t("Complete & Launch")}</button></div>)}@@ -792,12 +805,12 @@ function SettingsPageContent() {<div className="mb-6 rounded-xl border border-emerald-500/20 bg-emerald-500/5 px-5 py-4 text-center"><div className="flex items-center justify-center gap-2 text-[14px] font-semibold text-emerald-600 dark:text-emerald-400"><CheckCircle2 className="h-4 w-4" />- Configuration saved+ {t("Configuration saved")}</div><p className="mt-1 text-[13px] text-[var(--muted-foreground)]">{redirectCountdown > 0- ? `Redirecting to DeepTutor in ${redirectCountdown}s...`- : "Redirecting..."}+ ? t("Redirecting to DeepTutor in {{count}}s...", { count: redirectCountdown })+ : t("Redirecting...")}</p></div>)}@@ -806,7 +819,7 @@ function SettingsPageContent() {<div className="mb-6 flex items-start justify-between"><div><h1 className="text-[24px] font-semibold tracking-tight text-[var(--foreground)]">- Settings+ {t("Settings")}</h1>{toast ? (<p className="mt-1 text-[13px] text-[var(--primary)] animate-fade-in">@@ -814,7 +827,7 @@ function SettingsPageContent() {</p>) : (<p className="mt-1 text-[13px] text-[var(--muted-foreground)]">- {hasUnsavedChanges ? "Draft has unsaved changes" : "All changes saved"}+ {hasUnsavedChanges ? t("Draft has unsaved changes") : t("All changes saved")}</p>)}</div>@@ -825,12 +838,12 @@ function SettingsPageContent() {className="inline-flex items-center gap-1.5 rounded-lg border border-[var(--border)]/50 px-3 py-1.5 text-[12px] font-medium text-[var(--muted-foreground)] transition-colors hover:border-[var(--border)] hover:text-[var(--foreground)] disabled:opacity-40">{saving ? <Loader2 className="h-3 w-3 animate-spin" /> : <Save className="h-3 w-3" />}- Save Draft+ {t("Save Draft")}</button><buttononClick={applyCatalog}disabled={applying || isTourMode}- title={isTourMode ? "Complete the tour first" : undefined}+ title={isTourMode ? t("Complete the tour first") : undefined}className={`inline-flex items-center gap-1.5 rounded-lg px-3 py-1.5 text-[12px] font-medium transition-opacity disabled:opacity-40 ${isTourMode? "cursor-not-allowed border border-[var(--border)]/30 bg-[var(--muted)] text-[var(--muted-foreground)]"@@ -838,7 +851,7 @@ function SettingsPageContent() {}`}>{applying ? <Loader2 className="h-3 w-3 animate-spin" /> : <Wand2 className="h-3 w-3" />}- Apply+ {t("Apply")}</button></div></div>@@ -846,7 +859,7 @@ function SettingsPageContent() {{/* ── Preferences & Runtime ── */}<div className="mb-8 flex flex-wrap items-center gap-x-8 gap-y-3 border-b border-[var(--border)]/50 pb-6"><div className="flex items-center gap-2">- <span className="text-[12px] text-[var(--muted-foreground)]">Theme</span>+ <span className="text-[12px] text-[var(--muted-foreground)]">{t("Theme")}</span><div className="flex gap-0.5 rounded-lg bg-[var(--muted)] p-0.5">{(["light", "dark"] as const).map((v) => (<button@@ -858,14 +871,14 @@ function SettingsPageContent() {: "text-[var(--muted-foreground)] hover:text-[var(--foreground)]"}`}>- {v === "light" ? "Light" : "Dark"}+ {v === "light" ? t("Light") : t("Dark")}</button>))}</div></div><div className="flex items-center gap-2">- <span className="text-[12px] text-[var(--muted-foreground)]">Language</span>+ <span className="text-[12px] text-[var(--muted-foreground)]">{t("Language")}</span><div className="flex gap-0.5 rounded-lg bg-[var(--muted)] p-0.5">{(["en", "zh"] as const).map((v) => (<button@@ -886,20 +899,20 @@ function SettingsPageContent() {<div className="ml-auto flex items-center gap-4 text-[12px] text-[var(--muted-foreground)]"><span className="flex items-center gap-1.5"><span className={`inline-block h-1.5 w-1.5 rounded-full ${statusDotClass(status?.backend.status === "online", false)}`} />- Backend+ {t("Backend")}</span><span className="flex items-center gap-1.5"><span className={`inline-block h-1.5 w-1.5 rounded-full ${statusDotClass(Boolean(status?.llm.model), Boolean(status?.llm.error))}`} />- LLM+ {t("LLM")}{status?.llm.model && <span className="text-[var(--muted-foreground)]/50">· {status.llm.model}</span>}</span><span className="flex items-center gap-1.5"><span className={`inline-block h-1.5 w-1.5 rounded-full ${statusDotClass(Boolean(status?.embeddings.model), Boolean(status?.embeddings.error))}`} />- Emb+ {t("Emb")}</span><span className="flex items-center gap-1.5"><span className={`inline-block h-1.5 w-1.5 rounded-full ${statusDotClass(Boolean(status?.search.provider), false)}`} />- Search+ {t("Search")}</span></div></div>@@ -933,7 +946,7 @@ function SettingsPageContent() {className="inline-flex items-center gap-1 rounded-lg border border-[var(--border)]/50 px-2.5 py-1 text-[12px] text-[var(--muted-foreground)] transition-colors hover:border-[var(--border)] hover:text-[var(--foreground)]"><Plus className="h-3 w-3" />- Profile+ {t("Profile")}</button>{activeService !== "search" && (<button@@ -941,7 +954,7 @@ function SettingsPageContent() {className="inline-flex items-center gap-1 rounded-lg border border-[var(--border)]/50 px-2.5 py-1 text-[12px] text-[var(--muted-foreground)] transition-colors hover:border-[var(--border)] hover:text-[var(--foreground)]"><Plus className="h-3 w-3" />- Model+ {t("Model")}</button>)}</div>@@ -971,7 +984,7 @@ function SettingsPageContent() {><div className="text-[13px] font-medium">{profile.name}</div><div className="mt-0.5 truncate text-[11px] text-[var(--muted-foreground)]">- {profile.base_url || "No endpoint"}+ {profile.base_url || t("No endpoint")}</div></button>))}@@ -981,7 +994,7 @@ function SettingsPageContent() {className="flex w-full items-center gap-1.5 rounded-lg px-3 py-2 text-[11px] text-[var(--muted-foreground)]/40 transition-colors hover:text-red-500 disabled:opacity-30"><Trash2 className="h-3 w-3" />- Delete profile+ {t("Delete profile")}</button></div>@@ -989,11 +1002,11 @@ function SettingsPageContent() {<div className="space-y-5"><div className="rounded-xl border border-[var(--border)] p-5"><div className="mb-4 text-[13px] font-medium text-[var(--foreground)]">- Profile+ {t("Profile")}</div><div className="grid gap-4 sm:grid-cols-2"><div>- <div className="mb-1.5 text-[12px] text-[var(--muted-foreground)]">Name</div>+ <div className="mb-1.5 text-[12px] text-[var(--muted-foreground)]">{t("Name")}</div><inputclassName={inputClass}value={activeProfile.name}@@ -1002,23 +1015,33 @@ function SettingsPageContent() {</div><div><div className="mb-1.5 text-[12px] text-[var(--muted-foreground)]">- {activeService === "search" ? "Provider" : "Provider Hint / Binding"}+ {t("Provider")}+ </div>+ <div className="relative">+ <select+ className={selectClass}+ value={+ activeService === "search"+ ? activeProfile.provider || ""+ : activeProfile.binding || ""+ }+ onChange={(e) => {+ const val = e.target.value;+ const field = activeService === "search" ? "provider" : "binding";+ updateProfileField(field, val);+ const match = (providers[activeService] || []).find((p) => p.value === val);+ if (match?.base_url && !activeProfile.base_url) {+ updateProfileField("base_url", match.base_url);+ }+ }}+ >+ <option value="">{t("Select provider...")}</option>+ {(providers[activeService] || []).map((p) => (+ <option key={p.value} value={p.value}>{p.label}</option>+ ))}+ </select>+ <ChevronDown className="pointer-events-none absolute right-3 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-[var(--muted-foreground)]" /></div>- <input- className={inputClass}- value={- activeService === "search"- ? activeProfile.provider || ""- : activeProfile.binding || ""- }- onChange={(e) =>- updateProfileField(- activeService === "search" ? "provider" : "binding",- e.target.value,- )- }- placeholder={activeService === "search" ? "brave" : "openai"}- />{showSearchProviderWarning && (<pclassName={`mt-1.5 text-[11px] ${@@ -1031,16 +1054,16 @@ function SettingsPageContent() {>{isSupportedSearchProvider? isPerplexityMissingKey- ? "Perplexity requires API key. It will fail hard without credentials."- : "Supported provider."+ ? t("Perplexity requires API key. It will fail hard without credentials.")+ : t("Supported provider."): isDeprecatedSearchProvider- ? "Deprecated provider. Switch to brave/tavily/jina/searxng/duckduckgo/perplexity."- : "Unsupported provider. Use brave/tavily/jina/searxng/duckduckgo/perplexity."}+ ? t("Deprecated provider. Switch to brave/tavily/jina/searxng/duckduckgo/perplexity.")+ : t("Unsupported provider. Use brave/tavily/jina/searxng/duckduckgo/perplexity.")}</p>)}</div><div className="sm:col-span-2">- <div className="mb-1.5 text-[12px] text-[var(--muted-foreground)]">Base URL</div>+ <div className="mb-1.5 text-[12px] text-[var(--muted-foreground)]">{t("Base URL")}</div><inputclassName={inputClass}value={activeProfile.base_url}@@ -1049,7 +1072,7 @@ function SettingsPageContent() {/></div><div className="sm:col-span-2">- <div className="mb-1.5 text-[12px] text-[var(--muted-foreground)]">API Key</div>+ <div className="mb-1.5 text-[12px] text-[var(--muted-foreground)]">{t("API Key")}</div><inputclassName={inputClass}value={activeProfile.api_key}@@ -1058,17 +1081,17 @@ function SettingsPageContent() {/></div><div>- <div className="mb-1.5 text-[12px] text-[var(--muted-foreground)]">API Version</div>+ <div className="mb-1.5 text-[12px] text-[var(--muted-foreground)]">{t("API Version")}</div><inputclassName={inputClass}value={activeProfile.api_version}onChange={(e) => updateProfileField("api_version", e.target.value)}- placeholder="Optional"+ placeholder={t("Optional")}/></div>{activeService === "search" ? (<div>- <div className="mb-1.5 text-[12px] text-[var(--muted-foreground)]">Proxy</div>+ <div className="mb-1.5 text-[12px] text-[var(--muted-foreground)]">{t("Proxy")}</div><inputclassName={inputClass}value={activeProfile.proxy || ""}@@ -1079,7 +1102,7 @@ function SettingsPageContent() {) : (<div className="sm:col-span-2"><div className="mb-1.5 text-[12px] text-[var(--muted-foreground)]">- Extra Headers (JSON)+ {t("Extra Headers (JSON)")}</div><textareaclassName={`${inputClass} min-h-[84px] resize-y`}@@ -1095,14 +1118,14 @@ function SettingsPageContent() {{activeService !== "search" && (<div className="rounded-xl border border-[var(--border)] p-5"><div className="mb-4 flex items-center justify-between">- <div className="text-[13px] font-medium text-[var(--foreground)]">Models</div>+ <div className="text-[13px] font-medium text-[var(--foreground)]">{t("Models")}</div><buttononClick={removeActiveModel}disabled={!activeModel}className="inline-flex items-center gap-1 text-[11px] text-[var(--muted-foreground)]/40 transition-colors hover:text-red-500 disabled:opacity-30"><Trash2 className="h-3 w-3" />- Delete+ {t("Delete")}</button></div>{activeProfile.models.length > 0 && (@@ -1129,16 +1152,16 @@ function SettingsPageContent() {{activeModel && (<div className="grid gap-4 sm:grid-cols-2"><div>- <div className="mb-1.5 text-[12px] text-[var(--muted-foreground)]">Label</div>+ <div className="mb-1.5 text-[12px] text-[var(--muted-foreground)]">{t("Label")}</div><input className={inputClass} value={activeModel.name} onChange={(e) => updateModelField("name", e.target.value)} /></div><div>- <div className="mb-1.5 text-[12px] text-[var(--muted-foreground)]">Model ID</div>+ <div className="mb-1.5 text-[12px] text-[var(--muted-foreground)]">{t("Model ID")}</div><input className={inputClass} value={activeModel.model} onChange={(e) => updateModelField("model", e.target.value)} placeholder="gpt-4o" /></div>{activeService === "embedding" && (<div>- <div className="mb-1.5 text-[12px] text-[var(--muted-foreground)]">Dimension</div>+ <div className="mb-1.5 text-[12px] text-[var(--muted-foreground)]">{t("Dimension")}</div><input className={inputClass} value={activeModel.dimension || "3072"} onChange={(e) => updateModelField("dimension", e.target.value)} /></div>)}@@ -1150,7 +1173,7 @@ function SettingsPageContent() {</div>) : (<div className="rounded-xl border border-dashed border-[var(--border)] py-12 text-center text-[13px] text-[var(--muted-foreground)]">- No profiles configured. Add a profile to start.+ {t("No profiles configured. Add a profile to start.")}</div>)}</div>@@ -1165,7 +1188,7 @@ function SettingsPageContent() {aria-expanded={diagnosticsOpen}><Terminal className="h-3.5 w-3.5 text-[var(--muted-foreground)]" />- <span className="text-[13px] font-medium text-[var(--foreground)]">Diagnostics</span>+ <span className="text-[13px] font-medium text-[var(--foreground)]">{t("Diagnostics")}</span>{testRunning && <Loader2 className="h-3 w-3 animate-spin text-[var(--primary)]" />}</button><div className="ml-3 flex items-center gap-3">@@ -1176,13 +1199,13 @@ function SettingsPageContent() {className="inline-flex items-center gap-1.5 rounded-lg border border-[var(--border)]/50 px-2.5 py-1 text-[12px] text-[var(--muted-foreground)] transition-colors hover:border-[var(--border)] hover:text-[var(--foreground)] disabled:opacity-40">{serviceIcon(activeService)}- Run test+ {t("Run test")}</button><buttontype="button"onClick={() => setDiagnosticsOpen((v) => !v)}className="text-[var(--muted-foreground)] transition-colors hover:text-[var(--foreground)]"- aria-label={diagnosticsOpen ? "Collapse diagnostics" : "Expand diagnostics"}+ aria-label={diagnosticsOpen ? t("Collapse diagnostics") : t("Expand diagnostics")}aria-expanded={diagnosticsOpen}><ChevronDown className={`h-4 w-4 transition-transform ${diagnosticsOpen ? "rotate-180" : ""}`} />@@ -1192,10 +1215,7 @@ function SettingsPageContent() {{diagnosticsOpen && (<div className="border-t border-[var(--border)] px-5 py-4"><p className="mb-3 text-[12px] leading-relaxed text-[var(--muted-foreground)]">- Streams config snapshot, request target, response summary, and service-specific- validation for the active{" "}- <span className="font-medium text-[var(--foreground)]">{activeService}</span>{" "}- profile.+ {t("Streams config snapshot, request target, response summary, and service-specific validation for the active {{service}} profile.", { service: activeService })}</p><pre className="max-h-[360px] overflow-y-auto rounded-lg bg-[#0f0f0f] p-4 font-mono text-[12px] leading-6 text-[#777] dark:bg-[#0a0a0a]">{logs}@@ -1212,7 +1232,7 @@ function SettingsPageContent() {className="inline-flex items-center gap-1.5 text-[12px] text-[var(--muted-foreground)]/40 transition-colors hover:text-[var(--muted-foreground)]"><RotateCcw className="h-3 w-3" />- Run Terminal Tour+ {t("Run Terminal Tour")}</button>)}<span className="text-[11px] text-[var(--muted-foreground)]/30 ml-auto">@@ -1250,11 +1270,12 @@ function SettingsPageContent() {}export default function SettingsPage() {+ const { t } = useTranslation();return (<Suspensefallback={<div className="min-h-[50vh] flex items-center justify-center text-[13px] text-[var(--muted-foreground)]">- Loading settings...+ {t("Loading settings...")}</div>}>diff --git a/web/app/(workspace)/agents/[botId]/chat/page.tsx b/web/app/(workspace)/agents/[botId]/chat/page.tsxindex d1618d2d3..307265f7e 100644--- a/web/app/(workspace)/agents/[botId]/chat/page.tsx+++ b/web/app/(workspace)/agents/[botId]/chat/page.tsx@@ -2,6 +2,7 @@import { useCallback, useEffect, useRef, useState } from "react";import { useParams, useRouter } from "next/navigation";+import { useTranslation } from "react-i18next";import { ArrowLeft, Bot, Loader2, Send } from "lucide-react";import { apiUrl, wsUrl } from "@/lib/api";import AssistantResponse from "@/components/common/AssistantResponse";@@ -21,6 +22,7 @@ interface ChatMsg {export default function BotChatPage() {const { botId } = useParams<{ botId: string }>();const router = useRouter();+ const { t } = useTranslation();const [bot, setBot] = useState<BotInfo | null>(null);const [messages, setMessages] = useState<ChatMsg[]>([]);@@ -149,10 +151,10 @@ export default function BotChatPage() {<Bot size={22} /></div><p className="text-[14px] font-medium text-[var(--foreground)]">- Chat with {bot?.name ?? botId}+ {t("Chat with {{name}}", { name: bot?.name ?? botId })}</p><p className="mt-1 text-[13px] text-[var(--muted-foreground)]">- Send a message to start the conversation.+ {t("Send a message to start the conversation.")}</p></div>)}@@ -168,11 +170,11 @@ export default function BotChatPage() {{msg.thinking && msg.thinking.length > 0 && (<details className="mb-2"><summary className="cursor-pointer text-[12px] text-[var(--muted-foreground)] hover:text-[var(--foreground)]">- Thinking ({msg.thinking.length} steps)+ {t("Thinking ({{count}} steps)", { count: msg.thinking.length })}</summary><div className="mt-1 space-y-1 border-l-2 border-[var(--border)] pl-3">- {msg.thinking.map((t, j) => (- <p key={j} className="text-[12px] text-[var(--muted-foreground)]">{t}</p>+ {msg.thinking.map((th, j) => (+ <p key={j} className="text-[12px] text-[var(--muted-foreground)]">{th}</p>))}</div></details>@@ -188,14 +190,14 @@ export default function BotChatPage() {<div className="space-y-2">{thinking.length > 0 && (<div className="space-y-1 border-l-2 border-[var(--border)] pl-3">- {thinking.map((t, i) => (- <p key={i} className="text-[12px] text-[var(--muted-foreground)]">{t}</p>+ {thinking.map((th, i) => (+ <p key={i} className="text-[12px] text-[var(--muted-foreground)]">{th}</p>))}</div>)}<div className="flex items-center gap-2 text-[13px] text-[var(--muted-foreground)]"><Loader2 className="h-3.5 w-3.5 animate-spin" />- <span>{thinking.length > 0 ? "Working..." : "Thinking..."}</span>+ <span>{thinking.length > 0 ? t("Working...") : t("Thinking...")}</span></div></div>)}@@ -210,7 +212,7 @@ export default function BotChatPage() {value={input}onChange={(e) => setInput(e.target.value)}onKeyDown={handleKeyDown}- placeholder="Type a message..."+ placeholder={t("Type a message...")}rows={1}disabled={streaming}className="flex-1 resize-none rounded-xl border border-[var(--border)] bg-transparent px-4 py-2.5 text-[14px] text-[var(--foreground)] outline-none transition-colors focus:border-[var(--ring)] disabled:opacity-50 placeholder:text-[var(--muted-foreground)]/40"diff --git a/web/app/(workspace)/agents/page.tsx b/web/app/(workspace)/agents/page.tsxindex 8efabd70b..75b97fb56 100644--- a/web/app/(workspace)/agents/page.tsx+++ b/web/app/(workspace)/agents/page.tsx@@ -16,6 +16,7 @@ import {X,} from "lucide-react";import { useRouter } from "next/navigation";+import { useTranslation } from "react-i18next";import dynamic from "next/dynamic";import { apiUrl } from "@/lib/api";@@ -51,6 +52,7 @@ type BotFile = (typeof BOT_FILES)[number];export default function AgentsPage() {const router = useRouter();+ const { t } = useTranslation();const [bots, setBots] = useState<BotInfo[]>([]);const [souls, setSouls] = useState<SoulTemplate[]>([]);const [loading, setLoading] = useState(true);@@ -59,8 +61,8 @@ export default function AgentsPage() {useEffect(() => {if (!toast) return;- const t = setTimeout(() => setToast(""), 3500);- return () => clearTimeout(t);+ const timer = setTimeout(() => setToast(""), 3500);+ return () => clearTimeout(timer);}, [toast]);const loadBots = useCallback(async () => {@@ -88,13 +90,13 @@ export default function AgentsPage() {{/* Header */}<div className="mb-6"><h1 className="text-[24px] font-semibold tracking-tight text-[var(--foreground)]">- TutorBot Agents+ {t("TutorBot Agents")}</h1>{toast ? (<p className="mt-1 text-[13px] text-[var(--primary)] animate-fade-in">{toast}</p>) : (<p className="mt-1 text-[13px] text-[var(--muted-foreground)]">- Manage your in-process TutorBot instances+ {t("Manage your in-process TutorBot instances")}</p>)}</div>@@ -102,16 +104,16 @@ export default function AgentsPage() {{/* Tabs */}<div className="mb-6 flex items-center gap-1 border-b border-[var(--border)]/50 pb-3">{([- { key: "bots" as Tab, label: "Bots", icon: Bot },- { key: "profiles" as Tab, label: "Profiles", icon: FileText },- { key: "souls" as Tab, label: "Souls", icon: Heart },- ]).map((t) => {- const Icon = t.icon;- const active = activeTab === t.key;+ { key: "bots" as Tab, label: t("Bots"), icon: Bot },+ { key: "profiles" as Tab, label: t("Profiles"), icon: FileText },+ { key: "souls" as Tab, label: t("Souls"), icon: Heart },+ ]).map((tab) => {+ const Icon = tab.icon;+ const active = activeTab === tab.key;return (<button- key={t.key}- onClick={() => setActiveTab(t.key)}+ key={tab.key}+ onClick={() => setActiveTab(tab.key)}className={`inline-flex items-center gap-1.5 rounded-lg px-3 py-1.5 text-[13px] transition-colors ${active? "bg-[var(--muted)] font-medium text-[var(--foreground)]"@@ -119,7 +121,7 @@ export default function AgentsPage() {}`}><Icon className="h-3.5 w-3.5" />- {t.label}+ {tab.label}</button>);})}@@ -161,6 +163,7 @@ function BotsTab({onToast: (msg: string) => void;router: ReturnType<typeof useRouter>;}) {+ const { t } = useTranslation();const [showCreate, setShowCreate] = useState(false);const [creating, setCreating] = useState(false);@@ -229,10 +232,10 @@ function BotsTab({}, [onReload, onToast]);const destroyBot = useCallback(async (bid: string, name: string) => {- if (!window.confirm(`Permanently delete "${name}" (${bid})? This cannot be undone.`)) return;+ if (!window.confirm(t("Permanently delete \"{{name}}\" ({{id}})? This cannot be undone.", { name, id: bid }))) return;const res = await fetch(apiUrl(`/api/v1/tutorbot/${bid}/destroy`), { method: "DELETE" });if (res.ok) { onToast(`${name} deleted`); await onReload(); }- }, [onReload, onToast]);+ }, [onReload, onToast, t]);return (<>@@ -243,7 +246,7 @@ function BotsTab({className="inline-flex items-center gap-1.5 rounded-lg border border-[var(--border)]/50 px-3 py-1.5 text-[12px] font-medium text-[var(--muted-foreground)] transition-colors hover:border-[var(--border)] hover:text-[var(--foreground)]"><Plus className="h-3 w-3" />- New Bot+ {t("New Bot")}</button></div>@@ -251,18 +254,18 @@ function BotsTab({{showCreate && (<div className="mb-6 rounded-xl border border-[var(--border)] p-5"><div className="mb-4 flex items-center justify-between">- <h2 className="text-[15px] font-medium text-[var(--foreground)]">Create TutorBot</h2>+ <h2 className="text-[15px] font-medium text-[var(--foreground)]">{t("Create TutorBot")}</h2><button onClick={() => { setShowCreate(false); resetForm(); }} className="text-[var(--muted-foreground)] hover:text-[var(--foreground)]"><X className="h-4 w-4" /></button></div><div className="grid gap-3"><div>- <label className="mb-1 block text-[12px] font-medium text-[var(--muted-foreground)]">Name</label>+ <label className="mb-1 block text-[12px] font-medium text-[var(--muted-foreground)]">{t("Name")}</label><inputvalue={formName}onChange={(e) => setFormName(e.target.value)}- placeholder="e.g. Math Tutor"+ placeholder={t("e.g. Math Tutor")}className="w-full rounded-lg border border-[var(--border)] bg-transparent px-3 py-2 text-[13px] text-[var(--foreground)] outline-none focus:border-[var(--ring)] placeholder:text-[var(--muted-foreground)]/40"/>{botId && (@@ -270,16 +273,16 @@ function BotsTab({)}</div><div>- <label className="mb-1 block text-[12px] font-medium text-[var(--muted-foreground)]">Description <span className="font-normal opacity-60">(optional)</span></label>+ <label className="mb-1 block text-[12px] font-medium text-[var(--muted-foreground)]">{t("Description")} <span className="font-normal opacity-60">{t("(optional)")}</span></label><inputvalue={formDesc}onChange={(e) => setFormDesc(e.target.value)}- placeholder="A brief description of what this bot does"+ placeholder={t("A brief description of what this bot does")}className="w-full rounded-lg border border-[var(--border)] bg-transparent px-3 py-2 text-[13px] text-[var(--foreground)] outline-none focus:border-[var(--ring)] placeholder:text-[var(--muted-foreground)]/40"/></div><div>- <label className="mb-1 block text-[12px] font-medium text-[var(--muted-foreground)]">Soul</label>+ <label className="mb-1 block text-[12px] font-medium text-[var(--muted-foreground)]">{t("Soul")}</label><div className="flex flex-wrap gap-1.5 mb-2"><buttononClick={() => selectSoul("_custom")}@@ -289,7 +292,7 @@ function BotsTab({: "bg-[var(--muted)] text-[var(--muted-foreground)] hover:text-[var(--foreground)]"}`}>- Custom+ {t("Custom")}</button>{souls.map((s) => (<button@@ -308,20 +311,20 @@ function BotsTab({<textareavalue={formSoul}onChange={(e) => { setFormSoul(e.target.value); setFormSoulId("_custom"); }}- placeholder="Define the bot's personality, values, and communication style in markdown..."+ placeholder={t("Define the bot's personality, values, and communication style in markdown...")}rows={8}className="w-full rounded-lg border border-[var(--border)] bg-transparent px-3 py-2 font-mono text-[13px] leading-6 text-[var(--foreground)] outline-none focus:border-[var(--ring)] placeholder:text-[var(--muted-foreground)]/40"/><p className="mt-1 text-[11px] text-[var(--muted-foreground)]/60">- Pick a soul from the library above, or write your own. Manage the library in the Souls tab.+ {t("Pick a soul from the library above, or write your own. Manage the library in the Souls tab.")}</p></div><div>- <label className="mb-1 block text-[12px] font-medium text-[var(--muted-foreground)]">Model <span className="font-normal opacity-60">(optional)</span></label>+ <label className="mb-1 block text-[12px] font-medium text-[var(--muted-foreground)]">{t("Model")} <span className="font-normal opacity-60">{t("(optional)")}</span></label><inputvalue={formModel}onChange={(e) => setFormModel(e.target.value)}- placeholder="Uses default model if empty"+ placeholder={t("Uses default model if empty")}className="w-full rounded-lg border border-[var(--border)] bg-transparent px-3 py-2 text-[13px] text-[var(--foreground)] outline-none focus:border-[var(--ring)] placeholder:text-[var(--muted-foreground)]/40"/></div>@@ -332,7 +335,7 @@ function BotsTab({className="inline-flex items-center gap-1.5 rounded-lg bg-[var(--primary)] px-4 py-2 text-[13px] font-medium text-[var(--primary-foreground)] transition-opacity hover:opacity-90 disabled:opacity-40">{creating ? <Loader2 className="h-3.5 w-3.5 animate-spin" /> : <Play className="h-3.5 w-3.5" />}- Create & Start+ {t("Create & Start")}</button></div></div>@@ -349,9 +352,9 @@ function BotsTab({<div className="mb-3 rounded-xl bg-[var(--muted)] p-2.5 text-[var(--muted-foreground)]"><Bot size={18} /></div>- <p className="text-[14px] font-medium text-[var(--foreground)]">No TutorBots yet</p>+ <p className="text-[14px] font-medium text-[var(--foreground)]">{t("No TutorBots yet")}</p><p className="mt-1.5 max-w-xs text-[13px] text-[var(--muted-foreground)]">- Create your first TutorBot to get started.+ {t("Create your first TutorBot to get started.")}</p></div>) : (@@ -373,7 +376,7 @@ function BotsTab({)}{bot.model && <span>· {bot.model}</span>}{bot.started_at && (- <span>· started {new Date(bot.started_at).toLocaleString()}</span>+ <span>· {t("started {{time}}", { time: new Date(bot.started_at).toLocaleString() })}</span>)}</div></div>@@ -386,14 +389,14 @@ function BotsTab({className="inline-flex items-center gap-1.5 rounded-lg border border-[var(--border)]/50 px-3 py-1.5 text-[12px] font-medium text-[var(--primary)] transition-colors hover:border-[var(--primary)]/50"><MessageCircle className="h-3 w-3" />- Chat+ {t("Chat")}</button><buttononClick={() => stopBot(bot.bot_id)}className="inline-flex items-center gap-1.5 rounded-lg border border-[var(--border)]/50 px-3 py-1.5 text-[12px] font-medium text-red-400 transition-colors hover:border-red-400/50"><Square className="h-3 w-3" />- Stop+ {t("Stop")}</button></>) : (@@ -402,7 +405,7 @@ function BotsTab({className="inline-flex items-center gap-1.5 rounded-lg border border-[var(--border)]/50 px-3 py-1.5 text-[12px] font-medium text-[var(--muted-foreground)] transition-colors hover:border-[var(--border)] hover:text-[var(--foreground)]"><Play className="h-3 w-3" />- Start+ {t("Start")}</button>)}<button@@ -431,6 +434,7 @@ function ProfilesTab({loading: boolean;onToast: (msg: string) => void;}) {+ const { t } = useTranslation();const [selectedBot, setSelectedBot] = useState<string>("");const [activeFile, setActiveFile] = useState<BotFile>("SOUL.md");const [files, setFiles] = useState<Record<string, string>>({});@@ -511,9 +515,9 @@ function ProfilesTab({<div className="mb-3 rounded-xl bg-[var(--muted)] p-2.5 text-[var(--muted-foreground)]"><FileText size={18} /></div>- <p className="text-[14px] font-medium text-[var(--foreground)]">No bots to configure</p>+ <p className="text-[14px] font-medium text-[var(--foreground)]">{t("No bots to configure")}</p><p className="mt-1.5 max-w-xs text-[13px] text-[var(--muted-foreground)]">- Create a bot first in the Bots tab.+ {t("Create a bot first in the Bots tab.")}</p></div>);@@ -523,7 +527,7 @@ function ProfilesTab({<div className="space-y-4">{/* Bot selector */}<div className="flex items-center gap-3">- <label className="text-[12px] font-medium text-[var(--muted-foreground)] shrink-0">Bot</label>+ <label className="text-[12px] font-medium text-[var(--muted-foreground)] shrink-0">{t("Bot")}</label><selectvalue={selectedBot}onChange={(e) => setSelectedBot(e.target.value)}@@ -567,7 +571,7 @@ function ProfilesTab({: "text-[var(--muted-foreground)] hover:text-[var(--foreground)]"}`}>- {v === "edit" ? "Edit" : "Preview"}+ {v === "edit" ? t("Edit") : t("Preview")}</button>))}</div>@@ -577,7 +581,7 @@ function ProfilesTab({className="inline-flex items-center gap-1.5 rounded-lg border border-[var(--border)]/50 px-3 py-1.5 text-[12px] font-medium text-[var(--muted-foreground)] transition-colors hover:border-[var(--border)] hover:text-[var(--foreground)] disabled:opacity-40">{saving ? <Loader2 className="h-3 w-3 animate-spin" /> : <Save className="h-3 w-3" />}- Save+ {t("Save")}</button></div>@@ -594,11 +598,11 @@ function ProfilesTab({onKeyDown={handleKeyDown}spellCheck={false}className="min-h-[420px] w-full resize-none rounded-xl border border-[var(--border)] bg-transparent px-5 py-4 font-mono text-[13px] leading-7 text-[var(--foreground)] outline-none transition-colors focus:border-[var(--ring)] placeholder:text-[var(--muted-foreground)]/40"- placeholder={`Edit ${activeFile}...`}+ placeholder={t("Edit {{file}}...", { file: activeFile })}/><p className="mt-2 text-[11px] text-[var(--muted-foreground)]/40">- Cmd+S to save · Markdown supported- {hasChanges && " · Unsaved changes"}+ {t("Cmd+S to save · Markdown supported")}+ {hasChanges && ` · ${t("Unsaved changes")}`}</p></div>) : editor.trim() ? (@@ -607,9 +611,9 @@ function ProfilesTab({</div>) : (<div className="flex min-h-[300px] flex-col items-center justify-center rounded-xl border border-dashed border-[var(--border)] text-center">- <p className="text-[14px] font-medium text-[var(--foreground)]">{activeFile} is empty</p>+ <p className="text-[14px] font-medium text-[var(--foreground)]">{t("{{file}} is empty", { file: activeFile })}</p><p className="mt-1 text-[13px] text-[var(--muted-foreground)]">- Switch to Edit to add content.+ {t("Switch to Edit to add content.")}</p></div>)}@@ -628,6 +632,7 @@ function SoulsTab({onReload: () => Promise<void>;onToast: (msg: string) => void;}) {+ const { t } = useTranslation();const [editing, setEditing] = useState<string | null>(null);const [creating, setCreating] = useState(false);const [saving, setSaving] = useState(false);@@ -703,14 +708,14 @@ function SoulsTab({}, [newName, newContent, onReload, onToast]);const deleteSoul = useCallback(async (soul: SoulTemplate) => {- if (!window.confirm(`Delete soul "${soul.name}"?`)) return;+ if (!window.confirm(t("Delete soul \"{{name}}\"?", { name: soul.name }))) return;const res = await fetch(apiUrl(`/api/v1/tutorbot/souls/${soul.id}`), { method: "DELETE" });if (res.ok) {if (editing === soul.id) cancelEdit();onToast(`"${soul.name}" deleted`);await onReload();}- }, [editing, onReload, onToast]);+ }, [editing, onReload, onToast, t]);const handleKeyDown = useCallback((e: React.KeyboardEvent<HTMLTextAreaElement>, save: () => void) => {@@ -727,14 +732,14 @@ function SoulsTab({{/* Header */}<div className="flex items-center justify-between"><p className="text-[13px] text-[var(--muted-foreground)]">- Reusable soul templates for creating TutorBots.+ {t("Reusable soul templates for creating TutorBots.")}</p><buttononClick={startCreate}className="inline-flex items-center gap-1.5 rounded-lg border border-[var(--border)]/50 px-3 py-1.5 text-[12px] font-medium text-[var(--muted-foreground)] transition-colors hover:border-[var(--border)] hover:text-[var(--foreground)]"><Plus className="h-3 w-3" />- New Soul+ {t("New Soul")}</button></div>@@ -742,18 +747,18 @@ function SoulsTab({{creating && (<div className="rounded-xl border border-[var(--border)] p-5"><div className="mb-4 flex items-center justify-between">- <h2 className="text-[15px] font-medium text-[var(--foreground)]">New Soul</h2>+ <h2 className="text-[15px] font-medium text-[var(--foreground)]">{t("New Soul")}</h2><button onClick={() => setCreating(false)} className="text-[var(--muted-foreground)] hover:text-[var(--foreground)]"><X className="h-4 w-4" /></button></div><div className="grid gap-3"><div>- <label className="mb-1 block text-[12px] font-medium text-[var(--muted-foreground)]">Name</label>+ <label className="mb-1 block text-[12px] font-medium text-[var(--muted-foreground)]">{t("Name")}</label><inputvalue={newName}onChange={(e) => setNewName(e.target.value)}- placeholder="e.g. Creative Writer"+ placeholder={t("e.g. Creative Writer")}className="w-full rounded-lg border border-[var(--border)] bg-transparent px-3 py-2 text-[13px] text-[var(--foreground)] outline-none focus:border-[var(--ring)] placeholder:text-[var(--muted-foreground)]/40"/>{newName.trim() && (@@ -763,12 +768,12 @@ function SoulsTab({)}</div><div>- <label className="mb-1 block text-[12px] font-medium text-[var(--muted-foreground)]">Content</label>+ <label className="mb-1 block text-[12px] font-medium text-[var(--muted-foreground)]">{t("Content")}</label><textareavalue={newContent}onChange={(e) => setNewContent(e.target.value)}onKeyDown={(e) => handleKeyDown(e, createSoul)}- placeholder="Define the soul in markdown..."+ placeholder={t("Define the soul in markdown...")}rows={10}spellCheck={false}className="w-full rounded-lg border border-[var(--border)] bg-transparent px-3 py-2 font-mono text-[13px] leading-6 text-[var(--foreground)] outline-none focus:border-[var(--ring)] placeholder:text-[var(--muted-foreground)]/40"@@ -779,7 +784,7 @@ function SoulsTab({onClick={() => setCreating(false)}className="rounded-lg px-3 py-1.5 text-[12px] text-[var(--muted-foreground)] hover:text-[var(--foreground)]">- Cancel+ {t("Cancel")}</button><buttononClick={createSoul}@@ -787,7 +792,7 @@ function SoulsTab({className="inline-flex items-center gap-1.5 rounded-lg bg-[var(--primary)] px-4 py-2 text-[13px] font-medium text-[var(--primary-foreground)] transition-opacity hover:opacity-90 disabled:opacity-40">{saving ? <Loader2 className="h-3.5 w-3.5 animate-spin" /> : <Plus className="h-3.5 w-3.5" />}- Create+ {t("Create")}</button></div></div>@@ -800,9 +805,9 @@ function SoulsTab({<div className="mb-3 rounded-xl bg-[var(--muted)] p-2.5 text-[var(--muted-foreground)]"><Heart size={18} /></div>- <p className="text-[14px] font-medium text-[var(--foreground)]">No souls yet</p>+ <p className="text-[14px] font-medium text-[var(--foreground)]">{t("No souls yet")}</p><p className="mt-1.5 max-w-xs text-[13px] text-[var(--muted-foreground)]">- Create your first soul template. Default presets will be seeded automatically on next server restart.+ {t("Create your first soul template. Default presets will be seeded automatically on next server restart.")}</p></div>) : (@@ -812,7 +817,7 @@ function SoulsTab({<div key={soul.id} className="rounded-xl border border-[var(--ring)] p-5"><div className="grid gap-3"><div>- <label className="mb-1 block text-[12px] font-medium text-[var(--muted-foreground)]">Name</label>+ <label className="mb-1 block text-[12px] font-medium text-[var(--muted-foreground)]">{t("Name")}</label><inputvalue={editName}onChange={(e) => setEditName(e.target.value)}@@ -820,7 +825,7 @@ function SoulsTab({/></div><div>- <label className="mb-1 block text-[12px] font-medium text-[var(--muted-foreground)]">Content</label>+ <label className="mb-1 block text-[12px] font-medium text-[var(--muted-foreground)]">{t("Content")}</label><textareavalue={editContent}onChange={(e) => setEditContent(e.target.value)}@@ -835,7 +840,7 @@ function SoulsTab({onClick={cancelEdit}className="rounded-lg px-3 py-1.5 text-[12px] text-[var(--muted-foreground)] hover:text-[var(--foreground)]">- Cancel+ {t("Cancel")}</button><buttononClick={saveSoul}@@ -843,7 +848,7 @@ function SoulsTab({className="inline-flex items-center gap-1.5 rounded-lg bg-[var(--primary)] px-4 py-2 text-[13px] font-medium text-[var(--primary-foreground)] transition-opacity hover:opacity-90 disabled:opacity-40">{saving ? <Loader2 className="h-3.5 w-3.5 animate-spin" /> : <Save className="h-3.5 w-3.5" />}- Save+ {t("Save")}</button></div></div>diff --git a/web/app/(workspace)/co-writer/page.tsx b/web/app/(workspace)/co-writer/page.tsxindex 9e4063a12..f670b5317 100644--- a/web/app/(workspace)/co-writer/page.tsx+++ b/web/app/(workspace)/co-writer/page.tsx@@ -2,6 +2,7 @@import dynamic from "next/dynamic";import { useCallback, useEffect, useMemo, useRef, useState } from "react";+import { useTranslation } from "react-i18next";import {ArrowRight,ArrowUpRight,@@ -141,6 +142,7 @@ interface StreamEditResult {}export default function CoWriterPage() {+ const { t } = useTranslation();const textareaRef = useRef<HTMLTextAreaElement>(null);const selectionPopoverRef = useRef<HTMLDivElement>(null);const preserveSelectionTraceRef = useRef(false);@@ -262,7 +264,7 @@ export default function CoWriterPage() {.split("\n").find((line) => line.startsWith("#"))?.replace(/^#+\s*/, "")- .trim() || "Co-Writer Draft";+ .trim() || t("Co-Writer Draft");return {recordType: "co_writer" as const,title,@@ -439,14 +441,14 @@ export default function CoWriterPage() {const loadExampleTemplate = useCallback(() => {if (markdown === CO_WRITER_SAMPLE_TEMPLATE) {- setStatus("Example template is already loaded.");+ setStatus(t("Example template is already loaded."));setError("");return;}pushUndo(markdown);setMarkdown(CO_WRITER_SAMPLE_TEMPLATE);- setStatus("Loaded example template.");+ setStatus(t("Loaded example template."));setError("");}, [markdown, pushUndo]);@@ -565,12 +567,12 @@ export default function CoWriterPage() {const applyReactSelectionEdit = useCallback(async () => {if (!selectedRange) {- setError("Please select a text passage first.");+ setError(t("Please select a text passage first."));return;}if (selectionMode === "none" && !selectionInstruction.trim()) {- setError("Please enter an instruction or choose a mode.");+ setError(t("Please enter an instruction or choose a mode."));return;}@@ -662,7 +664,7 @@ export default function CoWriterPage() {}replaceSelectedText(selectedRange, editedText);- setStatus("Applied AI edit to the selection.");+ setStatus(t("Applied AI edit to the selection."));} catch (err) {if (err instanceof DOMException && err.name === "AbortError") {return;@@ -687,7 +689,7 @@ export default function CoWriterPage() {const applyEdit = async () => {if (!instruction.trim()) {- setError("Please enter an editing instruction first.");+ setError(t("Please enter an editing instruction first."));return;}setIsEditing(true);@@ -710,7 +712,7 @@ export default function CoWriterPage() {throw new Error(data?.detail || "Failed to edit document.");pushUndo(markdown);setMarkdown(data.edited_text || "");- setStatus(`Applied ${ACTION_LABELS[action].toLowerCase()} to the full draft.`);+ setStatus(t("Applied {{action}} to the full draft.", { action: t(ACTION_LABELS[action]).toLowerCase() }));setIsEditModalOpen(false);} catch (err) {setError(err instanceof Error ? err.message : "Failed to edit document.");@@ -734,7 +736,7 @@ export default function CoWriterPage() {throw new Error(data?.detail || "Failed to auto-mark document.");pushUndo(markdown);setMarkdown(data.marked_text || "");- setStatus("Applied auto-mark annotations.");+ setStatus(t("Applied auto-mark annotations."));} catch (err) {setError(err instanceof Error ? err.message : "Failed to auto-mark document.",@@ -903,34 +905,34 @@ export default function CoWriterPage() {<header className="flex shrink-0 items-center justify-between border-b border-[var(--border)] px-4 py-1.5"><div className="flex items-center gap-3 text-sm text-[var(--muted-foreground)]"><span className="font-medium text-[var(--foreground)]">- Co-Writer+ {t("Co-Writer")}</span><span className="hidden text-xs sm:inline">- {wordCount} words · {charCount} chars+ {wordCount} {t("words")} · {charCount} {t("chars")}</span></div><div className="flex items-center gap-1.5"><ToolbarIconBtn- title="Clear"+ title={t("Clear")}onClick={clearDocument}><Eraser size={15} /></ToolbarIconBtn><ToolbarIconBtn- title="Export Markdown"+ title={t("Export Markdown")}onClick={handleDownload}><Download size={15} /></ToolbarIconBtn><ToolbarIconBtn- title="Load Example Template"+ title={t("Load Example Template")}onClick={loadExampleTemplate}><FileText size={15} /></ToolbarIconBtn><div className="relative"><ToolbarIconBtn- title="Add to Notebook"+ title={t("Add to Notebook")}onClick={() => setShowSaveModal(true)}><BookPlus size={15} />@@ -942,7 +944,7 @@ export default function CoWriterPage() {rel="noreferrer"className="inline-flex items-center gap-1 rounded-full border border-[var(--border)] px-2.5 py-1 text-[11px] font-medium text-[var(--muted-foreground)] transition-colors hover:bg-[var(--muted)] hover:text-[var(--foreground)]">- <span>Pro Vide Writing</span>+ <span>{t("Pro Vide Writing")}</span><ArrowUpRight size={12} strokeWidth={1.8} aria-hidden="true" /></a><div className="mx-1 h-5 w-px bg-[var(--border)]" />@@ -951,7 +953,7 @@ export default function CoWriterPage() {className="inline-flex items-center gap-1.5 rounded-md bg-[var(--primary)] px-3 py-1 text-xs font-medium text-white transition-opacity hover:opacity-90"><WandSparkles size={13} />- Full Draft+ {t("Full Draft")}</button></div></header>@@ -971,7 +973,7 @@ export default function CoWriterPage() {return (<buttonkey={item.id}- title={item.title}+ title={t(item.title)}onClick={() =>item.action ? item.action() : insertSnippet(item.snippet || "")}@@ -1002,10 +1004,10 @@ export default function CoWriterPage() {><div className="flex shrink-0 items-center justify-between border-b border-[var(--border)] px-3 py-1"><span className="text-xs font-medium text-[var(--muted-foreground)]">- Editor+ {t("Editor")}</span><button- title="Collapse editor"+ title={t("Collapse editor")}onClick={() => setEditorCollapsed(true)}className="rounded p-0.5 text-[var(--muted-foreground)] transition-colors hover:bg-[var(--muted)] hover:text-[var(--foreground)]">@@ -1022,7 +1024,7 @@ export default function CoWriterPage() {onScroll={updateSelectionPopover}spellCheck={false}className="min-h-0 flex-1 resize-none bg-transparent p-4 font-mono text-[13px] leading-relaxed text-[var(--foreground)] outline-none placeholder:text-[var(--muted-foreground)]"- placeholder="Start writing in Markdown..."+ placeholder={t("Start writing in Markdown...")}/></div>)}@@ -1031,7 +1033,7 @@ export default function CoWriterPage() {{editorCollapsed && (<buttononClick={() => setEditorCollapsed(false)}- title="Expand editor"+ title={t("Expand editor")}className="flex w-7 shrink-0 items-center justify-center border-r border-[var(--border)] text-[var(--muted-foreground)] transition-colors hover:bg-[var(--muted)] hover:text-[var(--foreground)]"><ChevronRight size={14} />@@ -1041,7 +1043,7 @@ export default function CoWriterPage() {{previewCollapsed && (<buttononClick={() => setPreviewCollapsed(false)}- title="Expand preview"+ title={t("Expand preview")}className="flex w-7 shrink-0 items-center justify-center border-l border-[var(--border)] text-[var(--muted-foreground)] transition-colors hover:bg-[var(--muted)] hover:text-[var(--foreground)]"><ChevronLeft size={14} />@@ -1055,10 +1057,10 @@ export default function CoWriterPage() {><div className="flex shrink-0 items-center justify-between border-b border-[var(--border)] px-3 py-1"><span className="text-xs font-medium text-[var(--muted-foreground)]">- Preview+ {t("Preview")}</span><button- title="Collapse preview"+ title={t("Collapse preview")}onClick={() => setPreviewCollapsed(true)}className="rounded p-0.5 text-[var(--muted-foreground)] transition-colors hover:bg-[var(--muted)] hover:text-[var(--foreground)]">@@ -1067,7 +1069,7 @@ export default function CoWriterPage() {</div><div className="min-h-0 flex-1 overflow-y-auto p-5"><MarkdownRenderer- content={markdown || "_Nothing to preview yet._"}+ content={markdown || `_${t("Nothing to preview yet.")}_`}variant="prose"/></div>@@ -1103,13 +1105,13 @@ export default function CoWriterPage() {}}}className="h-10 w-full rounded-xl bg-transparent pl-3 pr-10 text-[13px] text-[var(--foreground)] outline-none placeholder:text-[var(--muted-foreground)]"- placeholder="Tell AI what to do with the selection..."+ placeholder={t("Tell AI what to do with the selection...")}/><buttononClick={() => void applyReactSelectionEdit()}disabled={isEditing || isAutoMarking}className="absolute right-1.5 top-1.5 inline-flex h-7 w-7 items-center justify-center rounded-full bg-[var(--primary)] text-white transition-opacity disabled:opacity-45"- title="Apply AI edit"+ title={t("Apply AI edit")}>{isEditing ? (<Loader2 size={13} className="animate-spin" />@@ -1130,11 +1132,11 @@ export default function CoWriterPage() {><span className="truncate">{selectionTools.length === 0- ? "Tools"+ ? t("Tools"): selectionTools.length === 1- ? TOOL_OPTIONS.find((item) => item.name === selectionTools[0])- ?.label || "Tools"- : `${selectionTools.length} tools`}+ ? t(TOOL_OPTIONS.find((item) => item.name === selectionTools[0])+ ?.label || "Tools")+ : t("{{count}} tools", { count: selectionTools.length })}</span><ChevronDownsize={13}@@ -1151,7 +1153,7 @@ export default function CoWriterPage() {onClick={() => toggleSelectionTool(tool.name)}className="flex w-full items-center justify-between rounded-lg px-2.5 py-2 text-left text-[12px] text-[var(--foreground)] transition-colors hover:bg-[var(--muted)]">- <span>{tool.label}</span>+ <span>{t(tool.label)}</span>{active ? <Check size={12} /> : <span className="w-3" />}</button>);@@ -1169,8 +1171,8 @@ export default function CoWriterPage() {className="flex h-9 w-full items-center justify-between rounded-xl border border-[var(--border)] px-3 text-[12px] text-[var(--foreground)] transition-colors hover:bg-[var(--muted)]"><span>- {MODE_OPTIONS.find((item) => item.value === selectionMode)?.label ||- "Mode"}+ {t(MODE_OPTIONS.find((item) => item.value === selectionMode)?.label ||+ "Mode")}</span><ChevronDownsize={13}@@ -1188,7 +1190,7 @@ export default function CoWriterPage() {}}className="flex w-full items-center justify-between rounded-lg px-2.5 py-2 text-left text-[12px] text-[var(--foreground)] transition-colors hover:bg-[var(--muted)]">- <span>{mode.label}</span>+ <span>{t(mode.label)}</span>{selectionMode === mode.value ? (<Check size={12} />) : (@@ -1212,7 +1214,7 @@ export default function CoWriterPage() {className={`shrink-0 transition-transform ${isTraceExpanded ? "rotate-180" : ""}`}/><span className="font-medium text-[var(--foreground)]">- Trace+ {t("Trace")}</span>{isEditing ? (<Loader2 size={12} className="ml-auto animate-spin" />@@ -1227,7 +1229,7 @@ export default function CoWriterPage() {{selectionTrace?.thinking ? (<div className="space-y-1.5"><div className="text-[11px] font-medium uppercase tracking-[0.08em] text-[var(--muted-foreground)]/60">- Thought+ {t("Thought")}</div><MarkdownRenderercontent={selectionTrace.thinking}@@ -1235,13 +1237,13 @@ export default function CoWriterPage() {/></div>) : isEditing ? (- <div className="opacity-70">Thinking...</div>+ <div className="opacity-70">{t("Thinking...")}</div>) : null}{selectionTrace && selectionTrace.toolTraces.length > 0 && (<div className="mt-3 space-y-1.5"><div className="text-[11px] font-medium uppercase tracking-[0.08em] text-[var(--muted-foreground)]/60">- Tool+ {t("Tool")}</div><div className="space-y-2">{selectionTrace.toolTraces.map((trace, index) => (@@ -1277,7 +1279,7 @@ export default function CoWriterPage() {{selectionTrace?.response ? (<div className="mt-3 space-y-1.5"><div className="text-[11px] font-medium uppercase tracking-[0.08em] text-[var(--muted-foreground)]/60">- Response+ {t("Response")}</div><MarkdownRenderercontent={selectionTrace.response}@@ -1292,7 +1294,7 @@ export default function CoWriterPage() {selectionTrace.toolTraces.length === 0 &&!selectionTrace.response ? (<div className="mt-2 opacity-70">- Running tools and preparing the final edit...+ {t("Running tools and preparing the final edit...")}</div>) : null}</div>@@ -1326,13 +1328,13 @@ export default function CoWriterPage() {<div className="w-full max-w-md rounded-xl border border-[var(--border)] bg-[var(--card)] shadow-xl"><div className="flex items-center justify-between border-b border-[var(--border)] px-4 py-3"><h2 className="text-sm font-semibold text-[var(--foreground)]">- Full Draft AI Edit+ {t("Full Draft AI Edit")}</h2><buttononClick={() => setIsEditModalOpen(false)}className="text-xs text-[var(--muted-foreground)] hover:text-[var(--foreground)]">- Close+ {t("Close")}</button></div>@@ -1348,7 +1350,7 @@ export default function CoWriterPage() {: "border border-[var(--border)] text-[var(--foreground)] hover:bg-[var(--muted)]"}`}>- {ACTION_LABELS[a]}+ {t(ACTION_LABELS[a])}</button>))}</div>@@ -1358,13 +1360,13 @@ export default function CoWriterPage() {onChange={(e) => setInstruction(e.target.value)}rows={4}className="w-full rounded-lg border border-[var(--border)] bg-[var(--background)] px-3 py-2 text-sm text-[var(--foreground)] outline-none focus:border-[var(--primary)]"- placeholder="Describe how you want the text edited..."+ placeholder={t("Describe how you want the text edited...")}/><div className="grid grid-cols-2 gap-3"><div><label className="mb-1 block text-[10px] font-medium uppercase tracking-wider text-[var(--muted-foreground)]">- Source+ {t("Source")}</label><selectvalue={source}@@ -1373,14 +1375,14 @@ export default function CoWriterPage() {}className="w-full rounded-md border border-[var(--border)] bg-[var(--background)] px-2 py-1.5 text-xs text-[var(--foreground)] outline-none focus:border-[var(--primary)]">- <option value="none">None</option>- <option value="rag">Knowledge Base</option>- <option value="web">Web Search</option>+ <option value="none">{t("None")}</option>+ <option value="rag">{t("Knowledge Base")}</option>+ <option value="web">{t("Web Search")}</option></select></div><div><label className="mb-1 block text-[10px] font-medium uppercase tracking-wider text-[var(--muted-foreground)]">- Knowledge Base+ {t("Knowledge Base")}</label><selectvalue={kbName}@@ -1388,7 +1390,7 @@ export default function CoWriterPage() {disabled={source !== "rag"}className="w-full rounded-md border border-[var(--border)] bg-[var(--background)] px-2 py-1.5 text-xs text-[var(--foreground)] outline-none focus:border-[var(--primary)] disabled:cursor-not-allowed disabled:opacity-40">- <option value="">Select...</option>+ <option value="">{t("Select...")}</option>{knowledgeBases.map((k) => (<option key={k.name} value={k.name}>{k.name}@@ -1410,7 +1412,7 @@ export default function CoWriterPage() {) : (<Highlighter size={13} />)}- Auto Mark+ {t("Auto Mark")}</button><buttononClick={applyEdit}@@ -1422,7 +1424,7 @@ export default function CoWriterPage() {) : (<ArrowRight size={13} />)}- Apply+ {t("Apply")}</button></div></div>@@ -1433,7 +1435,7 @@ export default function CoWriterPage() {open={showSaveModal}payload={notebookSavePayload}onClose={() => setShowSaveModal(false)}- onSaved={() => setStatus("Added to notebook.")}+ onSaved={() => setStatus(t("Added to notebook."))}/></div>);diff --git a/web/app/(workspace)/page.tsx b/web/app/(workspace)/page.tsxindex 2f1e2aa8b..fad70adcb 100644--- a/web/app/(workspace)/page.tsx+++ b/web/app/(workspace)/page.tsx@@ -709,7 +709,7 @@ export default function HomePage() {style={hasMessages ? { paddingBottom: `${Math.max(composerHeight + 24, 120)}px` } : undefined}><div className="flex items-center justify-between pb-2">- <span className="text-[13px] font-medium text-[var(--muted-foreground)]">{activeCap.label}</span>+ <span className="text-[13px] font-medium text-[var(--muted-foreground)]">{t(activeCap.label)}</span><div className="flex items-center gap-2">{chatSavePayload && (<buttondiff --git a/web/app/(workspace)/playground/page.tsx b/web/app/(workspace)/playground/page.tsxindex 38b4daa32..c20adc2ad 100644--- a/web/app/(workspace)/playground/page.tsx+++ b/web/app/(workspace)/playground/page.tsx@@ -22,6 +22,7 @@ import {X,type LucideIcon,} from "lucide-react";+import { useTranslation } from "react-i18next";import { apiUrl } from "@/lib/api";import AssistantResponse from "@/components/common/AssistantResponse";import MarkdownRenderer from "@/components/common/MarkdownRenderer";@@ -226,6 +227,7 @@ function normalizeDeepQuestionConfig(/* ------------------------------------------------------------------ */function TracePanel({ events }: { events: StreamEvent[] }) {+ const { t } = useTranslation();if (!events.length) return null;const grouped = new Map<string, StreamEvent[]>();@@ -246,7 +248,7 @@ function TracePanel({ events }: { events: StreamEvent[] }) {return (<details key={stage} className="group overflow-hidden rounded-lg border border-[var(--border)] bg-[var(--card)]"><summary className="flex cursor-pointer list-none items-center justify-between gap-3 px-3 py-2 text-[13px] font-medium text-[var(--foreground)] transition-colors hover:bg-[var(--muted)]/50">- <span>{stage === "session" ? "Details" : titleCase(stage)}</span>+ <span>{stage === "session" ? t("Details") : titleCase(stage)}</span><ChevronDown size={13} className="text-[var(--muted-foreground)] transition-transform group-open:rotate-180" /></summary><div className="border-t border-[var(--border)] px-3 py-2.5 space-y-1.5">@@ -263,7 +265,7 @@ function TracePanel({ events }: { events: StreamEvent[] }) {}if (ev.type === "tool_call" || ev.type === "tool_result") return (<div key={`${stage}-tc-${i}`} className="rounded-md border border-[var(--border)] bg-[var(--background)] px-2.5 py-1.5">- <div className="text-[10px] uppercase tracking-wider text-[var(--muted-foreground)]">{ev.type === "tool_call" ? "Tool call" : "Tool result"}</div>+ <div className="text-[10px] uppercase tracking-wider text-[var(--muted-foreground)]">{ev.type === "tool_call" ? t("Tool call") : t("Tool result")}</div><div className="mt-0.5 text-[12px] text-[var(--foreground)]">{ev.content || String(ev.metadata?.tool ?? "")}</div></div>);@@ -283,6 +285,7 @@ function TracePanel({ events }: { events: StreamEvent[] }) {/* ------------------------------------------------------------------ */function ToolExecutor({ tool, knowledgeBases }: { tool: ToolInfo; knowledgeBases: KnowledgeBase[] }) {+ const { t } = useTranslation();const params = tool.parameters ?? [];const [values, setValues] = useState<Record<string, string>>({});const [executing, setExecuting] = useState(false);@@ -385,8 +388,8 @@ function ToolExecutor({ tool, knowledgeBases }: { tool: ToolInfo; knowledgeBasesonChange={(e) => setParam(p.name, e.target.value)}className="w-full rounded-lg border border-[var(--border)] bg-[var(--background)] px-3 py-2 text-[13px] text-[var(--foreground)] outline-none focus:border-[var(--primary)]/40">- <option value="">Select knowledge base...</option>- {knowledgeBases.map((kb) => <option key={kb.name} value={kb.name}>{kb.name}{kb.is_default ? " (default)" : ""}</option>)}+ <option value="">{t("Select knowledge base...")}</option>+ {knowledgeBases.map((kb) => <option key={kb.name} value={kb.name}>{kb.name}{kb.is_default ? ` (${t("default")})` : ""}</option>)}</select>);}@@ -398,7 +401,7 @@ function ToolExecutor({ tool, knowledgeBases }: { tool: ToolInfo; knowledgeBasesonChange={(e) => setParam(p.name, e.target.value)}className="w-full rounded-lg border border-[var(--border)] bg-[var(--background)] px-3 py-2 text-[13px] text-[var(--foreground)] outline-none focus:border-[var(--primary)]/40">- <option value="">Select...</option>+ <option value="">{t("Select...")}</option>{p.enum.map((v) => <option key={v} value={v}>{v}</option>)}</select>);@@ -420,7 +423,7 @@ function ToolExecutor({ tool, knowledgeBases }: { tool: ToolInfo; knowledgeBases{/* Config params (non-query) */}{otherParams.length > 0 && (<div>- <h4 className="mb-2.5 text-[11px] font-semibold uppercase tracking-[0.12em] text-[var(--muted-foreground)]">Parameters</h4>+ <h4 className="mb-2.5 text-[11px] font-semibold uppercase tracking-[0.12em] text-[var(--muted-foreground)]">{t("Parameters")}</h4><div className="grid gap-3 md:grid-cols-2">{otherParams.map((p) => (<div key={`${tool.name}-${p.name}`}>@@ -441,13 +444,13 @@ function ToolExecutor({ tool, knowledgeBases }: { tool: ToolInfo; knowledgeBases<div className="rounded-xl border-2 border-dashed border-[var(--primary)]/30 bg-[var(--primary)]/[0.03] p-4"><label className="mb-2 flex items-center gap-1.5 text-[12px] font-semibold text-[var(--primary)]"><Terminal size={13} />- {queryParam.name === "code" ? "Code input" : "Query input"}+ {queryParam.name === "code" ? t("Code input") : t("Query input")}</label>{queryParam.name === "code" || queryParam.name === "topic" ? (<textareavalue={values[queryParam.name] ?? ""}onChange={(e) => setParam(queryParam.name, e.target.value)}- placeholder={queryParam.description || "Enter your input..."}+ placeholder={queryParam.description || t("Enter your input...")}rows={queryParam.name === "topic" ? 5 : 4}className="w-full resize-none rounded-lg border border-[var(--border)] bg-[var(--card)] px-3 py-2.5 font-mono text-[13px] text-[var(--foreground)] outline-none transition-colors focus:border-[var(--primary)]/40 placeholder:text-[var(--muted-foreground)]"/>@@ -457,7 +460,7 @@ function ToolExecutor({ tool, knowledgeBases }: { tool: ToolInfo; knowledgeBasesvalue={values[queryParam.name] ?? ""}onChange={(e) => setParam(queryParam.name, e.target.value)}onKeyDown={(e) => { if (e.key === "Enter" && !executing) execute(); }}- placeholder={queryParam.description || "Enter your query..."}+ placeholder={queryParam.description || t("Enter your query...")}className="w-full rounded-lg border border-[var(--border)] bg-[var(--card)] px-3 py-2.5 text-[14px] text-[var(--foreground)] outline-none transition-colors focus:border-[var(--primary)]/40 placeholder:text-[var(--muted-foreground)]"/>)}@@ -471,7 +474,7 @@ function ToolExecutor({ tool, knowledgeBases }: { tool: ToolInfo; knowledgeBasesclassName="inline-flex items-center gap-1.5 rounded-lg bg-[var(--primary)] px-4 py-2 text-[13px] font-medium text-[var(--primary-foreground)] transition-opacity disabled:opacity-50">{executing ? <Loader2 size={14} className="animate-spin" /> : <Play size={14} />}- {executing ? "Running..." : "Execute"}+ {executing ? t("Running...") : t("Execute")}</button>{/* Process Logs */}@@ -490,11 +493,11 @@ function ToolExecutor({ tool, knowledgeBases }: { tool: ToolInfo; knowledgeBases<div className="flex items-center gap-2">{result.success ? (<span className="inline-flex items-center gap-1 rounded-md bg-green-50 px-2 py-0.5 text-[11px] font-medium text-green-700 dark:bg-green-950/30 dark:text-green-400">- <Check size={10} /> Success+ <Check size={10} /> {t("Success")}</span>) : (<span className="inline-flex items-center gap-1 rounded-md bg-red-50 px-2 py-0.5 text-[11px] font-medium text-red-700 dark:bg-red-950/30 dark:text-red-400">- <X size={10} /> Failed+ <X size={10} /> {t("Failed")}</span>)}</div>@@ -508,13 +511,13 @@ function ToolExecutor({ tool, knowledgeBases }: { tool: ToolInfo; knowledgeBases{result.sources.length > 0 && (<details className="group rounded-lg border border-[var(--border)] bg-[var(--card)]"><summary className="flex cursor-pointer list-none items-center justify-between px-3 py-2 text-[13px] font-medium text-[var(--foreground)]">- Sources ({result.sources.length})+ {t("Sources")} ({result.sources.length})<ChevronDown size={13} className="text-[var(--muted-foreground)] transition-transform group-open:rotate-180" /></summary><div className="border-t border-[var(--border)] px-3 py-2.5 space-y-1.5">{result.sources.map((s, i) => (<div key={`src-${i}`} className="rounded-md bg-[var(--muted)] px-2.5 py-1.5 text-[12px]">- <div className="font-medium text-[var(--foreground)]">{s.title || s.query || s.type || "Source"}</div>+ <div className="font-medium text-[var(--foreground)]">{s.title || s.query || s.type || t("Source")}</div>{s.url && <div className="mt-0.5 break-all text-[11px] text-[var(--muted-foreground)]">{s.url}</div>}</div>))}@@ -532,6 +535,7 @@ function ToolExecutor({ tool, knowledgeBases }: { tool: ToolInfo; knowledgeBases/* ------------------------------------------------------------------ */function CapabilityResultPanel({ result }: { result: CapabilityExecResult | null | undefined }) {+ const { t } = useTranslation();if (!result) return null;const response = typeof result.data.response === "string" ? result.data.response : "";@@ -545,11 +549,11 @@ function CapabilityResultPanel({ result }: { result: CapabilityExecResult | null<div className="flex items-center gap-2">{result.success ? (<span className="inline-flex items-center gap-1 rounded-md bg-green-50 px-2 py-0.5 text-[11px] font-medium text-green-700 dark:bg-green-950/30 dark:text-green-400">- <Check size={10} /> Success+ <Check size={10} /> {t("Success")}</span>) : (<span className="inline-flex items-center gap-1 rounded-md bg-red-50 px-2 py-0.5 text-[11px] font-medium text-red-700 dark:bg-red-950/30 dark:text-red-400">- <X size={10} /> Failed+ <X size={10} /> {t("Failed")}</span>)}{typeof result.elapsedMs === "number" && (@@ -576,7 +580,7 @@ function CapabilityResultPanel({ result }: { result: CapabilityExecResult | null{extraKeys.length > 0 && response && (<details className="group rounded-lg border border-[var(--border)] bg-[var(--card)]"><summary className="flex cursor-pointer list-none items-center justify-between px-3 py-2 text-[13px] font-medium text-[var(--foreground)]">- Metadata+ {t("Metadata")}<ChevronDown size={13} className="text-[var(--muted-foreground)] transition-transform group-open:rotate-180" /></summary><div className="border-t border-[var(--border)] px-3 py-2.5">@@ -607,6 +611,7 @@ function DeepQuestionTester({config: DeepQuestionFormConfig;onConfigChange: (next: DeepQuestionFormConfig) => void;}) {+ const { t, i18n } = useTranslation();const [messages, setMessages] = useState<TesterMessage[]>([]);const [streaming, setStreaming] = useState(false);const [uploadedPdf, setUploadedPdf] = useState<File | null>(null);@@ -689,7 +694,7 @@ function DeepQuestionTester({content: userContent,tools: enabledTools,knowledge_bases: enabledTools.includes("rag") && knowledgeBase ? [knowledgeBase] : [],- language: "en",+ language: i18n.language,config: requestConfig,attachments,}),@@ -791,7 +796,7 @@ function DeepQuestionTester({: "bg-[var(--muted)] text-[var(--muted-foreground)] hover:text-[var(--foreground)]"}`}>- Custom+ {t("Custom")}</button><buttononClick={() => updateConfig("mode", "mimic")}@@ -801,7 +806,7 @@ function DeepQuestionTester({: "bg-[var(--muted)] text-[var(--muted-foreground)] hover:text-[var(--foreground)]"}`}>- Mimic Exam+ {t("Mimic Exam")}</button></div>@@ -809,20 +814,20 @@ function DeepQuestionTester({<div className="space-y-3"><div><label className="mb-1 block text-[12px] font-medium text-[var(--foreground)]">- Topic+ {t("Topic")}</label><textareavalue={config.topic}onChange={(e) => updateConfig("topic", e.target.value)}rows={3}- placeholder="e.g. Gradient Descent Optimization"+ placeholder={t("e.g. Gradient Descent Optimization")}className="w-full resize-none rounded-lg border border-[var(--border)] bg-[var(--card)] px-3 py-2.5 text-[13px] text-[var(--foreground)] outline-none transition-colors focus:border-[var(--primary)]/40 placeholder:text-[var(--muted-foreground)]"/></div><div className="grid gap-3 md:grid-cols-3"><div><label className="mb-1 block text-[12px] font-medium text-[var(--foreground)]">- Count+ {t("Count")}</label><inputtype="number"@@ -835,44 +840,44 @@ function DeepQuestionTester({</div><div><label className="mb-1 block text-[12px] font-medium text-[var(--foreground)]">- Difficulty+ {t("Difficulty")}</label><selectvalue={config.difficulty}onChange={(e) => updateConfig("difficulty", e.target.value)}className="w-full rounded-lg border border-[var(--border)] bg-[var(--card)] px-3 py-2 text-[13px] text-[var(--foreground)] outline-none focus:border-[var(--primary)]/40">- <option value="auto">Auto</option>- <option value="easy">Easy</option>- <option value="medium">Medium</option>- <option value="hard">Hard</option>+ <option value="auto">{t("Auto")}</option>+ <option value="easy">{t("Easy")}</option>+ <option value="medium">{t("Medium")}</option>+ <option value="hard">{t("Hard")}</option></select></div><div><label className="mb-1 block text-[12px] font-medium text-[var(--foreground)]">- Type+ {t("Type")}</label><selectvalue={config.question_type}onChange={(e) => updateConfig("question_type", e.target.value)}className="w-full rounded-lg border border-[var(--border)] bg-[var(--card)] px-3 py-2 text-[13px] text-[var(--foreground)] outline-none focus:border-[var(--primary)]/40">- <option value="auto">Auto</option>- <option value="choice">Multiple Choice</option>- <option value="written">Written</option>- <option value="coding">Coding</option>+ <option value="auto">{t("Auto")}</option>+ <option value="choice">{t("Multiple Choice")}</option>+ <option value="written">{t("Written")}</option>+ <option value="coding">{t("Coding")}</option></select></div></div><div><label className="mb-1 block text-[12px] font-medium text-[var(--foreground)]">- Preference+ {t("Preference")}</label><textareavalue={config.preference}onChange={(e) => updateConfig("preference", e.target.value)}rows={3}- placeholder="Extra constraints, style, focus areas..."+ placeholder={t("Extra constraints, style, focus areas...")}className="w-full resize-none rounded-lg border border-[var(--border)] bg-[var(--card)] px-3 py-2.5 text-[13px] text-[var(--foreground)] outline-none transition-colors focus:border-[var(--primary)]/40 placeholder:text-[var(--muted-foreground)]"/></div>@@ -881,11 +886,11 @@ function DeepQuestionTester({<div className="space-y-3"><div><label className="mb-1 block text-[12px] font-medium text-[var(--foreground)]">- Upload Exam Paper (PDF)+ {t("Upload Exam Paper (PDF)")}</label><label className="flex cursor-pointer items-center justify-center gap-2 rounded-xl border-2 border-dashed border-[var(--border)] bg-[var(--card)] px-4 py-6 text-[13px] text-[var(--muted-foreground)] transition-colors hover:border-[var(--primary)]/40 hover:text-[var(--foreground)]"><Upload size={16} />- <span>{uploadedPdf ? uploadedPdf.name : "Click to upload PDF"}</span>+ <span>{uploadedPdf ? uploadedPdf.name : t("Click to upload PDF")}</span><inputtype="file"accept=".pdf,application/pdf"@@ -899,11 +904,11 @@ function DeepQuestionTester({</label></div><div className="text-center text-[11px] uppercase tracking-[0.12em] text-[var(--muted-foreground)]">- Or+ {t("Or")}</div><div><label className="mb-1 block text-[12px] font-medium text-[var(--foreground)]">- Pre-parsed Directory+ {t("Pre-parsed Directory")}</label><div className="relative"><FileText size={14} className="pointer-events-none absolute left-3 top-1/2 -translate-y-1/2 text-[var(--muted-foreground)]" />@@ -914,14 +919,14 @@ function DeepQuestionTester({setUploadedPdf(null);updateConfig("paper_path", e.target.value);}}- placeholder="e.g. 2211asm1"+ placeholder={t("e.g. 2211asm1")}className="w-full rounded-lg border border-[var(--border)] bg-[var(--card)] py-2 pl-9 pr-3 text-[13px] text-[var(--foreground)] outline-none transition-colors focus:border-[var(--primary)]/40 placeholder:text-[var(--muted-foreground)]"/></div></div><div className="max-w-xs"><label className="mb-1 block text-[12px] font-medium text-[var(--foreground)]">- Max Questions+ {t("Max Questions")}</label><inputtype="number"@@ -939,7 +944,7 @@ function DeepQuestionTester({{messages.map((msg, i) => (<div key={`${msg.role}-${i}`}><div className="mb-1 text-[10px] uppercase tracking-[0.12em] text-[var(--muted-foreground)]">- {msg.role === "user" ? "You" : "Assistant"}+ {msg.role === "user" ? t("You") : t("Assistant")}</div>{msg.role === "user" ? (<div className="rounded-lg bg-[var(--muted)] px-3 py-2 text-[13px] text-[var(--foreground)]">{msg.content}</div>@@ -949,7 +954,7 @@ function DeepQuestionTester({<ProcessLogslogs={msg.processLogs || []}executing={streaming && i === messages.length - 1}- title="Process"+ title={t("Process")}/>{msg.error && (<div className="rounded-lg border border-red-200 bg-red-50 px-4 py-3 text-[13px] text-red-700 dark:border-red-900 dark:bg-red-950/30 dark:text-red-300">@@ -973,7 +978,7 @@ function DeepQuestionTester({className="inline-flex items-center gap-1.5 rounded-lg bg-[var(--primary)] px-3 py-1.5 text-[12px] font-medium text-[var(--primary-foreground)] disabled:cursor-not-allowed disabled:opacity-40">{streaming ? <Loader2 size={13} className="animate-spin" /> : <Play size={13} />}- {streaming ? "Running..." : "Generate"}+ {streaming ? t("Running...") : t("Generate")}</button></div></div>@@ -993,6 +998,7 @@ function DeepResearchTester({config: DeepResearchFormConfig;onConfigChange: (next: DeepResearchFormConfig) => void;}) {+ const { t, i18n } = useTranslation();const [input, setInput] = useState("");const [messages, setMessages] = useState<TesterMessage[]>([]);const [streaming, setStreaming] = useState(false);@@ -1028,7 +1034,7 @@ function DeepResearchTester({content,tools: enabledTools,knowledge_bases: config.sources.includes("kb") && knowledgeBase ? [knowledgeBase] : [],- language: "en",+ language: i18n.language,config: buildResearchWSConfig(config),}),},@@ -1136,7 +1142,7 @@ function DeepResearchTester({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)]">Sources</div>+ <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);@@ -1153,15 +1159,15 @@ function DeepResearchTester({}`}><Icon size={13} strokeWidth={1.7} />- {source.label}+ {t(source.label)}</button>);})}</div><div className="mt-2 text-[11px] text-[var(--muted-foreground)]">{config.sources.length- ? "Selected sources will be queried during research."- : "No source selected: the run will use llm-only research."}+ ? 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">@@ -1170,7 +1176,7 @@ function DeepResearchTester({onChange={(e) => setInput(e.target.value)}onKeyDown={(e) => { if (e.key === "Enter" && !e.shiftKey) { e.preventDefault(); run(); } }}rows={3}- placeholder="Describe the research topic..."+ placeholder={t("Describe the research topic...")}className="w-full resize-none bg-transparent text-[13px] leading-relaxed text-[var(--foreground)] outline-none placeholder:text-[var(--muted-foreground)]"/><div className="mt-2 flex justify-end">@@ -1180,7 +1186,7 @@ function DeepResearchTester({className="inline-flex items-center gap-1.5 rounded-lg bg-[var(--primary)] px-3 py-1.5 text-[12px] font-medium text-[var(--primary-foreground)] disabled:cursor-not-allowed disabled:opacity-40">{streaming ? <Loader2 size={13} className="animate-spin" /> : <Play size={13} />}- {streaming ? "Running..." : "Run Research"}+ {streaming ? t("Running...") : t("Run Research")}</button></div></div>@@ -1188,7 +1194,7 @@ function DeepResearchTester({{messages.map((msg, i) => (<div key={`${msg.role}-${i}`}><div className="mb-1 text-[10px] uppercase tracking-[0.12em] text-[var(--muted-foreground)]">- {msg.role === "user" ? "You" : "Assistant"}+ {msg.role === "user" ? t("You") : t("Assistant")}</div>{msg.role === "user" ? (<div className="rounded-lg bg-[var(--muted)] px-3 py-2 text-[13px] text-[var(--foreground)]">{msg.content}</div>@@ -1198,7 +1204,7 @@ function DeepResearchTester({<ProcessLogslogs={msg.processLogs || []}executing={streaming && i === messages.length - 1}- title="Process"+ title={t("Process")}/>{msg.error && (<div className="rounded-lg border border-red-200 bg-red-50 px-4 py-3 text-[13px] text-red-700 dark:border-red-900 dark:bg-red-950/30 dark:text-red-300">@@ -1231,6 +1237,7 @@ function CapabilityTester({enabledTools: string[];knowledgeBase: string;}) {+ const { t, i18n } = useTranslation();const [input, setInput] = useState("");const [messages, setMessages] = useState<TesterMessage[]>([]);const [streaming, setStreaming] = useState(false);@@ -1266,7 +1273,7 @@ function CapabilityTester({content,tools: enabledTools,knowledge_bases: enabledTools.includes("rag") && knowledgeBase ? [knowledgeBase] : [],- language: "en",+ language: i18n.language,}),},);@@ -1359,7 +1366,7 @@ function CapabilityTester({{messages.map((msg, i) => (<div key={`${msg.role}-${i}`}><div className="mb-1 text-[10px] uppercase tracking-[0.12em] text-[var(--muted-foreground)]">- {msg.role === "user" ? "You" : "Assistant"}+ {msg.role === "user" ? t("You") : t("Assistant")}</div>{msg.role === "user" ? (<div className="rounded-lg bg-[var(--muted)] px-3 py-2 text-[13px] text-[var(--foreground)]">{msg.content}</div>@@ -1369,7 +1376,7 @@ function CapabilityTester({<ProcessLogslogs={msg.processLogs || []}executing={streaming && i === messages.length - 1}- title="Process"+ title={t("Process")}/>{msg.error && (<div className="rounded-lg border border-red-200 bg-red-50 px-4 py-3 text-[13px] text-red-700 dark:border-red-900 dark:bg-red-950/30 dark:text-red-300">@@ -1391,7 +1398,7 @@ function CapabilityTester({onChange={(e) => setInput(e.target.value)}onKeyDown={(e) => { if (e.key === "Enter" && !e.shiftKey) { e.preventDefault(); send(); } }}rows={2}- placeholder={`Try ${getCapabilityLabel(capability.name)}...`}+ placeholder={`${t("Try")} ${t(getCapabilityLabel(capability.name))}...`}className="w-full resize-none bg-transparent text-[13px] leading-relaxed text-[var(--foreground)] outline-none placeholder:text-[var(--muted-foreground)]"/><div className="mt-2 flex justify-end">@@ -1401,7 +1408,7 @@ function CapabilityTester({className="inline-flex items-center gap-1.5 rounded-lg bg-[var(--primary)] px-3 py-1.5 text-[12px] font-medium text-[var(--primary-foreground)] disabled:cursor-not-allowed disabled:opacity-40">{streaming ? <Loader2 size={13} className="animate-spin" /> : <Play size={13} />}- {streaming ? "Running..." : "Send"}+ {streaming ? t("Running...") : t("Send")}</button></div></div>@@ -1414,6 +1421,7 @@ function CapabilityTester({/* ------------------------------------------------------------------ */export default function PlaygroundPage() {+ const { t } = useTranslation();const [tools, setToolsList] = useState<ToolInfo[]>([]);const [capabilities, setCapabilities] = useState<CapabilityInfo[]>([]);const [knowledgeBases, setKnowledgeBases] = useState<KnowledgeBase[]>([]);@@ -1550,9 +1558,9 @@ export default function PlaygroundPage() {<div className="min-h-screen bg-[var(--background)]"><div className="mx-auto max-w-5xl px-6 py-8"><div className="mb-6">- <h1 className="text-2xl font-bold tracking-tight text-[var(--foreground)]">Playground</h1>+ <h1 className="text-2xl font-bold tracking-tight text-[var(--foreground)]">{t("Playground")}</h1><p className="mt-1 text-[13px] text-[var(--muted-foreground)]">- Explore the building blocks of DeepTutor: reusable tools and higher-level capabilities.+ {t("Explore the building blocks of DeepTutor: reusable tools and higher-level capabilities.")}</p></div>@@ -1568,13 +1576,13 @@ export default function PlaygroundPage() {onClick={() => { setActiveKind("tool"); if (tools.length) setActiveName(tools[0].name); }}className={`rounded-md px-3.5 py-1.5 text-[13px] font-medium transition-all ${activeKind === "tool" ? "bg-[var(--card)] text-[var(--foreground)] shadow-sm" : "text-[var(--muted-foreground)] hover:text-[var(--foreground)]"}`}>- Tools+ {t("Tools")}</button><buttononClick={() => { setActiveKind("capability"); if (capabilityCatalog.length) setActiveName(capabilityCatalog[0].name); }}className={`rounded-md px-3.5 py-1.5 text-[13px] font-medium transition-all ${activeKind === "capability" ? "bg-[var(--card)] text-[var(--foreground)] shadow-sm" : "text-[var(--muted-foreground)] hover:text-[var(--foreground)]"}`}>- Capabilities+ {t("Capabilities")}</button></div>@@ -1585,7 +1593,7 @@ export default function PlaygroundPage() {<div className="mb-3 flex items-center gap-1.5">{activeKind === "tool" ? <Terminal className="h-3.5 w-3.5 text-[var(--muted-foreground)]" /> : <Sparkles className="h-3.5 w-3.5 text-[var(--muted-foreground)]" />}<h2 className="text-[11px] font-semibold uppercase tracking-[0.12em] text-[var(--muted-foreground)]">- {activeKind === "tool" ? "Tools" : "Capabilities"}+ {activeKind === "tool" ? t("Tools") : t("Capabilities")}</h2></div><div className="space-y-1">@@ -1604,7 +1612,7 @@ export default function PlaygroundPage() {<div className="flex items-center gap-1.5"><Icon size={13} strokeWidth={1.7} /><span className="text-[13px] font-medium">- {activeKind === "tool" ? getToolLabel(item.name) : getCapabilityLabel(item.name)}+ {activeKind === "tool" ? t(getToolLabel(item.name)) : t(getCapabilityLabel(item.name))}</span></div><div className={`mt-0.5 line-clamp-2 text-[11px] leading-relaxed ${activeName === item.name ? "text-[var(--primary-foreground)]/70" : "text-[var(--muted-foreground)]"}`}>@@ -1625,9 +1633,9 @@ export default function PlaygroundPage() {<div><div className="flex items-center gap-2 text-[11px] uppercase tracking-[0.12em] text-[var(--muted-foreground)]"><ToolIcon size={13} strokeWidth={1.7} />- Tool+ {t("Tool")}</div>- <h2 className="mt-1 text-xl font-bold tracking-tight text-[var(--foreground)]">{getToolLabel(activeTool.name)}</h2>+ <h2 className="mt-1 text-xl font-bold tracking-tight text-[var(--foreground)]">{t(getToolLabel(activeTool.name))}</h2><p className="mt-2 max-w-2xl text-[13px] leading-relaxed text-[var(--muted-foreground)]">{activeTool.description}</p>@@ -1645,16 +1653,16 @@ export default function PlaygroundPage() {<div><div className="flex items-center gap-2 text-[11px] uppercase tracking-[0.12em] text-[var(--muted-foreground)]"><CapIcon size={13} strokeWidth={1.7} />- Capability+ {t("Capability")}</div>- <h2 className="mt-1 text-xl font-bold tracking-tight text-[var(--foreground)]">{getCapabilityLabel(activeCapability.name)}</h2>+ <h2 className="mt-1 text-xl font-bold tracking-tight text-[var(--foreground)]">{t(getCapabilityLabel(activeCapability.name))}</h2><p className="mt-2 max-w-2xl text-[13px] leading-relaxed text-[var(--muted-foreground)]">{activeCapability.description}</p></div><div>- <h3 className="text-[11px] font-semibold uppercase tracking-[0.12em] text-[var(--muted-foreground)]">Enable Tools</h3>+ <h3 className="text-[11px] font-semibold uppercase tracking-[0.12em] text-[var(--muted-foreground)]">{t("Enable Tools")}</h3>{!!activeCapability.tools_used?.length ? (<div className="mt-2.5 flex flex-wrap gap-1.5">{activeCapability.tools_used.map((tool) => {@@ -1671,32 +1679,32 @@ export default function PlaygroundPage() {}`}><TIcon size={11} strokeWidth={1.7} />- {getToolLabel(tool)}+ {t(getToolLabel(tool))}</button>);})}</div>) : (<p className="mt-2 text-[12px] text-[var(--muted-foreground)]">- This capability runs without optional tools.+ {t("This capability runs without optional tools.")}</p>)}</div>{activeCapabilityConfig?.enabledTools.includes("rag") && (<div>- <h3 className="text-[11px] font-semibold uppercase tracking-[0.12em] text-[var(--muted-foreground)]">Knowledge Base</h3>+ <h3 className="text-[11px] font-semibold uppercase tracking-[0.12em] text-[var(--muted-foreground)]">{t("Knowledge Base")}</h3><div className="mt-2.5 max-w-sm"><selectvalue={activeCapabilityConfig.knowledgeBase}onChange={(e) => setCapabilityKnowledgeBase(e.target.value)}className="w-full rounded-lg border border-[var(--border)] bg-[var(--background)] px-3 py-2 text-[13px] text-[var(--foreground)] outline-none focus:border-[var(--primary)]/40">- <option value="">Select knowledge base...</option>+ <option value="">{t("Select knowledge base...")}</option>{knowledgeBases.map((kb) => (<option key={kb.name} value={kb.name}>{kb.name}- {kb.is_default ? " (default)" : ""}+ {kb.is_default ? ` (${t("default")})` : ""}</option>))}</select>@@ -1706,8 +1714,8 @@ export default function PlaygroundPage() {<div className="border-t border-[var(--border)] pt-6"><div className="mb-3">- <h3 className="text-[14px] font-semibold text-[var(--foreground)]">Try this capability</h3>- <p className="mt-0.5 text-[12px] text-[var(--muted-foreground)]">Run a focused conversation here without leaving the playground.</p>+ <h3 className="text-[14px] font-semibold text-[var(--foreground)]">{t("Try this capability")}</h3>+ <p className="mt-0.5 text-[12px] text-[var(--muted-foreground)]">{t("Run a focused conversation here without leaving the playground.")}</p></div>{activeCapability.name === "deep_question" ? (<DeepQuestionTesterdiff --git a/web/components/Mermaid.tsx b/web/components/Mermaid.tsxindex b3466d645..5285a4929 100644--- a/web/components/Mermaid.tsx+++ b/web/components/Mermaid.tsx@@ -126,7 +126,7 @@ export const Mermaid: React.FC<MermaidProps> = ({ chart, className = "" }) => {if (!stable && !svg) {return (<div className={`my-4 rounded-xl border border-[var(--border)] bg-[var(--muted)]/50 px-4 py-3 text-sm text-[var(--muted-foreground)] ${className}`}>- Rendering diagram...+ {t("Rendering diagram...")}</div>);}diff --git a/web/components/SessionList.tsx b/web/components/SessionList.tsxindex 6090f529a..909d5f37f 100644--- a/web/components/SessionList.tsx+++ b/web/components/SessionList.tsx@@ -2,6 +2,7 @@import { Check, Pencil, Trash2 } from "lucide-react";import { useMemo, useState } from "react";+import { useTranslation } from "react-i18next";import { type SessionSummary } from "@/lib/session-api";type SessionRuntimeStatus =@@ -109,6 +110,7 @@ export default function SessionList({onRename,onDelete,}: SessionListProps) {+ const { t } = useTranslation();const [editingId, setEditingId] = useState<string | null>(null);const [draftTitle, setDraftTitle] = useState("");@@ -164,7 +166,7 @@ export default function SessionList({if (compact) return null;return (<div className="px-3 py-4 text-center text-[11px] text-[var(--muted-foreground)]/70">- No conversations yet+ {t("No conversations yet")}</div>);}@@ -231,7 +233,7 @@ export default function SessionList({<buttononClick={(event) => { event.stopPropagation(); void commitEdit(); }}className="rounded p-0.5 text-[var(--muted-foreground)] hover:text-[var(--foreground)]"- aria-label="Save title"+ aria-label={t("Save title")}><Check size={10} /></button>@@ -239,7 +241,7 @@ export default function SessionList({<buttononClick={(event) => { event.stopPropagation(); startEdit(session); }}className="rounded p-0.5 text-[var(--muted-foreground)] hover:text-[var(--foreground)]"- aria-label="Rename chat"+ aria-label={t("Rename chat")}><Pencil size={10} /></button>@@ -247,7 +249,7 @@ export default function SessionList({<buttononClick={(event) => { event.stopPropagation(); void onDelete(session.session_id); }}className="rounded p-0.5 text-[var(--muted-foreground)] hover:text-[var(--destructive)]"- aria-label="Delete chat"+ aria-label={t("Delete chat")}><Trash2 size={10} /></button>@@ -338,7 +340,7 @@ export default function SessionList({void commitEdit();}}className="rounded p-0.5 text-[var(--muted-foreground)] hover:bg-[var(--background)] hover:text-[var(--foreground)]"- aria-label="Save title"+ aria-label={t("Save title")}><Check size={12} /></button>@@ -349,7 +351,7 @@ export default function SessionList({startEdit(session);}}className="rounded p-0.5 text-[var(--muted-foreground)] hover:bg-[var(--background)] hover:text-[var(--foreground)]"- aria-label="Rename chat"+ aria-label={t("Rename chat")}><Pencil size={11} /></button>@@ -360,7 +362,7 @@ export default function SessionList({void onDelete(session.session_id);}}className="rounded p-0.5 text-[var(--muted-foreground)] hover:bg-[var(--background)] hover:text-[var(--destructive)]"- aria-label="Delete chat"+ aria-label={t("Delete chat")}><Trash2 size={11} /></button>diff --git a/web/components/chat/AtMentionPopup.tsx b/web/components/chat/AtMentionPopup.tsxindex 5564b6f23..29069b49c 100644--- a/web/components/chat/AtMentionPopup.tsx+++ b/web/components/chat/AtMentionPopup.tsx@@ -1,5 +1,7 @@"use client";+import { useTranslation } from "react-i18next";+interface AtMentionPopupProps {open: boolean;onSelectNotebook: () => void;@@ -11,6 +13,8 @@ export default function AtMentionPopup({onSelectNotebook,onSelectHistory,}: AtMentionPopupProps) {+ const { t } = useTranslation();+if (!open) return null;return (@@ -19,13 +23,13 @@ export default function AtMentionPopup({onClick={onSelectNotebook}className="w-full rounded-xl px-3 py-2.5 text-left text-[14px] font-medium text-[var(--foreground)] transition hover:bg-[var(--muted)]/70">- Notebook+ {t("Notebook")}</button><buttononClick={onSelectHistory}className="w-full rounded-xl px-3 py-2.5 text-left text-[14px] font-medium text-[var(--foreground)] transition hover:bg-[var(--muted)]/70">- Chat History+ {t("Chat History")}</button></div>);diff --git a/web/components/chat/HistorySessionPicker.tsx b/web/components/chat/HistorySessionPicker.tsxindex 2a3374e38..09e6a20b4 100644--- a/web/components/chat/HistorySessionPicker.tsx+++ b/web/components/chat/HistorySessionPicker.tsx@@ -2,6 +2,7 @@import { useEffect, useMemo, useState } from "react";import { Check, Loader2, MessageSquare, Search, X } from "lucide-react";+import { useTranslation } from "react-i18next";import { listSessions, type SessionSummary } from "@/lib/session-api";export interface SelectedHistorySession {@@ -25,6 +26,7 @@ export default function HistorySessionPicker({onClose,onApply,}: HistorySessionPickerProps) {+ const { t } = useTranslation();const [sessions, setSessions] = useState<SessionSummary[]>([]);const [selectedIds, setSelectedIds] = useState<string[]>([]);const [query, setQuery] = useState("");@@ -90,10 +92,10 @@ export default function HistorySessionPicker({<div className="flex items-center justify-between border-b border-slate-200 px-5 py-4 dark:border-slate-700"><div><div className="text-[16px] font-semibold text-slate-900 dark:text-slate-100">- Select History Sessions+ {t("Select History Sessions")}</div><div className="mt-1 text-[12px] text-slate-500 dark:text-slate-400">- Choose one or more past conversations to analyze before this turn.+ {t("Choose one or more past conversations to analyze before this turn.")}</div></div><button@@ -111,7 +113,7 @@ export default function HistorySessionPicker({<inputvalue={query}onChange={(event) => setQuery(event.target.value)}- placeholder="Search sessions by title or last message"+ placeholder={t("Search sessions by title or last message")}className="w-full rounded-xl border border-slate-200 bg-white py-2.5 pl-9 pr-3 text-[13px] text-slate-900 outline-none transition focus:border-indigo-300 dark:border-slate-700 dark:bg-slate-900 dark:text-slate-100"/></div>@@ -152,7 +154,7 @@ export default function HistorySessionPicker({<div className="flex items-center gap-2"><span className="inline-flex items-center gap-1 rounded-md bg-sky-100 px-2 py-0.5 text-[11px] font-medium text-sky-700 dark:bg-sky-900/30 dark:text-sky-300"><MessageSquare size={11} />- History+ {t("History")}</span><span className="truncate text-[14px] font-medium text-slate-900 dark:text-slate-100">{session.title || "Untitled session"}@@ -174,7 +176,7 @@ export default function HistorySessionPicker({</div>) : (<div className="px-6 py-14 text-center text-[13px] text-slate-500 dark:text-slate-400">- No matching sessions found.+ {t("No matching sessions found.")}</div>)}</div>diff --git a/web/components/chat/home/ChatComposer.tsx b/web/components/chat/home/ChatComposer.tsxindex a0693b492..bbc26c80c 100644--- a/web/components/chat/home/ChatComposer.tsx+++ b/web/components/chat/home/ChatComposer.tsx@@ -228,8 +228,8 @@ export default function ChatComposer({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)]">{cap.label}</div>- <div className="truncate text-[11px] text-[var(--muted-foreground)]">{cap.description}</div>+ <div className="text-[13px] font-medium text-[var(--foreground)]">{t(cap.label)}</div>+ <div className="truncate text-[11px] text-[var(--muted-foreground)]">{t(cap.description)}</div></div>{selected && <div className="h-1.5 w-1.5 shrink-0 rounded-full bg-[var(--primary)]" />}</button>@@ -345,7 +345,7 @@ export default function ChatComposer({}`}><CapIcon size={14} strokeWidth={1.6} />- <span className="font-medium">{activeCap.label}</span>+ <span className="font-medium">{t(activeCap.label)}</span><ChevronDown size={11} className={`transition-transform ${capMenuOpen ? "rotate-180" : ""}`} /></button>@@ -367,7 +367,7 @@ export default function ChatComposer({}`}><Icon size={11} strokeWidth={1.7} />- {source.label}+ {t(source.label)}</button>);})@@ -387,7 +387,7 @@ export default function ChatComposer({{visibleTools.filter((vt) => selectedTools.has(vt.name)).map((vt, i) => (<span key={vt.name} className="shrink-0 text-[10px] text-[var(--muted-foreground)]/35">{i > 0 && <span className="text-[12px] leading-none">·</span>}- {vt.label}+ {t(vt.label)}</span>))}</div>@@ -411,7 +411,7 @@ export default function ChatComposer({} hover:bg-[var(--muted)]/40`}><Icon size={13} strokeWidth={1.7} />- <span className="flex-1 font-medium">{tool.label}</span>+ <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>);@@ -427,7 +427,7 @@ export default function ChatComposer({value={stateKnowledgeBase}onChange={(e) => onSetKB(e.target.value)}disabled={!ragActive}- title={ragActive ? "Select knowledge base" : "Enable Knowledge Base source first"}+ title={ragActive ? t("Select Knowledge Base") : t("Enable Knowledge Base source first")}className={`h-[28px] appearance-none rounded-full border bg-transparent py-0 pl-2.5 pr-5 text-[11px] outline-none transition-colors ${ragActive? "cursor-pointer border-[var(--border)]/40 text-[var(--muted-foreground)] hover:border-[var(--border)] hover:text-[var(--foreground)]"@@ -435,7 +435,7 @@ export default function ChatComposer({}`}style={{ backgroundImage: ragActive ? "url(\"data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='10' height='10' viewBox='0 0 24 24' fill='none' stroke='%239ca3af' stroke-width='2'%3E%3Cpath d='m6 9 6 6 6-6'/%3E%3C/svg%3E\")" : "none", backgroundRepeat: "no-repeat", backgroundPosition: "right 6px center" }}>- <option value="">{ragActive ? "No KB" : "—"}</option>+ <option value="">{ragActive ? t("No KB") : "—"}</option>{knowledgeBases.map((kb) => (<option key={kb.name} value={kb.name}>{kb.name}</option>))}diff --git a/web/components/chat/home/TracePanels.tsx b/web/components/chat/home/TracePanels.tsxindex f96d8dc11..1ffbe2f30 100644--- a/web/components/chat/home/TracePanels.tsx+++ b/web/components/chat/home/TracePanels.tsx@@ -141,7 +141,7 @@ function isTracePending(events: StreamEvent[]) {return hasRunning && !hasTerminal;}-function getTraceHeader(events: StreamEvent[], nowSeconds?: number, nested?: boolean) {+function getTraceHeader(events: StreamEvent[], nowSeconds?: number, nested?: boolean, t: (key: string) => string = (k) => k) {const label = getTraceLabel(events);const role = getTraceRole(events);const group = getTraceGroup(events);@@ -165,9 +165,9 @@ function getTraceHeader(events: StreamEvent[], nowSeconds?: number, nested?: boo) {title = label;} else if (role === "retrieve") {- title = "Retrieve";+ title = t("Retrieve");} else if (kind === "tool_planning") {- title = "Tool call";+ title = t("Tool call");} else if (group === "react_round") {if (nested) {title = meta.round ? `Round ${meta.round}` : label;@@ -177,13 +177,13 @@ function getTraceHeader(events: StreamEvent[], nowSeconds?: number, nested?: bootitle = [step, round].filter(Boolean).join(" · ");}} else if (role === "plan" && kind === "llm_planning") {- title = "Plan";+ title = t("Plan");} else if (role === "observe" || kind === "llm_observation") {- title = "Observe";+ title = t("Observe");} else if (role === "response" || kind === "llm_final_response") {- title = "Response";+ title = t("Response");} else if (role === "thought" || kind === "llm_reasoning") {- title = "Thought";+ title = t("Thought");} else if (kind === "llm_generation") {if (/^generate\s+/i.test(label)) title = label.replace(/^generate\s+/i, "Generating ");else if (/^write\s+/i.test(label)) title = label.replace(/^write\s+/i, "Writing ");@@ -634,7 +634,7 @@ export function CallTracePanel({const role = getTraceRole(callEvents);const group = getTraceGroup(callEvents);const kind = getTraceCallKind(callEvents);- const header = getTraceHeader(callEvents, nowSeconds, nested);+ const header = getTraceHeader(callEvents, nowSeconds, nested, t);const active = Boolean(isStreaming) && isGloballyLast && isTracePending(callEvents);const isFinalResponse = kind === "llm_final_response";@@ -797,7 +797,7 @@ export function CallTracePanel({}/* Non-round trace (retrieve, tool, etc.) — inline within the step */- const inlineHeader = getTraceHeader(trace.events, nowSeconds, true);+ const inlineHeader = getTraceHeader(trace.events, nowSeconds, true, t);const progressEvts = trace.events.filter((e) =>e.type === "progress" &&diff --git a/web/components/common/ProcessLogs.tsx b/web/components/common/ProcessLogs.tsxindex d854ee29b..61c29b9f9 100644--- a/web/components/common/ProcessLogs.tsx+++ b/web/components/common/ProcessLogs.tsx@@ -2,6 +2,7 @@import { useEffect, useRef, useState } from "react";import { ChevronDown, Loader2, Terminal } from "lucide-react";+import { useTranslation } from "react-i18next";interface ProcessLogsProps {logs: string[];@@ -13,9 +14,11 @@ interface ProcessLogsProps {export default function ProcessLogs({logs,executing,- title = "Process Logs",+ title,emptyMessage = "Waiting for output...",}: ProcessLogsProps) {+ const { t } = useTranslation();+ const resolvedTitle = title ?? t("Process Logs");const [open, setOpen] = useState(true);const logContainerRef = useRef<HTMLDivElement>(null);const stickToBottomRef = useRef(true);@@ -44,7 +47,7 @@ export default function ProcessLogs({<summary className="flex cursor-pointer list-none items-center justify-between gap-3 px-3 py-2 text-[13px] font-medium text-[var(--foreground)] transition-colors hover:bg-[var(--muted)]/50"><span className="inline-flex items-center gap-1.5"><Terminal size={13} strokeWidth={1.7} />- {title}+ {resolvedTitle}{logs.length > 0 && (<span className="rounded-full bg-[var(--muted)] px-1.5 py-0.5 text-[10px] font-normal text-[var(--muted-foreground)]">{logs.length}diff --git a/web/components/common/RichMarkdownRenderer.tsx b/web/components/common/RichMarkdownRenderer.tsxindex eea335b73..65abc3188 100644--- a/web/components/common/RichMarkdownRenderer.tsx+++ b/web/components/common/RichMarkdownRenderer.tsx@@ -4,18 +4,24 @@ import React, { useEffect, useMemo, useState } from "react";import dynamic from "next/dynamic";import ReactMarkdown from "react-markdown";import remarkGfm from "remark-gfm";+import { useTranslation } from "react-i18next";import "katex/dist/katex.min.css";import { processMarkdownContent } from "@/lib/latex";import { normalizeMarkdownForDisplay } from "@/lib/markdown-display";import type { MarkdownRendererProps } from "./MarkdownRenderer";-const LazyMermaid = dynamic(() => import("@/components/Mermaid"), {- ssr: false,- loading: () => (+function MermaidLoading() {+ const { t } = useTranslation();+ return (<div className="my-4 rounded-xl border border-[var(--border)] bg-[var(--muted)]/50 px-4 py-3 text-sm text-[var(--muted-foreground)]">- Rendering diagram...+ {t("Rendering diagram...")}</div>- ),+ );+}++const LazyMermaid = dynamic(() => import("@/components/Mermaid"), {+ ssr: false,+ loading: () => <MermaidLoading />,});const LazyCodeBlock = dynamic(() => import("./RichCodeBlock"), {diff --git a/web/components/math-animator/MathAnimatorConfigPanel.tsx b/web/components/math-animator/MathAnimatorConfigPanel.tsxindex 5191c38ca..ac190a263 100644--- a/web/components/math-animator/MathAnimatorConfigPanel.tsx+++ b/web/components/math-animator/MathAnimatorConfigPanel.tsx@@ -1,5 +1,6 @@"use client";+import { useTranslation } from "react-i18next";import type { MathAnimatorFormConfig } from "@/lib/math-animator-types";import { Field, INPUT_CLS } from "@/components/chat/home/composer-field";@@ -12,6 +13,7 @@ export default function MathAnimatorConfigPanel({value,onChange,}: MathAnimatorConfigPanelProps) {+ const { t } = useTranslation();const update = <K extends keyof MathAnimatorFormConfig>(key: K,val: MathAnimatorFormConfig[K],@@ -25,8 +27,8 @@ export default function MathAnimatorConfigPanel({onChange={(e) => update("output_mode", e.target.value as MathAnimatorFormConfig["output_mode"])}className={`${INPUT_CLS} w-full`}>- <option value="video">Video</option>- <option value="image">Image</option>+ <option value="video">{t("Video")}</option>+ <option value="image">{t("Image")}</option></select></Field>@@ -36,9 +38,9 @@ export default function MathAnimatorConfigPanel({onChange={(e) => update("quality", e.target.value as MathAnimatorFormConfig["quality"])}className={`${INPUT_CLS} w-full`}>- <option value="low">Low</option>- <option value="medium">Medium</option>- <option value="high">High</option>+ <option value="low">{t("Low")}</option>+ <option value="medium">{t("Medium")}</option>+ <option value="high">{t("High")}</option></select></Field>@@ -47,7 +49,7 @@ export default function MathAnimatorConfigPanel({type="text"value={value.style_hint}onChange={(e) => update("style_hint", e.target.value)}- placeholder="Style, pacing, color..."+ placeholder={t("Style, pacing, color...")}className={`${INPUT_CLS} w-full`}/></Field>diff --git a/web/components/math-animator/MathAnimatorViewer.tsx b/web/components/math-animator/MathAnimatorViewer.tsxindex 963464537..a18f169e6 100644--- a/web/components/math-animator/MathAnimatorViewer.tsx+++ b/web/components/math-animator/MathAnimatorViewer.tsx@@ -2,6 +2,7 @@import { useEffect, useMemo, useRef, useState } from "react";import { Code2, Expand, Image as ImageIcon, Timer, Video } from "lucide-react";+import { useTranslation } from "react-i18next";import { apiUrl } from "@/lib/api";import type { MathAnimatorResult } from "@/lib/math-animator-types";@@ -10,6 +11,7 @@ export default function MathAnimatorViewer({}: {result: MathAnimatorResult;}) {+ const { t } = useTranslation();const [fullscreenUrl, setFullscreenUrl] = useState<string | null>(null);const rootRef = useRef<HTMLDivElement>(null);const images = useMemo(@@ -77,7 +79,7 @@ export default function MathAnimatorViewer({<div ref={rootRef} className="mb-3 space-y-3 rounded-2xl border border-[var(--border)] bg-[var(--card)]/70 p-3">{videos.length > 0 ? (<section className="space-y-2">- <Header icon={Video} title="Video Output" />+ <Header icon={Video} title={t("Video Output")} />{videos.map((item) => (<div key={item.url}><video@@ -94,7 +96,7 @@ export default function MathAnimatorViewer({{images.length > 0 ? (<section className="space-y-2">- <Header icon={ImageIcon} title="Image Output" />+ <Header icon={ImageIcon} title={t("Image Output")} /><div className="grid grid-cols-1 gap-2 sm:grid-cols-2">{images.map((item) => (<button@@ -110,7 +112,7 @@ export default function MathAnimatorViewer({/><span className="absolute right-2 top-2 inline-flex items-center gap-1 rounded-md bg-black/55 px-2 py-1 text-[11px] text-white opacity-0 transition-opacity group-hover:opacity-100"><Expand size={12} />- Fullscreen+ {t("Fullscreen")}</span></button>))}@@ -122,7 +124,7 @@ export default function MathAnimatorViewer({<details className="overflow-hidden rounded-xl border border-[var(--border)] bg-[var(--background)]"><summary className="flex cursor-pointer items-center gap-2 px-3 py-2 text-[12px] font-medium text-[var(--foreground)]"><Code2 size={14} />- View Manim Code+ {t("View Manim Code")}</summary><pre className="max-h-[360px] overflow-auto border-t border-[var(--border)] px-3 py-3 font-mono text-[11px] leading-[1.6] text-[var(--foreground)]">{result.code.content}@@ -173,7 +175,7 @@ export default function MathAnimatorViewer({><imgsrc={fullscreenUrl}- alt="Fullscreen math animation output"+ alt={t("Fullscreen math animation output")}className="max-h-full max-w-full object-contain"/></div>diff --git a/web/components/notebook/NotebookRecordPicker.tsx b/web/components/notebook/NotebookRecordPicker.tsxindex f4527d3cc..4e2e715ef 100644--- a/web/components/notebook/NotebookRecordPicker.tsx+++ b/web/components/notebook/NotebookRecordPicker.tsx@@ -2,6 +2,7 @@import { useEffect } from "react";import { X } from "lucide-react";+import { useTranslation } from "react-i18next";import NotebookSelector from "@/app/(workspace)/guide/components/NotebookSelector";import { useNotebookSelection } from "@/app/(workspace)/guide/hooks/useNotebookSelection";import type { SelectedRecord } from "@/app/(workspace)/guide/types";@@ -19,6 +20,7 @@ export default function NotebookRecordPicker({onApply,actionLabel = "Use Selected Records ({n})",}: NotebookRecordPickerProps) {+ const { t } = useTranslation();const {notebooks,expandedNotebooks,@@ -47,10 +49,10 @@ export default function NotebookRecordPicker({<div className="flex items-center justify-between border-b border-slate-200 px-5 py-4 dark:border-slate-700"><div><h2 className="text-lg font-semibold text-slate-900 dark:text-slate-100">- Select Notebook Records+ {t("Select Notebook Records")}</h2><p className="mt-1 text-sm text-slate-500 dark:text-slate-400">- Choose records across one or more notebooks to ground the next request.+ {t("Choose records across one or more notebooks to ground the next request.")}</p></div><buttondiff --git a/web/components/notebook/SaveToNotebookModal.tsx b/web/components/notebook/SaveToNotebookModal.tsxindex d183ee82f..924ce616b 100644--- a/web/components/notebook/SaveToNotebookModal.tsx+++ b/web/components/notebook/SaveToNotebookModal.tsx@@ -2,6 +2,7 @@import { useEffect, useMemo, useState } from "react";import { Loader2, X } from "lucide-react";+import { useTranslation } from "react-i18next";import { apiUrl } from "@/lib/api";import { invalidateNotebookCaches, listNotebooks } from "@/lib/notebook-api";@@ -62,6 +63,7 @@ export default function SaveToNotebookModal({onClose,onSaved,}: SaveToNotebookModalProps) {+ const { t } = useTranslation();const [notebooks, setNotebooks] = useState<NotebookSummary[]>([]);const [selectedIds, setSelectedIds] = useState<string[]>([]);const [title, setTitle] = useState("");@@ -176,13 +178,13 @@ export default function SaveToNotebookModal({<div className="flex items-center justify-between border-b border-slate-200 px-5 py-4 dark:border-slate-700"><div><div className="mb-1 text-[11px] font-semibold uppercase tracking-[0.12em] text-indigo-500">- Notebook Output+ {t("Notebook Output")}</div><h2 className="text-lg font-semibold text-slate-900 dark:text-slate-100">- Save to Notebook+ {t("Save to Notebook")}</h2><p className="text-sm text-slate-500 dark:text-slate-400">- Select one or more notebooks. A summary will be generated automatically.+ {t("Select one or more notebooks. A summary will be generated automatically.")}</p></div><button@@ -196,7 +198,7 @@ export default function SaveToNotebookModal({<div className="space-y-5 bg-slate-50/70 px-5 py-5 dark:bg-slate-950/35"><div><label className="mb-2 block text-sm font-medium text-slate-700 dark:text-slate-200">- Title+ {t("Title")}</label><inputvalue={title}@@ -208,7 +210,7 @@ export default function SaveToNotebookModal({<div><div className="mb-2 flex items-center justify-between"><label className="block text-sm font-medium text-slate-700 dark:text-slate-200">- Notebooks+ {t("Notebooks")}</label>{selectedIds.length > 0 && (<span className="text-xs text-slate-500 dark:text-slate-400">@@ -219,7 +221,7 @@ export default function SaveToNotebookModal({<div className="max-h-64 space-y-2 overflow-y-auto rounded-xl border border-slate-200 bg-white p-2 dark:border-slate-800 dark:bg-slate-900">{notebooks.length === 0 ? (<div className="px-3 py-6 text-center text-sm text-slate-400 dark:text-slate-500">- No notebooks found.+ {t("No notebooks found.")}</div>) : (notebooks.map((notebook) => {@@ -257,12 +259,12 @@ export default function SaveToNotebookModal({<div><div className="mb-2 text-sm font-medium text-slate-700 dark:text-slate-200">- Summary preview+ {t("Summary preview")}</div><div className="min-h-24 rounded-xl border border-slate-200 bg-white px-4 py-3 text-sm text-slate-600 dark:border-slate-800 dark:bg-slate-900 dark:text-slate-300">{summaryPreview || (<span className="text-slate-400 dark:text-slate-500">- The generated summary will appear here during saving.+ {t("The generated summary will appear here during saving.")}</span>)}</div>@@ -280,7 +282,7 @@ export default function SaveToNotebookModal({onClick={onClose}className="rounded-xl px-4 py-2 text-sm text-slate-600 transition hover:bg-slate-100 dark:text-slate-300 dark:hover:bg-slate-800">- Cancel+ {t("Cancel")}</button><buttononClick={handleSave}@@ -288,7 +290,7 @@ export default function SaveToNotebookModal({className="inline-flex items-center gap-2 rounded-xl bg-gradient-to-r from-indigo-400 to-fuchsia-400 px-4 py-2 text-sm font-medium text-white transition hover:from-indigo-500 hover:to-fuchsia-500 disabled:cursor-not-allowed disabled:opacity-60">{isLoading && <Loader2 className="h-4 w-4 animate-spin" />}- Save+ {t("Save")}</button></div></div>diff --git a/web/components/quiz/QuestionFollowupPanel.tsx b/web/components/quiz/QuestionFollowupPanel.tsxindex c2ca19313..4c717460f 100644--- a/web/components/quiz/QuestionFollowupPanel.tsx+++ b/web/components/quiz/QuestionFollowupPanel.tsx@@ -7,6 +7,7 @@ import {SendHorizonal,Sparkles,} from "lucide-react";+import { useTranslation } from "react-i18next";import MarkdownRenderer from "@/components/common/MarkdownRenderer";import type { QuizQuestion } from "@/lib/quiz-types";@@ -47,6 +48,7 @@ export default function QuestionFollowupPanel({onInputChange,onSend,}: QuestionFollowupPanelProps) {+ const { t } = useTranslation();const visibleMessages = thread.messages.filter((message) => message.role !== "system");return (@@ -58,7 +60,7 @@ export default function QuestionFollowupPanel({><div className="min-w-0 flex items-center gap-2 text-[12px] font-medium text-[var(--foreground)]"><MessageSquarePlus size={13} className="text-[var(--primary)]" />- <span>Follow-up Chat</span>+ <span>{t("Follow-up Chat")}</span></div><div className="ml-auto flex min-w-0 items-center gap-1.5"><span className="rounded-full bg-[var(--muted)] px-1.5 py-0.5 text-[10px] uppercase tracking-[0.08em] text-[var(--muted-foreground)]">@@ -93,10 +95,10 @@ export default function QuestionFollowupPanel({<div className="rounded-md border border-dashed border-[var(--border)]/80 bg-[var(--muted)]/14 px-3 py-2.5 text-[12px] leading-[1.55] text-[var(--muted-foreground)]"><div className="mb-1 flex items-center gap-1.5 font-medium text-[var(--foreground)]"><Sparkles size={11} className="text-[var(--primary)]" />- Ask anything about this question+ {t("Ask anything about this question")}</div><div>- Try: why this answer is correct, where your reasoning went wrong, or ask for a cleaner explanation.+ {t("Try: why this answer is correct, where your reasoning went wrong, or ask for a cleaner explanation.")}</div></div>) : (@@ -140,7 +142,7 @@ export default function QuestionFollowupPanel({onChange={(event) => onInputChange(event.target.value)}rows={2}disabled={thread.isStreaming}- placeholder="Ask a follow-up question about this item..."+ placeholder={t("Ask a follow-up question about this item...")}className="min-h-[56px] flex-1 resize-none rounded-md border border-[var(--border)]/80 bg-[var(--background)] px-3 py-2 text-[13px] text-[var(--foreground)] outline-none transition-colors placeholder:text-[var(--muted-foreground)] focus:border-[var(--primary)]/35"/><button@@ -153,7 +155,7 @@ export default function QuestionFollowupPanel({) : (<SendHorizonal size={11} />)}- Send+ {t("Send")}</button></div></div>diff --git a/web/components/quiz/QuizConfigPanel.tsx b/web/components/quiz/QuizConfigPanel.tsxindex ec0ee322b..75178af6d 100644--- a/web/components/quiz/QuizConfigPanel.tsx+++ b/web/components/quiz/QuizConfigPanel.tsx@@ -2,6 +2,7 @@import { useRef, useState } from "react";import { FileText, Upload, X } from "lucide-react";+import { useTranslation } from "react-i18next";import type { DeepQuestionFormConfig, DeepQuestionMode } from "@/lib/quiz-types";import { Field, INPUT_CLS } from "@/components/chat/home/composer-field";@@ -18,6 +19,7 @@ export default function QuizConfigPanel({uploadedPdf,onUploadPdf,}: QuizConfigPanelProps) {+ const { t } = useTranslation();const fileRef = useRef<HTMLInputElement>(null);const [dragOver, setDragOver] = useState(false);@@ -42,7 +44,7 @@ export default function QuizConfigPanel({: "text-[var(--muted-foreground)]/50 hover:text-[var(--muted-foreground)]"}`}>- {m === "custom" ? "Custom" : "Mimic Paper"}+ {m === "custom" ? t("Custom") : t("Mimic Paper")}</button>))}</div>@@ -68,10 +70,10 @@ export default function QuizConfigPanel({onChange={(e) => update("difficulty", e.target.value)}className={`${INPUT_CLS} w-full`}>- <option value="auto">Auto</option>- <option value="easy">Easy</option>- <option value="medium">Medium</option>- <option value="hard">Hard</option>+ <option value="auto">{t("Auto")}</option>+ <option value="easy">{t("Easy")}</option>+ <option value="medium">{t("Medium")}</option>+ <option value="hard">{t("Hard")}</option></select></Field>@@ -81,10 +83,10 @@ export default function QuizConfigPanel({onChange={(e) => update("question_type", e.target.value)}className={`${INPUT_CLS} w-full`}>- <option value="auto">Auto</option>- <option value="choice">Multiple Choice</option>- <option value="written">Written</option>- <option value="coding">Coding</option>+ <option value="auto">{t("Auto")}</option>+ <option value="choice">{t("Multiple Choice")}</option>+ <option value="written">{t("Written")}</option>+ <option value="coding">{t("Coding")}</option></select></Field>@@ -93,7 +95,7 @@ export default function QuizConfigPanel({type="text"value={value.preference}onChange={(e) => update("preference", e.target.value)}- placeholder="Extra constraints..."+ placeholder={t("Extra constraints...")}className={`${INPUT_CLS} w-full`}/></Field>@@ -109,7 +111,7 @@ export default function QuizConfigPanel({type="button"onClick={() => onUploadPdf(null)}className="ml-auto shrink-0 text-[var(--muted-foreground)]/40 transition-colors hover:text-[var(--foreground)]"- aria-label="Remove PDF"+ aria-label={t("Remove PDF")}><X size={11} /></button>@@ -137,7 +139,7 @@ export default function QuizConfigPanel({}}><Upload size={11} />- <span>Upload PDF</span>+ <span>{t("Upload PDF")}</span><inputref={fileRef}type="file"@@ -164,7 +166,7 @@ export default function QuizConfigPanel({onUploadPdf(null);update("paper_path", e.target.value);}}- placeholder="e.g. 2211asm1"+ placeholder={t("e.g. 2211asm1")}className={`${INPUT_CLS} w-full`}/></Field>diff --git a/web/components/quiz/QuizViewer.tsx b/web/components/quiz/QuizViewer.tsxindex ec5de2a51..ef3a1c61c 100644--- a/web/components/quiz/QuizViewer.tsx+++ b/web/components/quiz/QuizViewer.tsx@@ -2,6 +2,7 @@import { useCallback, useEffect, useMemo, useRef, useState } from "react";import { Check, ChevronLeft, ChevronRight, Eye, RotateCcw } from "lucide-react";+import { useTranslation } from "react-i18next";import MarkdownRenderer from "@/components/common/MarkdownRenderer";import QuestionFollowupPanel, {type FollowupThreadState,@@ -75,6 +76,7 @@ export default function QuizViewer({sessionId,language = "en",}: QuizViewerProps) {+ const { t } = useTranslation();const [idx, setIdx] = useState(0);const [answers, setAnswers] = useState<Record<number, AnswerState>>({});const [threads, setThreads] = useState<Record<string, FollowupThreadState>>({});@@ -499,7 +501,7 @@ export default function QuizViewer({disabled={ans.submitted}rows={3}placeholder={- q.question_type === "coding" ? "Write your code here..." : "Type your answer..."+ q.question_type === "coding" ? t("Write your code here...") : t("Type your answer...")}className={`w-full resize-none rounded-lg border px-3 py-2 text-[13px] outline-none transition-colors placeholder:text-[var(--muted-foreground)] ${ans.submitted@@ -518,7 +520,7 @@ export default function QuizViewer({className="inline-flex items-center gap-1.5 rounded-lg bg-[var(--primary)] px-3 py-1.5 text-[12px] font-medium text-white transition-opacity disabled:opacity-30"><Eye size={13} />- Check Answer+ {t("Check Answer")}</button>) : (<>@@ -530,7 +532,7 @@ export default function QuizViewer({: "bg-red-100 text-red-700 dark:bg-red-950/30 dark:text-red-400"}`}>- {isCorrect ? "Correct" : "Incorrect"}+ {isCorrect ? t("Correct") : t("Incorrect")}</span>)}<button@@ -538,7 +540,7 @@ export default function QuizViewer({className="inline-flex items-center gap-1 rounded-lg bg-[var(--muted)] px-2.5 py-1.5 text-[12px] font-medium text-[var(--muted-foreground)] transition-colors hover:text-[var(--foreground)]"><RotateCcw size={11} />- Retry+ {t("Retry")}</button></>)}@@ -549,7 +551,7 @@ export default function QuizViewer({{!isChoice && q.correct_answer && (<div><div className="mb-1 text-[10px] font-semibold uppercase tracking-wider text-[var(--muted-foreground)]">- Reference Answer+ {t("Reference Answer")}</div><div className="text-[13px] leading-relaxed text-[var(--foreground)]"><MarkdownRenderer content={q.correct_answer} variant="prose" />@@ -559,7 +561,7 @@ export default function QuizViewer({{q.explanation && (<div><div className="mb-1 text-[10px] font-semibold uppercase tracking-wider text-[var(--muted-foreground)]">- Explanation+ {t("Explanation")}</div><div className="text-[13px] leading-relaxed text-[var(--muted-foreground)]"><MarkdownRenderer content={q.explanation} variant="prose" />@@ -577,7 +579,7 @@ export default function QuizViewer({className="inline-flex items-center gap-1 rounded-lg px-2 py-1 text-[12px] font-medium text-[var(--muted-foreground)] transition-colors hover:bg-[var(--muted)] hover:text-[var(--foreground)] disabled:opacity-30"><ChevronLeft size={13} />- Previous+ {t("Previous")}</button><div className="mx-3 h-1 flex-1 overflow-hidden rounded-full bg-[var(--muted)]">@@ -592,7 +594,7 @@ export default function QuizViewer({disabled={idx === total - 1}className="inline-flex items-center gap-1 rounded-lg px-2 py-1 text-[12px] font-medium text-[var(--muted-foreground)] transition-colors hover:bg-[var(--muted)] hover:text-[var(--foreground)] disabled:opacity-30">- Next+ {t("Next")}<ChevronRight size={13} /></button></div>diff --git a/web/components/research/ResearchConfigPanel.tsx b/web/components/research/ResearchConfigPanel.tsxindex 004a202a1..2fbca3ba9 100644--- a/web/components/research/ResearchConfigPanel.tsx+++ b/web/components/research/ResearchConfigPanel.tsx@@ -1,6 +1,7 @@"use client";import { ChevronDown } from "lucide-react";+import { useTranslation } from "react-i18next";import type {DeepResearchFormConfig,ResearchDepth,@@ -70,6 +71,7 @@ export default function ResearchConfigPanel({onChange,onToggleCollapsed,}: ResearchConfigPanelProps) {+ const { t } = useTranslation();const update = <K extends keyof DeepResearchFormConfig>(key: K,next: DeepResearchFormConfig[K],@@ -88,7 +90,7 @@ export default function ResearchConfigPanel({size={10}className={`shrink-0 text-[var(--muted-foreground)]/40 transition-transform ${collapsed ? "-rotate-90" : ""}`}/>- <span className="text-[10px] font-medium text-[var(--muted-foreground)]/55">Settings</span>+ <span className="text-[10px] font-medium text-[var(--muted-foreground)]/55">{t("Settings")}</span>{collapsed && summary !== "Incomplete settings" && (<span className="min-w-0 truncate text-[10px] text-[var(--muted-foreground)]/30">— {summary}</span>)}@@ -103,7 +105,7 @@ export default function ResearchConfigPanel({onChange={(e) => update("mode", e.target.value as ResearchMode)}className={`${INPUT_CLS} w-full`}>- <option value="">Select...</option>+ <option value="">{t("Select...")}</option>{MODE_OPTIONS.map((option) => (<option key={option.value} value={option.value}>{option.label}@@ -117,7 +119,7 @@ export default function ResearchConfigPanel({onChange={(e) => update("depth", e.target.value as ResearchDepth)}className={`${INPUT_CLS} w-full`}>- <option value="">Select...</option>+ <option value="">{t("Select...")}</option>{DEPTH_OPTIONS.map((option) => (<option key={option.value} value={option.value}>{option.label}diff --git a/web/components/research/ResearchOutlineEditor.tsx b/web/components/research/ResearchOutlineEditor.tsxindex d1e24cbee..69b549654 100644--- a/web/components/research/ResearchOutlineEditor.tsx+++ b/web/components/research/ResearchOutlineEditor.tsx@@ -2,6 +2,7 @@import { useCallback, useState } from "react";import { Plus, Play, Trash2, Loader2, CheckCircle2 } from "lucide-react";+import { useTranslation } from "react-i18next";import type { OutlineItem } from "@/lib/research-types";type OutlineStatus = "editing" | "researching" | "done";@@ -19,6 +20,7 @@ export default function ResearchOutlineEditor({onConfirm,status: externalStatus,}: ResearchOutlineEditorProps) {+ const { t } = useTranslation();const [items, setItems] = useState<OutlineItem[]>(initialOutline);const [localConfirmed, setLocalConfirmed] = useState(false);@@ -58,7 +60,7 @@ export default function ResearchOutlineEditor({<div className="border-b border-[var(--border)]/20 px-4 py-2.5"><div className="flex items-center justify-between"><h3 className="text-[13px] font-semibold text-[var(--foreground)]">- Research Outline+ {t("Research Outline")}</h3>{statusLabel && (<span className="flex items-center gap-1.5 text-[11px] text-[var(--muted-foreground)]/60">@@ -105,13 +107,13 @@ export default function ResearchOutlineEditor({type="text"value={item.title ?? ""}onChange={(e) => updateItem(index, "title", e.target.value)}- placeholder="Sub-topic title..."+ 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"/><textareavalue={item.overview ?? ""}onChange={(e) => updateItem(index, "overview", e.target.value)}- placeholder="Research direction and focus..."+ 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"/>@@ -139,7 +141,7 @@ export default function ResearchOutlineEditor({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} />- Add sub-topic+ {t("Add sub-topic")}</button><buttontype="button"@@ -148,7 +150,7 @@ export default function ResearchOutlineEditor({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} />- Start Research+ {t("Start Research")}</button></div>)}diff --git a/web/components/sidebar/SidebarShell.tsx b/web/components/sidebar/SidebarShell.tsxindex 7d0fd5cf3..1712981ee 100644--- a/web/components/sidebar/SidebarShell.tsx+++ b/web/components/sidebar/SidebarShell.tsx@@ -17,6 +17,7 @@ import {Settings,type LucideIcon,} from "lucide-react";+import { useTranslation } from "react-i18next";import SessionList from "@/components/SessionList";import { TutorBotRecent } from "@/components/sidebar/TutorBotRecent";import type { SessionSummary } from "@/lib/session-api";@@ -66,6 +67,7 @@ export function SidebarShell({}: SidebarShellProps) {const pathname = usePathname();const router = useRouter();+ const { t } = useTranslation();const [collapsed, setCollapsed] = useState(false);const handleNewChat = () => {@@ -83,7 +85,7 @@ export function SidebarShell({<buttononClick={() => setCollapsed(false)}className="mb-4 rounded-md p-1.5 text-[var(--muted-foreground)] transition-colors hover:text-[var(--foreground)]"- aria-label="Expand sidebar"+ aria-label={t("Expand sidebar")}><PanelLeftOpen size={15} /></button>@@ -91,7 +93,7 @@ export function SidebarShell({<buttononClick={handleNewChat}className="mb-3 rounded-lg p-2 text-[var(--muted-foreground)] transition-colors hover:bg-[var(--background)]/60 hover:text-[var(--foreground)]"- aria-label="New chat"+ aria-label={t("New Chat")}><Plus size={16} strokeWidth={2} /></button>@@ -156,7 +158,7 @@ export function SidebarShell({<buttononClick={() => setCollapsed(true)}className="rounded-md p-1 text-[var(--muted-foreground)] transition-colors hover:text-[var(--foreground)]"- aria-label="Collapse sidebar"+ aria-label={t("Collapse sidebar")}><PanelLeftClose size={15} /></button>@@ -171,7 +173,7 @@ export function SidebarShell({className="flex w-full items-center gap-2.5 rounded-lg px-3 py-2 text-[13.5px] text-[var(--muted-foreground)] transition-colors hover:bg-[var(--background)]/60 hover:text-[var(--foreground)]"><Plus size={16} strokeWidth={2} />- <span>New chat</span>+ <span>{t("New Chat")}</span></button>{PRIMARY_NAV.map((item) => {@@ -189,7 +191,7 @@ export function SidebarShell({}`}><item.icon size={16} strokeWidth={active ? 1.9 : 1.5} />- <span>{item.label}</span>+ <span>{t(item.label)}</span></Link>{hasSessionsBelow && (<div className={`${sessionViewportClassName} overflow-y-auto`}>@@ -229,7 +231,7 @@ export function SidebarShell({}`}><item.icon size={16} strokeWidth={active ? 1.9 : 1.5} />- <span>{item.label}</span>+ <span>{t(item.label)}</span></Link>);})}diff --git a/web/components/sidebar/UtilitySidebar.tsx b/web/components/sidebar/UtilitySidebar.tsxindex 04866cc01..b5cc82588 100644--- a/web/components/sidebar/UtilitySidebar.tsx+++ b/web/components/sidebar/UtilitySidebar.tsx@@ -2,6 +2,7 @@import { useCallback, useEffect, useRef, useState } from "react";import { useRouter } from "next/navigation";+import { useTranslation } from "react-i18next";import { SidebarShell } from "@/components/sidebar/SidebarShell";import { useAppShell } from "@/context/AppShellContext";import {@@ -12,6 +13,7 @@ import {} from "@/lib/session-api";export default function UtilitySidebar() {+ const { t } = useTranslation();const router = useRouter();const { activeSessionId, setActiveSessionId } = useAppShell();const [sessions, setSessions] = useState<SessionSummary[]>([]);@@ -62,7 +64,7 @@ export default function UtilitySidebar() {const handleDeleteSession = useCallback(async (sessionId: string) => {- if (!window.confirm("Delete this chat history?")) return;+ if (!window.confirm(t("Delete this chat history?"))) return;await deleteSession(sessionId);setSessions((prev) => prev.filter((session) => session.session_id !== sessionId));if (activeSessionId === sessionId) {diff --git a/web/components/sidebar/WorkspaceSidebar.tsx b/web/components/sidebar/WorkspaceSidebar.tsxindex 6c5c4c517..0a3a5b395 100644--- a/web/components/sidebar/WorkspaceSidebar.tsx+++ b/web/components/sidebar/WorkspaceSidebar.tsx@@ -2,6 +2,7 @@import { useCallback, useEffect, useRef, useState } from "react";import { usePathname, useRouter } from "next/navigation";+import { useTranslation } from "react-i18next";import { SidebarShell } from "@/components/sidebar/SidebarShell";import { useUnifiedChat } from "@/context/UnifiedChatContext";import {@@ -12,6 +13,7 @@ import {} from "@/lib/session-api";export default function WorkspaceSidebar() {+ const { t } = useTranslation();const pathname = usePathname();const router = useRouter();const { newSession, loadSession, selectedSessionId, sessionStatuses, sidebarRefreshToken } =@@ -86,7 +88,7 @@ export default function WorkspaceSidebar() {const handleDeleteSession = useCallback(async (sessionId: string) => {- if (!window.confirm("Delete this chat history?")) return;+ if (!window.confirm(t("Delete this chat history?"))) return;await deleteSession(sessionId);setSessions((prev) => prev.filter((session) => session.session_id !== sessionId));if (selectedSessionId === sessionId) {diff --git a/web/context/AppShellContext.tsx b/web/context/AppShellContext.tsxindex 049627a74..f40fcd635 100644--- a/web/context/AppShellContext.tsx+++ b/web/context/AppShellContext.tsx@@ -97,11 +97,16 @@ export function AppShellProvider({const [theme, setThemeState] = useState<Theme>(() => {return getStoredTheme() ?? getSystemTheme();});- const [language, setLanguageState] = useState<AppLanguage>(() => readStoredLanguage());+ // Always start with "en" to match SSR; hydrate from localStorage after mount+ const [language, setLanguageState] = useState<AppLanguage>("en");const [activeSessionId, setActiveSessionIdState] = useState<string | null>(() =>readStoredActiveSessionId(),);+ useEffect(() => {+ setLanguageState(readStoredLanguage());+ }, []);+useEffect(() => {return subscribeToThemeChanges((nextTheme) => {setThemeState(nextTheme);diff --git a/web/locales/en/app.json b/web/locales/en/app.jsonindex 53e2b6c03..f37a5e90b 100644--- a/web/locales/en/app.json+++ b/web/locales/en/app.json@@ -31,6 +31,26 @@"Generating questions...": "Generating questions...","View progress in the Logs panel": "View progress in the Logs panel","Select a question to view details": "Select a question to view details",+ "Brainstorm": "Brainstorm",+ "Code": "Code",+ "Reason": "Reason",+ "Arxiv Search": "Arxiv Search",+ "Papers": "Papers",+ "Deep Solve": "Deep Solve",+ "Quiz Generation": "Quiz Generation",+ "Math Animator": "Math Animator",+ "Flexible conversation with any tool": "Flexible conversation with any tool",+ "Multi-step reasoning & problem solving": "Multi-step reasoning & problem solving",+ "Auto-validated question generation": "Auto-validated question generation",+ "Comprehensive multi-agent research": "Comprehensive multi-agent research",+ "Generate math videos or storyboard images": "Generate math videos or storyboard images",+ "No KB": "No KB",+ "Enable Knowledge Base source first": "Enable Knowledge Base source first",+ "Tools": "Tools",+ "Send": "Send",+ "Drop images here": "Drop images here",+ "Attachment preview": "Attachment preview",+ "Describe the math animation or storyboard you want...": "Describe the math animation or storyboard you want...","Smart Solver": "Smart Solver","Vision Solver": "Vision Solver","Upload a Math Problem Image": "Upload a Math Problem Image",@@ -82,6 +102,9 @@"Co-Writer": "Co-Writer","Intelligent markdown editor with AI-powered writing assistance.": "Intelligent markdown editor with AI-powered writing assistance.","Guided Learning": "Guided Learning",+ "TutorBot": "TutorBot",+ "Knowledge": "Knowledge",+ "Memory": "Memory","Knowledge Bases": "Knowledge Bases","Refresh knowledge bases": "Refresh knowledge bases","New Knowledge Base": "New Knowledge Base",@@ -225,6 +248,8 @@"Generate Quiz": "Generate Quiz","Home": "Home","History": "History",+ "What would you like to learn?": "What would you like to learn?",+ "Ask anything — I'm here to help you understand.": "Ask anything — I'm here to help you understand.","Welcome to DeepTutor": "Welcome to DeepTutor","How can I help you today?": "How can I help you today?","Ask anything...": "Ask anything...",@@ -253,6 +278,7 @@"From Knowledge Base": "From Knowledge Base","From Web": "From Web","New Chat": "New Chat",+ "New chat": "New chat","Save to Notebook": "Save to Notebook","Click to edit": "Click to edit","Expand sidebar": "Expand sidebar",@@ -541,6 +567,7 @@"Reasoning": "Reasoning","e.g. 2211asm1": "e.g. 2211asm1","Please upload a PDF exam paper": "Please upload a PDF exam paper",+ "Remove PDF": "Remove PDF","Podcast Narration": "Podcast Narration","Click to expand": "Click to expand","Script only (TTS not configured)": "Script only (TTS not configured)",@@ -555,5 +582,280 @@"Podcast Audio": "Podcast Audio","Your browser does not support the audio element.": "Your browser does not support the audio element.","TTS not configured, script generation only.": "TTS not configured, script generation only.",- "After generation, you can play the podcast audio here.": "After generation, you can play the podcast audio here."+ "After generation, you can play the podcast audio here.": "After generation, you can play the podcast audio here.",+ "Cmd+S to save · Markdown supported": "Cmd+S to save · Markdown supported",+ "Refresh from a session or write directly in the editor.": "Refresh from a session or write directly in the editor.",+ "Manage your knowledge bases and notebooks in one place.": "Manage your knowledge bases and notebooks in one place.",+ "Create knowledge base": "Create knowledge base",+ "Knowledge base name": "Knowledge base name",+ "Choose files...": "Choose files...",+ "Create Process": "Create Process",+ "Upload documents": "Upload documents",+ "Select a knowledge base": "Select a knowledge base",+ "No ready knowledge base is available for upload. Create a new KB or reindex legacy KBs first.": "No ready knowledge base is available for upload. Create a new KB or reindex legacy KBs first.",+ "Upload": "Upload",+ "Upload Process": "Upload Process",+ "Knowledge bases": "Knowledge bases",+ "needs reindex": "needs reindex",+ "Set default": "Set default",+ "No knowledge bases yet. Create one to get started.": "No knowledge bases yet. Create one to get started.",+ "Create notebook": "Create notebook",+ "No notebooks yet. Create one to organize outputs.": "No notebooks yet. Create one to organize outputs.",+ "This notebook is empty for now.": "This notebook is empty for now.",+ "Select a notebook to inspect its saved records.": "Select a notebook to inspect its saved records.",+ "Unknown time": "Unknown time",+ "Open chat session": "Open chat session",+ "Open guided learning session": "Open guided learning session",+ "Query:": "Query:",+ "Delete knowledge base \"{{name}}\"?": "Delete knowledge base \"{{name}}\"?",+ "This knowledge base is in legacy index format and needs reindex before upload.": "This knowledge base is in legacy index format and needs reindex before upload.",+ "This knowledge base is currently {{status}} and cannot accept uploads yet.": "This knowledge base is currently {{status}} and cannot accept uploads yet.",+ "1 / 4 — LLM": "1 / 4 — LLM",+ "Configure your language model endpoint. This powers all chat and reasoning.": "Configure your language model endpoint. This powers all chat and reasoning.",+ "2 / 4 — Embedding": "2 / 4 — Embedding",+ "Set the embedding model for knowledge retrieval.": "Set the embedding model for knowledge retrieval.",+ "3 / 4 — Search": "3 / 4 — Search",+ "Optional: add a web search provider for real-time information.": "Optional: add a web search provider for real-time information.",+ "4 / 4 — Complete": "4 / 4 — Complete",+ "When you are ready, click here to test and launch DeepTutor.": "When you are ready, click here to test and launch DeepTutor.",+ "Skip tour": "Skip tour",+ "Got it": "Got it",+ "Passed": "Passed",+ "Failed": "Failed",+ "Skipped": "Skipped",+ "Running tests...": "Running tests...",+ "Test Results": "Test Results",+ "Back to editing": "Back to editing",+ "Launch anyway": "Launch anyway",+ "Confirm & Launch": "Confirm & Launch",+ "Please wait...": "Please wait...",+ "Draft saved": "Draft saved",+ "Applied to .env": "Applied to .env",+ "Diagnostics stream disconnected": "Diagnostics stream disconnected",+ "Failed to complete tour": "Failed to complete tour",+ "Run {{command}} in your terminal.": "Run {{command}} in your terminal.",+ "Run python scripts/start_tour.py in your terminal.": "Run python scripts/start_tour.py in your terminal.",+ "Setup Tour": "Setup Tour",+ "Configure your endpoints below, run tests, then launch DeepTutor.": "Configure your endpoints below, run tests, then launch DeepTutor.",+ "Complete & Launch": "Complete & Launch",+ "Configuration saved": "Configuration saved",+ "Redirecting to DeepTutor in {{count}}s...": "Redirecting to DeepTutor in {{count}}s...",+ "Redirecting...": "Redirecting...",+ "Draft has unsaved changes": "Draft has unsaved changes",+ "All changes saved": "All changes saved",+ "Save Draft": "Save Draft",+ "Complete the tour first": "Complete the tour first",+ "Backend": "Backend",+ "Emb": "Emb",+ "Profile": "Profile",+ "No endpoint": "No endpoint",+ "Delete profile": "Delete profile",+ "Provider Hint / Binding": "Provider Hint / Binding",+ "Select provider...": "Select provider...",+ "Perplexity requires API key. It will fail hard without credentials.": "Perplexity requires API key. It will fail hard without credentials.",+ "Supported provider.": "Supported provider.",+ "Deprecated provider. Switch to brave/tavily/jina/searxng/duckduckgo/perplexity.": "Deprecated provider. Switch to brave/tavily/jina/searxng/duckduckgo/perplexity.",+ "Unsupported provider. Use brave/tavily/jina/searxng/duckduckgo/perplexity.": "Unsupported provider. Use brave/tavily/jina/searxng/duckduckgo/perplexity.",+ "API Version": "API Version",+ "Proxy": "Proxy",+ "Extra Headers (JSON)": "Extra Headers (JSON)",+ "Models": "Models",+ "Label": "Label",+ "Model ID": "Model ID",+ "Dimension": "Dimension",+ "No profiles configured. Add a profile to start.": "No profiles configured. Add a profile to start.",+ "Diagnostics": "Diagnostics",+ "Run test": "Run test",+ "Collapse diagnostics": "Collapse diagnostics",+ "Expand diagnostics": "Expand diagnostics",+ "Streams config snapshot, request target, response summary, and service-specific validation for the active {{service}} profile.": "Streams config snapshot, request target, response summary, and service-specific validation for the active {{service}} profile.",+ "Run Terminal Tour": "Run Terminal Tour",+ "Loading settings...": "Loading settings...",+ "words": "words",+ "chars": "chars",+ "Export Markdown": "Export Markdown",+ "Load Example Template": "Load Example Template",+ "Pro Vide Writing": "Pro Vide Writing",+ "Full Draft": "Full Draft",+ "Editor": "Editor",+ "Collapse editor": "Collapse editor",+ "Start writing in Markdown...": "Start writing in Markdown...",+ "Expand editor": "Expand editor",+ "Expand preview": "Expand preview",+ "Collapse preview": "Collapse preview",+ "Nothing to preview yet.": "Nothing to preview yet.",+ "Tell AI what to do with the selection...": "Tell AI what to do with the selection...",+ "Apply AI edit": "Apply AI edit",+ "{{count}} tools": "{{count}} tools",+ "Mode": "Mode",+ "Trace": "Trace",+ "Thought": "Thought",+ "Thinking...": "Thinking...",+ "Tool": "Tool",+ "Response": "Response",+ "Running tools and preparing the final edit...": "Running tools and preparing the final edit...",+ "Full Draft AI Edit": "Full Draft AI Edit",+ "Describe how you want the text edited...": "Describe how you want the text edited...",+ "Source": "Source",+ "None": "None",+ "Select...": "Select...",+ "Auto Mark": "Auto Mark",+ "Example template is already loaded.": "Example template is already loaded.",+ "Loaded example template.": "Loaded example template.",+ "Applied AI edit to the selection.": "Applied AI edit to the selection.",+ "Applied {{action}} to the full draft.": "Applied {{action}} to the full draft.",+ "Applied auto-mark annotations.": "Applied auto-mark annotations.",+ "Added to notebook.": "Added to notebook.",+ "Please select a text passage first.": "Please select a text passage first.",+ "Please enter an instruction or choose a mode.": "Please enter an instruction or choose a mode.",+ "Please enter an editing instruction first.": "Please enter an editing instruction first.",+ "Co-Writer Draft": "Co-Writer Draft",+ "Undo": "Undo",+ "Redo": "Redo",+ "Heading 1": "Heading 1",+ "Heading 2": "Heading 2",+ "Heading 3": "Heading 3",+ "Heading 4": "Heading 4",+ "Heading 5": "Heading 5",+ "Heading 6": "Heading 6",+ "Bold": "Bold",+ "Italic": "Italic",+ "Strikethrough": "Strikethrough",+ "Inline Code": "Inline Code",+ "Blockquote": "Blockquote",+ "Bullet List": "Bullet List",+ "Numbered List": "Numbered List",+ "Task List": "Task List",+ "Horizontal Rule": "Horizontal Rule",+ "Table": "Table",+ "Link": "Link",+ "Image": "Image",+ "Code Block": "Code Block",+ "Mermaid Diagram": "Mermaid Diagram",+ "Math Block": "Math Block",+ "TutorBot Agents": "TutorBot Agents",+ "Manage your in-process TutorBot instances": "Manage your in-process TutorBot instances",+ "Bots": "Bots",+ "Profiles": "Profiles",+ "Souls": "Souls",+ "New Bot": "New Bot",+ "Create TutorBot": "Create TutorBot",+ "(optional)": "(optional)",+ "e.g. Math Tutor": "e.g. Math Tutor",+ "A brief description of what this bot does": "A brief description of what this bot does",+ "Soul": "Soul",+ "Define the bot's personality, values, and communication style in markdown...": "Define the bot's personality, values, and communication style in markdown...",+ "Pick a soul from the library above, or write your own. Manage the library in the Souls tab.": "Pick a soul from the library above, or write your own. Manage the library in the Souls tab.",+ "Uses default model if empty": "Uses default model if empty",+ "Create & Start": "Create & Start",+ "No TutorBots yet": "No TutorBots yet",+ "Create your first TutorBot to get started.": "Create your first TutorBot to get started.",+ "Stop": "Stop",+ "Permanently delete \"{{name}}\" ({{id}})? This cannot be undone.": "Permanently delete \"{{name}}\" ({{id}})? This cannot be undone.",+ "started {{time}}": "started {{time}}",+ "No bots to configure": "No bots to configure",+ "Create a bot first in the Bots tab.": "Create a bot first in the Bots tab.",+ "Bot": "Bot",+ "Edit {{file}}...": "Edit {{file}}...",+ "Unsaved changes": "Unsaved changes",+ "{{file}} is empty": "{{file}} is empty",+ "Switch to Edit to add content.": "Switch to Edit to add content.",+ "Reusable soul templates for creating TutorBots.": "Reusable soul templates for creating TutorBots.",+ "New Soul": "New Soul",+ "Content": "Content",+ "e.g. Creative Writer": "e.g. Creative Writer",+ "Define the soul in markdown...": "Define the soul in markdown...",+ "No souls yet": "No souls yet",+ "Create your first soul template. Default presets will be seeded automatically on next server restart.": "Create your first soul template. Default presets will be seeded automatically on next server restart.",+ "Delete soul \"{{name}}\"?": "Delete soul \"{{name}}\"?",+ "Send a message to start the conversation.": "Send a message to start the conversation.",+ "Chat with {{name}}": "Chat with {{name}}",+ "Type a message...": "Type a message...",+ "Thinking ({{count}} steps)": "Thinking ({{count}} steps)",+ "Working...": "Working...",+ "Playground": "Playground",+ "Explore the building blocks of DeepTutor: reusable tools and higher-level capabilities.": "Explore the building blocks of DeepTutor: reusable tools and higher-level capabilities.",+ "Capabilities": "Capabilities",+ "Capability": "Capability",+ "Enable Tools": "Enable Tools",+ "This capability runs without optional tools.": "This capability runs without optional tools.",+ "Try this capability": "Try this capability",+ "Run a focused conversation here without leaving the playground.": "Run a focused conversation here without leaving the playground.",+ "Select knowledge base...": "Select knowledge base...",+ "Code input": "Code input",+ "Query input": "Query input",+ "Enter your input...": "Enter your input...",+ "Enter your query...": "Enter your query...",+ "Running...": "Running...",+ "Execute": "Execute",+ "Details": "Details",+ "Tool call": "Tool call",+ "Tool result": "Tool result",+ "Auto": "Auto",+ "Coding": "Coding",+ "Preference": "Preference",+ "Max Questions": "Max Questions",+ "Or": "Or",+ "You": "You",+ "Generate": "Generate",+ "Selected sources will be queried during research.": "Selected sources will be queried during research.",+ "No source selected: the run will use llm-only research.": "No source selected: the run will use llm-only research.",+ "Describe the research topic...": "Describe the research topic...",+ "Run Research": "Run Research",+ "Code Execution": "Code Execution",+ "default": "default",+ "Extra constraints, style, focus areas...": "Extra constraints, style, focus areas...",+ "Try": "Try",+ "No conversations yet": "No conversations yet",+ "Save title": "Save title",+ "Rename chat": "Rename chat",+ "Delete chat": "Delete chat",+ "Notebook": "Notebook",+ "Select History Sessions": "Select History Sessions",+ "Choose one or more past conversations to analyze before this turn.": "Choose one or more past conversations to analyze before this turn.",+ "No matching sessions found.": "No matching sessions found.",+ "Search sessions by title or last message": "Search sessions by title or last message",+ "Retrieve": "Retrieve",+ "Plan": "Plan",+ "Observe": "Observe",+ "Rendering diagram...": "Rendering diagram...",+ "Process Logs": "Process Logs",+ "Raw logs": "Raw logs",+ "Notebook Output": "Notebook Output",+ "Select one or more notebooks. A summary will be generated automatically.": "Select one or more notebooks. A summary will be generated automatically.",+ "Title": "Title",+ "No notebooks found.": "No notebooks found.",+ "Summary preview": "Summary preview",+ "The generated summary will appear here during saving.": "The generated summary will appear here during saving.",+ "Select Notebook Records": "Select Notebook Records",+ "Choose records across one or more notebooks to ground the next request.": "Choose records across one or more notebooks to ground the next request.",+ "Follow-up Chat": "Follow-up Chat",+ "Ask anything about this question": "Ask anything about this question",+ "Try: why this answer is correct, where your reasoning went wrong, or ask for a cleaner explanation.": "Try: why this answer is correct, where your reasoning went wrong, or ask for a cleaner explanation.",+ "Ask a follow-up question about this item...": "Ask a follow-up question about this item...",+ "Mimic Paper": "Mimic Paper",+ "Upload PDF": "Upload PDF",+ "Extra constraints...": "Extra constraints...",+ "Check Answer": "Check Answer",+ "Correct": "Correct",+ "Incorrect": "Incorrect",+ "Retry": "Retry",+ "Reference Answer": "Reference Answer",+ "Previous": "Previous",+ "Write your code here...": "Write your code here...",+ "Type your answer...": "Type your answer...",+ "Research Outline": "Research Outline",+ "Add sub-topic": "Add sub-topic",+ "Sub-topic title...": "Sub-topic title...",+ "Research direction and focus...": "Research direction and focus...",+ "Video": "Video",+ "Low": "Low",+ "High": "High",+ "Style, pacing, color...": "Style, pacing, color...",+ "Fullscreen": "Fullscreen",+ "View Manim Code": "View Manim Code",+ "Video Output": "Video Output",+ "Image Output": "Image Output",+ "Fullscreen math animation output": "Fullscreen math animation output",+ "Delete this chat history?": "Delete this chat history?"}diff --git a/web/locales/zh/app.json b/web/locales/zh/app.jsonindex 8b66e923d..b6c4fe3a7 100644--- a/web/locales/zh/app.json+++ b/web/locales/zh/app.json@@ -31,6 +31,26 @@"Generating questions...": "正在生成题目…","View progress in the Logs panel": "可在日志面板查看进度","Select a question to view details": "请选择一道题查看详情",+ "Brainstorm": "头脑风暴",+ "Code": "代码",+ "Reason": "推理",+ "Arxiv Search": "论文搜索",+ "Papers": "论文",+ "Deep Solve": "深度解题",+ "Quiz Generation": "题目生成",+ "Math Animator": "数学动画",+ "Flexible conversation with any tool": "灵活对话,可使用任意工具",+ "Multi-step reasoning & problem solving": "多步推理与问题求解",+ "Auto-validated question generation": "自动校验的题目生成",+ "Comprehensive multi-agent research": "多智能体综合研究",+ "Generate math videos or storyboard images": "生成数学视频或分镜图",+ "No KB": "无知识库",+ "Enable Knowledge Base source first": "请先启用知识库来源",+ "Tools": "工具",+ "Send": "发送",+ "Drop images here": "将图片拖放到此处",+ "Attachment preview": "附件预览",+ "Describe the math animation or storyboard you want...": "描述你想要的数学动画或分镜…","Smart Solver": "智能解题","Vision Solver": "视觉解题","Upload a Math Problem Image": "上传数学题目图片",@@ -82,6 +102,9 @@"Co-Writer": "智能写作","Intelligent markdown editor with AI-powered writing assistance.": "带 AI 写作辅助的智能 Markdown 编辑器。","Guided Learning": "引导式学习",+ "TutorBot": "辅导机器人",+ "Knowledge": "知识库",+ "Memory": "记忆","Knowledge Bases": "知识库","Refresh knowledge bases": "刷新知识库列表","New Knowledge Base": "新建知识库",@@ -225,6 +248,8 @@"Generate Quiz": "生成测验","Home": "首页","History": "历史记录",+ "What would you like to learn?": "你想学点什么?",+ "Ask anything — I'm here to help you understand.": "随便问——我来帮你搞懂。","Welcome to DeepTutor": "欢迎使用 DeepTutor","How can I help you today?": "今天我能帮您什么?","Ask anything...": "问我任何问题...",@@ -253,6 +278,7 @@"From Knowledge Base": "来自知识库","From Web": "来自网络","New Chat": "新对话",+ "New chat": "新对话","Save to Notebook": "保存到笔记本","Click to edit": "点击编辑","Expand sidebar": "展开侧边栏",@@ -541,6 +567,7 @@"Reasoning": "推理","e.g. 2211asm1": "例如:2211asm1","Please upload a PDF exam paper": "请上传 PDF 试卷",+ "Remove PDF": "移除 PDF","Podcast Narration": "播客/旁白","Click to expand": "点击展开","Script only (TTS not configured)": "仅脚本(未配置 TTS)",@@ -555,5 +582,280 @@"Podcast Audio": "播客音频","Your browser does not support the audio element.": "您的浏览器不支持音频元素。","TTS not configured, script generation only.": "TTS 未配置,仅生成脚本。",- "After generation, you can play the podcast audio here.": "生成后,您可以在这里播放播客音频。"+ "After generation, you can play the podcast audio here.": "生成后,您可以在这里播放播客音频。",+ "Cmd+S to save · Markdown supported": "Cmd+S 保存 · 支持 Markdown",+ "Refresh from a session or write directly in the editor.": "从会话中刷新或直接在编辑器中编写。",+ "Manage your knowledge bases and notebooks in one place.": "在一个地方管理你的知识库和笔记本。",+ "Create knowledge base": "创建知识库",+ "Knowledge base name": "知识库名称",+ "Choose files...": "选择文件…",+ "Create Process": "创建进度",+ "Upload documents": "上传文档",+ "Select a knowledge base": "选择知识库",+ "No ready knowledge base is available for upload. Create a new KB or reindex legacy KBs first.": "没有可用于上传的就绪知识库。请先创建新知识库或重新索引旧知识库。",+ "Upload": "上传",+ "Upload Process": "上传进度",+ "Knowledge bases": "知识库列表",+ "needs reindex": "需要重新索引",+ "Set default": "设为默认",+ "No knowledge bases yet. Create one to get started.": "暂无知识库。创建一个开始使用吧。",+ "Create notebook": "创建笔记本",+ "No notebooks yet. Create one to organize outputs.": "暂无笔记本。创建一个来整理输出内容吧。",+ "This notebook is empty for now.": "该笔记本暂无内容。",+ "Select a notebook to inspect its saved records.": "选择一个笔记本以查看其保存的记录。",+ "Unknown time": "未知时间",+ "Open chat session": "打开聊天会话",+ "Open guided learning session": "打开引导学习会话",+ "Query:": "问题:",+ "Delete knowledge base \"{{name}}\"?": "确定删除知识库「{{name}}」吗?",+ "This knowledge base is in legacy index format and needs reindex before upload.": "该知识库使用旧版索引格式,需要重新索引后才能上传。",+ "This knowledge base is currently {{status}} and cannot accept uploads yet.": "该知识库当前处于{{status}}状态,暂时无法上传。",+ "1 / 4 — LLM": "1 / 4 — LLM",+ "Configure your language model endpoint. This powers all chat and reasoning.": "配置你的语言模型端点,用于驱动所有对话和推理。",+ "2 / 4 — Embedding": "2 / 4 — 向量模型",+ "Set the embedding model for knowledge retrieval.": "设置用于知识检索的向量模型。",+ "3 / 4 — Search": "3 / 4 — 搜索",+ "Optional: add a web search provider for real-time information.": "可选:添加网络搜索提供商以获取实时信息。",+ "4 / 4 — Complete": "4 / 4 — 完成",+ "When you are ready, click here to test and launch DeepTutor.": "准备好后,点击此处测试并启动 DeepTutor。",+ "Skip tour": "跳过引导",+ "Got it": "知道了",+ "Passed": "通过",+ "Failed": "失败",+ "Skipped": "已跳过",+ "Running tests...": "正在运行测试…",+ "Test Results": "测试结果",+ "Back to editing": "返回编辑",+ "Launch anyway": "仍然启动",+ "Confirm & Launch": "确认并启动",+ "Please wait...": "请稍候…",+ "Draft saved": "草稿已保存",+ "Applied to .env": "已应用到 .env",+ "Diagnostics stream disconnected": "诊断流已断开",+ "Failed to complete tour": "完成引导失败",+ "Run {{command}} in your terminal.": "请在终端中运行 {{command}}。",+ "Run python scripts/start_tour.py in your terminal.": "请在终端中运行 python scripts/start_tour.py。",+ "Setup Tour": "设置引导",+ "Configure your endpoints below, run tests, then launch DeepTutor.": "在下方配置你的端点,运行测试,然后启动 DeepTutor。",+ "Complete & Launch": "完成并启动",+ "Configuration saved": "配置已保存",+ "Redirecting to DeepTutor in {{count}}s...": "{{count}} 秒后跳转到 DeepTutor…",+ "Redirecting...": "正在跳转…",+ "Draft has unsaved changes": "草稿有未保存的更改",+ "All changes saved": "所有更改已保存",+ "Save Draft": "保存草稿",+ "Complete the tour first": "请先完成引导",+ "Backend": "后端",+ "Emb": "向量",+ "Profile": "配置文件",+ "No endpoint": "未设置端点",+ "Delete profile": "删除配置文件",+ "Provider Hint / Binding": "提供商提示 / 绑定",+ "Select provider...": "选择提供商...",+ "Perplexity requires API key. It will fail hard without credentials.": "Perplexity 需要 API 密钥,缺少凭证将无法使用。",+ "Supported provider.": "受支持的提供商。",+ "Deprecated provider. Switch to brave/tavily/jina/searxng/duckduckgo/perplexity.": "已弃用的提供商。请切换到 brave/tavily/jina/searxng/duckduckgo/perplexity。",+ "Unsupported provider. Use brave/tavily/jina/searxng/duckduckgo/perplexity.": "不受支持的提供商。请使用 brave/tavily/jina/searxng/duckduckgo/perplexity。",+ "API Version": "API 版本",+ "Proxy": "代理",+ "Extra Headers (JSON)": "额外请求头 (JSON)",+ "Models": "模型列表",+ "Label": "标签",+ "Model ID": "模型 ID",+ "Dimension": "维度",+ "No profiles configured. Add a profile to start.": "暂无配置文件。添加一个以开始使用。",+ "Diagnostics": "诊断",+ "Run test": "运行测试",+ "Collapse diagnostics": "收起诊断",+ "Expand diagnostics": "展开诊断",+ "Streams config snapshot, request target, response summary, and service-specific validation for the active {{service}} profile.": "为当前 {{service}} 配置文件流式输出配置快照、请求目标、响应摘要和服务特定验证。",+ "Run Terminal Tour": "运行终端引导",+ "Loading settings...": "加载设置中…",+ "TutorBot Agents": "TutorBot 代理",+ "Manage your in-process TutorBot instances": "管理正在运行的 TutorBot 实例",+ "Bots": "机器人",+ "Profiles": "配置",+ "Souls": "灵魂",+ "New Bot": "新建机器人",+ "Create TutorBot": "创建 TutorBot",+ "(optional)": "(可选)",+ "e.g. Math Tutor": "例如:数学辅导",+ "A brief description of what this bot does": "简要描述该机器人的功能",+ "Soul": "灵魂",+ "Define the bot's personality, values, and communication style in markdown...": "用 Markdown 定义机器人的性格、价值观和沟通风格…",+ "Pick a soul from the library above, or write your own. Manage the library in the Souls tab.": "从上方的灵魂库中选择,或自行编写。可在「灵魂」标签页管理灵魂库。",+ "Uses default model if empty": "留空则使用默认模型",+ "Create & Start": "创建并启动",+ "No TutorBots yet": "暂无 TutorBot",+ "Create your first TutorBot to get started.": "创建你的第一个 TutorBot 开始使用。",+ "Stop": "停止",+ "Permanently delete \"{{name}}\" ({{id}})? This cannot be undone.": "永久删除「{{name}}」({{id}})?此操作不可撤销。",+ "started {{time}}": "启动于 {{time}}",+ "No bots to configure": "没有可配置的机器人",+ "Create a bot first in the Bots tab.": "请先在「机器人」标签页创建一个机器人。",+ "Bot": "机器人",+ "Edit {{file}}...": "编辑 {{file}}…",+ "Unsaved changes": "有未保存的更改",+ "{{file}} is empty": "{{file}} 为空",+ "Switch to Edit to add content.": "切换到编辑模式以添加内容。",+ "Reusable soul templates for creating TutorBots.": "可复用的灵魂模板,用于创建 TutorBot。",+ "New Soul": "新建灵魂",+ "Content": "内容",+ "e.g. Creative Writer": "例如:创意写手",+ "Define the soul in markdown...": "用 Markdown 定义灵魂…",+ "No souls yet": "暂无灵魂模板",+ "Create your first soul template. Default presets will be seeded automatically on next server restart.": "创建你的第一个灵魂模板。默认预设将在下次服务器重启时自动填充。",+ "Delete soul \"{{name}}\"?": "删除灵魂「{{name}}」?",+ "Send a message to start the conversation.": "发送消息开始对话。",+ "Chat with {{name}}": "与 {{name}} 聊天",+ "Type a message...": "输入消息…",+ "Thinking ({{count}} steps)": "思考中({{count}} 步)",+ "Working...": "处理中…",+ "Thinking...": "思考中…",+ "words": "词",+ "chars": "字符",+ "Export Markdown": "导出 Markdown",+ "Load Example Template": "加载示例模板",+ "Pro Vide Writing": "Pro Vide Writing",+ "Full Draft": "全文",+ "Editor": "编辑器",+ "Collapse editor": "收起编辑器",+ "Start writing in Markdown...": "开始用 Markdown 写作…",+ "Expand editor": "展开编辑器",+ "Expand preview": "展开预览",+ "Collapse preview": "收起预览",+ "Nothing to preview yet.": "暂无内容可预览。",+ "Tell AI what to do with the selection...": "告诉 AI 如何处理所选内容…",+ "Apply AI edit": "应用 AI 编辑",+ "{{count}} tools": "{{count}} 个工具",+ "Mode": "模式",+ "Trace": "追踪",+ "Thought": "思考",+ "Tool": "工具",+ "Response": "回复",+ "Running tools and preparing the final edit...": "正在运行工具并准备最终编辑…",+ "Full Draft AI Edit": "全文 AI 编辑",+ "Describe how you want the text edited...": "描述你想如何编辑文本…",+ "Source": "来源",+ "None": "无",+ "Select...": "选择…",+ "Auto Mark": "自动批注",+ "Example template is already loaded.": "示例模板已加载。",+ "Loaded example template.": "已加载示例模板。",+ "Applied AI edit to the selection.": "已将 AI 编辑应用到所选内容。",+ "Applied {{action}} to the full draft.": "已对全文草稿执行{{action}}。",+ "Applied auto-mark annotations.": "已应用自动批注。",+ "Added to notebook.": "已添加到笔记本。",+ "Please select a text passage first.": "请先选择一段文本。",+ "Please enter an instruction or choose a mode.": "请输入指令或选择一种模式。",+ "Please enter an editing instruction first.": "请先输入编辑指令。",+ "Co-Writer Draft": "智能写作草稿",+ "Undo": "撤销",+ "Redo": "重做",+ "Heading 1": "标题 1",+ "Heading 2": "标题 2",+ "Heading 3": "标题 3",+ "Heading 4": "标题 4",+ "Heading 5": "标题 5",+ "Heading 6": "标题 6",+ "Bold": "粗体",+ "Italic": "斜体",+ "Strikethrough": "删除线",+ "Inline Code": "行内代码",+ "Blockquote": "引用",+ "Bullet List": "无序列表",+ "Numbered List": "有序列表",+ "Task List": "任务列表",+ "Horizontal Rule": "分割线",+ "Table": "表格",+ "Link": "链接",+ "Image": "图片",+ "Code Block": "代码块",+ "Mermaid Diagram": "Mermaid 图表",+ "Math Block": "数学公式",+ "Playground": "实验场",+ "Explore the building blocks of DeepTutor: reusable tools and higher-level capabilities.": "探索 DeepTutor 的核心模块:可复用工具与高级能力。",+ "Capabilities": "能力",+ "Capability": "能力",+ "Enable Tools": "启用工具",+ "This capability runs without optional tools.": "该能力无需额外工具即可运行。",+ "Try this capability": "试用此能力",+ "Run a focused conversation here without leaving the playground.": "无需离开实验场,在此进行专注对话。",+ "Select knowledge base...": "选择知识库…",+ "Code input": "代码输入",+ "Query input": "查询输入",+ "Enter your input...": "输入内容…",+ "Enter your query...": "输入查询…",+ "Running...": "运行中…",+ "Execute": "执行",+ "Details": "详情",+ "Tool call": "工具调用",+ "Tool result": "工具结果",+ "Auto": "自动",+ "Coding": "编程题",+ "Preference": "偏好",+ "Max Questions": "最大题目数",+ "Or": "或",+ "You": "你",+ "Generate": "生成",+ "Selected sources will be queried during research.": "所选来源将在研究过程中被查询。",+ "No source selected: the run will use llm-only research.": "未选择来源:将仅使用 LLM 进行研究。",+ "Describe the research topic...": "描述研究主题…",+ "Run Research": "开始研究",+ "Code Execution": "代码执行",+ "default": "默认",+ "Extra constraints, style, focus areas...": "额外约束、风格、重点方向…",+ "Try": "试试",+ "No conversations yet": "暂无对话",+ "Save title": "保存标题",+ "Rename chat": "重命名对话",+ "Delete chat": "删除对话",+ "Notebook": "笔记本",+ "Select History Sessions": "选择历史会话",+ "Choose one or more past conversations to analyze before this turn.": "选择一个或多个历史对话,在本轮对话前进行分析。",+ "No matching sessions found.": "未找到匹配的会话。",+ "Search sessions by title or last message": "按标题或最后消息搜索会话",+ "Retrieve": "检索",+ "Plan": "规划",+ "Observe": "观察",+ "Rendering diagram...": "正在渲染图表…",+ "Process Logs": "处理日志",+ "Raw logs": "原始日志",+ "Notebook Output": "笔记本输出",+ "Select one or more notebooks. A summary will be generated automatically.": "选择一个或多个笔记本,系统将自动生成摘要。",+ "Title": "标题",+ "No notebooks found.": "未找到笔记本。",+ "Summary preview": "摘要预览",+ "The generated summary will appear here during saving.": "保存时生成的摘要将显示在此处。",+ "Select Notebook Records": "选择笔记本记录",+ "Choose records across one or more notebooks to ground the next request.": "从一个或多个笔记本中选择记录,作为下一轮请求的依据。",+ "Follow-up Chat": "追问对话",+ "Ask anything about this question": "关于此题可以问任何问题",+ "Try: why this answer is correct, where your reasoning went wrong, or ask for a cleaner explanation.": "试试:为什么这个答案正确、你的推理哪里出错了、或要求更清晰的解释。",+ "Ask a follow-up question about this item...": "就此题提出追问…",+ "Mimic Paper": "仿真试卷",+ "Upload PDF": "上传 PDF",+ "Extra constraints...": "额外约束…",+ "Check Answer": "检查答案",+ "Correct": "正确",+ "Incorrect": "错误",+ "Retry": "重试",+ "Reference Answer": "参考答案",+ "Previous": "上一题",+ "Write your code here...": "在此输入代码…",+ "Type your answer...": "在此输入答案…",+ "Research Outline": "研究大纲",+ "Add sub-topic": "添加子主题",+ "Sub-topic title...": "子主题标题…",+ "Research direction and focus...": "研究方向与重点…",+ "Video": "视频",+ "Low": "低",+ "High": "高",+ "Style, pacing, color...": "风格、节奏、配色…",+ "Fullscreen": "全屏",+ "View Manim Code": "查看 Manim 代码",+ "Video Output": "视频输出",+ "Image Output": "图片输出",+ "Fullscreen math animation output": "全屏数学动画输出",+ "Delete this chat history?": "确定删除此聊天记录吗?"}