Skip to content

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

feat(capabilities): unify infra, merge Animator into Visualize, split settings UI

Bingxi Zhao (Frank)acd0d9329d91
diff --git a/deeptutor/agents/visualize/agents/analysis_agent.py b/deeptutor/agents/visualize/agents/analysis_agent.py
index a49384124..535776b99 100644
--- a/deeptutor/agents/visualize/agents/analysis_agent.py
+++ b/deeptutor/agents/visualize/agents/analysis_agent.py
@@ -35,6 +35,20 @@ class AnalysisAgent(BaseAgent):
render_mode: str = "auto",
attachments: list[Attachment] | None = None,
) -> VisualizationAnalysis:
+ # Manim modes short-circuit the LLM call entirely — MathAnimatorPipeline
+ # has its own ConceptAnalysisAgent that produces the manim-specific
+ # design brief. We only need a stub VisualizationAnalysis here so the
+ # capability runner can dispatch on render_type.
+ if render_mode in ("manim_video", "manim_image"):
+ return VisualizationAnalysis(
+ render_type=render_mode, # type: ignore[arg-type]
+ description="",
+ data_description="",
+ chart_type="",
+ visual_elements=[],
+ rationale=f"User selected {render_mode} explicitly.",
+ )
+
if render_mode in ("svg", "chartjs", "mermaid", "html"):
system_prompt = self.get_prompt("system_fixed")
user_template = self.get_prompt("user_template_fixed")
diff --git a/deeptutor/agents/visualize/models.py b/deeptutor/agents/visualize/models.py
index d0963f692..66ef70866 100644
--- a/deeptutor/agents/visualize/models.py
+++ b/deeptutor/agents/visualize/models.py
@@ -10,10 +10,18 @@ from pydantic import BaseModel, Field
class VisualizationAnalysis(BaseModel):
"""Output of the analysis stage."""
- render_type: Literal["svg", "chartjs", "mermaid", "html"] = Field(
+ render_type: Literal[
+ "svg",
+ "chartjs",
+ "mermaid",
+ "html",
+ "manim_video",
+ "manim_image",
+ ] = Field(
description=(
- "Whether to render as raw SVG, a Chart.js configuration, a Mermaid "
- "diagram, or a self-contained interactive HTML page."
+ "Render output: raw SVG, a Chart.js configuration, a Mermaid "
+ "diagram, a self-contained interactive HTML page, or a Manim "
+ "animation (video) / storyboard image."
),
)
description: str = Field(
diff --git a/deeptutor/agents/visualize/prompts/en/analysis_agent.yaml b/deeptutor/agents/visualize/prompts/en/analysis_agent.yaml
index bf9310164..76b2d0618 100644
--- a/deeptutor/agents/visualize/prompts/en/analysis_agent.yaml
+++ b/deeptutor/agents/visualize/prompts/en/analysis_agent.yaml
@@ -2,21 +2,34 @@ system: |
You are a visualization analyst. Given a user request and conversation history,
decide the best rendering approach and produce a structured analysis.
- Choose between four render types:
- - "svg": Use when the visualization is a custom illustration, schematic, or any
- free-form graphic that requires precise coordinate-level control and does not
- fit a standard chart or structured diagram.
- - "chartjs": Use when the visualization involves quantitative data that fits a
- standard chart type (bar, line, pie, doughnut, radar, scatter, bubble, polar area).
- - "mermaid": Use when the visualization is a structured diagram such as a flowchart,
- sequence diagram, class diagram, state diagram, entity-relationship diagram,
- Gantt chart, mindmap, or any graph that can be expressed with Mermaid.js syntax.
- Prefer mermaid over svg for these structured diagram types.
- - "html": Use when the user wants an interactive learning/explanation page —
- e.g. a draggable demo, an animation with controls, a step-by-step walkthrough,
- clickable practice exercises, or a concept visualization. Prefer the static
- options (svg/chartjs/mermaid) when they are sufficient. Choose html only when
- "user interaction + state changes + mixed text/graphics" is the core experience.
+ Choose between six render types:
+ - "svg": Custom illustration, schematic, or free-form graphic that needs
+ coordinate-level control.
+ - "chartjs": Quantitative data that fits a standard chart type (bar, line,
+ pie, doughnut, radar, scatter, bubble, polar area).
+ - "mermaid": Structured diagram (flowchart, sequence diagram, class diagram,
+ state diagram, ERD, Gantt, mindmap). Prefer mermaid over svg for these
+ structured types.
+ - "html": Interactive learning/explanation page — draggable demo, animation
+ with controls, step-by-step walkthrough, clickable practice exercises.
+ - "manim_video": User explicitly wants a math animation / video showing
+ evolution over time (e.g. derivation unfolding step-by-step, dynamic
+ geometric transformation, motion / limit visualisation). Rendered as MP4
+ via Manim.
+ - "manim_image": User wants Manim-rendered storyboard images (multiple
+ high-quality static frames), not a dynamic video.
+
+ Priority rules:
+ 1. If a static figure (svg/chartjs/mermaid) is enough, prefer it — they're
+ the fastest and cheapest.
+ 2. Choose html only when "user interaction + state changes + mixed
+ text/graphics" is the core experience.
+ 3. Choose manim_video only when the user explicitly wants animation / video
+ / temporal evolution.
+ 4. Choose manim_image only when the user explicitly wants Manim-styled
+ static frames.
+ 5. Do not default to manim just because the topic is mathematical — only
+ when the user genuinely needs dynamic visualisation.
Return your analysis as a single JSON object. Do not include any text outside the JSON.
@@ -29,10 +42,10 @@ user_template: |
Return JSON:
{{
- "render_type": "svg" or "chartjs" or "mermaid" or "html",
+ "render_type": "svg" or "chartjs" or "mermaid" or "html" or "manim_video" or "manim_image",
"description": "High-level description of what the visualization should show",
"data_description": "Description of the data or elements to be visualized",
- "chart_type": "Chart.js chart type if chartjs; Mermaid diagram type if mermaid; an interaction tag (e.g. interactive / animation / walkthrough / quiz) if html; otherwise empty string",
+ "chart_type": "Chart.js chart type if chartjs; Mermaid diagram type if mermaid; an interaction tag (e.g. interactive / animation / walkthrough / quiz) if html; an animation-style tag (e.g. derivation / geometry / transformation) if manim_*; otherwise empty string",
"visual_elements": ["key visual elements or interactive modules to include"],
"rationale": "Why this render_type was chosen"
}}
diff --git a/deeptutor/agents/visualize/prompts/zh/analysis_agent.yaml b/deeptutor/agents/visualize/prompts/zh/analysis_agent.yaml
index 8fa19e8fa..f80fe5a7c 100644
--- a/deeptutor/agents/visualize/prompts/zh/analysis_agent.yaml
+++ b/deeptutor/agents/visualize/prompts/zh/analysis_agent.yaml
@@ -1,11 +1,20 @@
system: |
你是一个可视化分析师。根据用户请求和对话历史,决定最佳的渲染方式并生成结构化分析。
- 在四种渲染类型中选择:
+ 在六种渲染类型中选择:
- "svg":当可视化是自定义插图、示意图或任何需要精确坐标控制的自由图形,且不适合标准图表或结构化图形时使用。
- "chartjs":当可视化涉及可以用标准图表类型(柱状图、折线图、饼图、环形图、雷达图、散点图、气泡图、极坐标图)表示的定量数据时使用。
- "mermaid":当可视化是结构化图形时使用,如流程图、序列图、类图、状态图、实体关系图、甘特图、思维导图或任何可以用 Mermaid.js 语法表达的图形。对于这些结构化图形类型,优先使用 mermaid 而非 svg。
- - "html":当用户需要一个交互式学习/讲解页面,例如可拖动的演示、带控件的动画、分步走读、可点击的练习题、概念可视化页面等。如果一个静态图(svg/chartjs/mermaid)足够表达用户需求,请优先使用前三种;只有当"用户操作 + 状态变化 + 图文混排"是核心体验时才选 html。
+ - "html":当用户需要一个交互式学习/讲解页面,例如可拖动的演示、带控件的动画、分步走读、可点击的练习题、概念可视化页面等。
+ - "manim_video":当用户明确希望生成数学动画/视频,需要时间维度上的演化(例如逐步展开公式推导、动态展示几何变换、可视化运动/极限过程)时使用。这条路径会用 Manim 渲染成 MP4。
+ - "manim_image":当用户希望生成由 Manim 渲染的高质量数学分镜图(多张定格图像),而非动态视频时使用。
+
+ 选择优先级原则:
+ 1. 如果一个静态图(svg/chartjs/mermaid)足够表达用户需求,优先选择静态图——它们最快且最便宜。
+ 2. 只有当"用户操作 + 状态变化 + 图文混排"是核心体验时才选 html。
+ 3. 只有当用户明确表达"动画/视频/演变过程"等时间维度需求,才选 manim_video。
+ 4. 只有当用户明确希望用 Manim 风格生成多张静态分镜,才选 manim_image。
+ 5. 不要因为话题是数学就默认选 manim——除非用户确实需要动态演示。
返回一个 JSON 对象,不要包含 JSON 以外的任何文本。
@@ -18,10 +27,10 @@ user_template: |
返回 JSON:
{{
- "render_type": "svg" 或 "chartjs" 或 "mermaid" 或 "html",
+ "render_type": "svg" 或 "chartjs" 或 "mermaid" 或 "html" 或 "manim_video" 或 "manim_image",
"description": "可视化应展示的内容的高层描述",
"data_description": "要可视化的数据或元素的描述",
- "chart_type": "如果是 chartjs 则填写 Chart.js 图表类型;如果是 mermaid 则填写 Mermaid 图表类型;如果是 html 则填写交互形式(如 interactive / animation / walkthrough / quiz);否则为空字符串",
+ "chart_type": "如果是 chartjs 则填写 Chart.js 图表类型;如果是 mermaid 则填写 Mermaid 图表类型;如果是 html 则填写交互形式(如 interactive / animation / walkthrough / quiz);如果是 manim_* 则填写动画风格简标(如 derivation / geometry / transformation);否则为空字符串",
"visual_elements": ["需要包含的关键视觉元素或交互模块"],
"rationale": "为什么选择这种 render_type"
}}
diff --git a/deeptutor/api/routers/capabilities_settings.py b/deeptutor/api/routers/capabilities_settings.py
new file mode 100644
index 000000000..ff1a3f982
--- /dev/null
+++ b/deeptutor/api/routers/capabilities_settings.py
@@ -0,0 +1,38 @@
+"""Capabilities settings endpoint.
+
+Surfaces the per-capability tunables (temperature, max_tokens, stage
+budgets, iteration limits) currently scattered across
+``data/user/settings/agents.yaml`` and ``data/user/settings/main.yaml``.
+
+Mirrors the pattern used by ``/api/v1/memory/settings``:
+
+* ``GET /settings`` → returns the full schema with defaults merged in.
+* ``PUT /settings`` → merges payload back into both YAML files and
+ returns the new state.
+
+Validation lives in
+:mod:`deeptutor.services.config.capabilities_settings` so the API stays
+a thin transport layer.
+"""
+
+from __future__ import annotations
+
+from typing import Any
+
+from fastapi import APIRouter
+
+router = APIRouter()
+
+
[email protected]("/settings")
+async def get_capabilities_settings_endpoint() -> dict[str, Any]:
+ from deeptutor.services.config.capabilities_settings import capabilities_settings_dict
+
+ return capabilities_settings_dict()
+
+
[email protected]("/settings")
+async def put_capabilities_settings(payload: dict[str, Any]) -> dict[str, Any]:
+ from deeptutor.services.config.capabilities_settings import save_capabilities_settings
+
+ return save_capabilities_settings(payload)
diff --git a/deeptutor/api/routers/tools.py b/deeptutor/api/routers/tools.py
new file mode 100644
index 000000000..cbd6029f7
--- /dev/null
+++ b/deeptutor/api/routers/tools.py
@@ -0,0 +1,194 @@
+"""
+Tools API Router
+================
+
+Read-only listing of the chat agent's built-in tools, used by the Settings UI
+to render the "Tools" sub-page. Returns each tool's definition (name,
+description, parameters) alongside its bilingual prompt hints, so the frontend
+can show authoritative copy without duplicating the catalog.
+"""
+
+from __future__ import annotations
+
+import logging
+from typing import Any, Literal
+
+from fastapi import APIRouter
+from pydantic import BaseModel
+
+from deeptutor.api.routers.settings import get_enabled_optional_tools
+from deeptutor.core.tool_protocol import BaseTool, ToolDefinition, ToolPromptHints
+from deeptutor.tools.builtin import (
+ BUILTIN_TOOL_TYPES,
+ COMING_SOON_TOOL_TYPES,
+ TOOL_ALIASES,
+ USER_TOGGLEABLE_TOOL_NAMES,
+)
+
+logger = logging.getLogger(__name__)
+
+router = APIRouter()
+
+
+class ToolParameterPayload(BaseModel):
+ name: str
+ type: str
+ description: str = ""
+ required: bool = True
+ default: Any = None
+ enum: list[str] | None = None
+
+
+class ToolAliasPayload(BaseModel):
+ name: str
+ description: str = ""
+ input_format: str = ""
+ when_to_use: str = ""
+ phase: str = ""
+
+
+class ToolHintsPayload(BaseModel):
+ short_description: str = ""
+ when_to_use: str = ""
+ input_format: str = ""
+ guideline: str = ""
+ note: str = ""
+ phase: str = ""
+ aliases: list[ToolAliasPayload] = []
+
+
+class BuiltinToolPayload(BaseModel):
+ name: str
+ description: str
+ parameters: list[ToolParameterPayload]
+ hints: dict[Literal["en", "zh"], ToolHintsPayload]
+ aliases: list[str] = []
+ # True iff the user is allowed to switch this tool on/off from the
+ # /settings/tools UI. Locked-on tools (auto-mounted by the chat
+ # pipeline under context gates) report ``False`` and the UI renders
+ # them as informational entries only.
+ toggleable: bool = False
+ # Whether the tool is currently on. For toggleable tools this
+ # reflects the user's saved preference; for locked-on tools this is
+ # always ``True``.
+ enabled: bool = True
+ # ``coming_soon`` tools are NOT registered with the runtime — the chat
+ # agent cannot invoke them. They are listed here only so the settings
+ # page can render a placeholder card explaining the capability is on
+ # the roadmap. The frontend should lock the toggle and show a badge.
+ coming_soon: bool = False
+
+
+class ToolsListResponse(BaseModel):
+ tools: list[BuiltinToolPayload]
+ enabled_optional_tools: list[str]
+
+
+def _serialise_definition(definition: ToolDefinition) -> tuple[str, str, list[ToolParameterPayload]]:
+ params = [
+ ToolParameterPayload(
+ name=p.name,
+ type=p.type,
+ description=p.description,
+ required=p.required,
+ default=p.default,
+ enum=p.enum,
+ )
+ for p in definition.parameters
+ ]
+ return definition.name, definition.description, params
+
+
+def _serialise_hints(hints: ToolPromptHints) -> ToolHintsPayload:
+ return ToolHintsPayload(
+ short_description=hints.short_description,
+ when_to_use=hints.when_to_use,
+ input_format=hints.input_format,
+ guideline=hints.guideline,
+ note=hints.note,
+ phase=hints.phase,
+ aliases=[
+ ToolAliasPayload(
+ name=alias.name,
+ description=alias.description,
+ input_format=alias.input_format,
+ when_to_use=alias.when_to_use,
+ phase=alias.phase,
+ )
+ for alias in hints.aliases
+ ],
+ )
+
+
+def _collect_aliases_for(tool_name: str) -> list[str]:
+ return sorted(alias for alias, (target, _) in TOOL_ALIASES.items() if target == tool_name)
+
+
+def _build_tool_payload(
+ tool: BaseTool,
+ *,
+ enabled_optional: set[str],
+ coming_soon: bool = False,
+) -> BuiltinToolPayload:
+ name, description, parameters = _serialise_definition(tool.get_definition())
+ toggleable = (not coming_soon) and (name in USER_TOGGLEABLE_TOOL_NAMES)
+ if coming_soon:
+ enabled = False
+ elif toggleable:
+ enabled = name in enabled_optional
+ else:
+ enabled = True
+ return BuiltinToolPayload(
+ name=name,
+ description=description,
+ parameters=parameters,
+ hints={
+ "en": _serialise_hints(tool.get_prompt_hints(language="en")),
+ "zh": _serialise_hints(tool.get_prompt_hints(language="zh")),
+ },
+ aliases=_collect_aliases_for(name),
+ toggleable=toggleable,
+ enabled=enabled,
+ coming_soon=coming_soon,
+ )
+
+
[email protected]("", response_model=ToolsListResponse)
+async def list_builtin_tools() -> ToolsListResponse:
+ """Return all built-in tools the chat agent can invoke, plus any
+ coming-soon placeholders for the settings page."""
+ enabled_optional = set(get_enabled_optional_tools())
+ payloads: list[BuiltinToolPayload] = []
+ for tool_type in BUILTIN_TOOL_TYPES:
+ try:
+ instance = tool_type()
+ payloads.append(_build_tool_payload(instance, enabled_optional=enabled_optional))
+ except Exception:
+ logger.exception("Failed to serialise tool %s", tool_type.__name__)
+ for tool_type in COMING_SOON_TOOL_TYPES:
+ try:
+ instance = tool_type()
+ payloads.append(
+ _build_tool_payload(
+ instance,
+ enabled_optional=enabled_optional,
+ coming_soon=True,
+ )
+ )
+ except Exception:
+ logger.exception(
+ "Failed to serialise coming-soon tool %s", tool_type.__name__
+ )
+ # Guard against the unlikely case of name collision (e.g. someone
+ # accidentally registers the same tool both as built-in and coming-soon).
+ seen: set[str] = set()
+ deduped: list[BuiltinToolPayload] = []
+ for payload in payloads:
+ if payload.name in seen:
+ continue
+ seen.add(payload.name)
+ deduped.append(payload)
+ return ToolsListResponse(
+ tools=deduped,
+ enabled_optional_tools=sorted(enabled_optional),
+ )
diff --git a/deeptutor/capabilities/_answer_now.py b/deeptutor/capabilities/_answer_now.py
index ad54ab707..5fbad87fd 100644
--- a/deeptutor/capabilities/_answer_now.py
+++ b/deeptutor/capabilities/_answer_now.py
@@ -17,11 +17,13 @@ manim code, ...). This module provides the shared plumbing:
fast-path output so the user knows which stages were skipped.
The orchestrator no longer re-routes ``answer_now`` to ``chat``; instead
-each capability checks for the payload at the top of ``run()`` and
-dispatches to its own answer-now path. ``chat`` keeps its original
-synthesis behavior; structured-output capabilities (deep_question,
-math_animator, visualize) collapse the remaining stages into a single
-LLM call (or a code-gen + render pair, in math_animator's case).
+each capability that supports it checks for the payload at the top of
+``run()`` and dispatches to its own answer-now path. ``chat`` keeps its
+original synthesis behavior; ``visualize`` / ``math_animator`` collapse
+their remaining stages into a single LLM call (or a code-gen + render
+pair). ``deep_solve`` / ``deep_question`` / ``deep_research`` deliberately
+do not expose Answer Now — their UI gates the button so this module is
+never invoked for them.
"""
from __future__ import annotations
@@ -31,6 +33,7 @@ from typing import Any, AsyncIterator
from deeptutor.core.context import UnifiedContext
from deeptutor.core.stream_bus import StreamBus
from deeptutor.core.trace import build_trace_metadata, merge_trace_metadata, new_call_id
+from deeptutor.services.config import get_chat_params
from deeptutor.services.llm import (
clean_thinking_tags,
get_llm_config,
@@ -169,7 +172,7 @@ async def stream_synthesis(
trace_meta: dict[str, Any],
system_prompt: str,
user_prompt: str,
- max_tokens: int = 1800,
+ max_tokens: int | None = None,
push_content: bool = True,
response_format: dict[str, Any] | None = None,
) -> AsyncIterator[str]:
@@ -180,10 +183,32 @@ async def stream_synthesis(
parse them, e.g. structured JSON outputs). When ``push_content``
is true (default), every chunk is also pushed as a ``CONTENT``
event so the frontend renders the answer live.
+
+ ``temperature`` and the default ``max_tokens`` are sourced from
+ ``capabilities.chat`` in ``agents.yaml`` (the same knobs the chat
+ capability uses for its own answer-now fallback), so users can tune
+ answer-now globally from the Settings UI instead of touching code.
+ Callers may still pass an explicit ``max_tokens`` to override the
+ setting per call site (e.g. visualize bumps it for ``html``).
"""
llm_config = get_llm_config()
model = getattr(llm_config, "model", None)
+ chat_cfg = get_chat_params()
+ try:
+ temperature = float(chat_cfg.get("temperature", 0.2))
+ except (TypeError, ValueError):
+ temperature = 0.2
+ if max_tokens is None:
+ answer_now_cfg = chat_cfg.get("answer_now") or {}
+ if isinstance(answer_now_cfg, dict):
+ try:
+ max_tokens = int(answer_now_cfg.get("max_tokens", 8000))
+ except (TypeError, ValueError):
+ max_tokens = 8000
+ else:
+ max_tokens = 8000
+
await stream.progress(
trace_meta.get("label", "Answer now"),
source=source,
@@ -194,7 +219,7 @@ async def stream_synthesis(
),
)
- extra_kwargs: dict[str, Any] = {"temperature": 0.2}
+ extra_kwargs: dict[str, Any] = {"temperature": temperature}
if model:
extra_kwargs.update(get_token_limit_kwargs(model, max_tokens))
if response_format is not None:
diff --git a/deeptutor/capabilities/_i18n.py b/deeptutor/capabilities/_i18n.py
new file mode 100644
index 000000000..a802ae6f2
--- /dev/null
+++ b/deeptutor/capabilities/_i18n.py
@@ -0,0 +1,54 @@
+"""Shared i18n helper for capability status / UI strings.
+
+Capability ``run()`` methods stream short status messages to the chat UI
+(``stream.thinking``, ``stream.progress``, ``stream.error``). Those strings
+must respect the user's locale. This module wires them into the existing
+``PromptManager`` so each capability can keep its UI copy alongside its
+LLM prompts under ``deeptutor/capabilities/prompts/{en,zh}/<name>.yaml``.
+
+Conventions:
+
+* YAML files contain a single top-level ``status:`` mapping, key → string.
+* Strings may use ``{name}`` placeholders rendered via ``str.format``.
+* Missing keys / files fall back to the ``default`` argument so a new
+ hardcoded string still works while its translation is being added.
+"""
+
+from __future__ import annotations
+
+from typing import Any
+
+from deeptutor.services.prompt import get_prompt_manager
+
+
+class StatusI18n:
+ """Per-capability localized status-string lookup.
+
+ Construct once at the top of ``run()`` with the capability name and
+ ``context.language``, then call ``t(key, default, **kwargs)`` wherever
+ a hardcoded English string was previously emitted.
+ """
+
+ __slots__ = ("_strings",)
+
+ def __init__(self, capability_name: str, language: str) -> None:
+ prompts = get_prompt_manager().load_prompts(
+ module_name="capabilities",
+ agent_name=capability_name,
+ language=language,
+ )
+ raw = prompts.get("status") if isinstance(prompts, dict) else None
+ self._strings: dict[str, Any] = raw if isinstance(raw, dict) else {}
+
+ def t(self, key: str, default: str = "", /, **kwargs: Any) -> str:
+ value = self._strings.get(key)
+ text = value if isinstance(value, str) and value else default
+ if kwargs and text:
+ try:
+ return text.format(**kwargs)
+ except (KeyError, IndexError, ValueError):
+ return text
+ return text
+
+
+__all__ = ["StatusI18n"]
diff --git a/deeptutor/capabilities/_shared.py b/deeptutor/capabilities/_shared.py
new file mode 100644
index 000000000..5c89f2e5a
--- /dev/null
+++ b/deeptutor/capabilities/_shared.py
@@ -0,0 +1,49 @@
+"""Shared plumbing for capability ``run()`` endpoints.
+
+Capabilities all converge on the same final emission:
+
+ await stream.result({"response": ..., ...}, source="<cap>")
+
+The basic chat capability also attaches a per-turn ``cost_summary`` so the
+frontend can render ``$cost · tokens · calls`` in its message footer.
+Several other capabilities used to duplicate that merge inline (solve,
+research, question followup) and the rest skipped it entirely (auto,
+visualize, math_animator), so the footer only appeared for some
+capabilities. This module centralizes the merge + emit so every capability
+emits the same envelope shape.
+"""
+
+from __future__ import annotations
+
+from typing import Any
+
+from deeptutor.core.agentic.usage import UsageTracker
+from deeptutor.core.stream_bus import StreamBus
+
+
+async def emit_capability_result(
+ stream: StreamBus,
+ payload: dict[str, Any],
+ *,
+ source: str,
+ usage: UsageTracker | None = None,
+) -> None:
+ """Emit the final capability result, attaching cost_summary if available.
+
+ ``payload`` is mutated in place: when ``usage`` has at least one
+ recorded call, its ``summary()`` is merged into
+ ``payload["metadata"]["cost_summary"]``. Any pre-existing
+ ``payload["metadata"]`` dict is preserved.
+ """
+ if usage is not None:
+ cs = usage.summary()
+ if cs:
+ meta = payload.get("metadata")
+ if not isinstance(meta, dict):
+ meta = {}
+ payload["metadata"] = meta
+ meta["cost_summary"] = cs
+ await stream.result(payload, source=source)
+
+
+__all__ = ["emit_capability_result"]
diff --git a/deeptutor/capabilities/math_animator.py b/deeptutor/capabilities/math_animator.py
index 5142c38bd..86e24e9ee 100644
--- a/deeptutor/capabilities/math_animator.py
+++ b/deeptutor/capabilities/math_animator.py
@@ -6,7 +6,10 @@ import importlib.util
import time
from typing import Any
+from deeptutor.capabilities._i18n import StatusI18n
+from deeptutor.capabilities._shared import emit_capability_result
from deeptutor.capabilities.request_contracts import get_capability_request_schema
+from deeptutor.core.agentic.usage import UsageTracker
from deeptutor.core.capability_protocol import BaseCapability, CapabilityManifest
from deeptutor.core.context import UnifiedContext
from deeptutor.core.stream_bus import StreamBus
@@ -51,12 +54,14 @@ class MathAnimatorCapability(BaseCapability):
llm_config = get_llm_config()
request_config = validate_math_animator_request_config(context.config_overrides)
+ usage = UsageTracker(model=getattr(llm_config, "model", None))
+ i18n = StatusI18n(self.name, context.language)
pipeline = MathAnimatorPipeline(
api_key=llm_config.api_key,
base_url=llm_config.base_url,
api_version=llm_config.api_version,
language=context.language,
- trace_callback=self._build_trace_bridge(stream),
+ trace_callback=self._build_trace_bridge(stream, i18n=i18n),
)
answer_now_payload = extract_answer_now_context(context)
@@ -67,6 +72,8 @@ class MathAnimatorCapability(BaseCapability):
payload=answer_now_payload,
pipeline=pipeline,
request_config=request_config,
+ usage=usage,
+ i18n=i18n,
)
return
@@ -112,7 +119,7 @@ class MathAnimatorCapability(BaseCapability):
design=design,
)
await stream.progress(
- message="Manim code prepared.",
+ message=i18n.t("code_prepared", "Manim code prepared."),
source=self.name,
stage="code_generation",
)
@@ -120,7 +127,12 @@ class MathAnimatorCapability(BaseCapability):
async def _on_retry(retry_attempt) -> None:
await stream.progress(
- message=f"Retry {retry_attempt.attempt}: {retry_attempt.error}",
+ message=i18n.t(
+ "retry",
+ f"Retry {retry_attempt.attempt}: {retry_attempt.error}",
+ attempt=retry_attempt.attempt,
+ error=retry_attempt.error,
+ ),
source=self.name,
stage="code_retry",
metadata={**render_call_meta, "trace_layer": "raw"},
@@ -148,7 +160,12 @@ class MathAnimatorCapability(BaseCapability):
stage_start = time.perf_counter()
async with stream.stage("code_retry", source=self.name):
await stream.progress(
- message=f"Rendering {request_config.output_mode} with quality={request_config.quality}.",
+ message=i18n.t(
+ "rendering",
+ f"Rendering {request_config.output_mode} with quality={request_config.quality}.",
+ mode=request_config.output_mode,
+ quality=request_config.quality,
+ ),
source=self.name,
stage="code_retry",
metadata={**render_call_meta, "call_state": "running"},
@@ -178,10 +195,16 @@ class MathAnimatorCapability(BaseCapability):
timings["summary"] = round(time.perf_counter() - stage_start, 3)
async with stream.stage("render_output", source=self.name):
+ artifact_count = len(render_result.artifacts)
+ artifact_key = "artifacts_one" if artifact_count == 1 else "artifacts_many"
await stream.progress(
- message=(
- f"Prepared {len(render_result.artifacts)} "
- f"{'artifact' if len(render_result.artifacts) == 1 else 'artifacts'}."
+ message=i18n.t(
+ artifact_key,
+ (
+ f"Prepared {artifact_count} "
+ f"{'artifact' if artifact_count == 1 else 'artifacts'}."
+ ),
+ count=artifact_count,
),
source=self.name,
stage="render_output",
@@ -190,7 +213,8 @@ class MathAnimatorCapability(BaseCapability):
timings["render_output"] = 0.0
visual_review = getattr(render_result, "visual_review", None)
- await stream.result(
+ await emit_capability_result(
+ stream,
{
"response": summary.summary_text,
"summary": summary.model_dump(),
@@ -212,6 +236,7 @@ class MathAnimatorCapability(BaseCapability):
"design": design.model_dump(),
},
source=self.name,
+ usage=usage,
)
async def _run_answer_now(
@@ -222,6 +247,8 @@ class MathAnimatorCapability(BaseCapability):
payload: dict[str, Any],
pipeline, # MathAnimatorPipeline
request_config, # MathAnimatorRequestConfig
+ usage: UsageTracker | None = None,
+ i18n: StatusI18n | None = None,
) -> None:
"""
Fast-path for ``math_animator``:
@@ -243,6 +270,8 @@ class MathAnimatorCapability(BaseCapability):
make_skip_notice,
)
+ if i18n is None:
+ i18n = StatusI18n(self.name, context.language)
original = str(payload.get("original_user_message") or context.user_message).strip()
partial = str(payload.get("partial_response") or "").strip()
trace_summary = format_trace_summary(payload.get("events"), language=context.language)
@@ -291,7 +320,10 @@ class MathAnimatorCapability(BaseCapability):
design=design,
)
await stream.progress(
- message="Manim code prepared (answer-now fast path).",
+ message=i18n.t(
+ "code_prepared_answer_now",
+ "Manim code prepared (answer-now fast path).",
+ ),
source=self.name,
stage="code_generation",
)
@@ -299,7 +331,12 @@ class MathAnimatorCapability(BaseCapability):
async def _on_retry(retry_attempt) -> None:
await stream.progress(
- message=f"Retry {retry_attempt.attempt}: {retry_attempt.error}",
+ message=i18n.t(
+ "retry",
+ f"Retry {retry_attempt.attempt}: {retry_attempt.error}",
+ attempt=retry_attempt.attempt,
+ error=retry_attempt.error,
+ ),
source=self.name,
stage="code_retry",
metadata={**render_call_meta, "trace_layer": "raw"},
@@ -327,9 +364,14 @@ class MathAnimatorCapability(BaseCapability):
stage_start = time.perf_counter()
async with stream.stage("code_retry", source=self.name):
await stream.progress(
- message=(
- f"Rendering {request_config.output_mode} "
- f"(quality={request_config.quality}) — answer-now fast path."
+ message=i18n.t(
+ "rendering_answer_now",
+ (
+ f"Rendering {request_config.output_mode} "
+ f"(quality={request_config.quality}) — answer-now fast path."
+ ),
+ mode=request_config.output_mode,
+ quality=request_config.quality,
),
source=self.name,
stage="code_retry",
@@ -347,11 +389,19 @@ class MathAnimatorCapability(BaseCapability):
timings["code_retry"] = round(time.perf_counter() - stage_start, 3)
async with stream.stage("render_output", source=self.name):
+ artifact_count = len(render_result.artifacts)
+ artifact_key = (
+ "artifacts_one_answer_now" if artifact_count == 1 else "artifacts_many_answer_now"
+ )
await stream.progress(
- message=(
- f"Prepared {len(render_result.artifacts)} "
- f"{'artifact' if len(render_result.artifacts) == 1 else 'artifacts'} "
- "(answer-now)."
+ message=i18n.t(
+ artifact_key,
+ (
+ f"Prepared {artifact_count} "
+ f"{'artifact' if artifact_count == 1 else 'artifacts'} "
+ "(answer-now)."
+ ),
+ count=artifact_count,
),
source=self.name,
stage="render_output",
@@ -365,13 +415,15 @@ class MathAnimatorCapability(BaseCapability):
language=context.language,
stages_skipped=["concept_analysis", "concept_design", "summary"],
)
- summary_text = (
- notice or "Answer-now: code generated and rendered without prior analysis/design."
+ summary_text = notice or i18n.t(
+ "answer_now_summary_fallback",
+ "Answer-now: code generated and rendered without prior analysis/design.",
)
if notice:
await stream.content(summary_text, source=self.name, stage="summary")
- await stream.result(
+ await emit_capability_result(
+ stream,
{
"response": summary_text,
"summary": {
@@ -400,9 +452,10 @@ class MathAnimatorCapability(BaseCapability):
"metadata": {"answer_now": True},
},
source=self.name,
+ usage=usage,
)
- def _build_trace_bridge(self, stream: StreamBus):
+ def _build_trace_bridge(self, stream: StreamBus, i18n: StatusI18n | None = None):
async def _trace_bridge(update: dict[str, Any]) -> None:
event = str(update.get("event", "") or "")
stage = str(update.get("phase") or update.get("stage") or "concept_analysis")
@@ -467,8 +520,13 @@ class MathAnimatorCapability(BaseCapability):
)
return
if state == "error":
+ fallback = (
+ i18n.t("llm_call_failed", "LLM call failed.")
+ if i18n is not None
+ else "LLM call failed."
+ )
await stream.error(
- str(update.get("response", "") or "LLM call failed."),
+ str(update.get("response", "") or fallback),
source=self.name,
stage=stage,
metadata=merge_trace_metadata(
diff --git a/deeptutor/capabilities/prompts/en/deep_question.yaml b/deeptutor/capabilities/prompts/en/deep_question.yaml
new file mode 100644
index 000000000..a9f31d5a6
--- /dev/null
+++ b/deeptutor/capabilities/prompts/en/deep_question.yaml
@@ -0,0 +1,6 @@
+status:
+ topic_required: "Topic is required for custom question generation."
+ parsing_uploaded: "Parsing uploaded exam paper and extracting templates..."
+ parsing_directory: "Loading parsed exam paper and extracting templates..."
+ mimic_needs_paper: "Mimic mode requires either an uploaded PDF or a parsed exam directory."
+ llm_call_failed: "LLM call failed."
diff --git a/deeptutor/capabilities/prompts/en/math_animator.yaml b/deeptutor/capabilities/prompts/en/math_animator.yaml
new file mode 100644
index 000000000..2fef5a267
--- /dev/null
+++ b/deeptutor/capabilities/prompts/en/math_animator.yaml
@@ -0,0 +1,12 @@
+status:
+ code_prepared: "Manim code prepared."
+ code_prepared_answer_now: "Manim code prepared (answer-now fast path)."
+ retry: "Retry {attempt}: {error}"
+ rendering: "Rendering {mode} with quality={quality}."
+ rendering_answer_now: "Rendering {mode} (quality={quality}) — answer-now fast path."
+ artifacts_one: "Prepared {count} artifact."
+ artifacts_many: "Prepared {count} artifacts."
+ artifacts_one_answer_now: "Prepared {count} artifact (answer-now)."
+ artifacts_many_answer_now: "Prepared {count} artifacts (answer-now)."
+ llm_call_failed: "LLM call failed."
+ answer_now_summary_fallback: "Answer-now: code generated and rendered without prior analysis/design."
diff --git a/deeptutor/capabilities/prompts/en/visualize.yaml b/deeptutor/capabilities/prompts/en/visualize.yaml
new file mode 100644
index 000000000..b2b25b7f1
--- /dev/null
+++ b/deeptutor/capabilities/prompts/en/visualize.yaml
@@ -0,0 +1,18 @@
+status:
+ analyzing: "Analyzing visualization requirements..."
+ generating: "Generating visualization code..."
+ code_generated: "Code generated."
+ reviewing: "Reviewing and optimizing code..."
+ html_ready_review_skipped: "HTML page ready (review skipped)."
+ html_invalid_fallback: "HTML did not validate; using fallback template."
+ code_optimized: "Code optimized: {notes}"
+ code_no_changes: "Code looks good — no changes needed."
+ manim_code_prepared: "Manim code prepared."
+ manim_rendering: "Rendering {mode} with quality={quality}."
+ manim_artifacts_one: "Prepared {count} artifact."
+ manim_artifacts_many: "Prepared {count} artifacts."
+ manim_retry: "Retry {attempt}: {error}"
+ llm_call_failed: "LLM call failed."
+ answer_now_skipped_analysis: "Answer-now: skipped analysis stage."
+ answer_now_skipped_review: "Answer-now: skipped review stage."
+ render_type_detected: "Render type: {render_type} — {description}"
diff --git a/deeptutor/capabilities/prompts/zh/deep_question.yaml b/deeptutor/capabilities/prompts/zh/deep_question.yaml
new file mode 100644
index 000000000..f33b0374a
--- /dev/null
+++ b/deeptutor/capabilities/prompts/zh/deep_question.yaml
@@ -0,0 +1,6 @@
+status:
+ topic_required: "自定义出题模式需要提供主题。"
+ parsing_uploaded: "正在解析上传的试卷并提取题型模板..."
+ parsing_directory: "正在加载已解析的试卷并提取题型模板..."
+ mimic_needs_paper: "仿题模式需要上传 PDF 或提供已解析的试卷目录。"
+ llm_call_failed: "LLM 调用失败。"
diff --git a/deeptutor/capabilities/prompts/zh/math_animator.yaml b/deeptutor/capabilities/prompts/zh/math_animator.yaml
new file mode 100644
index 000000000..4c61ad745
--- /dev/null
+++ b/deeptutor/capabilities/prompts/zh/math_animator.yaml
@@ -0,0 +1,12 @@
+status:
+ code_prepared: "Manim 代码已准备完成。"
+ code_prepared_answer_now: "Manim 代码已准备完成(极速回答路径)。"
+ retry: "第 {attempt} 次重试:{error}"
+ rendering: "正在以 quality={quality} 渲染 {mode}。"
+ rendering_answer_now: "正在以 quality={quality} 渲染 {mode}——极速回答路径。"
+ artifacts_one: "已准备 {count} 个产物。"
+ artifacts_many: "已准备 {count} 个产物。"
+ artifacts_one_answer_now: "已准备 {count} 个产物(极速回答)。"
+ artifacts_many_answer_now: "已准备 {count} 个产物(极速回答)。"
+ llm_call_failed: "LLM 调用失败。"
+ answer_now_summary_fallback: "极速回答:未经过分析/设计阶段,已直接生成并渲染代码。"
diff --git a/deeptutor/capabilities/prompts/zh/visualize.yaml b/deeptutor/capabilities/prompts/zh/visualize.yaml
new file mode 100644
index 000000000..4212a6ea8
--- /dev/null
+++ b/deeptutor/capabilities/prompts/zh/visualize.yaml
@@ -0,0 +1,18 @@
+status:
+ analyzing: "正在分析可视化需求..."
+ generating: "正在生成可视化代码..."
+ code_generated: "代码已生成。"
+ reviewing: "正在审查并优化代码..."
+ html_ready_review_skipped: "HTML 页面已就绪(已跳过审查)。"
+ html_invalid_fallback: "HTML 校验未通过;已使用备用模板。"
+ code_optimized: "代码已优化:{notes}"
+ code_no_changes: "代码无需修改。"
+ manim_code_prepared: "Manim 代码已准备完成。"
+ manim_rendering: "正在以 quality={quality} 渲染 {mode}。"
+ manim_artifacts_one: "已准备 {count} 个产物。"
+ manim_artifacts_many: "已准备 {count} 个产物。"
+ manim_retry: "第 {attempt} 次重试:{error}"
+ llm_call_failed: "LLM 调用失败。"
+ answer_now_skipped_analysis: "极速回答:已跳过分析阶段。"
+ answer_now_skipped_review: "极速回答:已跳过审查阶段。"
+ render_type_detected: "渲染类型:{render_type} — {description}"
diff --git a/deeptutor/capabilities/request_contracts.py b/deeptutor/capabilities/request_contracts.py
index 1b75a97e5..c169d2703 100644
--- a/deeptutor/capabilities/request_contracts.py
+++ b/deeptutor/capabilities/request_contracts.py
@@ -33,8 +33,6 @@ class ChatRequestConfig(BaseModel):
class DeepSolveRequestConfig(BaseModel):
model_config = ConfigDict(extra="forbid")
- detailed_answer: bool = True
-
class DeepQuestionRequestConfig(BaseModel):
model_config = ConfigDict(extra="forbid")
@@ -43,8 +41,13 @@ class DeepQuestionRequestConfig(BaseModel):
topic: str = ""
num_questions: int = Field(default=1, ge=1, le=50)
difficulty: str = ""
- question_type: str = ""
- preference: str = ""
+ # Allowed-types whitelist. Empty list means "any type — let the
+ # planner pick per question". Frontend sends the user's multi-select.
+ question_types: list[str] = Field(default_factory=list)
+ # Optional per-type quantity targets. When non-empty, sum must equal
+ # ``num_questions`` (frontend keeps them in sync). Empty dict means
+ # "no per-type targets — distribute freely across allowed types".
+ per_type_counts: dict[str, int] = Field(default_factory=dict)
paper_path: str = ""
max_questions: int = Field(default=10, ge=1, le=100)
@@ -52,7 +55,21 @@ class DeepQuestionRequestConfig(BaseModel):
class VisualizeRequestConfig(BaseModel):
model_config = ConfigDict(extra="forbid")
- render_mode: Literal["auto", "svg", "chartjs", "mermaid", "html"] = "auto"
+ render_mode: Literal[
+ "auto",
+ "svg",
+ "chartjs",
+ "mermaid",
+ "html",
+ "manim_video",
+ "manim_image",
+ ] = "auto"
+ # Only meaningful when the routed render_type is manim_video / manim_image
+ # (either chosen explicitly or selected by AnalysisAgent in auto mode).
+ # Mirrors MathAnimatorRequestConfig defaults so the auto path stays
+ # zero-config.
+ quality: Literal["low", "medium", "high"] = "medium"
+ style_hint: str = Field(default="", max_length=500)
class AutoRequestConfig(BaseModel):
diff --git a/deeptutor/capabilities/visualize.py b/deeptutor/capabilities/visualize.py
index 845b56f52..66f7b4e1c 100644
--- a/deeptutor/capabilities/visualize.py
+++ b/deeptutor/capabilities/visualize.py
@@ -2,26 +2,56 @@
Visualize Capability
====================
-Three-stage visualization pipeline: Analyze -> Generate -> Review.
-Produces SVG or Chart.js code from user requests and conversation context.
+Unified visualization capability. AnalysisAgent picks one of six render
+types — svg / chartjs / mermaid / html (text-emitting, three-stage pipeline)
+or manim_video / manim_image (Manim subprocess pipeline). The result
+envelope carries ``render_type`` as the discriminator so the frontend can
+delegate to the right viewer.
"""
from __future__ import annotations
from typing import Any
-from deeptutor.capabilities.request_contracts import get_capability_request_schema
+from deeptutor.capabilities._i18n import StatusI18n
+from deeptutor.capabilities._shared import emit_capability_result
+from deeptutor.capabilities.request_contracts import (
+ VisualizeRequestConfig,
+ get_capability_request_schema,
+ validate_visualize_request_config,
+)
+from deeptutor.core.agentic.usage import UsageTracker
from deeptutor.core.capability_protocol import BaseCapability, CapabilityManifest
from deeptutor.core.context import UnifiedContext
from deeptutor.core.stream_bus import StreamBus
from deeptutor.core.trace import merge_trace_metadata
+# Stages exposed in the manifest. The first three cover the text-emitting
+# path (svg/chartjs/mermaid/html); the rest cover the manim subprocess
+# path. A given turn only streams a subset of these.
+_VISUALIZE_STAGES = [
+ "analyzing",
+ "generating",
+ "reviewing",
+ "concept_analysis",
+ "concept_design",
+ "code_generation",
+ "code_retry",
+ "summary",
+ "render_output",
+]
+
+_MANIM_RENDER_TYPES = {"manim_video", "manim_image"}
+
class VisualizeCapability(BaseCapability):
manifest = CapabilityManifest(
name="visualize",
- description="Generate SVG, Chart.js, Mermaid, or interactive HTML visualizations.",
- stages=["analyzing", "generating", "reviewing"],
+ description=(
+ "Generate SVG, Chart.js, Mermaid, interactive HTML, or Manim "
+ "animation/storyboard visualizations."
+ ),
+ stages=_VISUALIZE_STAGES,
tools_used=[],
cli_aliases=["visualize", "viz"],
request_schema=get_capability_request_schema("visualize"),
@@ -36,29 +66,42 @@ class VisualizeCapability(BaseCapability):
from deeptutor.capabilities._answer_now import extract_answer_now_context
from deeptutor.services.llm.config import get_llm_config
+ request_config = validate_visualize_request_config(context.config_overrides)
+ render_mode = request_config.render_mode
+ i18n = StatusI18n(self.name, context.language)
+
+ llm_config_for_usage = get_llm_config()
+ usage = UsageTracker(model=getattr(llm_config_for_usage, "model", None))
+
answer_now_payload = extract_answer_now_context(context)
if answer_now_payload is not None:
- await self._run_answer_now(context, stream, answer_now_payload)
- return
+ # Manim takes ~30-90s even on the fast path; answer-now's point is
+ # to skip slow analysis when the user is impatient, so we redirect
+ # explicit manim answer-now requests to the full path. The text
+ # paths keep their dedicated fast-path implementation.
+ if render_mode in _MANIM_RENDER_TYPES:
+ pass # fall through to the full manim path below
+ else:
+ await self._run_answer_now(
+ context, stream, answer_now_payload, usage=usage, i18n=i18n
+ )
+ return
llm_config = get_llm_config()
history_context = str(context.metadata.get("conversation_context_text", "") or "").strip()
- render_mode = (
- str(context.config_overrides.get("render_mode", "auto") or "auto").strip().lower()
- )
pipeline = VisualizePipeline(
api_key=llm_config.api_key,
base_url=llm_config.base_url,
api_version=llm_config.api_version,
language=context.language,
- trace_callback=self._build_trace_bridge(stream),
+ trace_callback=self._build_trace_bridge(stream, i18n=i18n),
)
- # Stage 1: Analyze
+ # Stage 1: Analyze (routing decision)
async with stream.stage("analyzing", source=self.name):
await stream.thinking(
- "Analyzing visualization requirements...",
+ i18n.t("analyzing", "Analyzing visualization requirements..."),
source=self.name,
stage="analyzing",
)
@@ -69,15 +112,34 @@ class VisualizeCapability(BaseCapability):
attachments=context.attachments,
)
await stream.progress(
- message=f"Render type: {analysis.render_type} — {analysis.description}",
+ message=i18n.t(
+ "render_type_detected",
+ f"Render type: {analysis.render_type} — {analysis.description}",
+ render_type=analysis.render_type,
+ description=analysis.description,
+ ),
source=self.name,
stage="analyzing",
)
+ # Branch: manim path takes over completely after the analysis stage,
+ # using its own multi-agent pipeline + Manim subprocess.
+ if analysis.render_type in _MANIM_RENDER_TYPES:
+ await self._run_manim_path(
+ context=context,
+ stream=stream,
+ render_type=analysis.render_type,
+ visualize_config=request_config,
+ history_context=history_context,
+ usage=usage,
+ i18n=i18n,
+ )
+ return
+
# Stage 2: Generate code
async with stream.stage("generating", source=self.name):
await stream.thinking(
- "Generating visualization code...",
+ i18n.t("generating", "Generating visualization code..."),
source=self.name,
stage="generating",
)
@@ -87,7 +149,7 @@ class VisualizeCapability(BaseCapability):
analysis=analysis,
)
await stream.progress(
- message="Code generated.",
+ message=i18n.t("code_generated", "Code generated."),
source=self.name,
stage="generating",
)
@@ -109,7 +171,10 @@ class VisualizeCapability(BaseCapability):
review_notes="Skipped LLM review for html render_type.",
)
await stream.progress(
- message="HTML page ready (review skipped).",
+ message=i18n.t(
+ "html_ready_review_skipped",
+ "HTML page ready (review skipped).",
+ ),
source=self.name,
stage="reviewing",
)
@@ -125,13 +190,16 @@ class VisualizeCapability(BaseCapability):
review_notes="Used fallback HTML template.",
)
await stream.progress(
- message="HTML did not validate; using fallback template.",
+ message=i18n.t(
+ "html_invalid_fallback",
+ "HTML did not validate; using fallback template.",
+ ),
source=self.name,
stage="reviewing",
)
else:
await stream.thinking(
- "Reviewing and optimizing code...",
+ i18n.t("reviewing", "Reviewing and optimizing code..."),
source=self.name,
stage="reviewing",
)
@@ -143,13 +211,20 @@ class VisualizeCapability(BaseCapability):
final_code = review.optimized_code
if review.changed:
await stream.progress(
- message=f"Code optimized: {review.review_notes}",
+ message=i18n.t(
+ "code_optimized",
+ f"Code optimized: {review.review_notes}",
+ notes=review.review_notes,
+ ),
source=self.name,
stage="reviewing",
)
else:
await stream.progress(
- message="Code looks good — no changes needed.",
+ message=i18n.t(
+ "code_no_changes",
+ "Code looks good — no changes needed.",
+ ),
source=self.name,
stage="reviewing",
)
@@ -167,7 +242,8 @@ class VisualizeCapability(BaseCapability):
await stream.content(content_md, source=self.name, stage="reviewing")
# Structured result for the frontend viewer
- await stream.result(
+ await emit_capability_result(
+ stream,
{
"response": content_md,
"render_type": analysis.render_type,
@@ -179,6 +255,223 @@ class VisualizeCapability(BaseCapability):
"review": review.model_dump(),
},
source=self.name,
+ usage=usage,
+ )
+
+ async def _run_manim_path(
+ self,
+ *,
+ context: UnifiedContext,
+ stream: StreamBus,
+ render_type: str,
+ visualize_config: VisualizeRequestConfig,
+ history_context: str,
+ usage: UsageTracker | None = None,
+ i18n: StatusI18n | None = None,
+ ) -> None:
+ """
+ Manim sub-pipeline. Mirrors ``MathAnimatorCapability.run`` but emits
+ the final result with ``render_type`` as the discriminator so the
+ unified frontend dispatcher can route to ``MathAnimatorViewer``.
+ """
+ import importlib.util
+ import time
+
+ if importlib.util.find_spec("manim") is None:
+ raise RuntimeError(
+ "Manim rendering requires optional dependencies. "
+ "Install with `pip install 'deeptutor[math-animator]'` "
+ "or `pip install -r requirements/math-animator.txt`."
+ )
+
+ from deeptutor.agents.math_animator.pipeline import MathAnimatorPipeline
+ from deeptutor.agents.math_animator.request_config import MathAnimatorRequestConfig
+ from deeptutor.core.trace import build_trace_metadata, new_call_id
+ from deeptutor.services.llm.config import get_llm_config
+
+ if i18n is None:
+ i18n = StatusI18n(self.name, context.language)
+ output_mode = "image" if render_type == "manim_image" else "video"
+ request_config = MathAnimatorRequestConfig(
+ output_mode=output_mode, # type: ignore[arg-type]
+ quality=visualize_config.quality,
+ style_hint=visualize_config.style_hint,
+ )
+
+ llm_config = get_llm_config()
+ pipeline = MathAnimatorPipeline(
+ api_key=llm_config.api_key,
+ base_url=llm_config.base_url,
+ api_version=llm_config.api_version,
+ language=context.language,
+ trace_callback=self._build_trace_bridge(stream, i18n=i18n),
+ )
+
+ timings: dict[str, float] = {}
+ turn_id = str(
+ context.metadata.get("turn_id", "") or context.session_id or "visualize-manim"
+ )
+ render_call_meta = build_trace_metadata(
+ call_id=new_call_id("manim-render"),
+ phase="render_output",
+ label="Render output",
+ call_kind="math_render_output",
+ trace_role="render",
+ trace_kind="progress",
+ output_mode=request_config.output_mode,
+ quality=request_config.quality,
+ )
+
+ stage_start = time.perf_counter()
+ async with stream.stage("concept_analysis", source=self.name):
+ analysis = await pipeline.run_analysis(
+ user_input=context.user_message,
+ history_context=history_context,
+ request_config=request_config,
+ attachments=context.attachments,
+ )
+ timings["concept_analysis"] = round(time.perf_counter() - stage_start, 3)
+
+ stage_start = time.perf_counter()
+ async with stream.stage("concept_design", source=self.name):
+ design = await pipeline.run_design(
+ user_input=context.user_message,
+ request_config=request_config,
+ analysis=analysis,
+ )
+ timings["concept_design"] = round(time.perf_counter() - stage_start, 3)
+
+ stage_start = time.perf_counter()
+ async with stream.stage("code_generation", source=self.name):
+ generated = await pipeline.run_code_generation(
+ user_input=context.user_message,
+ request_config=request_config,
+ analysis=analysis,
+ design=design,
+ )
+ await stream.progress(
+ message=i18n.t("manim_code_prepared", "Manim code prepared."),
+ source=self.name,
+ stage="code_generation",
+ )
+ timings["code_generation"] = round(time.perf_counter() - stage_start, 3)
+
+ async def _on_retry(retry_attempt) -> None:
+ await stream.progress(
+ message=i18n.t(
+ "manim_retry",
+ f"Retry {retry_attempt.attempt}: {retry_attempt.error}",
+ attempt=retry_attempt.attempt,
+ error=retry_attempt.error,
+ ),
+ source=self.name,
+ stage="code_retry",
+ metadata={**render_call_meta, "trace_layer": "raw"},
+ )
+
+ async def _on_render_progress(message: str, raw: bool) -> None:
+ await stream.progress(
+ message=message,
+ source=self.name,
+ stage="render_output",
+ metadata={
+ **render_call_meta,
+ "trace_layer": "raw" if raw else "summary",
+ },
+ )
+
+ async def _on_retry_status(message: str) -> None:
+ await stream.progress(
+ message=message,
+ source=self.name,
+ stage="code_retry",
+ metadata={"trace_layer": "summary"},
+ )
+
+ stage_start = time.perf_counter()
+ async with stream.stage("code_retry", source=self.name):
+ await stream.progress(
+ message=i18n.t(
+ "manim_rendering",
+ (
+ f"Rendering {request_config.output_mode} "
+ f"with quality={request_config.quality}."
+ ),
+ mode=request_config.output_mode,
+ quality=request_config.quality,
+ ),
+ source=self.name,
+ stage="code_retry",
+ metadata={**render_call_meta, "call_state": "running"},
+ )
+ final_code, render_result = await pipeline.run_render(
+ turn_id=turn_id,
+ user_input=context.user_message,
+ request_config=request_config,
+ initial_code=generated.code,
+ on_retry=_on_retry,
+ on_render_progress=_on_render_progress,
+ on_retry_status=_on_retry_status,
+ )
+ timings["code_retry"] = round(time.perf_counter() - stage_start, 3)
+
+ stage_start = time.perf_counter()
+ async with stream.stage("summary", source=self.name):
+ summary = await pipeline.run_summary(
+ user_input=context.user_message,
+ request_config=request_config,
+ analysis=analysis,
+ design=design,
+ render_result=render_result,
+ )
+ if summary.summary_text:
+ await stream.content(summary.summary_text, source=self.name, stage="summary")
+ timings["summary"] = round(time.perf_counter() - stage_start, 3)
+
+ async with stream.stage("render_output", source=self.name):
+ artifact_count = len(render_result.artifacts)
+ artifact_key = "manim_artifacts_one" if artifact_count == 1 else "manim_artifacts_many"
+ await stream.progress(
+ message=i18n.t(
+ artifact_key,
+ (
+ f"Prepared {artifact_count} "
+ f"{'artifact' if artifact_count == 1 else 'artifacts'}."
+ ),
+ count=artifact_count,
+ ),
+ source=self.name,
+ stage="render_output",
+ metadata={**render_call_meta, "call_state": "complete"},
+ )
+ timings["render_output"] = 0.0
+ visual_review = getattr(render_result, "visual_review", None)
+
+ await emit_capability_result(
+ stream,
+ {
+ "response": summary.summary_text,
+ "render_type": render_type,
+ "summary": summary.model_dump(),
+ "code": {
+ "language": "python",
+ "content": final_code,
+ },
+ "output_mode": request_config.output_mode,
+ "artifacts": [artifact.model_dump() for artifact in render_result.artifacts],
+ "timings": timings,
+ "render": {
+ "quality": request_config.quality,
+ "retry_attempts": render_result.retry_attempts,
+ "retry_history": [item.model_dump() for item in render_result.retry_history],
+ "source_code_path": render_result.source_code_path,
+ "visual_review": visual_review.model_dump() if visual_review else None,
+ },
+ "analysis": analysis.model_dump(),
+ "design": design.model_dump(),
+ },
+ source=self.name,
+ usage=usage,
)
async def _run_answer_now(
@@ -186,6 +479,9 @@ class VisualizeCapability(BaseCapability):
context: UnifiedContext,
stream: StreamBus,
payload: dict[str, Any],
+ *,
+ usage: UsageTracker | None = None,
+ i18n: StatusI18n | None = None,
) -> None:
"""
Fast-path for ``visualize``: skip analysis + review and emit final
@@ -206,6 +502,8 @@ class VisualizeCapability(BaseCapability):
stream_synthesis,
)
+ if i18n is None:
+ i18n = StatusI18n(self.name, context.language)
original = str(payload.get("original_user_message") or context.user_message).strip()
partial = str(payload.get("partial_response") or "").strip()
trace_summary = format_trace_summary(payload.get("events"), language=context.language)
@@ -285,7 +583,8 @@ class VisualizeCapability(BaseCapability):
body = (notice + "\n\n" + content_md).strip() if notice else content_md
await stream.content(body, source=self.name, stage="generating")
- await stream.result(
+ await emit_capability_result(
+ stream,
{
"response": body,
"render_type": render_type,
@@ -295,7 +594,10 @@ class VisualizeCapability(BaseCapability):
},
"analysis": {
"render_type": render_type,
- "description": "Answer-now: skipped analysis stage.",
+ "description": i18n.t(
+ "answer_now_skipped_analysis",
+ "Answer-now: skipped analysis stage.",
+ ),
"data_description": "",
"chart_type": "",
"visual_elements": [],
@@ -304,14 +606,18 @@ class VisualizeCapability(BaseCapability):
"review": {
"optimized_code": final_code,
"changed": False,
- "review_notes": "Answer-now: skipped review stage.",
+ "review_notes": i18n.t(
+ "answer_now_skipped_review",
+ "Answer-now: skipped review stage.",
+ ),
},
"metadata": {"answer_now": True},
},
source=self.name,
+ usage=usage,
)
- def _build_trace_bridge(self, stream: StreamBus):
+ def _build_trace_bridge(self, stream: StreamBus, i18n: StatusI18n | None = None):
async def _trace_bridge(update: dict[str, Any]) -> None:
event = str(update.get("event", "") or "")
stage = str(update.get("phase") or update.get("stage") or "analyzing")
@@ -376,8 +682,13 @@ class VisualizeCapability(BaseCapability):
)
return
if state == "error":
+ fallback = (
+ i18n.t("llm_call_failed", "LLM call failed.")
+ if i18n is not None
+ else "LLM call failed."
+ )
await stream.error(
- str(update.get("response", "") or "LLM call failed."),
+ str(update.get("response", "") or fallback),
source=self.name,
stage=stage,
metadata=merge_trace_metadata(
diff --git a/deeptutor/services/config/capabilities_settings.py b/deeptutor/services/config/capabilities_settings.py
new file mode 100644
index 000000000..42b4d3f84
--- /dev/null
+++ b/deeptutor/services/config/capabilities_settings.py
@@ -0,0 +1,400 @@
+"""Read/write the per-capability tunables surfaced by the Settings UI.
+
+This is the source of truth for the ``/api/v1/capabilities/settings``
+endpoint. It bridges two on-disk files:
+
+* ``data/user/settings/agents.yaml`` — per-capability LLM params
+ (``temperature``, stage ``max_tokens``). Owned by
+ :func:`get_chat_params` / :func:`get_agent_params` in
+ :mod:`deeptutor.services.config.loader`.
+* ``data/user/settings/main.yaml`` — per-capability runtime knobs that
+ aren't LLM params (research's ``researching.*`` and question's
+ ``exploring.*`` subtrees).
+
+The schema we expose to the UI is a single dict so the frontend can
+render one form. Saving splits the payload back into the right files.
+
+We deliberately do not include capabilities whose pipelines do not
+actually read the corresponding YAML keys today — surfacing knobs that
+don't do anything would be misleading. As we lift more hardcoded
+constants into settings, capabilities can be added here.
+"""
+
+from __future__ import annotations
+
+from pathlib import Path
+from typing import Any
+
+import yaml
+
+from deeptutor.services.config.loader import (
+ DEFAULT_CHAT_PARAMS,
+ PROJECT_ROOT,
+ get_runtime_settings_dir,
+)
+from deeptutor.utils.config_manager import ConfigManager
+
+
+# ── Schema definition ────────────────────────────────────────────────────
+
+
+# The keys here drive both the GET response shape and the PUT validation.
+# Each capability lists its (file, sub-path) reads so we know how to
+# round-trip values without disturbing unrelated YAML keys.
+_AGENTS_YAML_CAPABILITY_SECTIONS: dict[str, tuple[str, ...]] = {
+ "solve": ("capabilities", "solve"),
+ "research": ("capabilities", "research"),
+ "question": ("capabilities", "question"),
+ "co_writer": ("capabilities", "co_writer"),
+ "vision_solver": ("plugins", "vision_solver"),
+ "math_animator": ("plugins", "math_animator"),
+}
+
+_SIMPLE_LLM_DEFAULTS: dict[str, dict[str, Any]] = {
+ "solve": {"temperature": 0.3, "max_tokens": 8192},
+ "research": {"temperature": 0.5, "max_tokens": 16834},
+ "question": {"temperature": 0.7, "max_tokens": 4096},
+ "co_writer": {"temperature": 0.6, "max_tokens": 4096},
+ "vision_solver": {"temperature": 0.3, "max_tokens": 12000},
+ "math_animator": {"temperature": 0.2, "max_tokens": 16834},
+}
+
+# main.yaml subtrees that capabilities read at runtime (besides LLM params).
+_MAIN_YAML_RUNTIME_DEFAULTS: dict[str, dict[str, Any]] = {
+ "solve": {
+ "max_iterations_per_step": 7,
+ "max_replans": 2,
+ },
+ "research": {
+ "researching": {
+ "note_agent_mode": "auto",
+ "tool_timeout": 60,
+ "tool_max_retries": 3,
+ "paper_search_years_limit": 5,
+ },
+ },
+ "question": {
+ "exploring": {
+ "max_iterations": 7,
+ "tool_summarizer": {
+ "enabled": True,
+ "max_tokens": 1024,
+ },
+ },
+ },
+}
+
+
+# ── Helpers ──────────────────────────────────────────────────────────────
+
+
+def _agents_yaml_path() -> Path:
+ return get_runtime_settings_dir(PROJECT_ROOT) / "agents.yaml"
+
+
+def _read_agents_yaml() -> dict[str, Any]:
+ path = _agents_yaml_path()
+ if not path.exists():
+ return {}
+ with open(path, encoding="utf-8") as f:
+ return yaml.safe_load(f) or {}
+
+
+def _write_agents_yaml(data: dict[str, Any]) -> None:
+ path = _agents_yaml_path()
+ path.parent.mkdir(parents=True, exist_ok=True)
+ with open(path, "w", encoding="utf-8") as f:
+ yaml.safe_dump(data, f, default_flow_style=False, allow_unicode=True, sort_keys=False)
+
+
+def _get_at(d: dict[str, Any], path: tuple[str, ...]) -> dict[str, Any]:
+ """Walk a nested dict by path, returning {} if any segment is missing."""
+ node: Any = d
+ for key in path:
+ if not isinstance(node, dict):
+ return {}
+ node = node.get(key, {})
+ return node if isinstance(node, dict) else {}
+
+
+def _set_at(d: dict[str, Any], path: tuple[str, ...], value: dict[str, Any]) -> None:
+ """Insert ``value`` at ``path`` in ``d``, creating intermediate dicts."""
+ node = d
+ for key in path[:-1]:
+ nxt = node.get(key)
+ if not isinstance(nxt, dict):
+ nxt = {}
+ node[key] = nxt
+ node = nxt
+ node[path[-1]] = value
+
+
+def _deep_merge(into: dict[str, Any], src: dict[str, Any]) -> dict[str, Any]:
+ """Merge ``src`` into ``into`` recursively (keys in src win)."""
+ for key, value in src.items():
+ if isinstance(value, dict) and isinstance(into.get(key), dict):
+ _deep_merge(into[key], value)
+ else:
+ into[key] = value
+ return into
+
+
+def _coerce_float(raw: Any, default: float, *, lo: float = 0.0, hi: float = 2.0) -> float:
+ try:
+ value = float(raw)
+ except (TypeError, ValueError):
+ return default
+ return max(lo, min(hi, value))
+
+
+def _coerce_int(raw: Any, default: int, *, lo: int = 1, hi: int = 200_000) -> int:
+ try:
+ value = int(raw)
+ except (TypeError, ValueError):
+ return default
+ return max(lo, min(hi, value))
+
+
+def _coerce_bool(raw: Any, default: bool) -> bool:
+ if isinstance(raw, bool):
+ return raw
+ if isinstance(raw, str):
+ if raw.lower() in {"true", "1", "yes", "on"}:
+ return True
+ if raw.lower() in {"false", "0", "no", "off"}:
+ return False
+ return default
+
+
+# ── Schema build / read ──────────────────────────────────────────────────
+
+
+# Only the chat sub-sections actually read by ``AgenticChatPipeline.__init__``.
+# Add a stage here once a real LLM call site starts consuming its max_tokens.
+_CHAT_STAGES_IN_USE: tuple[str, ...] = ("responding", "answer_now")
+
+
+def _build_chat_block(agents_cfg: dict[str, Any]) -> dict[str, Any]:
+ """Read agents.yaml.capabilities.chat into the UI schema with defaults."""
+ chat_cfg: dict[str, Any] = _get_at(agents_cfg, ("capabilities", "chat"))
+ merged: dict[str, Any] = {}
+ _deep_merge(merged, DEFAULT_CHAT_PARAMS)
+ _deep_merge(merged, chat_cfg)
+ return {
+ "temperature": _coerce_float(
+ merged.get("temperature"), DEFAULT_CHAT_PARAMS["temperature"]
+ ),
+ "max_iterations": _coerce_int(
+ merged.get("max_iterations"), DEFAULT_CHAT_PARAMS["max_iterations"], lo=1, hi=100
+ ),
+ "stage_budgets": {
+ stage: _coerce_int(
+ (merged.get(stage) or {}).get("max_tokens"),
+ DEFAULT_CHAT_PARAMS[stage]["max_tokens"],
+ lo=1,
+ hi=200_000,
+ )
+ for stage in _CHAT_STAGES_IN_USE
+ },
+ }
+
+
+def _build_simple_llm_block(
+ agents_cfg: dict[str, Any], capability: str
+) -> dict[str, Any]:
+ defaults = _SIMPLE_LLM_DEFAULTS[capability]
+ section = _get_at(agents_cfg, _AGENTS_YAML_CAPABILITY_SECTIONS[capability])
+ return {
+ "temperature": _coerce_float(section.get("temperature"), defaults["temperature"]),
+ "max_tokens": _coerce_int(section.get("max_tokens"), defaults["max_tokens"]),
+ }
+
+
+def _build_main_runtime_block(main_cfg: dict[str, Any], capability: str) -> dict[str, Any]:
+ defaults = _MAIN_YAML_RUNTIME_DEFAULTS.get(capability)
+ if defaults is None:
+ return {}
+ if capability == "solve":
+ solve_cfg = _get_at(main_cfg, ("capabilities", "solve"))
+ return {
+ "max_iterations_per_step": _coerce_int(
+ solve_cfg.get("max_iterations_per_step"),
+ defaults["max_iterations_per_step"],
+ lo=1,
+ hi=50,
+ ),
+ "max_replans": _coerce_int(
+ solve_cfg.get("max_replans"),
+ defaults["max_replans"],
+ lo=0,
+ hi=10,
+ ),
+ }
+ if capability == "research":
+ researching_cfg = _get_at(main_cfg, ("capabilities", "research", "researching"))
+ d = defaults["researching"]
+ return {
+ "researching": {
+ "note_agent_mode": str(researching_cfg.get("note_agent_mode") or d["note_agent_mode"]),
+ "tool_timeout": _coerce_int(researching_cfg.get("tool_timeout"), d["tool_timeout"], lo=1, hi=600),
+ "tool_max_retries": _coerce_int(researching_cfg.get("tool_max_retries"), d["tool_max_retries"], lo=0, hi=10),
+ "paper_search_years_limit": _coerce_int(
+ researching_cfg.get("paper_search_years_limit"),
+ d["paper_search_years_limit"],
+ lo=1,
+ hi=50,
+ ),
+ },
+ }
+ if capability == "question":
+ exploring_cfg = _get_at(main_cfg, ("capabilities", "question", "exploring"))
+ d = defaults["exploring"]
+ summarizer_cfg = (
+ exploring_cfg.get("tool_summarizer")
+ if isinstance(exploring_cfg.get("tool_summarizer"), dict)
+ else {}
+ )
+ return {
+ "exploring": {
+ "max_iterations": _coerce_int(
+ exploring_cfg.get("max_iterations"), d["max_iterations"], lo=1, hi=50
+ ),
+ "tool_summarizer": {
+ "enabled": _coerce_bool(
+ summarizer_cfg.get("enabled"), d["tool_summarizer"]["enabled"]
+ ),
+ "max_tokens": _coerce_int(
+ summarizer_cfg.get("max_tokens"), d["tool_summarizer"]["max_tokens"]
+ ),
+ },
+ },
+ }
+ return {}
+
+
+def capabilities_settings_dict() -> dict[str, Any]:
+ """Return the full schema as a JSON-safe dict (defaults merged in)."""
+ agents_cfg = _read_agents_yaml()
+ main_cfg = ConfigManager().load_config()
+
+ result: dict[str, Any] = {"chat": _build_chat_block(agents_cfg)}
+ for cap in _AGENTS_YAML_CAPABILITY_SECTIONS:
+ block = _build_simple_llm_block(agents_cfg, cap)
+ block.update(_build_main_runtime_block(main_cfg, cap))
+ result[cap] = block
+ return result
+
+
+# ── Write path ───────────────────────────────────────────────────────────
+
+
+def _apply_chat_into_agents_yaml(agents_cfg: dict[str, Any], block: dict[str, Any]) -> None:
+ current = _get_at(agents_cfg, ("capabilities", "chat"))
+ new_chat: dict[str, Any] = dict(current) if isinstance(current, dict) else {}
+ if "temperature" in block:
+ new_chat["temperature"] = _coerce_float(block.get("temperature"), DEFAULT_CHAT_PARAMS["temperature"])
+ if "max_iterations" in block:
+ new_chat["max_iterations"] = _coerce_int(
+ block.get("max_iterations"), DEFAULT_CHAT_PARAMS["max_iterations"], lo=1, hi=100
+ )
+ stage_budgets = block.get("stage_budgets") or {}
+ if isinstance(stage_budgets, dict):
+ for stage, default_sub in DEFAULT_CHAT_PARAMS.items():
+ if not isinstance(default_sub, dict):
+ continue
+ if stage in stage_budgets:
+ existing = new_chat.get(stage) if isinstance(new_chat.get(stage), dict) else {}
+ existing = dict(existing)
+ existing["max_tokens"] = _coerce_int(
+ stage_budgets[stage], default_sub["max_tokens"], lo=1, hi=200_000
+ )
+ new_chat[stage] = existing
+ _set_at(agents_cfg, ("capabilities", "chat"), new_chat)
+
+
+def _apply_simple_llm_into_agents_yaml(
+ agents_cfg: dict[str, Any], capability: str, block: dict[str, Any]
+) -> None:
+ defaults = _SIMPLE_LLM_DEFAULTS[capability]
+ section_path = _AGENTS_YAML_CAPABILITY_SECTIONS[capability]
+ current = _get_at(agents_cfg, section_path)
+ new_section: dict[str, Any] = dict(current) if isinstance(current, dict) else {}
+ if "temperature" in block:
+ new_section["temperature"] = _coerce_float(block.get("temperature"), defaults["temperature"])
+ if "max_tokens" in block:
+ new_section["max_tokens"] = _coerce_int(block.get("max_tokens"), defaults["max_tokens"])
+ _set_at(agents_cfg, section_path, new_section)
+
+
+def _apply_main_runtime(main_payload: dict[str, Any], capability: str, block: dict[str, Any]) -> None:
+ defaults = _MAIN_YAML_RUNTIME_DEFAULTS.get(capability)
+ if defaults is None:
+ return
+ if capability == "solve":
+ solve_section: dict[str, Any] = {}
+ if "max_iterations_per_step" in block:
+ solve_section["max_iterations_per_step"] = _coerce_int(
+ block.get("max_iterations_per_step"),
+ defaults["max_iterations_per_step"],
+ lo=1,
+ hi=50,
+ )
+ if "max_replans" in block:
+ solve_section["max_replans"] = _coerce_int(
+ block.get("max_replans"),
+ defaults["max_replans"],
+ lo=0,
+ hi=10,
+ )
+ if solve_section:
+ main_payload.setdefault("capabilities", {})["solve"] = solve_section
+ if capability == "research" and isinstance(block.get("researching"), dict):
+ d = defaults["researching"]
+ r = block["researching"]
+ main_payload.setdefault("capabilities", {}).setdefault("research", {})["researching"] = {
+ "note_agent_mode": str(r.get("note_agent_mode") or d["note_agent_mode"]),
+ "tool_timeout": _coerce_int(r.get("tool_timeout"), d["tool_timeout"], lo=1, hi=600),
+ "tool_max_retries": _coerce_int(r.get("tool_max_retries"), d["tool_max_retries"], lo=0, hi=10),
+ "paper_search_years_limit": _coerce_int(
+ r.get("paper_search_years_limit"), d["paper_search_years_limit"], lo=1, hi=50
+ ),
+ }
+ if capability == "question" and isinstance(block.get("exploring"), dict):
+ d = defaults["exploring"]
+ e = block["exploring"]
+ sm = e.get("tool_summarizer") if isinstance(e.get("tool_summarizer"), dict) else {}
+ main_payload.setdefault("capabilities", {}).setdefault("question", {})["exploring"] = {
+ "max_iterations": _coerce_int(e.get("max_iterations"), d["max_iterations"], lo=1, hi=50),
+ "tool_summarizer": {
+ "enabled": _coerce_bool(sm.get("enabled"), d["tool_summarizer"]["enabled"]),
+ "max_tokens": _coerce_int(sm.get("max_tokens"), d["tool_summarizer"]["max_tokens"]),
+ },
+ }
+
+
+def save_capabilities_settings(payload: dict[str, Any]) -> dict[str, Any]:
+ """Merge ``payload`` into both YAML files and return the new state.
+
+ Unknown keys are dropped; values are coerced + clamped via the helpers
+ above so the YAML cannot pick up junk.
+ """
+ agents_cfg = _read_agents_yaml()
+ main_payload: dict[str, Any] = {}
+
+ if isinstance(payload.get("chat"), dict):
+ _apply_chat_into_agents_yaml(agents_cfg, payload["chat"])
+
+ for cap in _AGENTS_YAML_CAPABILITY_SECTIONS:
+ block = payload.get(cap)
+ if not isinstance(block, dict):
+ continue
+ _apply_simple_llm_into_agents_yaml(agents_cfg, cap, block)
+ _apply_main_runtime(main_payload, cap, block)
+
+ _write_agents_yaml(agents_cfg)
+ if main_payload:
+ ConfigManager().save_config(main_payload)
+ return capabilities_settings_dict()
+
+
+__all__ = ["capabilities_settings_dict", "save_capabilities_settings"]
diff --git a/deeptutor/services/llm/capabilities.py b/deeptutor/services/llm/capabilities.py
index 280882207..1731324a6 100644
--- a/deeptutor/services/llm/capabilities.py
+++ b/deeptutor/services/llm/capabilities.py
@@ -117,6 +117,16 @@ PROVIDER_CAPABILITIES: dict[str, dict[str, object]] = {
"vision_url_supported": False,
"system_in_messages": True,
},
+ # MiniMax's OpenAI-compatible endpoint supports Chat Completions tools /
+ # function calling for M-series text models. Response-format support is
+ # still disabled by the model override below.
+ "minimax": {
+ "supports_response_format": False,
+ "supports_streaming": True,
+ "supports_tools": True,
+ "supports_vision": False,
+ "system_in_messages": True,
+ },
# Local providers (generally OpenAI-compatible)
"ollama": {
"supports_response_format": True, # Ollama supports JSON mode
diff --git a/tests/api/test_tools_router.py b/tests/api/test_tools_router.py
new file mode 100644
index 000000000..8b3b0517b
--- /dev/null
+++ b/tests/api/test_tools_router.py
@@ -0,0 +1,85 @@
+from __future__ import annotations
+
+import pytest
+
+from deeptutor.api.routers import settings as settings_router
+from deeptutor.api.routers import tools as tools_router
+from deeptutor.tools.builtin import (
+ BUILTIN_TOOL_NAMES,
+ COMING_SOON_TOOL_NAMES,
+ USER_TOGGLEABLE_TOOL_NAMES,
+)
+
+
+async def test_list_builtin_tools_marks_toggleable_set(
+ monkeypatch: pytest.MonkeyPatch, tmp_path
+) -> None:
+ """The /api/v1/tools response must clearly separate user-toggleable
+ tools from locked-on (auto-mounted) tools so the /settings/tools UI
+ can render the right control per row."""
+ settings_file = tmp_path / "interface.json"
+ monkeypatch.setattr(settings_router, "_settings_file", lambda: settings_file)
+
+ response = await tools_router.list_builtin_tools()
+ by_name = {tool.name: tool for tool in response.tools}
+
+ # Every registered tool + every coming-soon placeholder shows up.
+ assert set(by_name) == set(BUILTIN_TOOL_NAMES) | set(COMING_SOON_TOOL_NAMES)
+
+ # Coming-soon entries are NOT toggleable and report enabled=False so
+ # the UI can lock the toggle and badge them appropriately.
+ for name in COMING_SOON_TOOL_NAMES:
+ assert by_name[name].coming_soon is True, name
+ assert by_name[name].toggleable is False, name
+ assert by_name[name].enabled is False, name
+
+ # Exactly the documented set is toggleable. Pinning the literal here
+ # (in addition to the constant) is intentional — this list is the
+ # product contract for the /settings/tools "体验增强" section.
+ toggleable_names = {name for name, tool in by_name.items() if tool.toggleable}
+ assert toggleable_names == set(USER_TOGGLEABLE_TOOL_NAMES)
+ assert toggleable_names == {
+ "brainstorm",
+ "web_search",
+ "paper_search",
+ "code_execution",
+ "reason",
+ }
+
+ # Locked-on (non-toggleable, non-coming-soon) tools always report
+ # enabled=True.
+ for name, tool in by_name.items():
+ if not tool.toggleable and not tool.coming_soon:
+ assert tool.enabled is True, name
+
+ # On a fresh settings file the default toggleable set is "all on".
+ assert set(response.enabled_optional_tools) == set(USER_TOGGLEABLE_TOOL_NAMES)
+ for name in USER_TOGGLEABLE_TOOL_NAMES:
+ assert by_name[name].enabled is True
+
+
+async def test_list_builtin_tools_reflects_user_toggle(
+ monkeypatch: pytest.MonkeyPatch, tmp_path
+) -> None:
+ settings_file = tmp_path / "interface.json"
+ monkeypatch.setattr(settings_router, "_settings_file", lambda: settings_file)
+
+ # User disables a subset of toggleable tools.
+ await settings_router.update_enabled_tools(
+ settings_router.EnabledToolsUpdate(enabled_tools=["web_search", "reason"])
+ )
+
+ response = await tools_router.list_builtin_tools()
+ by_name = {tool.name: tool for tool in response.tools}
+
+ assert response.enabled_optional_tools == ["reason", "web_search"]
+ assert by_name["web_search"].enabled is True
+ assert by_name["reason"].enabled is True
+ assert by_name["brainstorm"].enabled is False
+ assert by_name["code_execution"].enabled is False
+ assert by_name["paper_search"].enabled is False
+ # Locked-on tools stay on regardless.
+ assert by_name["rag"].enabled is True
+ assert by_name["web_fetch"].enabled is True
diff --git a/tests/capabilities/test_answer_now.py b/tests/capabilities/test_answer_now.py
index 169b93abf..189af3ae0 100644
--- a/tests/capabilities/test_answer_now.py
+++ b/tests/capabilities/test_answer_now.py
@@ -281,174 +281,209 @@ class TestChatAnswerNow:
assert result.metadata.get("answer_now") is True
assert "Hello world" in str(result.metadata.get("response", ""))
-
-class TestDeepSolveAnswerNow:
@pytest.mark.asyncio
- async def test_jumps_to_writing_stage(self) -> None:
+ async def test_chat_answer_now_strips_protocol_label(self) -> None:
+ from deeptutor.agents.chat import agentic_pipeline as ap_module
+
+ async def _fake_stream(self: Any, _messages: Any, **_kwargs: Any):
+ for chunk in ("``FI", "NISH``\n", "Hello now"):
+ yield chunk
+
cfg = _fake_llm_config()
- chunks = ["The Fourier transform ", "decomposes signals."]
+
with (
- patch.object(_answer_now, "get_llm_config", return_value=cfg),
- patch.object(_answer_now, "llm_stream", _make_stream_factory(chunks)),
+ patch.object(
+ ap_module.AgenticChatPipeline,
+ "_stream_messages",
+ _fake_stream,
+ ),
+ patch(
+ "deeptutor.agents.chat.agentic_pipeline.get_llm_config",
+ return_value=cfg,
+ ),
):
- from deeptutor.capabilities.deep_solve import DeepSolveCapability
+ from deeptutor.capabilities.chat import ChatCapability
ctx = _build_context(
- capability="deep_solve",
+ capability="chat",
payload={
- "original_user_message": "Explain Fourier transform",
- "partial_response": "Planning ...",
- "events": [
- {
- "type": "thinking",
- "stage": "planning",
- "content": "Need to break this into intuition + math",
- }
- ],
+ "original_user_message": "Explain Fourier",
+ "partial_response": "Partial trace",
+ "events": [],
},
- language="en",
)
bus = StreamBus()
- cap = DeepSolveCapability()
+ cap = ChatCapability()
events = await _drain(bus, cap.run(ctx, bus))
- stage_starts = [e for e in events if e.type == StreamEventType.STAGE_START]
- assert any(e.stage == "writing" for e in stage_starts)
-
text = _content_text(events)
- assert "Skipped" in text # the skip notice prepended
- assert "decomposes signals" in text
-
+ assert "FINISH" not in text
+ assert text == "Hello now"
result = _result_event(events)
- assert result.metadata.get("metadata", {}).get("answer_now") is True
- assert result.metadata.get("response", "").endswith("decomposes signals.")
- assert result.metadata.get("output_dir") == ""
+ assert result.metadata.get("response") == "Hello now"
-
-class TestDeepQuestionAnswerNow:
@pytest.mark.asyncio
- async def test_emits_quiz_envelope(self) -> None:
+ async def test_chat_answer_now_strips_bare_protocol_label(self) -> None:
+ from deeptutor.agents.chat import agentic_pipeline as ap_module
+
+ async def _fake_stream(self: Any, _messages: Any, **_kwargs: Any):
+ for chunk in ("FI", "NISH\n", "Hello bare"):
+ yield chunk
+
cfg = _fake_llm_config()
- payload_json = json.dumps(
- {
- "questions": [
- {
- "question_id": "q_1",
- "question": "What is 2+2?",
- "question_type": "choice",
- "options": {"A": "3", "B": "4", "C": "5"},
- "correct_answer": "B",
- "explanation": "Basic arithmetic.",
- "difficulty": "easy",
- "concentration": "arithmetic",
- },
- {
- "question_id": "q_2",
- "question": "Define derivative.",
- "question_type": "written",
- "correct_answer": "Limit of difference quotient.",
- "explanation": "Standard textbook definition.",
- },
- ]
- }
- )
+
with (
- patch.object(_answer_now, "get_llm_config", return_value=cfg),
- patch.object(_answer_now, "llm_stream", _make_stream_factory([payload_json])),
+ patch.object(
+ ap_module.AgenticChatPipeline,
+ "_stream_messages",
+ _fake_stream,
+ ),
+ patch(
+ "deeptutor.agents.chat.agentic_pipeline.get_llm_config",
+ return_value=cfg,
+ ),
):
- from deeptutor.capabilities.deep_question import DeepQuestionCapability
+ from deeptutor.capabilities.chat import ChatCapability
ctx = _build_context(
- capability="deep_question",
+ capability="chat",
payload={
- "original_user_message": "Generate calc warm-ups",
+ "original_user_message": "Explain Fourier",
+ "partial_response": "",
"events": [],
},
- config_overrides={"num_questions": 2, "topic": "calculus warm-ups"},
)
bus = StreamBus()
- cap = DeepQuestionCapability()
+ cap = ChatCapability()
events = await _drain(bus, cap.run(ctx, bus))
+ text = _content_text(events)
+ assert "FINISH" not in text
+ assert text == "Hello bare"
result = _result_event(events)
- summary = result.metadata.get("summary") or {}
- results = summary.get("results") or []
- assert len(results) == 2
- assert results[0]["qa_pair"]["question"] == "What is 2+2?"
- assert results[0]["qa_pair"]["options"]["B"] == "4"
- assert result.metadata.get("mode") == "answer_now"
- assert result.metadata.get("metadata", {}).get("answer_now") is True
+ assert result.metadata.get("response") == "Hello bare"
+
+ @pytest.mark.asyncio
+ async def test_chat_answer_now_strips_variable_backtick_protocol_label(self) -> None:
+ from deeptutor.agents.chat import agentic_pipeline as ap_module
+
+ async def _fake_stream(self: Any, _messages: Any, **_kwargs: Any):
+ for chunk in ("```FI", "NISH```\n", "Hello fenced"):
+ yield chunk
+
+ cfg = _fake_llm_config()
+
+ with (
+ patch.object(
+ ap_module.AgenticChatPipeline,
+ "_stream_messages",
+ _fake_stream,
+ ),
+ patch(
+ "deeptutor.agents.chat.agentic_pipeline.get_llm_config",
+ return_value=cfg,
+ ),
+ ):
+ from deeptutor.capabilities.chat import ChatCapability
+
+ ctx = _build_context(
+ capability="chat",
+ payload={
+ "original_user_message": "Explain Fourier",
+ "partial_response": "",
+ "events": [],
+ },
+ )
+ bus = StreamBus()
+ cap = ChatCapability()
+ events = await _drain(bus, cap.run(ctx, bus))
- # The rendered markdown should make it into a CONTENT event so
- # the chat surface still shows a textual recap of the quiz.
text = _content_text(events)
- assert "What is 2+2?" in text
- assert "Skipped" in text # skip notice
+ assert "FINISH" not in text
+ assert text == "Hello fenced"
+ result = _result_event(events)
+ assert result.metadata.get("response") == "Hello fenced"
@pytest.mark.asyncio
- async def test_handles_unparseable_json_gracefully(self) -> None:
+ async def test_chat_answer_now_strips_spaced_protocol_label(self) -> None:
+ from deeptutor.agents.chat import agentic_pipeline as ap_module
+
+ async def _fake_stream(self: Any, _messages: Any, **_kwargs: Any):
+ for chunk in ("\u200b`` FI", "NISH ``\n", "Hello spaced"):
+ yield chunk
+
cfg = _fake_llm_config()
+
with (
- patch.object(_answer_now, "get_llm_config", return_value=cfg),
- patch.object(_answer_now, "llm_stream", _make_stream_factory(["not json at all"])),
+ patch.object(
+ ap_module.AgenticChatPipeline,
+ "_stream_messages",
+ _fake_stream,
+ ),
+ patch(
+ "deeptutor.agents.chat.agentic_pipeline.get_llm_config",
+ return_value=cfg,
+ ),
):
- from deeptutor.capabilities.deep_question import DeepQuestionCapability
+ from deeptutor.capabilities.chat import ChatCapability
ctx = _build_context(
- capability="deep_question",
- payload={"original_user_message": "x", "events": []},
- config_overrides={"num_questions": 1, "topic": "x"},
+ capability="chat",
+ payload={
+ "original_user_message": "Explain Fourier",
+ "partial_response": "",
+ "events": [],
+ },
)
bus = StreamBus()
- cap = DeepQuestionCapability()
+ cap = ChatCapability()
events = await _drain(bus, cap.run(ctx, bus))
- # Should still produce a result event with a placeholder
- # question, not crash with a JSONDecodeError.
+ text = _content_text(events)
+ assert "FINISH" not in text
+ assert text == "Hello spaced"
result = _result_event(events)
- results = (result.metadata.get("summary") or {}).get("results") or []
- assert len(results) == 1
- assert results[0]["qa_pair"]["question_type"] == "written"
-
+ assert result.metadata.get("response") == "Hello spaced"
-class TestDeepResearchAnswerNow:
@pytest.mark.asyncio
- async def test_emits_report_envelope(self) -> None:
+ async def test_chat_answer_now_preserves_normal_word_prefix(self) -> None:
+ from deeptutor.agents.chat import agentic_pipeline as ap_module
+
+ async def _fake_stream(self: Any, _messages: Any, **_kwargs: Any):
+ for chunk in ("FIN", "ISHED tasks stay visible."):
+ yield chunk
+
cfg = _fake_llm_config()
- chunks = ["# Report\n\n", "Body section.\n\n", "## Conclusion\n\nWrap-up."]
+
with (
- patch.object(_answer_now, "get_llm_config", return_value=cfg),
- patch.object(_answer_now, "llm_stream", _make_stream_factory(chunks)),
+ patch.object(
+ ap_module.AgenticChatPipeline,
+ "_stream_messages",
+ _fake_stream,
+ ),
+ patch(
+ "deeptutor.agents.chat.agentic_pipeline.get_llm_config",
+ return_value=cfg,
+ ),
):
- from deeptutor.capabilities.deep_research import DeepResearchCapability
+ from deeptutor.capabilities.chat import ChatCapability
ctx = _build_context(
- capability="deep_research",
+ capability="chat",
payload={
- "original_user_message": "State of LLM evals 2025",
- "events": [
- {
- "type": "tool_result",
- "stage": "researching",
- "content": "Found 3 evals.",
- "metadata": {"tool": "web_search"},
- }
- ],
+ "original_user_message": "Explain finished states",
+ "partial_response": "",
+ "events": [],
},
- language="en",
)
bus = StreamBus()
- cap = DeepResearchCapability()
+ cap = ChatCapability()
events = await _drain(bus, cap.run(ctx, bus))
- stage_starts = [e for e in events if e.type == StreamEventType.STAGE_START]
- assert any(e.stage == "reporting" for e in stage_starts)
-
+ text = _content_text(events)
+ assert text == "FINISHED tasks stay visible."
result = _result_event(events)
- assert result.metadata.get("metadata", {}).get("answer_now") is True
- response = str(result.metadata.get("response", ""))
- assert "# Report" in response
- assert "Conclusion" in response
+ assert result.metadata.get("response") == "FINISHED tasks stay visible."
class TestVisualizeAnswerNow:
@@ -629,17 +664,24 @@ class TestNormalPathWhenNoAnswerNow:
pipeline would be silently shadowed."""
@pytest.mark.asyncio
- async def test_deep_solve_without_payload_calls_main_solver(self) -> None:
+ async def test_deep_solve_without_payload_calls_pipeline(self) -> None:
from deeptutor.capabilities.deep_solve import DeepSolveCapability
- # We patch MainSolver at its import site inside the capability.
+ # Without an answer_now payload the capability must go through the
+ # normal SolvePipeline path (not the fast-path), and forward its
+ # ``stream.result`` payload to the consumer.
with (
- patch("deeptutor.agents.solve.main_solver.MainSolver") as SolverCls,
+ patch("deeptutor.capabilities.deep_solve.SolvePipeline") as PipelineCls,
patch("deeptutor.services.llm.config.get_llm_config", return_value=_fake_llm_config()),
):
- solver = SolverCls.return_value
- solver.ainit = AsyncMock()
- solver.solve = AsyncMock(return_value={"final_answer": "from solver"})
+ pipeline = PipelineCls.return_value
+
+ async def _run(*, stream: StreamBus, **_kwargs: Any) -> dict[str, Any]:
+ payload = {"response": "from pipeline", "metadata": {}}
+ await stream.result(payload, source="deep_solve")
+ return payload
+
+ pipeline.run = AsyncMock(side_effect=_run)
cap = DeepSolveCapability()
ctx = _build_context(
@@ -650,6 +692,6 @@ class TestNormalPathWhenNoAnswerNow:
bus = StreamBus()
events = await _drain(bus, cap.run(ctx, bus))
- solver.solve.assert_awaited_once()
+ pipeline.run.assert_awaited_once()
result = _result_event(events)
- assert "from solver" in str(result.metadata.get("response", ""))
+ assert "from pipeline" in str(result.metadata.get("response", ""))
diff --git a/tests/capabilities/test_rag_consistency.py b/tests/capabilities/test_rag_consistency.py
index 4c9fb4251..854f86dd2 100644
--- a/tests/capabilities/test_rag_consistency.py
+++ b/tests/capabilities/test_rag_consistency.py
@@ -4,12 +4,14 @@ After the refactor, RAG is no longer a user-selectable tool — its availability
is derived from whether any knowledge bases are attached for the turn.
These tests pin the contract that:
-* ``deep_solve`` *adds* ``rag`` to the effective tool set iff a knowledge
- base is attached, and disables planner-side retrieval otherwise.
-* ``deep_research`` still strips ``kb`` from the user-selected sources list
- when no knowledge base is attached (its sources picker is a separate,
- research-specific concept), and surfaces a clear error if every source is
- unusable.
+* ``deep_solve`` forwards the right ``kb_name`` to the pipeline (``None`` when
+ no KB is attached, the KB name when one is), and strips a legacy ``rag``
+ toggle from the enabled-tools list because the pipeline owns rag mounting.
+* ``deep_research`` uses the same tool-composition policy as chat
+ (``compose_enabled_tools``): the user's composer toggles flow through
+ to the pipeline unchanged, ``rag`` auto-mounts iff a KB is attached.
+ The legacy per-source gating (``sources: ["kb", "web", "papers"]``)
+ has been removed.
"""
from __future__ import annotations
@@ -49,25 +51,22 @@ async def test_deep_solve_omits_rag_when_no_knowledge_base() -> None:
captured_kwargs: dict[str, Any] = {}
- class _FakeSolver:
+ class _FakePipeline:
def __init__(self, **kwargs: Any) -> None:
captured_kwargs.update(kwargs)
- async def ainit(self) -> None:
- return None
-
- def set_trace_callback(self, _cb: Any) -> None:
- return None
-
- async def solve(self, **_kwargs: Any) -> dict[str, Any]:
- return {"final_answer": "ok", "metadata": {}}
+ async def run(self, *, stream: StreamBus, **_kwargs: Any) -> dict[str, Any]:
+ payload = {"response": "ok", "metadata": {}}
+ await stream.result(payload, source="deep_solve")
+ return payload
capability = DeepSolveCapability()
bus = StreamBus()
context = UnifiedContext(
user_message="solve x^2 = 4",
active_capability="deep_solve",
- # A legacy caller passing "rag" should be ignored — KBs are the signal.
+ # A legacy caller passing "rag" should be dropped — the pipeline owns
+ # rag mounting based on whether a KB is attached.
enabled_tools=["rag", "web_search"],
knowledge_bases=[],
language="en",
@@ -75,8 +74,8 @@ async def test_deep_solve_omits_rag_when_no_knowledge_base() -> None:
with (
patch(
- "deeptutor.agents.solve.main_solver.MainSolver",
- new=_FakeSolver,
+ "deeptutor.capabilities.deep_solve.SolvePipeline",
+ new=_FakePipeline,
),
patch(
"deeptutor.services.llm.config.get_llm_config",
@@ -88,27 +87,22 @@ async def test_deep_solve_omits_rag_when_no_knowledge_base() -> None:
assert "rag" not in captured_kwargs["enabled_tools"]
assert "web_search" in captured_kwargs["enabled_tools"]
assert captured_kwargs["kb_name"] is None
- assert captured_kwargs["disable_planner_retrieve"] is True
@pytest.mark.asyncio
-async def test_deep_solve_adds_rag_when_knowledge_base_attached() -> None:
+async def test_deep_solve_forwards_kb_when_knowledge_base_attached() -> None:
from deeptutor.capabilities.deep_solve import DeepSolveCapability
captured_kwargs: dict[str, Any] = {}
- class _FakeSolver:
+ class _FakePipeline:
def __init__(self, **kwargs: Any) -> None:
captured_kwargs.update(kwargs)
- async def ainit(self) -> None:
- return None
-
- def set_trace_callback(self, _cb: Any) -> None:
- return None
-
- async def solve(self, **_kwargs: Any) -> dict[str, Any]:
- return {"final_answer": "ok", "metadata": {}}
+ async def run(self, *, stream: StreamBus, **_kwargs: Any) -> dict[str, Any]:
+ payload = {"response": "ok", "metadata": {}}
+ await stream.result(payload, source="deep_solve")
+ return payload
capability = DeepSolveCapability()
bus = StreamBus()
@@ -122,8 +116,8 @@ async def test_deep_solve_adds_rag_when_knowledge_base_attached() -> None:
with (
patch(
- "deeptutor.agents.solve.main_solver.MainSolver",
- new=_FakeSolver,
+ "deeptutor.capabilities.deep_solve.SolvePipeline",
+ new=_FakePipeline,
),
patch(
"deeptutor.services.llm.config.get_llm_config",
@@ -132,103 +126,79 @@ async def test_deep_solve_adds_rag_when_knowledge_base_attached() -> None:
):
await _drain(bus, capability.run(context, bus))
- assert "rag" in captured_kwargs["enabled_tools"]
+ # The capability strips ``rag`` from the LLM-visible toggle list; the
+ # pipeline auto-mounts it internally based on ``kb_name``.
+ assert "rag" not in captured_kwargs["enabled_tools"]
+ assert "web_search" in captured_kwargs["enabled_tools"]
assert captured_kwargs["kb_name"] == "my-kb"
- assert captured_kwargs["disable_planner_retrieve"] is False
# ---------------------------------------------------------------------------
-# deep_research: kb in sources without KB → kb dropped or hard error
+# deep_research: tool composition matches chat (no sources gating)
# ---------------------------------------------------------------------------
@pytest.mark.asyncio
-async def test_deep_research_drops_kb_source_when_no_knowledge_base() -> None:
+async def test_deep_research_forwards_enabled_tools_and_kb_unchanged() -> None:
+ """The capability passes the user's composer toggles (``enabled_tools``)
+ and the attached KB (``kb_name``) through to the pipeline as-is. There
+ is no per-source gating: ``compose_enabled_tools`` (run inside the
+ pipeline) is the single arbiter of what the block loop sees."""
from deeptutor.capabilities.deep_research import DeepResearchCapability
- captured_config: dict[str, Any] = {}
+ captured_kwargs: dict[str, Any] = {}
- async def _fake_outline(self, **kwargs: Any): # noqa: ARG001
- captured_config.update(kwargs.get("config") or {})
- return [{"title": "Subtopic 1", "overview": "Overview 1"}]
+ class _FakePipeline:
+ def __init__(self, **kwargs: Any) -> None:
+ captured_kwargs.update(kwargs)
+
+ async def run(self, *, stream: StreamBus, **_kwargs: Any) -> dict[str, Any]:
+ return {
+ "response": "",
+ "output_dir": "",
+ "outline_preview": True,
+ "topic": "topic",
+ "sub_topics": [{"title": "Subtopic 1", "overview": "Overview 1"}],
+ }
capability = DeepResearchCapability()
bus = StreamBus()
context = UnifiedContext(
user_message="A topic to research",
active_capability="deep_research",
- enabled_tools=["web_search"],
- knowledge_bases=[],
+ enabled_tools=["web_search", "paper_search"],
+ knowledge_bases=["my-kb"],
config_overrides={
"mode": "report",
"depth": "standard",
- "sources": ["kb", "web"],
},
language="en",
)
with (
- patch.object(
- DeepResearchCapability,
- "_generate_outline_preview",
- new=_fake_outline,
- ),
- patch(
- "deeptutor.services.llm.config.get_llm_config",
- return_value=_fake_llm_config(),
- ),
patch(
- "deeptutor.services.config.load_config_with_main",
- return_value={},
+ "deeptutor.capabilities.deep_research.ResearchPipeline",
+ new=_FakePipeline,
),
- ):
- events = await _drain(bus, capability.run(context, bus))
-
- researching = captured_config.get("researching", {})
- assert researching.get("enable_rag") is False
- assert researching.get("enable_web_search") is True
- assert captured_config["intent"]["sources"] == ["web"]
-
- warnings = [
- e
- for e in events
- if e.type == StreamEventType.PROGRESS
- and (e.metadata or {}).get("reason") == "kb_without_kb_name"
- ]
- assert warnings, "expected a kb_without_kb_name warning event"
-
-
-async def test_deep_research_errors_when_only_kb_source_and_no_knowledge_base() -> None:
- from deeptutor.capabilities.deep_research import DeepResearchCapability
-
- capability = DeepResearchCapability()
- bus = StreamBus()
- context = UnifiedContext(
- user_message="topic",
- active_capability="deep_research",
- enabled_tools=[],
- knowledge_bases=[],
- config_overrides={
- "mode": "report",
- "depth": "standard",
- "sources": ["kb"],
- },
- language="en",
- )
-
- with (
patch(
"deeptutor.services.llm.config.get_llm_config",
return_value=_fake_llm_config(),
),
patch(
- "deeptutor.services.config.load_config_with_main",
+ "deeptutor.capabilities.deep_research.load_config_with_main",
return_value={},
),
):
- events = await _drain(bus, capability.run(context, bus))
+ await _drain(bus, capability.run(context, bus))
- errors = [e for e in events if e.type == StreamEventType.ERROR]
- assert errors, "expected an error event when no usable source remains"
- assert "source" in errors[0].content.lower()
+ assert captured_kwargs["enabled_tools"] == ["web_search", "paper_search"]
+ assert captured_kwargs["kb_name"] == "my-kb"
+ runtime_config = captured_kwargs.get("runtime_config") or {}
+ researching = runtime_config.get("researching", {})
+ # The legacy per-source enable_* flags must not appear in the
+ # runtime config — composition is the pipeline's job.
+ assert "enable_rag" not in researching
+ assert "enable_web_search" not in researching
+ assert "enable_paper_search" not in researching
+ assert "enable_run_code" not in researching
+ assert "sources" not in runtime_config.get("intent", {})
diff --git a/tests/services/llm/test_capabilities.py b/tests/services/llm/test_capabilities.py
index cc37fae7d..2452b2a69 100644
--- a/tests/services/llm/test_capabilities.py
+++ b/tests/services/llm/test_capabilities.py
@@ -5,6 +5,7 @@ from deeptutor.services.llm.capabilities import (
get_effective_temperature,
has_thinking_tags,
supports_response_format,
+ supports_tools,
supports_vision,
)
@@ -57,6 +58,13 @@ def test_moonshot_vision_models() -> None:
assert supports_vision("moonshot", "kimi-latest") is False
+def test_minimax_openai_compat_supports_tools_without_response_format() -> None:
+ """MiniMax M-series models support OpenAI-compatible tool calls, but
+ the provider still should not receive json_object response_format."""
+ assert supports_tools("minimax", "MiniMax-M2.7-highspeed") is True
+ assert supports_response_format("minimax", "MiniMax-M2.7-highspeed") is False
+
+
def test_qwen_model_override_enables_vision() -> None:
assert supports_vision("dashscope", "qwen-vl-plus") is True
assert supports_vision("openai", "qwen2.5-vl-72b-instruct") is True
diff --git a/tests/services/llm/test_client.py b/tests/services/llm/test_client.py
index fbf89f3fd..fd9ac44c0 100644
--- a/tests/services/llm/test_client.py
+++ b/tests/services/llm/test_client.py
@@ -44,12 +44,18 @@ def test_client_complete_sync(monkeypatch: MonkeyPatch) -> None:
def test_client_reports_multimodal_image_support() -> None:
- assert LLMClient(
- LLMConfig(model="gpt-4o", api_key="key", base_url="https://example.com")
- ).supports_multimodal_images() is True
- assert LLMClient(
- LLMConfig(model="gpt-3.5-turbo", api_key="key", base_url="https://example.com")
- ).supports_multimodal_images() is False
+ assert (
+ LLMClient(
+ LLMConfig(model="gpt-4o", api_key="key", base_url="https://example.com")
+ ).supports_multimodal_images()
+ is True
+ )
+ assert (
+ LLMClient(
+ LLMConfig(model="gpt-3.5-turbo", api_key="key", base_url="https://example.com")
+ ).supports_multimodal_images()
+ is False
+ )
@pytest.mark.asyncio
diff --git a/web/app/(utility)/settings/appearance/page.tsx b/web/app/(utility)/settings/appearance/page.tsx
new file mode 100644
index 000000000..3b83a19cf
--- /dev/null
+++ b/web/app/(utility)/settings/appearance/page.tsx
@@ -0,0 +1,92 @@
+"use client";
+
+import { useTranslation } from "react-i18next";
+
+import { useSettings } from "@/components/settings/SettingsContext";
+import { ThemePreviewCard } from "@/components/settings/ThemePreviewCard";
+import {
+ SettingRow,
+ SettingSection,
+ SettingsPageHeader,
+} from "@/components/settings/shared";
+
+export default function AppearanceSettingsPage() {
+ const { t } = useTranslation();
+ const { theme, language, updateTheme, updateLanguage } = useSettings();
+
+ return (
+ <div data-tour="tour-appearance">
+ <SettingsPageHeader
+ title={t("Appearance")}
+ description={t(
+ "Tune the visual theme and interface language. Changes apply immediately and are stored in your account.",
+ )}
+ />
+
+ <SettingSection
+ title={t("Language")}
+ description={t("Choose the interface language.")}
+ >
+ <SettingRow
+ title={t("Interface language")}
+ description={t(
+ "Affects the UI only. Model output language is controlled by your prompt.",
+ )}
+ control={
+ <div className="flex gap-0.5 rounded-lg bg-[var(--muted)] p-0.5">
+ {(["en", "zh"] as const).map((v) => (
+ <button
+ key={v}
+ onClick={() => updateLanguage(v)}
+ className={`rounded-md px-2.5 py-1 text-[12px] transition-all ${
+ language === v
+ ? "bg-[var(--card)] font-medium text-[var(--foreground)] shadow-sm"
+ : "text-[var(--muted-foreground)] hover:text-[var(--foreground)]"
+ }`}
+ >
+ {v === "en" ? t("language.english") : t("language.chinese")}
+ </button>
+ ))}
+ </div>
+ }
+ />
+ </SettingSection>
+
+ <SettingSection
+ title={t("Theme")}
+ description={t(
+ "Pick the colour palette and interface style. Each tile previews the theme it applies.",
+ )}
+ >
+ <div className="py-4">
+ {/* Order is intentional: warm-light → cool-light → warm-dark →
+ cool-dark. Cream is the default, Snow is its cool sibling,
+ Dark mirrors Cream's accent, Glass mirrors Snow's. */}
+ <div className="grid grid-cols-2 gap-3 sm:grid-cols-4">
+ {(
+ [
+ { id: "light", label: t("Cream") },
+ { id: "snow", label: t("Snow") },
+ { id: "dark", label: t("Dark") },
+ { id: "glass", label: t("Glass") },
+ ] as const
+ ).map(({ id, label }) => (
+ <ThemePreviewCard
+ key={id}
+ theme={id}
+ label={label}
+ selected={theme === id}
+ onSelect={updateTheme}
+ />
+ ))}
+ </div>
+ <p className="mt-4 text-[11.5px] leading-relaxed text-[var(--muted-foreground)]/80">
+ {t(
+ "Cream is a warm, paper-like default with a terracotta accent. Snow is its cool, blue-tinted sibling with a royal-blue accent. Dark keeps Cream's warmth on near-black. Glass adds translucent purple panels on a deep gradient.",
+ )}
+ </p>
+ </div>
+ </SettingSection>
+ </div>
+ );
+}
diff --git a/web/app/(utility)/settings/capabilities/page.tsx b/web/app/(utility)/settings/capabilities/page.tsx
new file mode 100644
index 000000000..e55a336c5
--- /dev/null
+++ b/web/app/(utility)/settings/capabilities/page.tsx
@@ -0,0 +1,597 @@
+"use client";
+
+import { useCallback, useEffect, useRef, useState } from "react";
+import { Loader2 } from "lucide-react";
+import { useTranslation } from "react-i18next";
+
+import { apiFetch, apiUrl } from "@/lib/api";
+import {
+ SettingRow,
+ SettingSection,
+ SettingsPageHeader,
+} from "@/components/settings/shared";
+import { useSettings } from "@/components/settings/SettingsContext";
+
+// ── Shape mirrors deeptutor/services/config/capabilities_settings.py ──────
+
+interface SimpleLLMBlock {
+ temperature: number;
+ max_tokens: number;
+}
+
+interface ChatBlock {
+ temperature: number;
+ max_iterations: number;
+ stage_budgets: {
+ responding: number;
+ answer_now: number;
+ };
+}
+
+interface ResearchExtras {
+ researching: {
+ note_agent_mode: string;
+ tool_timeout: number;
+ tool_max_retries: number;
+ paper_search_years_limit: number;
+ };
+}
+
+interface QuestionExtras {
+ exploring: {
+ max_iterations: number;
+ tool_summarizer: {
+ enabled: boolean;
+ max_tokens: number;
+ };
+ };
+}
+
+interface SolveExtras {
+ max_iterations_per_step: number;
+ max_replans: number;
+}
+
+interface CapabilitiesSettingsDTO {
+ chat: ChatBlock;
+ solve: SimpleLLMBlock & SolveExtras;
+ research: SimpleLLMBlock & ResearchExtras;
+ question: SimpleLLMBlock & QuestionExtras;
+ co_writer: SimpleLLMBlock;
+ vision_solver: SimpleLLMBlock;
+ math_animator: SimpleLLMBlock;
+}
+
+function isValidCapabilitiesDTO(value: unknown): value is CapabilitiesSettingsDTO {
+ if (!value || typeof value !== "object") return false;
+ const v = value as Record<string, unknown>;
+ const chat = v.chat as Record<string, unknown> | undefined;
+ const solve = v.solve as Record<string, unknown> | undefined;
+ return (
+ !!chat &&
+ typeof chat.temperature === "number" &&
+ typeof chat.max_iterations === "number" &&
+ !!chat.stage_budgets &&
+ !!solve &&
+ typeof solve.max_iterations_per_step === "number" &&
+ typeof solve.max_replans === "number" &&
+ !!v.research &&
+ !!v.question
+ );
+}
+
+export default function CapabilitiesSettingsPage() {
+ const { t } = useTranslation();
+ const { registerExtension } = useSettings();
+ const [settings, setSettings] = useState<CapabilitiesSettingsDTO | null>(null);
+ const [serverSnapshot, setServerSnapshot] =
+ useState<CapabilitiesSettingsDTO | null>(null);
+ const [loadError, setLoadError] = useState<string | null>(null);
+
+ const load = useCallback(async () => {
+ try {
+ const res = await apiFetch(apiUrl("/api/v1/capabilities/settings"));
+ if (!res.ok) {
+ setLoadError(
+ t(
+ "Failed to load capability settings (HTTP {{status}}). Make sure the backend is running the latest build — the /api/v1/capabilities/settings endpoint was added in this release.",
+ { status: res.status },
+ ),
+ );
+ return;
+ }
+ const data: unknown = await res.json();
+ if (!isValidCapabilitiesDTO(data)) {
+ setLoadError(
+ t(
+ "The backend returned an unexpected payload for /api/v1/capabilities/settings. Restart the backend to pick up the latest schema.",
+ ),
+ );
+ return;
+ }
+ setSettings(data);
+ setServerSnapshot(data);
+ setLoadError(null);
+ } catch (err) {
+ setLoadError(
+ err instanceof Error ? err.message : t("Failed to load capability settings."),
+ );
+ }
+ }, [t]);
+
+ useEffect(() => {
+ void load();
+ }, [load]);
+
+ const dirty =
+ !!settings &&
+ !!serverSnapshot &&
+ JSON.stringify(settings) !== JSON.stringify(serverSnapshot);
+
+ const settingsRef = useRef(settings);
+ settingsRef.current = settings;
+ const save = useCallback(async () => {
+ const current = settingsRef.current;
+ if (!current) return;
+ const res = await apiFetch(apiUrl("/api/v1/capabilities/settings"), {
+ method: "PUT",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify(current),
+ });
+ if (!res.ok) {
+ throw new Error(
+ t("Failed to save capability settings (HTTP {{status}})", {
+ status: res.status,
+ }),
+ );
+ }
+ const data: unknown = await res.json();
+ if (!isValidCapabilitiesDTO(data)) {
+ throw new Error(t("Backend returned an unexpected payload after save."));
+ }
+ setSettings(data);
+ setServerSnapshot(data);
+ }, [t]);
+
+ useEffect(() => {
+ registerExtension("capabilities", { dirty, save });
+ return () => registerExtension("capabilities", null);
+ }, [dirty, save, registerExtension]);
+
+ function patchChat<K extends keyof ChatBlock>(
+ key: K,
+ value: ChatBlock[K],
+ ) {
+ if (!settings) return;
+ setSettings({ ...settings, chat: { ...settings.chat, [key]: value } });
+ }
+
+ function patchStageBudget(
+ stage: keyof ChatBlock["stage_budgets"],
+ value: number,
+ ) {
+ if (!settings) return;
+ setSettings({
+ ...settings,
+ chat: {
+ ...settings.chat,
+ stage_budgets: { ...settings.chat.stage_budgets, [stage]: value },
+ },
+ });
+ }
+
+ function patchSimple(
+ cap: "solve" | "co_writer" | "vision_solver" | "math_animator",
+ value: Partial<SimpleLLMBlock>,
+ ) {
+ if (!settings) return;
+ setSettings({ ...settings, [cap]: { ...settings[cap], ...value } });
+ }
+
+ function patchSolveExtras(value: Partial<SolveExtras>) {
+ if (!settings) return;
+ setSettings({ ...settings, solve: { ...settings.solve, ...value } });
+ }
+
+ function patchResearch(value: Partial<SimpleLLMBlock>) {
+ if (!settings) return;
+ setSettings({ ...settings, research: { ...settings.research, ...value } });
+ }
+
+ function patchResearching(
+ value: Partial<ResearchExtras["researching"]>,
+ ) {
+ if (!settings) return;
+ setSettings({
+ ...settings,
+ research: {
+ ...settings.research,
+ researching: { ...settings.research.researching, ...value },
+ },
+ });
+ }
+
+ function patchQuestion(value: Partial<SimpleLLMBlock>) {
+ if (!settings) return;
+ setSettings({ ...settings, question: { ...settings.question, ...value } });
+ }
+
+ function patchExploring(
+ value: Partial<QuestionExtras["exploring"]>,
+ ) {
+ if (!settings) return;
+ setSettings({
+ ...settings,
+ question: {
+ ...settings.question,
+ exploring: { ...settings.question.exploring, ...value },
+ },
+ });
+ }
+
+ function patchExploringSummarizer(
+ value: Partial<QuestionExtras["exploring"]["tool_summarizer"]>,
+ ) {
+ if (!settings) return;
+ setSettings({
+ ...settings,
+ question: {
+ ...settings.question,
+ exploring: {
+ ...settings.question.exploring,
+ tool_summarizer: {
+ ...settings.question.exploring.tool_summarizer,
+ ...value,
+ },
+ },
+ },
+ });
+ }
+
+ if (loadError) {
+ return (
+ <div className="grid h-[60vh] place-items-center px-6">
+ <div className="max-w-xl rounded-lg border border-[var(--border)] bg-[var(--background)] p-4 text-[13px] text-[var(--muted-foreground)]">
+ <div className="mb-2 font-medium text-[var(--foreground)]">
+ {t("Couldn't load capability settings")}
+ </div>
+ <div>{loadError}</div>
+ <button
+ type="button"
+ onClick={() => void load()}
+ className="mt-3 rounded-md border border-[var(--border)] bg-[var(--card)] px-3 py-1 text-[12px] hover:bg-[var(--muted)]"
+ >
+ {t("Retry")}
+ </button>
+ </div>
+ </div>
+ );
+ }
+
+ if (!settings) {
+ return (
+ <div className="grid h-[60vh] place-items-center text-[13px] text-[var(--muted-foreground)]">
+ <Loader2 className="h-4 w-4 animate-spin" />
+ </div>
+ );
+ }
+
+ return (
+ <div data-tour="tour-capabilities">
+ <SettingsPageHeader
+ title={t("Capabilities")}
+ description={t(
+ "Per-capability LLM parameters and runtime knobs. Values are persisted to data/user/settings/agents.yaml (LLM params) and data/user/settings/main.yaml (runtime knobs).",
+ )}
+ />
+
+ <SettingSection
+ title={t("Chat")}
+ description={t(
+ "The agentic chat loop. Stage budgets cap max_tokens per stage; lower the intermediate stages on small-context models.",
+ )}
+ >
+ <NumberRow
+ label={t("Temperature")}
+ help={t("Sampling temperature shared across every chat stage.")}
+ value={settings.chat.temperature}
+ onChange={(n) => patchChat("temperature", n)}
+ min={0}
+ max={2}
+ step={0.05}
+ isFloat
+ />
+ <NumberRow
+ label={t("Max iterations")}
+ help={t("Hard cap on chat loop iterations per turn.")}
+ value={settings.chat.max_iterations}
+ onChange={(n) => patchChat("max_iterations", n)}
+ min={1}
+ max={100}
+ />
+ <NumberRow
+ label={t("Max tokens")}
+ help={t(
+ "Per-iteration budget for the chat LLM call (which emits THINK / TOOL / FINISH labels in a single stream).",
+ )}
+ value={settings.chat.stage_budgets.responding}
+ onChange={(n) => patchStageBudget("responding", n)}
+ min={256}
+ max={200000}
+ step={100}
+ />
+ <NumberRow
+ label={t("Answer-now (max tokens)")}
+ help={t("Budget for the user-forced short-circuit response.")}
+ value={settings.chat.stage_budgets.answer_now}
+ onChange={(n) => patchStageBudget("answer_now", n)}
+ min={256}
+ max={200000}
+ step={100}
+ />
+ </SettingSection>
+
+ <SettingSection
+ title={t("Solve")}
+ description={t("Deep solve pipeline: chained THINK / TOOL / FINISH / REPLAN loop.")}
+ >
+ <NumberRow
+ label={t("Temperature")}
+ value={settings.solve.temperature}
+ onChange={(n) => patchSimple("solve", { temperature: n })}
+ min={0}
+ max={2}
+ step={0.05}
+ isFloat
+ />
+ <NumberRow
+ label={t("Max tokens")}
+ value={settings.solve.max_tokens}
+ onChange={(n) => patchSimple("solve", { max_tokens: n })}
+ min={256}
+ max={200000}
+ step={100}
+ />
+ <NumberRow
+ label={t("Max iterations per step")}
+ help={t(
+ "Cap on the THINK / TOOL inner loop within a single plan step.",
+ )}
+ value={settings.solve.max_iterations_per_step}
+ onChange={(n) => patchSolveExtras({ max_iterations_per_step: n })}
+ min={1}
+ max={50}
+ />
+ <NumberRow
+ label={t("Max replans")}
+ help={t("How many times the planner may revise the plan within one turn.")}
+ value={settings.solve.max_replans}
+ onChange={(n) => patchSolveExtras({ max_replans: n })}
+ min={0}
+ max={10}
+ />
+ </SettingSection>
+
+ <SettingSection
+ title={t("Question")}
+ description={t("Deep question (quiz) generation pipeline.")}
+ >
+ <NumberRow
+ label={t("Temperature")}
+ value={settings.question.temperature}
+ onChange={(n) => patchQuestion({ temperature: n })}
+ min={0}
+ max={2}
+ step={0.05}
+ isFloat
+ />
+ <NumberRow
+ label={t("Max tokens")}
+ value={settings.question.max_tokens}
+ onChange={(n) => patchQuestion({ max_tokens: n })}
+ min={256}
+ max={200000}
+ step={100}
+ />
+ <NumberRow
+ label={t("Explore max iterations")}
+ help={t("Cap on the explore loop before planning.")}
+ value={settings.question.exploring.max_iterations}
+ onChange={(n) => patchExploring({ max_iterations: n })}
+ min={1}
+ max={50}
+ />
+ <ToggleRow
+ label={t("Tool summarizer enabled")}
+ help={t("Summarize long tool outputs to keep the prompt budget low.")}
+ value={settings.question.exploring.tool_summarizer.enabled}
+ onChange={(v) => patchExploringSummarizer({ enabled: v })}
+ />
+ <NumberRow
+ label={t("Tool summarizer (max tokens)")}
+ value={settings.question.exploring.tool_summarizer.max_tokens}
+ onChange={(n) => patchExploringSummarizer({ max_tokens: n })}
+ min={128}
+ max={200000}
+ step={100}
+ />
+ </SettingSection>
+
+ <SettingSection
+ title={t("Research")}
+ description={t(
+ "Deep research pipeline. Iteration count is controlled per request via the depth selector (quick / standard / deep / manual) in the chat input, not here.",
+ )}
+ >
+ <NumberRow
+ label={t("Temperature")}
+ value={settings.research.temperature}
+ onChange={(n) => patchResearch({ temperature: n })}
+ min={0}
+ max={2}
+ step={0.05}
+ isFloat
+ />
+ <NumberRow
+ label={t("Max tokens")}
+ value={settings.research.max_tokens}
+ onChange={(n) => patchResearch({ max_tokens: n })}
+ min={256}
+ max={200000}
+ step={100}
+ />
+ <NumberRow
+ label={t("Tool timeout (s)")}
+ help={t("Per-tool wall-clock timeout for the researching phase.")}
+ value={settings.research.researching.tool_timeout}
+ onChange={(n) => patchResearching({ tool_timeout: n })}
+ min={1}
+ max={600}
+ />
+ <NumberRow
+ label={t("Tool max retries")}
+ value={settings.research.researching.tool_max_retries}
+ onChange={(n) => patchResearching({ tool_max_retries: n })}
+ min={0}
+ max={10}
+ />
+ <NumberRow
+ label={t("Paper search years limit")}
+ help={t("How far back paper search will scan.")}
+ value={settings.research.researching.paper_search_years_limit}
+ onChange={(n) => patchResearching({ paper_search_years_limit: n })}
+ min={1}
+ max={50}
+ />
+ </SettingSection>
+
+ <SettingSection
+ title={t("Math animator")}
+ description={t("Manim animation / image generation pipeline.")}
+ >
+ <NumberRow
+ label={t("Temperature")}
+ value={settings.math_animator.temperature}
+ onChange={(n) => patchSimple("math_animator", { temperature: n })}
+ min={0}
+ max={2}
+ step={0.05}
+ isFloat
+ />
+ <NumberRow
+ label={t("Max tokens")}
+ value={settings.math_animator.max_tokens}
+ onChange={(n) => patchSimple("math_animator", { max_tokens: n })}
+ min={256}
+ max={200000}
+ step={100}
+ />
+ </SettingSection>
+
+ <SettingSection
+ title={t("Co-writer")}
+ description={t("Selection edit / inline rewrite agent.")}
+ >
+ <NumberRow
+ label={t("Temperature")}
+ value={settings.co_writer.temperature}
+ onChange={(n) => patchSimple("co_writer", { temperature: n })}
+ min={0}
+ max={2}
+ step={0.05}
+ isFloat
+ />
+ <NumberRow
+ label={t("Max tokens")}
+ value={settings.co_writer.max_tokens}
+ onChange={(n) => patchSimple("co_writer", { max_tokens: n })}
+ min={256}
+ max={200000}
+ step={100}
+ />
+ </SettingSection>
+ </div>
+ );
+}
+
+// ── Field components (mirrors memory page) ─────────────────────────────
+
+interface NumberRowProps {
+ label: string;
+ help?: string;
+ value: number;
+ onChange: (n: number) => void;
+ min?: number;
+ max?: number;
+ step?: number;
+ isFloat?: boolean;
+}
+
+function NumberRow({
+ label,
+ help,
+ value,
+ onChange,
+ min,
+ max,
+ step = 1,
+ isFloat = false,
+}: NumberRowProps) {
+ return (
+ <SettingRow
+ title={label}
+ description={help}
+ control={
+ <input
+ type="number"
+ value={value}
+ min={min}
+ max={max}
+ step={step}
+ onChange={(e) => {
+ const raw = e.target.value;
+ if (raw === "") return;
+ const n = isFloat ? parseFloat(raw) : parseInt(raw, 10);
+ if (!Number.isNaN(n)) onChange(n);
+ }}
+ className="w-28 rounded-md border border-[var(--border)] bg-[var(--background)] px-2 py-1 text-right text-[12px] outline-none focus:border-[var(--primary)]"
+ />
+ }
+ />
+ );
+}
+
+interface ToggleRowProps {
+ label: string;
+ help?: string;
+ value: boolean;
+ onChange: (v: boolean) => void;
+}
+
+function ToggleRow({ label, help, value, onChange }: ToggleRowProps) {
+ return (
+ <SettingRow
+ title={label}
+ description={help}
+ control={
+ <button
+ type="button"
+ role="switch"
+ aria-checked={value}
+ onClick={() => onChange(!value)}
+ className={
+ "relative inline-flex h-5 w-9 items-center rounded-full transition " +
+ (value ? "bg-[var(--primary)]" : "bg-[var(--muted)]")
+ }
+ >
+ <span
+ className={
+ "inline-block h-4 w-4 transform rounded-full bg-white shadow transition " +
+ (value ? "translate-x-4" : "translate-x-0.5")
+ }
+ />
+ </button>
+ }
+ />
+ );
+}
diff --git a/web/app/(utility)/settings/embedding/page.tsx b/web/app/(utility)/settings/embedding/page.tsx
new file mode 100644
index 000000000..71a59b96a
--- /dev/null
+++ b/web/app/(utility)/settings/embedding/page.tsx
@@ -0,0 +1,21 @@
+"use client";
+
+import { useTranslation } from "react-i18next";
+
+import { ServiceConfigEditor } from "@/components/settings/ServiceConfigEditor";
+import { SettingsPageHeader } from "@/components/settings/shared";
+
+export default function EmbeddingSettingsPage() {
+ const { t } = useTranslation();
+ return (
+ <div>
+ <SettingsPageHeader
+ title={t("Embedding")}
+ description={t(
+ "Configure embedding model profiles. Used by retrieval and knowledge-base ingestion.",
+ )}
+ />
+ <ServiceConfigEditor service="embedding" />
+ </div>
+ );
+}
diff --git a/web/app/(utility)/settings/layout.tsx b/web/app/(utility)/settings/layout.tsx
new file mode 100644
index 000000000..51a337955
--- /dev/null
+++ b/web/app/(utility)/settings/layout.tsx
@@ -0,0 +1,38 @@
+import SettingsMiniNav from "@/components/settings/SettingsMiniNav";
+import { SettingsLoadStatusBanner } from "@/components/settings/SettingsLoadStatusBanner";
+import { SettingsProvider } from "@/components/settings/SettingsContext";
+import { SettingsToolbar } from "@/components/settings/SettingsToolbar";
+import { SettingsTourOverlay } from "@/components/settings/SettingsTourOverlay";
+
+export default function SettingsLayout({
+ children,
+}: Readonly<{
+ children: React.ReactNode;
+}>) {
+ return (
+ <SettingsProvider>
+ <div className="flex h-full overflow-hidden">
+ <SettingsMiniNav />
+ <main className="flex min-w-0 flex-1 flex-col overflow-hidden bg-[var(--background)]">
+ <div className="mx-auto w-full max-w-5xl px-10 pt-6">
+ <SettingsToolbar />
+ <SettingsLoadStatusBanner />
+ </div>
+ {/* Inner scroll container. Sticky elements inside (e.g. the
+ profile-list aside in ServiceConfigEditor) anchor to this
+ ancestor instead of <main>, so the left column stays put
+ while the right side scrolls. ``min-h-0`` is required for
+ the flex child to constrain to remaining space — without
+ it, ``overflow-y-auto`` would never clip and sticky would
+ keep failing to engage. */}
+ <div className="min-h-0 flex-1 overflow-y-auto overflow-x-hidden [scrollbar-gutter:stable]">
+ <div className="mx-auto w-full max-w-5xl px-10 pb-16">
+ <div className="mt-4">{children}</div>
+ </div>
+ </div>
+ </main>
+ <SettingsTourOverlay />
+ </div>
+ </SettingsProvider>
+ );
+}
diff --git a/web/app/(utility)/settings/llm/page.tsx b/web/app/(utility)/settings/llm/page.tsx
new file mode 100644
index 000000000..b7aacbde5
--- /dev/null
+++ b/web/app/(utility)/settings/llm/page.tsx
@@ -0,0 +1,21 @@
+"use client";
+
+import { useTranslation } from "react-i18next";
+
+import { ServiceConfigEditor } from "@/components/settings/ServiceConfigEditor";
+import { SettingsPageHeader } from "@/components/settings/shared";
+
+export default function LlmSettingsPage() {
+ const { t } = useTranslation();
+ return (
+ <div>
+ <SettingsPageHeader
+ title={t("LLM")}
+ description={t(
+ "Configure language model profiles. The active model is used for chat and most agent reasoning.",
+ )}
+ />
+ <ServiceConfigEditor service="llm" />
+ </div>
+ );
+}
diff --git a/web/app/(utility)/settings/mcp/page.tsx b/web/app/(utility)/settings/mcp/page.tsx
new file mode 100644
index 000000000..3c941d469
--- /dev/null
+++ b/web/app/(utility)/settings/mcp/page.tsx
@@ -0,0 +1,35 @@
+"use client";
+
+import { Plug } from "lucide-react";
+import { useTranslation } from "react-i18next";
+
+import { SettingsPageHeader } from "@/components/settings/shared";
+
+export default function McpSettingsPage() {
+ const { t } = useTranslation();
+
+ return (
+ <div data-tour="tour-mcp">
+ <SettingsPageHeader
+ title={t("MCP servers")}
+ description={t(
+ "Connect external MCP (Model Context Protocol) servers to extend the agent's capabilities.",
+ )}
+ />
+
+ <div className="flex flex-col items-center justify-center gap-3 rounded-xl border border-dashed border-[var(--border)]/70 bg-[var(--card)]/30 px-6 py-16 text-center">
+ <div className="flex h-10 w-10 items-center justify-center rounded-full bg-[var(--muted)]/60">
+ <Plug className="h-4 w-4 text-[var(--muted-foreground)]" />
+ </div>
+ <div className="text-[14px] font-medium text-[var(--foreground)]">
+ {t("MCP server support is coming soon")}
+ </div>
+ <p className="max-w-md text-[12.5px] leading-relaxed text-[var(--muted-foreground)]">
+ {t(
+ "We're working on a way to register and authenticate MCP servers from this page so the chat agent can call tools they expose. Until then, this section is reserved as a placeholder.",
+ )}
+ </p>
+ </div>
+ </div>
+ );
+}
diff --git a/web/app/(utility)/settings/memory/page.tsx b/web/app/(utility)/settings/memory/page.tsx
new file mode 100644
index 000000000..47713b915
--- /dev/null
+++ b/web/app/(utility)/settings/memory/page.tsx
@@ -0,0 +1,378 @@
+"use client";
+
+import { useCallback, useEffect, useRef, useState } from "react";
+import { Loader2 } from "lucide-react";
+import { useTranslation } from "react-i18next";
+
+import { apiFetch, apiUrl } from "@/lib/api";
+import {
+ SettingRow,
+ SettingSection,
+ SettingsPageHeader,
+} from "@/components/settings/shared";
+import { useSettings } from "@/components/settings/SettingsContext";
+
+interface MemorySettingsDTO {
+ update: { l2_budget: number; l3_budget: number };
+ audit: { l2_budget: number; l3_budget: number };
+ dedup: { iterations: number; auto_after_update: boolean };
+ merge: {
+ auto_after_update: boolean;
+ auto_after_audit: boolean;
+ auto_after_dedup: boolean;
+ };
+ chunking: {
+ overlap_ratio: number;
+ boundary: "paragraph" | "sentence";
+ min_chunk_chars: number;
+ max_chunk_chars: number;
+ };
+ reference: {
+ enforce_required: boolean;
+ drop_invalid_refs: boolean;
+ };
+}
+
+export default function MemorySettingsPage() {
+ const { t } = useTranslation();
+ const { registerExtension } = useSettings();
+ const [settings, setSettings] = useState<MemorySettingsDTO | null>(null);
+ const [serverSnapshot, setServerSnapshot] = useState<MemorySettingsDTO | null>(
+ null,
+ );
+
+ const load = useCallback(async () => {
+ const res = await apiFetch(apiUrl("/api/v1/memory/settings"));
+ const data = (await res.json()) as MemorySettingsDTO;
+ setSettings(data);
+ setServerSnapshot(data);
+ }, []);
+
+ useEffect(() => {
+ void load();
+ }, [load]);
+
+ const dirty =
+ !!settings &&
+ !!serverSnapshot &&
+ JSON.stringify(settings) !== JSON.stringify(serverSnapshot);
+
+ // Latest-save ref so the closure handed to registerExtension always
+ // reflects the current settings without re-registering on each render.
+ const settingsRef = useRef(settings);
+ settingsRef.current = settings;
+ const save = useCallback(async () => {
+ const current = settingsRef.current;
+ if (!current) return;
+ const res = await apiFetch(apiUrl("/api/v1/memory/settings"), {
+ method: "PUT",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify(current),
+ });
+ const data = (await res.json()) as MemorySettingsDTO;
+ setSettings(data);
+ setServerSnapshot(data);
+ }, []);
+
+ useEffect(() => {
+ registerExtension("memory", { dirty, save });
+ return () => registerExtension("memory", null);
+ }, [dirty, save, registerExtension]);
+
+ function patch<K extends keyof MemorySettingsDTO>(
+ key: K,
+ value: Partial<MemorySettingsDTO[K]>,
+ ) {
+ if (!settings) return;
+ setSettings({ ...settings, [key]: { ...settings[key], ...value } });
+ }
+
+ if (!settings) {
+ return (
+ <div className="grid h-[60vh] place-items-center text-[13px] text-[var(--muted-foreground)]">
+ <Loader2 className="h-4 w-4 animate-spin" />
+ </div>
+ );
+ }
+
+ return (
+ <div data-tour="tour-memory">
+ <SettingsPageHeader
+ title={t("Memory")}
+ description={t(
+ "Tune the chunk-based consolidator: how many LLM rounds per Update / Audit / Dedup, how aggressively to chunk, and how strictly to validate references.",
+ )}
+ />
+ <SettingSection
+ title={t("Update mode")}
+ description={t(
+ "Default LLM rounds for chunk-based incremental fact extraction. Per-doc overrides live in the workbench.",
+ )}
+ >
+ <NumberRow
+ label={t("L2 budget (per surface)")}
+ help={t("Maximum chunks the chunker emits for an L2 update.")}
+ value={settings.update.l2_budget}
+ onChange={(n) => patch("update", { l2_budget: n })}
+ min={1}
+ max={200}
+ />
+ <NumberRow
+ label={t("L3 budget (per slot)")}
+ help={t("Maximum chunks for an L3 update across the 7 L2 docs.")}
+ value={settings.update.l3_budget}
+ onChange={(n) => patch("update", { l3_budget: n })}
+ min={1}
+ max={200}
+ />
+ </SettingSection>
+
+ <SettingSection
+ title={t("Audit mode")}
+ description={t(
+ "Default LLM rounds for line-level edits against raw evidence.",
+ )}
+ >
+ <NumberRow
+ label={t("L2 budget (per surface)")}
+ value={settings.audit.l2_budget}
+ onChange={(n) => patch("audit", { l2_budget: n })}
+ min={1}
+ max={200}
+ />
+ <NumberRow
+ label={t("L3 budget (per slot)")}
+ value={settings.audit.l3_budget}
+ onChange={(n) => patch("audit", { l3_budget: n })}
+ min={1}
+ max={200}
+ />
+ </SettingSection>
+
+ <SettingSection
+ title={t("Dedup")}
+ description={t(
+ "Iterative dedup over the full doc. Stops early when an iteration emits zero edits.",
+ )}
+ >
+ <NumberRow
+ label={t("Iterations")}
+ value={settings.dedup.iterations}
+ onChange={(n) => patch("dedup", { iterations: n })}
+ min={1}
+ max={20}
+ />
+ <ToggleRow
+ label={t("Run dedup automatically after Update")}
+ value={settings.dedup.auto_after_update}
+ onChange={(v) => patch("dedup", { auto_after_update: v })}
+ />
+ </SettingSection>
+
+ <SettingSection
+ title={t("Merge footnotes")}
+ description={t(
+ "No-LLM consolidation: collapse duplicate ref rows into one footnote each, then renumber. Idempotent, safe to run any time.",
+ )}
+ >
+ <ToggleRow
+ label={t("Merge automatically after Update")}
+ value={settings.merge.auto_after_update}
+ onChange={(v) => patch("merge", { auto_after_update: v })}
+ />
+ <ToggleRow
+ label={t("Merge automatically after Audit")}
+ value={settings.merge.auto_after_audit}
+ onChange={(v) => patch("merge", { auto_after_audit: v })}
+ />
+ <ToggleRow
+ label={t("Merge automatically after Dedup")}
+ value={settings.merge.auto_after_dedup}
+ onChange={(v) => patch("merge", { auto_after_dedup: v })}
+ />
+ </SettingSection>
+
+ <SettingSection
+ title={t("Chunking")}
+ description={t("Lower-level knobs that shape how content is split.")}
+ >
+ <NumberRow
+ label={t("Overlap ratio")}
+ help={t("Fraction of chunk size carried into the next chunk. 0–0.5.")}
+ value={settings.chunking.overlap_ratio}
+ onChange={(n) => patch("chunking", { overlap_ratio: n })}
+ min={0}
+ max={0.5}
+ step={0.05}
+ isFloat
+ />
+ <SelectRow
+ label={t("Boundary")}
+ help={t("Where the chunker prefers to cut.")}
+ value={settings.chunking.boundary}
+ options={[
+ { value: "paragraph", label: t("Paragraph") },
+ { value: "sentence", label: t("Sentence") },
+ ]}
+ onChange={(v) => patch("chunking", { boundary: v as "paragraph" | "sentence" })}
+ />
+ <NumberRow
+ label={t("Min chunk chars")}
+ help={t("Floor for individual chunk size.")}
+ value={settings.chunking.min_chunk_chars}
+ onChange={(n) => patch("chunking", { min_chunk_chars: n })}
+ min={200}
+ max={64000}
+ step={100}
+ />
+ <NumberRow
+ label={t("Max chunk chars")}
+ help={t("Ceiling for individual chunk size.")}
+ value={settings.chunking.max_chunk_chars}
+ onChange={(n) => patch("chunking", { max_chunk_chars: n })}
+ min={200}
+ max={64000}
+ step={100}
+ />
+ </SettingSection>
+
+ <SettingSection
+ title={t("References")}
+ description={t(
+ "How strictly facts must cite the chunk they were extracted from.",
+ )}
+ >
+ <ToggleRow
+ label={t("Require ref on every fact")}
+ help={t("Drops facts that come back without a ref.")}
+ value={settings.reference.enforce_required}
+ onChange={(v) => patch("reference", { enforce_required: v })}
+ />
+ <ToggleRow
+ label={t("Drop invalid refs (vs reject the whole fact)")}
+ help={t("On: keep the fact, drop only out-of-pool refs. Off: any bad ref rejects the fact.")}
+ value={settings.reference.drop_invalid_refs}
+ onChange={(v) => patch("reference", { drop_invalid_refs: v })}
+ />
+ </SettingSection>
+ </div>
+ );
+}
+
+// ── Field components ────────────────────────────────────────────────
+
+interface NumberRowProps {
+ label: string;
+ help?: string;
+ value: number;
+ onChange: (n: number) => void;
+ min?: number;
+ max?: number;
+ step?: number;
+ isFloat?: boolean;
+}
+
+function NumberRow({
+ label,
+ help,
+ value,
+ onChange,
+ min,
+ max,
+ step = 1,
+ isFloat = false,
+}: NumberRowProps) {
+ return (
+ <SettingRow
+ title={label}
+ description={help}
+ control={
+ <input
+ type="number"
+ value={value}
+ min={min}
+ max={max}
+ step={step}
+ onChange={(e) => {
+ const raw = e.target.value;
+ if (raw === "") return;
+ const n = isFloat ? parseFloat(raw) : parseInt(raw, 10);
+ if (!Number.isNaN(n)) onChange(n);
+ }}
+ className="w-24 rounded-md border border-[var(--border)] bg-[var(--background)] px-2 py-1 text-right text-[12px] outline-none focus:border-[var(--primary)]"
+ />
+ }
+ />
+ );
+}
+
+interface ToggleRowProps {
+ label: string;
+ help?: string;
+ value: boolean;
+ onChange: (v: boolean) => void;
+}
+
+function ToggleRow({ label, help, value, onChange }: ToggleRowProps) {
+ return (
+ <SettingRow
+ title={label}
+ description={help}
+ control={
+ <button
+ type="button"
+ role="switch"
+ aria-checked={value}
+ onClick={() => onChange(!value)}
+ className={
+ "relative inline-flex h-5 w-9 items-center rounded-full transition " +
+ (value ? "bg-[var(--primary)]" : "bg-[var(--muted)]")
+ }
+ >
+ <span
+ className={
+ "inline-block h-4 w-4 transform rounded-full bg-white shadow transition " +
+ (value ? "translate-x-4" : "translate-x-0.5")
+ }
+ />
+ </button>
+ }
+ />
+ );
+}
+
+interface SelectRowProps {
+ label: string;
+ help?: string;
+ value: string;
+ options: { value: string; label: string }[];
+ onChange: (v: string) => void;
+}
+
+function SelectRow({ label, help, value, options, onChange }: SelectRowProps) {
+ return (
+ <SettingRow
+ title={label}
+ description={help}
+ control={
+ <div className="flex gap-0.5 rounded-lg bg-[var(--muted)] p-0.5">
+ {options.map((o) => (
+ <button
+ key={o.value}
+ type="button"
+ onClick={() => onChange(o.value)}
+ className={
+ "rounded-md px-2.5 py-1 text-[12px] transition-all " +
+ (value === o.value
+ ? "bg-[var(--card)] font-medium text-[var(--foreground)] shadow-sm"
+ : "text-[var(--muted-foreground)] hover:text-[var(--foreground)]")
+ }
+ >
+ {o.label}
+ </button>
+ ))}
+ </div>
+ }
+ />
+ );
+}
diff --git a/web/app/(utility)/settings/page.tsx b/web/app/(utility)/settings/page.tsx
index 20ce56722..0c78d1fe8 100644
--- a/web/app/(utility)/settings/page.tsx
+++ b/web/app/(utility)/settings/page.tsx
@@ -1,1955 +1,5 @@
-/* eslint-disable i18n/no-literal-ui-text */
-"use client";
+import { redirect } from "next/navigation";
-import { Suspense, useCallback, useEffect, useRef, useState } from "react";
-import {
- Brain,
- CheckCircle2,
- ChevronDown,
- ChevronRight,
- Database,
- Eye,
- EyeOff,
- Info,
- Loader2,
- Plus,
- Rocket,
- Save,
- Search,
- Terminal,
- Trash2,
- Wand2,
-} from "lucide-react";
-
-import { useTranslation } from "react-i18next";
-
-import { writeStoredLanguage } from "@/context/app-shell-storage";
-import { ModelAccessSummary } from "@/features/multi-user/components/ModelAccessSummary";
-import type { ModelAccess } from "@/features/multi-user/types";
-import { apiFetch, apiUrl } from "@/lib/api";
-import { setTheme as applyThemePreference } from "@/lib/theme";
-
-type ServiceName = "llm" | "embedding" | "search";
-
-type CatalogModel = {
- id: string;
- name: string;
- model: string;
- dimension?: string;
- send_dimensions?: boolean;
- // CSV of dims supported natively by the current model — refreshed by the
- // backend on every successful "Run test" for an embedding service.
- supported_dimensions?: string;
- context_window?: string;
- context_window_source?: string;
- context_window_detected_at?: string;
-};
-
-type CatalogProfile = {
- id: string;
- name: string;
- binding?: string;
- provider?: string;
- base_url: string;
- api_key: string;
- api_version: string;
- extra_headers?: Record<string, string> | string;
- proxy?: string;
- max_results?: number;
- models: CatalogModel[];
-};
-
-type CatalogService = {
- active_profile_id: string | null;
- active_model_id?: string | null;
- profiles: CatalogProfile[];
-};
-
-type Catalog = {
- version: number;
- services: {
- llm: CatalogService;
- embedding: CatalogService;
- search: CatalogService;
- };
-};
-
-type UiSettings = {
- theme: "light" | "dark" | "glass" | "snow";
- language: "en" | "zh";
-};
-
-type ProviderOption = {
- value: string;
- label: string;
- base_url?: string;
- default_dim?: string;
-};
-
-type SettingsPayload = {
- ui: UiSettings;
- catalog?: Catalog;
- model_access?: ModelAccess;
- providers?: Record<ServiceName, ProviderOption[]>;
-};
-
-type SystemStatus = {
- backend: { status: string; timestamp: string };
- llm: { status: string; model?: string; error?: string };
- embeddings: { status: string; model?: string; error?: string };
- search: { status: string; provider?: string; error?: string };
-};
-
-const SERVICES = ["llm", "embedding", "search"] as const;
-
-// ---------------------------------------------------------------------------
-
-function cloneCatalog(catalog: Catalog): Catalog {
- return JSON.parse(JSON.stringify(catalog)) as Catalog;
-}
-
-function getActiveProfile(
- catalog: Catalog,
- serviceName: ServiceName,
-): CatalogProfile | null {
- const service = catalog.services[serviceName];
- return (
- service.profiles.find(
- (profile) => profile.id === service.active_profile_id,
- ) ??
- service.profiles[0] ??
- null
- );
-}
-
-function getActiveModel(
- catalog: Catalog,
- serviceName: ServiceName,
-): CatalogModel | null {
- if (serviceName === "search") return null;
- const service = catalog.services[serviceName];
- const profile = getActiveProfile(catalog, serviceName);
- if (!profile) return null;
- return (
- profile.models.find((model) => model.id === service.active_model_id) ??
- profile.models[0] ??
- null
- );
-}
-
-function serviceIcon(service: ServiceName) {
- if (service === "llm") return <Brain className="h-3.5 w-3.5" />;
- if (service === "embedding") return <Database className="h-3.5 w-3.5" />;
- return <Search className="h-3.5 w-3.5" />;
-}
-
-function serviceLabel(
- service: ServiceName,
- t: (key: string) => string,
-): string {
- if (service === "llm") return t("LLM");
- if (service === "embedding") return t("Embedding");
- return t("Search");
-}
-
-function activeProfileDetail(
- profile: CatalogProfile | null,
- service: ServiceName,
- t: (key: string) => string,
-): string {
- if (!profile) return t("No profile");
- if (service === "search") return profile.provider || t("No provider");
- return profile.base_url || t("No endpoint");
-}
-
-function activeModelDetail(
- profile: CatalogProfile | null,
- model: CatalogModel | null,
- service: ServiceName,
- t: (key: string) => string,
-): string {
- if (service === "search") return profile?.provider || t("No provider");
- return model?.model || model?.name || t("No model selected");
-}
-
-function servicePendingApply(
- catalog: Catalog,
- draft: Catalog,
- service: ServiceName,
-): boolean {
- return (
- JSON.stringify(catalog.services[service]) !==
- JSON.stringify(draft.services[service])
- );
-}
-
-function statusDotClass(configured: boolean, hasError: boolean): string {
- if (hasError) return "bg-red-400";
- if (configured) return "bg-emerald-500";
- return "bg-[var(--border)]";
-}
-
-function defaultCatalog(): Catalog {
- return {
- version: 1,
- services: {
- llm: { active_profile_id: null, active_model_id: null, profiles: [] },
- embedding: {
- active_profile_id: null,
- active_model_id: null,
- profiles: [],
- },
- search: { active_profile_id: null, profiles: [] },
- },
- };
-}
-
-const fieldControlClass =
- "w-full rounded-lg border border-[var(--border)] px-3 py-2 text-[14px] text-[var(--foreground)] outline-none transition-colors focus:border-[var(--ring)]";
-
-const inputClass = `${fieldControlClass} bg-transparent placeholder:text-[var(--muted-foreground)]/40`;
-
-const nativeSelectClass = `${fieldControlClass} bg-[var(--background)] cursor-pointer disabled:cursor-not-allowed disabled:opacity-60`;
-
-const selectClass = `${nativeSelectClass} appearance-none`;
-
-const selectOptionClass = "bg-[var(--background)] text-[var(--foreground)]";
-
-function stringifyExtraHeaders(value: CatalogProfile["extra_headers"]): string {
- if (!value) return "";
- if (typeof value === "string") return value;
- try {
- return JSON.stringify(value);
- } catch {
- return "";
- }
-}
-
-function formatContextWindowSource(
- source: string | undefined,
- t: (key: string) => string,
-): string {
- if (source === "manual") return t("Manual");
- if (source === "metadata") return t("Auto");
- if (source === "known_model") return t("Known");
- if (source === "default") return t("Default");
- return t("Unset");
-}
-
-function formatContextWindowUpdatedAt(
- value: string | undefined,
- language: "en" | "zh",
-): string {
- if (!value) return "";
- const parsed = new Date(value);
- if (Number.isNaN(parsed.getTime())) return value;
- return parsed.toLocaleString(language === "zh" ? "zh-CN" : "en-US", {
- dateStyle: "medium",
- timeStyle: "short",
- });
-}
-
-// ---------------------------------------------------------------------------
-// Tour onboarding steps
-// ---------------------------------------------------------------------------
-
-const TOUR_GUIDE_STEPS = [
- {
- target: "tour-llm",
- service: "llm" as const,
- titleKey: "settingsTour.llm.title",
- descKey: "settingsTour.llm.desc",
- },
- {
- target: "tour-embedding",
- service: "embedding" as const,
- titleKey: "settingsTour.embedding.title",
- descKey: "settingsTour.embedding.desc",
- },
- {
- target: "tour-search",
- service: "search" as const,
- titleKey: "settingsTour.search.title",
- descKey: "settingsTour.search.desc",
- },
- {
- target: "tour-save-test",
- titleKey: "settingsTour.saveTest.title",
- descKey: "settingsTour.saveTest.desc",
- },
- {
- target: "tour-actions",
- titleKey: "settingsTour.apply.title",
- descKey: "settingsTour.apply.desc",
- },
-];
-
-const supportedSearchProviders = [
- "brave",
- "tavily",
- "jina",
- "searxng",
- "duckduckgo",
- "perplexity",
-] as const;
-const deprecatedSearchProviders = new Set([
- "exa",
- "serper",
- "baidu",
- "openrouter",
-]);
-
-// ---------------------------------------------------------------------------
-// Spotlight overlay component
-// ---------------------------------------------------------------------------
-
-function SpotlightOverlay({
- stepIndex,
- onNext,
- onSkip,
-}: {
- stepIndex: number;
- onNext: () => void;
- onSkip: () => void;
-}) {
- const { t } = useTranslation();
- const [rect, setRect] = useState<DOMRect | null>(null);
- const guideStep = TOUR_GUIDE_STEPS[stepIndex];
-
- useEffect(() => {
- if (!guideStep) return;
- const frame = window.requestAnimationFrame(() => {
- const el = document.querySelector(`[data-tour="${guideStep.target}"]`);
- setRect(el ? el.getBoundingClientRect() : null);
- });
- return () => window.cancelAnimationFrame(frame);
- }, [guideStep]);
-
- if (!guideStep || !rect) return null;
-
- const pad = 8;
- const holeLeft = rect.left - pad;
- const holeTop = rect.top - pad;
- const holeW = rect.width + pad * 2;
- const holeH = rect.height + pad * 2;
-
- const clipPath = `polygon(
- 0% 0%, 100% 0%, 100% 100%, 0% 100%, 0% 0%,
- ${holeLeft}px ${holeTop}px,
- ${holeLeft}px ${holeTop + holeH}px,
- ${holeLeft + holeW}px ${holeTop + holeH}px,
- ${holeLeft + holeW}px ${holeTop}px,
- ${holeLeft}px ${holeTop}px
- )`;
-
- const tooltipTop = holeTop + holeH + 12;
- const tooltipLeft = Math.max(16, Math.min(holeLeft, window.innerWidth - 340));
-
- return (
- <div className="fixed inset-0 z-[9999]">
- <div
- className="absolute inset-0 bg-black/50 transition-all duration-300"
- style={{ clipPath }}
- />
- <div
- className="absolute z-10 w-[320px] rounded-xl border border-[var(--border)] bg-[var(--card)] p-4 shadow-2xl"
- style={{ top: tooltipTop, left: tooltipLeft }}
- >
- <div className="mb-1 text-[13px] font-semibold text-[var(--foreground)]">
- {t(guideStep.titleKey)}
- </div>
- <p className="mb-4 text-[12px] leading-relaxed text-[var(--muted-foreground)]">
- {t(guideStep.descKey)}
- </p>
- <div className="flex items-center justify-between">
- <button
- onClick={onSkip}
- className="text-[12px] text-[var(--muted-foreground)]/60 transition-colors hover:text-[var(--muted-foreground)]"
- >
- {t("Skip tour")}
- </button>
- <button
- onClick={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 ? t("Next") : t("Got it")}
- <ChevronRight className="h-3 w-3" />
- </button>
- </div>
- </div>
- </div>
- );
-}
-
-// ---------------------------------------------------------------------------
-// Embedding dimension field — dropdown when supported list is known, free
-// input otherwise, with a "Detected: Xd · Use this" affordance after a test.
-// ---------------------------------------------------------------------------
-
-const CUSTOM_DIM_SENTINEL = "__custom__";
-const AUTO_DIM_SENTINEL = "";
-
-function parseSupportedCsv(csv: string | undefined): number[] {
- if (!csv) return [];
- return csv
- .split(",")
- .map((s) => s.trim())
- .filter(Boolean)
- .map((s) => Number(s))
- .filter((n) => Number.isFinite(n) && n > 0);
-}
-
-type EmbeddingCapabilities = {
- detected_dim?: number;
- default_dim?: number;
- supported_dimensions?: number[];
- supports_variable_dimensions?: boolean;
- model_known?: boolean;
- active_dim?: number;
- active_dim_source?: string;
-};
-
-function sourceBadge(
- source: string | undefined,
- t: (key: string) => string,
-): { label: string; tone: "muted" | "ok" | "warn" } | null {
- // The probe is the single source of truth: a successful test always emits
- // ``"detected"``. Other codes are legacy and no longer produced.
- if (source === "detected") {
- return { label: t("Source: detected from API probe"), tone: "ok" };
- }
- return null;
-}
-
-function DimensionField({
- activeModel,
- activeBinding,
- capabilities,
- embeddingDefaultDim,
- inputClass,
- onChangeDimension,
-}: {
- activeModel: CatalogModel;
- activeBinding?: string;
- capabilities: EmbeddingCapabilities | null;
- embeddingDefaultDim: (binding?: string) => string;
- inputClass: string;
- onChangeDimension: (value: string) => void;
-}) {
- const { t } = useTranslation();
- const fallback = embeddingDefaultDim(activeBinding);
- // Raw catalog state — empty string means "not yet configured / auto on
- // next test". We never substitute the fallback into the input value, only
- // into the placeholder, so the user can fully clear the field.
- const rawValue = activeModel.dimension ?? "";
- const isEmpty = rawValue === "";
- const currentNum = isEmpty ? NaN : Number(rawValue);
-
- // Live capabilities (from current run) override the cached CSV on disk.
- const liveSupported = capabilities?.supported_dimensions;
- const cachedSupported = parseSupportedCsv(activeModel.supported_dimensions);
- const supported =
- liveSupported && liveSupported.length > 0 ? liveSupported : cachedSupported;
- const supportsVariable =
- capabilities?.supports_variable_dimensions ?? supported.length > 1;
-
- const useDropdown = supported.length > 1 && supportsVariable;
- const currentInList =
- Number.isFinite(currentNum) && supported.includes(currentNum);
- // True when the user explicitly opted out of the dropdown by picking
- // "Custom…". Stays true until they click "Use a supported value" or pick
- // a real value from the dropdown again.
- const [customRequested, setCustomRequested] = useState<boolean>(false);
- // Force custom mode when the catalog has a non-empty value that isn't in
- // the list — that's a sign the user typed something custom and we should
- // respect it. Empty catalog stays in dropdown mode (showing "Auto").
- const customMode =
- customRequested || (useDropdown && !isEmpty && !currentInList);
-
- const detected = capabilities?.detected_dim;
- const showDetectedBadge =
- typeof detected === "number" &&
- detected > 0 &&
- detected !== currentNum &&
- !isEmpty;
-
- const sourceInfo = sourceBadge(capabilities?.active_dim_source, t);
-
- const disabled = activeModel.send_dimensions === false;
-
- const handleSelect = (value: string) => {
- if (value === CUSTOM_DIM_SENTINEL) {
- setCustomRequested(true);
- return;
- }
- setCustomRequested(false);
- // AUTO_DIM_SENTINEL is "" — clears the catalog, triggers auto-fill on
- // the next test. Real numeric values flow through unchanged.
- onChangeDimension(value);
- };
-
- const dropdownValue = isEmpty
- ? AUTO_DIM_SENTINEL
- : currentInList
- ? String(currentNum)
- : CUSTOM_DIM_SENTINEL;
-
- return (
- <div className="space-y-1.5">
- {useDropdown && !customMode ? (
- <select
- className={nativeSelectClass}
- value={dropdownValue}
- onChange={(e) => handleSelect(e.target.value)}
- disabled={disabled}
- >
- <option className={selectOptionClass} value={AUTO_DIM_SENTINEL}>
- {t("Auto (probe on next test)")}
- </option>
- {supported.map((dim) => (
- <option className={selectOptionClass} key={dim} value={String(dim)}>
- {dim}
- </option>
- ))}
- <option className={selectOptionClass} value={CUSTOM_DIM_SENTINEL}>
- {t("Custom…")}
- </option>
- </select>
- ) : (
- <input
- className={inputClass}
- value={rawValue}
- placeholder={fallback}
- onChange={(e) => onChangeDimension(e.target.value)}
- disabled={disabled}
- inputMode="numeric"
- />
- )}
- {useDropdown && customMode && (
- <button
- type="button"
- onClick={() => {
- setCustomRequested(false);
- if (isEmpty) {
- return;
- }
- // Snap to the closest supported value to keep the catalog honest.
- const closest = supported.reduce((acc, dim) =>
- Math.abs(dim - currentNum) < Math.abs(acc - currentNum)
- ? dim
- : acc,
- );
- onChangeDimension(String(closest));
- }}
- className="text-[11px] text-[var(--muted-foreground)] underline-offset-2 hover:underline"
- >
- {t("Use a supported value")}
- </button>
- )}
- {sourceInfo && (
- <div
- className={`text-[11px] ${
- sourceInfo.tone === "warn"
- ? "text-amber-600 dark:text-amber-400"
- : sourceInfo.tone === "ok"
- ? "text-emerald-600 dark:text-emerald-400"
- : "text-[var(--muted-foreground)]"
- }`}
- >
- {sourceInfo.label}
- </div>
- )}
- {showDetectedBadge && (
- <div className="flex items-center gap-2 text-[11px] text-[var(--muted-foreground)]">
- <span>
- {t("Detected")}: <strong>{detected}d</strong>
- </span>
- <button
- type="button"
- onClick={() => onChangeDimension(String(detected))}
- className="rounded-md border border-[var(--border)]/60 px-1.5 py-0.5 text-[10px] text-[var(--foreground)] transition-colors hover:border-[var(--border)]"
- disabled={disabled}
- >
- {t("Use this")}
- </button>
- </div>
- )}
- </div>
- );
-}
-
-// ═══════════════════════════════════════════════════════════════════════════
-// Main component
-// ═══════════════════════════════════════════════════════════════════════════
-
-function SettingsPageContent() {
- const { t } = useTranslation();
-
- const [status, setStatus] = useState<SystemStatus | null>(null);
- const [theme, setTheme] = useState<"light" | "dark" | "glass" | "snow">(
- "light",
- );
- const [language, setLanguage] = useState<"en" | "zh">("en");
- const [catalog, setCatalog] = useState<Catalog>(defaultCatalog());
- const [draft, setDraft] = useState<Catalog>(defaultCatalog());
- const [modelAccess, setModelAccess] = useState<ModelAccess | null>(null);
- // ``null`` means "we haven't received a /settings response yet". We render
- // a loading skeleton while it's null so non-admin users never see an empty
- // catalog editor flash before the API answers with model_access.
- const [catalogEditable, setCatalogEditable] = useState<boolean | null>(null);
- const [activeService, setActiveService] = useState<ServiceName>("llm");
- const [logs, setLogs] = useState<string>("Waiting for test run...");
- const [testRunning, setTestRunning] = useState<ServiceName | null>(null);
- const [saving, setSaving] = useState(false);
- const [applying, setApplying] = useState(false);
- const [showApiKey, setShowApiKey] = useState(false);
- const [toast, setToast] = useState<string>("");
- const [diagnosticsOpen, setDiagnosticsOpen] = useState(false);
- const [providers, setProviders] = useState<
- Record<ServiceName, ProviderOption[]>
- >({ llm: [], embedding: [], search: [] });
- // Most-recent capabilities snapshot from the embedding test run. Cleared
- // when the user kicks off another run, populated when the backend emits
- // the `capabilities` SSE event. Drives the source badge + "Detected: Xd"
- // affordance.
- const [embeddingCapabilities, setEmbeddingCapabilities] =
- useState<EmbeddingCapabilities | null>(null);
- const eventSourceRef = useRef<EventSource | null>(null);
-
- // Tour-specific state
- const [tourGuideStep, setTourGuideStep] = useState(-1);
-
- // -- Data loading -------------------------------------------------------
-
- useEffect(() => {
- const load = async () => {
- try {
- const settingsResponse = await apiFetch(apiUrl("/api/v1/settings"));
- if (!settingsResponse.ok) {
- throw new Error(`Settings fetch failed: ${settingsResponse.status}`);
- }
- const settingsPayload =
- (await settingsResponse.json()) as SettingsPayload;
- if (settingsPayload.catalog) {
- setCatalog(settingsPayload.catalog);
- setDraft(cloneCatalog(settingsPayload.catalog));
- setCatalogEditable(true);
- setModelAccess(null);
- } else {
- setCatalogEditable(false);
- setModelAccess(settingsPayload.model_access ?? null);
- }
- setTheme(settingsPayload.ui.theme);
- setLanguage(settingsPayload.ui.language);
- if (settingsPayload.providers) setProviders(settingsPayload.providers);
- } catch (err) {
- console.error("Failed to load settings:", err);
- }
-
- try {
- const statusResponse = await apiFetch(apiUrl("/api/v1/system/status"));
- if (!statusResponse.ok) {
- throw new Error(`Status fetch failed: ${statusResponse.status}`);
- }
- const statusPayload = (await statusResponse.json()) as SystemStatus;
- setStatus(statusPayload);
- } catch (err) {
- console.error("Failed to load system status:", err);
- }
- };
- load();
- return () => {
- if (eventSourceRef.current) eventSourceRef.current.close();
- };
- }, []);
-
- useEffect(() => {
- if (!toast) return;
- const timer = setTimeout(() => setToast(""), 3500);
- return () => clearTimeout(timer);
- }, [toast]);
-
- // Reset stale ``embeddingCapabilities`` whenever the active embedding
- // profile or model changes. Without this, a 4096d detection on profile A
- // bleeds into profile B's "Detected: …" affordance after a switch.
- useEffect(() => {
- setEmbeddingCapabilities(null);
- }, [
- draft.services.embedding.active_profile_id,
- draft.services.embedding.active_model_id,
- ]);
-
- // -- Tour guide auto-switch active service tab --------------------------
-
- useEffect(() => {
- const currentStep = TOUR_GUIDE_STEPS[tourGuideStep];
- if (currentStep?.service) {
- setActiveService(currentStep.service);
- }
- }, [tourGuideStep]);
-
- // -- Derived ------------------------------------------------------------
-
- const settingsLoading = catalogEditable === null;
- const activeProfile = getActiveProfile(draft, activeService);
- const activeModel = getActiveModel(draft, activeService);
- const hasUnsavedChanges =
- catalogEditable === true &&
- JSON.stringify(catalog) !== JSON.stringify(draft);
- const searchProviderRaw =
- activeService === "search"
- ? (activeProfile?.provider || "").trim().toLowerCase()
- : "";
- const showSearchProviderWarning =
- activeService === "search" && Boolean(searchProviderRaw);
- const isDeprecatedSearchProvider =
- deprecatedSearchProviders.has(searchProviderRaw);
- const isSupportedSearchProvider = supportedSearchProviders.includes(
- searchProviderRaw as (typeof supportedSearchProviders)[number],
- );
- const isPerplexityMissingKey =
- activeService === "search" &&
- searchProviderRaw === "perplexity" &&
- !String(activeProfile?.api_key || "").trim();
-
- // Category-label typography. English looks great with `uppercase` + wide
- // letter-spacing, but CJK glyphs are already square blocks — extra tracking
- // pushes them apart and `uppercase` is a no-op. For zh we drop both and
- // bump size by ~1px to keep visual weight comparable.
- const labelClass = (size: "sm" | "md" | "lg"): string => {
- if (language === "zh") {
- if (size === "sm") return "text-[10.5px] font-medium";
- if (size === "lg") return "text-[12px] font-medium";
- return "text-[11px] font-medium";
- }
- if (size === "sm")
- return "text-[9.5px] font-semibold uppercase tracking-[0.16em]";
- if (size === "lg") return "text-[11px] uppercase tracking-[0.16em]";
- return "text-[10px] font-semibold uppercase tracking-[0.16em]";
- };
-
- useEffect(() => {
- setShowApiKey(false);
- }, [activeService, activeProfile?.id]);
-
- // -- UI preference helpers ----------------------------------------------
-
- const persistUi = async (
- nextTheme: "light" | "dark" | "glass" | "snow",
- nextLanguage: "en" | "zh",
- ) => {
- await apiFetch(apiUrl("/api/v1/settings/ui"), {
- method: "PUT",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({ theme: nextTheme, language: nextLanguage }),
- });
- };
-
- const updateTheme = async (
- nextTheme: "light" | "dark" | "glass" | "snow",
- ) => {
- setTheme(nextTheme);
- applyThemePreference(nextTheme);
- await persistUi(nextTheme, language);
- };
-
- const updateLanguage = async (nextLanguage: "en" | "zh") => {
- setLanguage(nextLanguage);
- writeStoredLanguage(nextLanguage);
- await persistUi(theme, nextLanguage);
- };
-
- // -- Catalog mutations --------------------------------------------------
-
- const mutateCatalog = (mutator: (next: Catalog) => void) => {
- setDraft((current) => {
- const next = cloneCatalog(current);
- mutator(next);
- return next;
- });
- };
-
- const embeddingDefaultDim = (binding?: string) => {
- const match = (providers.embedding || []).find(
- (p) => p.value === (binding || "openai"),
- );
- return match?.default_dim || "3072";
- };
-
- const addProfile = () => {
- mutateCatalog((next) => {
- const service = next.services[activeService];
- const profileId = `${activeService}-profile-${Date.now()}`;
- const profile: CatalogProfile = {
- id: profileId,
- name: "New Profile",
- binding: activeService === "search" ? undefined : "openai",
- provider: activeService === "search" ? "brave" : undefined,
- base_url: "",
- api_key: "",
- api_version: "",
- extra_headers: activeService === "search" ? undefined : {},
- proxy: activeService === "search" ? "" : undefined,
- models: [],
- };
- if (activeService !== "search") {
- const modelId = `${activeService}-model-${Date.now()}`;
- profile.models.push({
- id: modelId,
- name: "New Model",
- model: "",
- ...(activeService === "embedding"
- ? { dimension: embeddingDefaultDim(), send_dimensions: true }
- : {}),
- });
- service.active_model_id = modelId;
- }
- service.profiles.push(profile);
- service.active_profile_id = profileId;
- });
- };
-
- const removeActiveProfile = () => {
- mutateCatalog((next) => {
- const service = next.services[activeService];
- service.profiles = service.profiles.filter(
- (profile) => profile.id !== service.active_profile_id,
- );
- service.active_profile_id = service.profiles[0]?.id ?? null;
- if (activeService !== "search") {
- service.active_model_id = service.profiles[0]?.models?.[0]?.id ?? null;
- }
- });
- };
-
- const addModel = () => {
- if (activeService === "search") return;
- mutateCatalog((next) => {
- const service = next.services[activeService];
- const profile =
- service.profiles.find(
- (item) => item.id === service.active_profile_id,
- ) ?? null;
- if (!profile) return;
- const modelId = `${activeService}-model-${Date.now()}`;
- profile.models.push({
- id: modelId,
- name: "New Model",
- model: "",
- ...(activeService === "embedding"
- ? {
- dimension: embeddingDefaultDim(profile.binding),
- send_dimensions: true,
- }
- : {}),
- });
- service.active_model_id = modelId;
- });
- };
-
- const removeActiveModel = () => {
- if (activeService === "search") return;
- mutateCatalog((next) => {
- const service = next.services[activeService];
- const profile =
- service.profiles.find(
- (item) => item.id === service.active_profile_id,
- ) ?? null;
- if (!profile) return;
- profile.models = profile.models.filter(
- (item) => item.id !== service.active_model_id,
- );
- service.active_model_id = profile.models[0]?.id ?? null;
- });
- };
-
- const updateProfileField = (field: keyof CatalogProfile, value: string) => {
- mutateCatalog((next) => {
- const profile = getActiveProfile(next, activeService);
- if (!profile) return;
- (profile[field] as string | undefined) = value;
- });
- };
-
- const updateModelField = (field: keyof CatalogModel, value: string) => {
- if (activeService === "search") return;
- mutateCatalog((next) => {
- const model = getActiveModel(next, activeService);
- if (!model) return;
- (model[field] as string | undefined) = value;
- });
- };
-
- const updateContextWindowField = (value: string) => {
- if (activeService !== "llm") return;
- const normalized = value.replace(/[^\d]/g, "");
- mutateCatalog((next) => {
- const model = getActiveModel(next, activeService);
- if (!model) return;
- if (normalized) {
- model.context_window = normalized;
- model.context_window_source = "manual";
- delete model.context_window_detected_at;
- } else {
- delete model.context_window;
- delete model.context_window_source;
- delete model.context_window_detected_at;
- }
- });
- };
-
- const updateModelBoolField = (field: keyof CatalogModel, value: boolean) => {
- if (activeService === "search") return;
- mutateCatalog((next) => {
- const model = getActiveModel(next, activeService);
- if (!model) return;
- (model[field] as boolean | undefined) = value;
- });
- };
-
- // -- Save / Apply -------------------------------------------------------
-
- const saveCatalog = async () => {
- if (!catalogEditable) return;
- setSaving(true);
- try {
- const response = await apiFetch(apiUrl("/api/v1/settings/catalog"), {
- method: "PUT",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({ catalog: draft }),
- });
- const payload = await response.json();
- setCatalog(payload.catalog);
- setDraft(cloneCatalog(payload.catalog));
- setToast(t("Draft saved"));
- } finally {
- setSaving(false);
- }
- };
-
- const applyCatalog = async () => {
- if (!catalogEditable) return;
- setApplying(true);
- try {
- const response = await apiFetch(apiUrl("/api/v1/settings/apply"), {
- method: "POST",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({ catalog: draft }),
- });
- const payload = await response.json();
- setCatalog(payload.catalog);
- setDraft(cloneCatalog(payload.catalog));
- setToast(t("Applied to runtime settings"));
- const statusResponse = await apiFetch(apiUrl("/api/v1/system/status"));
- setStatus((await statusResponse.json()) as SystemStatus);
- } finally {
- setApplying(false);
- }
- };
-
- // -- Diagnostics (existing single-service test) -------------------------
-
- const runDetailedTest = async () => {
- if (!catalogEditable) return;
- if (eventSourceRef.current) {
- eventSourceRef.current.close();
- eventSourceRef.current = null;
- }
- setLogs(`Preparing ${activeService} diagnostics...\n`);
- setTestRunning(activeService);
- if (activeService === "embedding") {
- setEmbeddingCapabilities(null);
- }
- try {
- const response = await apiFetch(
- apiUrl(`/api/v1/settings/tests/${activeService}/start`),
- {
- method: "POST",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({ catalog: draft }),
- },
- );
- const payload = (await response.json()) as {
- run_id?: string;
- detail?: string;
- };
- if (!response.ok || !payload.run_id) {
- throw new Error(payload.detail || "Could not start diagnostics.");
- }
- const source = new EventSource(
- apiUrl(
- `/api/v1/settings/tests/${activeService}/${payload.run_id}/events`,
- ),
- );
- eventSourceRef.current = source;
- source.onmessage = (event) => {
- const entry = JSON.parse(event.data) as {
- type: string;
- message: string;
- catalog?: Catalog;
- detected_dim?: number;
- default_dim?: number;
- supported_dimensions?: number[];
- supports_variable_dimensions?: boolean;
- model_known?: boolean;
- active_dim?: number;
- active_dim_source?: string;
- };
- setLogs((current) => `${current}[${entry.type}] ${entry.message}\n`);
- if (entry.type === "capabilities") {
- setEmbeddingCapabilities({
- detected_dim: entry.detected_dim,
- default_dim: entry.default_dim,
- supported_dimensions: entry.supported_dimensions,
- supports_variable_dimensions: entry.supports_variable_dimensions,
- model_known: entry.model_known,
- active_dim: entry.active_dim,
- active_dim_source: entry.active_dim_source,
- });
- }
- if (entry.catalog) {
- setCatalog(entry.catalog);
- setDraft(cloneCatalog(entry.catalog));
- }
- if (entry.type === "completed" || entry.type === "failed") {
- source.close();
- eventSourceRef.current = null;
- setTestRunning(null);
- setToast(entry.message);
- }
- };
- source.onerror = () => {
- source.close();
- eventSourceRef.current = null;
- setTestRunning(null);
- setLogs(
- (current) => `${current}[failed] Diagnostics stream disconnected.\n`,
- );
- setToast(t("Diagnostics stream disconnected"));
- };
- } catch (error) {
- const message =
- error instanceof Error ? error.message : "Could not start diagnostics.";
- setLogs((current) => `${current}[failed] ${message}\n`);
- setToast(message);
- setTestRunning(null);
- }
- };
-
- // -- Tour ---------------------------------------------------------------
-
- const runTour = useCallback(() => {
- setTourGuideStep(0);
- }, []);
-
- // ═══════════════════════════════════════════════════════════════════════
- // Render
- // ═══════════════════════════════════════════════════════════════════════
-
- return (
- <div className="h-full overflow-y-auto [scrollbar-gutter:stable]">
- <div className="mx-auto max-w-[960px] px-6 py-8">
- {/* ── Header ── */}
- <div className="mb-6 flex items-start justify-between">
- <div>
- <h1 className="text-[24px] font-semibold tracking-tight text-[var(--foreground)]">
- {t("Settings")}
- </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)]">
- {hasUnsavedChanges
- ? t("Draft has unsaved changes")
- : t("All changes saved")}
- </p>
- )}
- </div>
- <div className="flex items-center gap-2">
- {catalogEditable === true && (
- <>
- <button
- onClick={runTour}
- 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)]"
- >
- <Rocket className="h-3 w-3" />
- {t("Tour")}
- </button>
- <button
- data-tour="tour-save-test"
- onClick={saveCatalog}
- disabled={saving}
- 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" />
- )}
- {t("Save Draft")}
- </button>
- <button
- data-tour="tour-actions"
- onClick={applyCatalog}
- disabled={applying}
- className="inline-flex items-center gap-1.5 rounded-lg bg-[var(--foreground)] px-3 py-1.5 text-[12px] font-medium text-[var(--background)] transition-opacity hover:opacity-80 disabled:opacity-40"
- >
- {applying ? (
- <Loader2 className="h-3 w-3 animate-spin" />
- ) : (
- <Wand2 className="h-3 w-3" />
- )}
- {t("Apply")}
- </button>
- </>
- )}
- </div>
- </div>
-
- {/* ── Preferences ── */}
- <div className="mb-5 flex flex-wrap items-center gap-x-8 gap-y-3">
- <div className="flex items-center gap-2">
- <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">
- {(["snow", "light", "dark", "glass"] as const).map((v) => (
- <button
- key={v}
- onClick={() => updateTheme(v)}
- className={`rounded-md px-2.5 py-1 text-[12px] transition-all ${
- theme === v
- ? "bg-[var(--card)] font-medium text-[var(--foreground)] shadow-sm"
- : "text-[var(--muted-foreground)] hover:text-[var(--foreground)]"
- }`}
- >
- {v === "snow"
- ? t("Snow")
- : v === "light"
- ? t("Light")
- : v === "dark"
- ? t("Dark")
- : t("Glass")}
- </button>
- ))}
- </div>
- </div>
-
- <div className="flex items-center gap-2">
- <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
- key={v}
- onClick={() => updateLanguage(v)}
- className={`rounded-md px-2.5 py-1 text-[12px] transition-all ${
- language === v
- ? "bg-[var(--card)] font-medium text-[var(--foreground)] shadow-sm"
- : "text-[var(--muted-foreground)] hover:text-[var(--foreground)]"
- }`}
- >
- {v === "en" ? t("language.english") : t("language.chinese")}
- </button>
- ))}
- </div>
- </div>
- </div>
-
- {settingsLoading && (
- <div className="mt-5 rounded-2xl border border-[var(--border)]/50 bg-[var(--card)] p-5 animate-pulse">
- <div className="h-4 w-32 rounded bg-[var(--muted)]/60" />
- <div className="mt-4 grid gap-3 sm:grid-cols-3">
- {[0, 1, 2].map((i) => (
- <div
- key={i}
- className="h-20 rounded-xl border border-[var(--border)]/40 bg-[var(--background)]/40"
- />
- ))}
- </div>
- </div>
- )}
-
- {catalogEditable === false && (
- <>
- {modelAccess && <ModelAccessSummary access={modelAccess} />}
- <p className="mt-5 text-[12px] leading-relaxed text-[var(--muted-foreground)]">
- {t(
- "Model endpoints are assigned by your administrator. You can still personalize theme and language here.",
- )}
- </p>
- </>
- )}
-
- {/* ── Runtime status ── */}
- {catalogEditable === true && (
- <>
- <div className="mb-8 grid grid-cols-2 overflow-hidden rounded-xl border border-[var(--border)]/60 sm:grid-cols-4">
- <div
- className="px-4 py-3.5"
- title={status?.backend.timestamp || t("Backend status")}
- >
- <div className="flex items-center gap-2">
- <span
- className={`h-1.5 w-1.5 rounded-full ${statusDotClass(
- status?.backend.status === "online",
- false,
- )}`}
- />
- <span
- className={`${labelClass("md")} text-[var(--muted-foreground)]`}
- >
- {t("Backend")}
- </span>
- </div>
- <div className="mt-2 truncate text-[13px] font-medium text-[var(--foreground)]">
- {status?.backend.status === "online"
- ? t("Online")
- : t("Checking")}
- </div>
- <div className="mt-0.5 truncate text-[11px] text-[var(--muted-foreground)]">
- {(() => {
- const ts = status?.backend.timestamp;
- if (!ts) return "—";
- const parsed = new Date(ts);
- if (Number.isNaN(parsed.getTime())) return "";
- return parsed.toLocaleTimeString(
- language === "zh" ? "zh-CN" : "en-US",
- { hour: "2-digit", minute: "2-digit" },
- );
- })()}
- </div>
- </div>
-
- {SERVICES.map((service, i) => {
- const profile = getActiveProfile(draft, service);
- const model = getActiveModel(draft, service);
- const serviceStatus =
- service === "llm"
- ? status?.llm
- : service === "embedding"
- ? status?.embeddings
- : status?.search;
- const runtimeModel =
- service === "llm"
- ? status?.llm.model
- : service === "embedding"
- ? status?.embeddings.model
- : undefined;
- const configured =
- service === "search"
- ? Boolean(profile?.provider || status?.search.provider)
- : Boolean(model?.model || runtimeModel);
- const pendingApply = servicePendingApply(
- catalog,
- draft,
- service,
- );
- const detail = activeModelDetail(profile, model, service, t);
- const profileName = profile?.name || t("No profile");
- const isActiveTab = activeService === service;
- const borderClasses =
- i === 0
- ? "border-l border-[var(--border)]/40"
- : i === 1
- ? "border-t border-[var(--border)]/40 sm:border-t-0 sm:border-l"
- : "border-t border-l border-[var(--border)]/40 sm:border-t-0";
- return (
- <button
- key={service}
- type="button"
- onClick={() => setActiveService(service)}
- title={`${serviceLabel(service, t)} · ${profileName} · ${detail}`}
- className={`relative px-4 py-3.5 text-left transition-colors ${borderClasses} ${
- isActiveTab
- ? "bg-[var(--muted)]/55"
- : "hover:bg-[var(--muted)]/30"
- }`}
- >
- <div className="flex items-center gap-2">
- <span
- className={`h-1.5 w-1.5 rounded-full ${statusDotClass(
- configured,
- Boolean(serviceStatus?.error),
- )}`}
- />
- <span
- className={`truncate ${labelClass("md")} text-[var(--muted-foreground)]`}
- >
- {serviceLabel(service, t)}
- </span>
- {pendingApply && (
- <span className="ml-auto shrink-0 text-[10px] font-medium text-amber-600 dark:text-amber-400">
- {t("Pending")}
- </span>
- )}
- </div>
- <div className="mt-2 truncate text-[13px] font-medium text-[var(--foreground)]">
- {detail}
- </div>
- <div className="mt-0.5 truncate text-[11px] text-[var(--muted-foreground)]">
- {profileName}
- </div>
- </button>
- );
- })}
- </div>
-
- {/* ── Service Configuration ── */}
- <div className="mb-8">
- <div className="mb-5 flex items-center justify-between">
- <div className="flex items-center gap-1">
- {(["llm", "embedding", "search"] as const).map((service) => (
- <button
- key={service}
- data-tour={`tour-${service}`}
- onClick={() => setActiveService(service)}
- className={`inline-flex items-center gap-1.5 rounded-lg px-3 py-1.5 text-[13px] transition-colors ${
- activeService === service
- ? "bg-[var(--muted)] font-medium text-[var(--foreground)]"
- : "text-[var(--muted-foreground)] hover:text-[var(--foreground)]"
- }`}
- >
- {serviceIcon(service)}
- {service.toUpperCase()}
- <span className="text-[11px] text-[var(--muted-foreground)]/60">
- {draft.services[service].profiles.length}
- </span>
- </button>
- ))}
- </div>
- <div className="flex items-center gap-2">
- <button
- onClick={addProfile}
- 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" />
- {t("Profile")}
- </button>
- {activeService !== "search" && (
- <button
- onClick={addModel}
- 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" />
- {t("Model")}
- </button>
- )}
- </div>
- </div>
-
- {activeProfile ? (
- <div className="grid grid-cols-[200px_1fr] gap-5">
- {/* ── Profile list ── */}
- <div className="space-y-2">
- {draft.services[activeService].profiles.map((profile) => {
- const isActive =
- profile.id ===
- draft.services[activeService].active_profile_id;
- const activeProfileModel =
- activeService === "search"
- ? null
- : (profile.models.find(
- (model) =>
- model.id ===
- draft.services[activeService].active_model_id,
- ) ??
- profile.models[0] ??
- null);
- const profileDetail = activeProfileDetail(
- profile,
- activeService,
- t,
- );
- const modelDetail = activeModelDetail(
- profile,
- activeProfileModel,
- activeService,
- t,
- );
- return (
- <button
- key={profile.id}
- onClick={() =>
- mutateCatalog((next) => {
- next.services[activeService].active_profile_id =
- profile.id;
- if (activeService !== "search") {
- next.services[activeService].active_model_id =
- profile.models[0]?.id ?? null;
- }
- })
- }
- className={`relative w-full overflow-hidden rounded-xl px-3.5 py-3 text-left transition-colors ${
- isActive
- ? "bg-[var(--muted)]/60 text-[var(--foreground)]"
- : "text-[var(--muted-foreground)] hover:bg-[var(--muted)]/30"
- }`}
- >
- {isActive && (
- <span className="absolute inset-y-3 left-0 w-0.5 rounded-r-full bg-[var(--foreground)]/80" />
- )}
- <div className="truncate text-[13px] font-semibold">
- {profile.name}
- </div>
- <div className="mt-0.5 truncate text-[11px] text-[var(--muted-foreground)]">
- {profileDetail}
- </div>
- {isActive ? (
- <div className="mt-2.5 border-t border-[var(--border)]/40 pt-2">
- <div
- className={`${labelClass("sm")} text-[var(--muted-foreground)]/70`}
- >
- {activeService === "search"
- ? t("Active provider")
- : t("Active model")}
- </div>
- <div className="mt-0.5 truncate text-[12px] font-medium text-[var(--foreground)]">
- {modelDetail}
- </div>
- </div>
- ) : (
- activeService !== "search" && (
- <div className="mt-1 text-[11px] text-[var(--muted-foreground)]/60">
- {t("{{count}} models", {
- count: profile.models.length,
- })}
- </div>
- )
- )}
- </button>
- );
- })}
- <button
- onClick={removeActiveProfile}
- disabled={!activeProfile}
- 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" />
- {t("Delete profile")}
- </button>
- </div>
-
- {/* ── Editor ── */}
- <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)]">
- {t("Profile")}
- </div>
- <div className="grid gap-4 sm:grid-cols-2">
- <div>
- <div className="mb-1.5 text-[12px] text-[var(--muted-foreground)]">
- {t("Name")}
- </div>
- <input
- className={inputClass}
- value={activeProfile.name}
- onChange={(e) =>
- updateProfileField("name", e.target.value)
- }
- />
- </div>
- <div>
- <div className="mb-1.5 text-[12px] text-[var(--muted-foreground)]">
- {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) {
- updateProfileField(
- "base_url",
- match.base_url,
- );
- }
- if (
- activeService === "embedding" &&
- match?.default_dim
- ) {
- updateModelField(
- "dimension",
- match.default_dim,
- );
- }
- }}
- >
- <option className={selectOptionClass} value="">
- {t("Select provider...")}
- </option>
- {(providers[activeService] || []).map((p) => (
- <option
- className={selectOptionClass}
- 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>
- {showSearchProviderWarning && (
- <p
- className={`mt-1.5 text-[11px] ${
- isSupportedSearchProvider
- ? "text-emerald-600 dark:text-emerald-400"
- : isDeprecatedSearchProvider
- ? "text-amber-600 dark:text-amber-400"
- : "text-red-500"
- }`}
- >
- {isSupportedSearchProvider
- ? isPerplexityMissingKey
- ? t(
- "Perplexity requires API key. It will fail hard without credentials.",
- )
- : t("Supported provider.")
- : isDeprecatedSearchProvider
- ? 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)]">
- {activeService === "embedding"
- ? t("Endpoint URL")
- : t("Base URL")}
- </div>
- <input
- className={inputClass}
- value={activeProfile.base_url}
- onChange={(e) =>
- updateProfileField("base_url", e.target.value)
- }
- placeholder={
- activeService === "embedding"
- ? "https://api.openai.com/v1/embeddings"
- : "https://api.openai.com/v1"
- }
- />
- {activeService === "embedding" && (
- <p className="mt-1.5 text-[11px] text-[var(--muted-foreground)]">
- {t(
- "Embedding requests are sent to this URL exactly; DeepTutor does not append /embeddings or /api/embed at request time.",
- )}
- </p>
- )}
- </div>
- <div className="sm:col-span-2">
- <div className="mb-1.5 text-[12px] text-[var(--muted-foreground)]">
- {t("API Key")}
- </div>
- <div className="relative">
- <input
- type={showApiKey ? "text" : "password"}
- autoComplete="new-password"
- spellCheck={false}
- className={`${inputClass} pr-10 font-mono`}
- value={activeProfile.api_key}
- onChange={(e) =>
- updateProfileField("api_key", e.target.value)
- }
- placeholder="sk-..."
- />
- <button
- type="button"
- onClick={() => setShowApiKey((prev) => !prev)}
- className="absolute right-1 top-1/2 -translate-y-1/2 rounded-md p-1.5 text-[var(--muted-foreground)] hover:bg-[var(--muted)] hover:text-[var(--foreground)]"
- aria-label={
- showApiKey
- ? t("Hide API key")
- : t("Show API key")
- }
- title={
- showApiKey
- ? t("Hide API key")
- : t("Show API key")
- }
- >
- {showApiKey ? (
- <EyeOff className="h-4 w-4" />
- ) : (
- <Eye className="h-4 w-4" />
- )}
- </button>
- </div>
- </div>
- <div>
- <div className="mb-1.5 text-[12px] text-[var(--muted-foreground)]">
- {t("API Version")}
- </div>
- <input
- className={inputClass}
- value={activeProfile.api_version}
- onChange={(e) =>
- updateProfileField("api_version", e.target.value)
- }
- placeholder={t("Optional")}
- />
- </div>
- {activeService === "search" ? (
- <div>
- <div className="mb-1.5 text-[12px] text-[var(--muted-foreground)]">
- {t("Proxy")}
- </div>
- <input
- className={inputClass}
- value={activeProfile.proxy || ""}
- onChange={(e) =>
- updateProfileField("proxy", e.target.value)
- }
- placeholder="http://127.0.0.1:7890 (optional)"
- />
- </div>
- ) : (
- <div className="sm:col-span-2">
- <div className="mb-1.5 text-[12px] text-[var(--muted-foreground)]">
- {t("Extra Headers (JSON)")}
- </div>
- <textarea
- className={`${inputClass} min-h-[84px] resize-y`}
- value={stringifyExtraHeaders(
- activeProfile.extra_headers,
- )}
- onChange={(e) =>
- updateProfileField(
- "extra_headers",
- e.target.value,
- )
- }
- placeholder='{"APP-Code":"your-app-code"}'
- />
- </div>
- )}
- </div>
- </div>
-
- {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)]">
- {t("Models")}
- </div>
- <button
- onClick={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" />
- {t("Delete")}
- </button>
- </div>
- {activeProfile.models.length > 0 && (
- <div className="mb-4 flex flex-wrap gap-1.5">
- {activeProfile.models.map((model) => (
- <button
- key={model.id}
- onClick={() =>
- mutateCatalog((next) => {
- next.services[
- activeService
- ].active_model_id = model.id;
- })
- }
- className={`rounded-lg px-3 py-1.5 text-[13px] transition-colors ${
- model.id ===
- draft.services[activeService].active_model_id
- ? "bg-[var(--foreground)] font-medium text-[var(--background)] shadow-sm"
- : "text-[var(--muted-foreground)] hover:bg-[var(--muted)]/50"
- }`}
- >
- <span className="inline-flex items-center gap-1.5">
- {model.id ===
- draft.services[activeService]
- .active_model_id && (
- <CheckCircle2 className="h-3 w-3" />
- )}
- {model.name}
- </span>
- </button>
- ))}
- </div>
- )}
- {activeModel && (
- <div className="grid gap-4 sm:grid-cols-2">
- <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)]">
- {t("Model ID")}
- </div>
- <input
- className={inputClass}
- value={activeModel.model}
- onChange={(e) =>
- updateModelField("model", e.target.value)
- }
- placeholder="gpt-4o"
- />
- </div>
- {activeService === "llm" && (
- <>
- <div>
- <div className="mb-1.5 text-[12px] text-[var(--muted-foreground)]">
- {t("Context Window")}
- </div>
- <input
- className={inputClass}
- inputMode="numeric"
- value={activeModel.context_window || ""}
- onChange={(e) =>
- updateContextWindowField(e.target.value)
- }
- placeholder="65536"
- />
- </div>
- <div className="rounded-xl border border-[var(--border)]/70 bg-[var(--muted)]/30 px-3.5 py-3">
- <div className="flex items-center justify-between gap-3">
- <div
- className={`${labelClass("lg")} text-[var(--muted-foreground)]/70`}
- >
- {t("Source")}
- </div>
- <span className="rounded-full border border-[var(--border)]/70 bg-[var(--card)] px-2.5 py-1 text-[11px] font-medium text-[var(--foreground)]">
- {formatContextWindowSource(
- activeModel.context_window_source,
- t,
- )}
- </span>
- </div>
- <p className="mt-2 text-[12px] leading-relaxed text-[var(--muted-foreground)]">
- {activeModel.context_window_source ===
- "metadata"
- ? t(
- "Detected from the provider during the latest LLM test and saved into model_catalog.json.",
- )
- : activeModel.context_window_source ===
- "known_model"
- ? t(
- "Matched built-in model metadata during the latest LLM test and saved into model_catalog.json.",
- )
- : activeModel.context_window_source ===
- "default"
- ? t(
- "The provider did not expose a context window, so the runtime fallback was saved during the latest LLM test.",
- )
- : activeModel.context_window_source ===
- "manual"
- ? t(
- "Manual override from Settings. Save Draft to persist your edit.",
- )
- : t(
- "Run the LLM test to auto-fill this field, or enter a value manually.",
- )}
- </p>
- {activeModel.context_window_detected_at && (
- <div className="mt-2 text-[11px] text-[var(--muted-foreground)]/70">
- {t("Detected at")}:{" "}
- {formatContextWindowUpdatedAt(
- activeModel.context_window_detected_at,
- language,
- )}
- </div>
- )}
- </div>
- </>
- )}
- {activeService === "embedding" && (
- <div>
- <div className="mb-1.5 flex items-center justify-between gap-2">
- <span className="text-[12px] text-[var(--muted-foreground)]">
- {t("Dimension")}
- </span>
- <label className="inline-flex cursor-pointer items-center gap-1.5 text-[11px] text-[var(--muted-foreground)] select-none">
- <input
- type="checkbox"
- className="h-3 w-3 cursor-pointer accent-[var(--foreground)]"
- checked={
- activeModel.send_dimensions !== false
- }
- onChange={(e) =>
- updateModelBoolField(
- "send_dimensions",
- e.target.checked,
- )
- }
- />
- <span>{t("Send dimensions")}</span>
- <span
- tabIndex={0}
- className="group/info relative inline-flex cursor-help focus:outline-none"
- >
- <Info className="h-3 w-3 opacity-50 transition-opacity group-hover/info:opacity-100 group-focus/info:opacity-100" />
- <span
- role="tooltip"
- className="pointer-events-none absolute top-full left-1/2 z-20 mt-1.5 w-64 -translate-x-1/2 rounded-lg border border-[var(--border)] bg-[var(--card)] p-2.5 text-[11px] leading-relaxed text-[var(--foreground)] opacity-0 shadow-lg transition-opacity duration-75 group-hover/info:opacity-100 group-focus/info:opacity-100"
- >
- {t(
- "Some embedding models (e.g. Qwen text-embedding-v4) reject the `dimensions` request param. Turn this off if your provider returns HTTP 400.",
- )}
- </span>
- </span>
- </label>
- </div>
- <DimensionField
- activeModel={activeModel}
- activeBinding={activeProfile?.binding}
- capabilities={embeddingCapabilities}
- embeddingDefaultDim={embeddingDefaultDim}
- inputClass={inputClass}
- onChangeDimension={(value) =>
- updateModelField("dimension", value)
- }
- />
- </div>
- )}
- </div>
- )}
- </div>
- )}
- </div>
- </div>
- ) : (
- <div className="rounded-xl border border-dashed border-[var(--border)] py-12 text-center text-[13px] text-[var(--muted-foreground)]">
- {t("No profiles configured. Add a profile to start.")}
- </div>
- )}
- </div>
-
- {/* ── Diagnostics ── */}
- <div className="mb-6 rounded-xl border border-[var(--border)]">
- <div className="flex items-center justify-between px-5 py-3.5">
- <button
- type="button"
- onClick={() => setDiagnosticsOpen((v) => !v)}
- className="flex min-w-0 flex-1 items-center gap-2 text-left"
- aria-expanded={diagnosticsOpen}
- >
- <Terminal className="h-3.5 w-3.5 text-[var(--muted-foreground)]" />
- <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">
- <button
- type="button"
- onClick={() => {
- if (!diagnosticsOpen) setDiagnosticsOpen(true);
- runDetailedTest();
- }}
- disabled={testRunning !== null}
- 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)}
- {t("Run test")}
- </button>
- <button
- type="button"
- onClick={() => setDiagnosticsOpen((v) => !v)}
- className="text-[var(--muted-foreground)] transition-colors hover:text-[var(--foreground)]"
- aria-label={
- diagnosticsOpen
- ? t("Collapse diagnostics")
- : t("Expand diagnostics")
- }
- aria-expanded={diagnosticsOpen}
- >
- <ChevronDown
- className={`h-4 w-4 transition-transform ${diagnosticsOpen ? "rotate-180" : ""}`}
- />
- </button>
- </div>
- </div>
- {diagnosticsOpen && (
- <div className="border-t border-[var(--border)] px-5 py-4">
- <p className="mb-3 text-[12px] leading-relaxed text-[var(--muted-foreground)]">
- {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}
- </pre>
- </div>
- )}
- </div>
-
- {/* ── Footer note ── */}
- <p className="mt-2 pb-4 text-[11px] leading-relaxed text-[var(--muted-foreground)]/40">
- {t("settings.configNote")}
- </p>
- </>
- )}
- </div>
-
- {/* ── Spotlight overlay (tour onboarding) ── */}
- {catalogEditable === true &&
- tourGuideStep >= 0 &&
- tourGuideStep < TOUR_GUIDE_STEPS.length && (
- <SpotlightOverlay
- stepIndex={tourGuideStep}
- onNext={() => {
- if (tourGuideStep < TOUR_GUIDE_STEPS.length - 1) {
- setTourGuideStep((s) => s + 1);
- } else {
- setTourGuideStep(-1);
- }
- }}
- onSkip={() => setTourGuideStep(-1)}
- />
- )}
- </div>
- );
-}
-
-export default function SettingsPage() {
- const { t } = useTranslation();
- return (
- <Suspense
- fallback={
- <div className="min-h-[50vh] flex items-center justify-center text-[13px] text-[var(--muted-foreground)]">
- {t("Loading settings...")}
- </div>
- }
- >
- <SettingsPageContent />
- </Suspense>
- );
+export default function SettingsIndexPage() {
+ redirect("/settings/appearance");
}
diff --git a/web/app/(utility)/settings/search/page.tsx b/web/app/(utility)/settings/search/page.tsx
new file mode 100644
index 000000000..87376856d
--- /dev/null
+++ b/web/app/(utility)/settings/search/page.tsx
@@ -0,0 +1,21 @@
+"use client";
+
+import { useTranslation } from "react-i18next";
+
+import { ServiceConfigEditor } from "@/components/settings/ServiceConfigEditor";
+import { SettingsPageHeader } from "@/components/settings/shared";
+
+export default function SearchSettingsPage() {
+ const { t } = useTranslation();
+ return (
+ <div>
+ <SettingsPageHeader
+ title={t("Search")}
+ description={t(
+ "Configure web search providers. Used by the web_search tool and any agent step that hits the open web.",
+ )}
+ />
+ <ServiceConfigEditor service="search" />
+ </div>
+ );
+}
diff --git a/web/app/(utility)/settings/status/page.tsx b/web/app/(utility)/settings/status/page.tsx
new file mode 100644
index 000000000..55bd25a5e
--- /dev/null
+++ b/web/app/(utility)/settings/status/page.tsx
@@ -0,0 +1,142 @@
+"use client";
+
+import { useTranslation } from "react-i18next";
+
+import {
+ type ServiceName,
+ getActiveModel,
+ getActiveProfile,
+ servicePendingApply,
+ useSettings,
+} from "@/components/settings/SettingsContext";
+import {
+ activeModelDetail,
+ labelClass,
+ statusDotClass,
+ SettingsPageHeader,
+} from "@/components/settings/shared";
+
+const SERVICES: ServiceName[] = ["llm", "embedding", "search"];
+
+function serviceLabel(service: ServiceName, t: (k: string) => string): string {
+ if (service === "llm") return t("LLM");
+ if (service === "embedding") return t("Embedding");
+ return t("Search");
+}
+
+export default function StatusSettingsPage() {
+ const { t } = useTranslation();
+ const { status, catalog, draft, language } = useSettings();
+
+ return (
+ <div data-tour="tour-status">
+ <SettingsPageHeader
+ title={t("Status")}
+ description={t(
+ "Live state of the backend and the model services your configuration applies to.",
+ )}
+ />
+
+ <div className="grid grid-cols-1 gap-3 sm:grid-cols-2 xl:grid-cols-4">
+ {/* Backend tile */}
+ <div className="rounded-xl border border-[var(--border)]/60 bg-[var(--card)] px-4 py-4">
+ <div className="flex items-center gap-2">
+ <span
+ className={`h-1.5 w-1.5 rounded-full ${statusDotClass(
+ status?.backend.status === "online",
+ false,
+ )}`}
+ />
+ <span
+ className={`${labelClass("md", language)} text-[var(--muted-foreground)]`}
+ >
+ {t("Backend")}
+ </span>
+ </div>
+ <div className="mt-2 truncate text-[14px] font-medium text-[var(--foreground)]">
+ {status?.backend.status === "online" ? t("Online") : t("Checking")}
+ </div>
+ <div className="mt-0.5 truncate text-[11px] text-[var(--muted-foreground)]">
+ {(() => {
+ const ts = status?.backend.timestamp;
+ if (!ts) return "—";
+ const parsed = new Date(ts);
+ if (Number.isNaN(parsed.getTime())) return "";
+ return parsed.toLocaleTimeString(
+ language === "zh" ? "zh-CN" : "en-US",
+ { hour: "2-digit", minute: "2-digit", second: "2-digit" },
+ );
+ })()}
+ </div>
+ </div>
+
+ {SERVICES.map((service) => {
+ const profile = getActiveProfile(draft, service);
+ const model = getActiveModel(draft, service);
+ const serviceStatus =
+ service === "llm"
+ ? status?.llm
+ : service === "embedding"
+ ? status?.embeddings
+ : status?.search;
+ const runtimeModel =
+ service === "llm"
+ ? status?.llm.model
+ : service === "embedding"
+ ? status?.embeddings.model
+ : undefined;
+ const configured =
+ service === "search"
+ ? Boolean(profile?.provider || status?.search.provider)
+ : Boolean(model?.model || runtimeModel);
+ const pendingApply = servicePendingApply(catalog, draft, service);
+ const detail = activeModelDetail(profile, model, service, t);
+ const profileName = profile?.name || t("No profile");
+
+ return (
+ <div
+ key={service}
+ className="rounded-xl border border-[var(--border)]/60 bg-[var(--card)] px-4 py-4"
+ >
+ <div className="flex items-center gap-2">
+ <span
+ className={`h-1.5 w-1.5 rounded-full ${statusDotClass(
+ configured,
+ Boolean(serviceStatus?.error),
+ )}`}
+ />
+ <span
+ className={`${labelClass("md", language)} text-[var(--muted-foreground)]`}
+ >
+ {serviceLabel(service, t)}
+ </span>
+ {pendingApply && (
+ <span className="ml-auto text-[10px] font-medium text-amber-600 dark:text-amber-400">
+ {t("Pending")}
+ </span>
+ )}
+ </div>
+ <div className="mt-2 truncate text-[14px] font-medium text-[var(--foreground)]">
+ {detail}
+ </div>
+ <div className="mt-0.5 truncate text-[11px] text-[var(--muted-foreground)]">
+ {profileName}
+ </div>
+ {serviceStatus?.error && (
+ <p className="mt-2 truncate text-[11px] text-red-500" title={serviceStatus.error}>
+ {serviceStatus.error}
+ </p>
+ )}
+ </div>
+ );
+ })}
+ </div>
+
+ <p className="mt-6 text-[11.5px] leading-relaxed text-[var(--muted-foreground)]/70">
+ {t(
+ "Status reflects the runtime values after the last Apply. Draft changes only take effect once applied.",
+ )}
+ </p>
+ </div>
+ );
+}
diff --git a/web/app/(utility)/settings/tools/page.tsx b/web/app/(utility)/settings/tools/page.tsx
new file mode 100644
index 000000000..633d3aab8
--- /dev/null
+++ b/web/app/(utility)/settings/tools/page.tsx
@@ -0,0 +1,454 @@
+"use client";
+
+import { useCallback, useEffect, useMemo, useState } from "react";
+import { ChevronDown, Loader2, Lock, Wrench } from "lucide-react";
+import { useTranslation } from "react-i18next";
+
+import { useSettings } from "@/components/settings/SettingsContext";
+import { SettingsPageHeader } from "@/components/settings/shared";
+import { apiFetch, apiUrl } from "@/lib/api";
+import { invalidateEnabledOptionalToolsCache } from "@/lib/tools-settings";
+
+type ToolParameter = {
+ name: string;
+ type: string;
+ description: string;
+ required: boolean;
+ default: unknown;
+ enum: string[] | null;
+};
+
+type ToolHints = {
+ short_description: string;
+ when_to_use: string;
+ input_format: string;
+ guideline: string;
+ note: string;
+ phase: string;
+ aliases: { name: string; description: string; phase: string }[];
+};
+
+type BuiltinTool = {
+ name: string;
+ description: string;
+ parameters: ToolParameter[];
+ hints: { en: ToolHints; zh: ToolHints };
+ aliases: string[];
+ toggleable: boolean;
+ enabled: boolean;
+ // ``coming_soon`` tools are listed for visibility but the chat agent
+ // cannot invoke them. The settings UI surfaces them with a locked-off
+ // toggle and a "Coming soon" badge.
+ coming_soon?: boolean;
+};
+
+type ToolsResponse = {
+ tools: BuiltinTool[];
+ enabled_optional_tools: string[];
+};
+
+type ToolCategory = "experience" | "builtin";
+
+const CATEGORY_ORDER: ToolCategory[] = ["experience", "builtin"];
+
+export default function ToolsSettingsPage() {
+ const { t } = useTranslation();
+ const { language } = useSettings();
+ const [tools, setTools] = useState<BuiltinTool[] | null>(null);
+ const [error, setError] = useState<string | null>(null);
+ const [expanded, setExpanded] = useState<Set<string>>(new Set());
+ const [enabled, setEnabled] = useState<Set<string>>(new Set());
+ const [pending, setPending] = useState<Set<string>>(new Set());
+ const [saveError, setSaveError] = useState<string | null>(null);
+
+ useEffect(() => {
+ let cancelled = false;
+ (async () => {
+ try {
+ const res = await apiFetch(apiUrl("/api/v1/tools"));
+ if (!res.ok) throw new Error(`HTTP ${res.status}`);
+ const payload = (await res.json()) as ToolsResponse;
+ if (!cancelled) {
+ setTools(payload.tools);
+ setEnabled(new Set(payload.enabled_optional_tools ?? []));
+ }
+ } catch (err) {
+ if (!cancelled) {
+ setError(err instanceof Error ? err.message : String(err));
+ }
+ }
+ })();
+ return () => {
+ cancelled = true;
+ };
+ }, []);
+
+ const persist = useCallback(async (next: Set<string>) => {
+ const body = JSON.stringify({ enabled_tools: Array.from(next) });
+ const res = await apiFetch(apiUrl("/api/v1/settings/enabled-tools"), {
+ method: "PUT",
+ headers: { "Content-Type": "application/json" },
+ body,
+ });
+ if (!res.ok) throw new Error(`HTTP ${res.status}`);
+ const payload = (await res.json()) as { enabled_optional_tools: string[] };
+ // Bust the cached snapshot any other page in this tab is holding.
+ invalidateEnabledOptionalToolsCache();
+ return new Set(payload.enabled_optional_tools);
+ }, []);
+
+ const handleToggleEnabled = useCallback(
+ async (toolName: string) => {
+ if (pending.has(toolName)) return;
+ const before = enabled;
+ const next = new Set(before);
+ if (next.has(toolName)) next.delete(toolName);
+ else next.add(toolName);
+ setEnabled(next);
+ setPending((prev) => new Set(prev).add(toolName));
+ setSaveError(null);
+ try {
+ const saved = await persist(next);
+ setEnabled(saved);
+ } catch (err) {
+ setEnabled(before);
+ setSaveError(err instanceof Error ? err.message : String(err));
+ } finally {
+ setPending((prev) => {
+ const out = new Set(prev);
+ out.delete(toolName);
+ return out;
+ });
+ }
+ },
+ [enabled, pending, persist],
+ );
+
+ const grouped = useMemo(() => {
+ if (!tools) return null;
+ // Two-bucket split: toggleable tools (体验增强 / Experience Enhancement)
+ // first, then locked-on built-ins. Within each bucket we preserve the
+ // backend's order (which mirrors USER_TOGGLEABLE_TOOL_NAMES / the
+ // BUILTIN_TOOL_TYPES registration order). Coming-soon tools are
+ // surfaced alongside the toggleable ones — same conceptual bucket,
+ // just temporarily unavailable.
+ const out: Record<ToolCategory, BuiltinTool[]> = {
+ experience: [],
+ builtin: [],
+ };
+ for (const tool of tools) {
+ if (tool.coming_soon) {
+ out.experience.push(tool);
+ } else {
+ out[tool.toggleable ? "experience" : "builtin"].push(tool);
+ }
+ }
+ return out;
+ }, [tools]);
+
+ const toggleExpanded = (name: string) => {
+ setExpanded((prev) => {
+ const next = new Set(prev);
+ if (next.has(name)) next.delete(name);
+ else next.add(name);
+ return next;
+ });
+ };
+
+ const categoryLabel = (cat: ToolCategory) => {
+ if (cat === "experience") {
+ return language === "zh" ? "体验增强" : "Experience Enhancement";
+ }
+ return language === "zh" ? "内置工具" : "Built-in Tools";
+ };
+
+ const categoryHint = (cat: ToolCategory) => {
+ if (cat === "experience") {
+ return language === "zh"
+ ? "用户可选;按需为 chat agent 开启或关闭。"
+ : "User-toggleable. Switch on or off to shape the chat agent's behavior.";
+ }
+ return language === "zh"
+ ? "Chat agent 在需要时自动挂载,无需手动开关。"
+ : "Mounted automatically by the chat agent when needed. Not user-toggleable.";
+ };
+
+ return (
+ <div data-tour="tour-tools">
+ <SettingsPageHeader
+ title={t("Tools")}
+ description={t(
+ "Switch user-toggleable tools on or off. Locked tools are mounted automatically when the chat agent needs them.",
+ )}
+ />
+
+ {error && (
+ <div className="rounded-xl border border-red-500/40 bg-red-500/5 px-4 py-3 text-[12px] text-red-500">
+ {t("Failed to load tools")}: {error}
+ </div>
+ )}
+
+ {saveError && (
+ <div className="mb-4 rounded-xl border border-red-500/40 bg-red-500/5 px-4 py-3 text-[12px] text-red-500">
+ {t("Failed to save")}: {saveError}
+ </div>
+ )}
+
+ {!tools && !error && (
+ <div className="flex items-center gap-2 text-[12px] text-[var(--muted-foreground)]">
+ <Loader2 className="h-3.5 w-3.5 animate-spin" />
+ {t("Loading...")}
+ </div>
+ )}
+
+ {grouped && (
+ <div className="space-y-8">
+ {CATEGORY_ORDER.map((category) => {
+ const list = grouped[category];
+ if (list.length === 0) return null;
+ return (
+ <section key={category}>
+ <header className="mb-3 flex items-baseline justify-between gap-3">
+ <div className="min-w-0">
+ <h2 className="text-[14px] font-semibold tracking-tight text-[var(--foreground)]">
+ {categoryLabel(category)}
+ </h2>
+ <p className="mt-0.5 text-[11.5px] text-[var(--muted-foreground)]">
+ {categoryHint(category)}
+ </p>
+ </div>
+ <span className="shrink-0 text-[11px] text-[var(--muted-foreground)]">
+ {list.length}
+ </span>
+ </header>
+ <div className="overflow-hidden rounded-xl border border-[var(--border)]/60 bg-[var(--card)]/40">
+ {list.map((tool, idx) => {
+ const isOpen = expanded.has(tool.name);
+ const hints = tool.hints[language];
+ const isPending = pending.has(tool.name);
+ const isComingSoon = !!tool.coming_soon;
+ const isEnabled =
+ !isComingSoon &&
+ (tool.toggleable ? enabled.has(tool.name) : true);
+ return (
+ <div
+ key={tool.name}
+ className={
+ idx > 0
+ ? "border-t border-[var(--border)]/50"
+ : undefined
+ }
+ >
+ <div className="flex w-full items-start gap-3 px-5 py-4">
+ <Wrench
+ className={`mt-0.5 h-3.5 w-3.5 shrink-0 ${
+ isComingSoon
+ ? "text-[var(--muted-foreground)]/40"
+ : "text-[var(--muted-foreground)]"
+ }`}
+ />
+ <button
+ type="button"
+ onClick={() => toggleExpanded(tool.name)}
+ className="flex min-w-0 flex-1 items-start gap-3 text-left"
+ aria-expanded={isOpen}
+ >
+ <div className="min-w-0 flex-1">
+ <div className="flex items-center gap-2">
+ <span
+ className={`font-mono text-[13px] font-medium ${
+ isComingSoon
+ ? "text-[var(--foreground)]/60"
+ : "text-[var(--foreground)]"
+ }`}
+ >
+ {tool.name}
+ </span>
+ {tool.aliases.length > 0 && (
+ <span className="text-[10.5px] text-[var(--muted-foreground)]/70">
+ {tool.aliases.join(" · ")}
+ </span>
+ )}
+ {isComingSoon && (
+ <span className="inline-flex items-center gap-1 rounded-full border border-[var(--border)] bg-[var(--muted)]/40 px-2 py-0.5 text-[10px] font-medium uppercase tracking-wide text-[var(--muted-foreground)]">
+ {language === "zh"
+ ? "敬请期待"
+ : "Coming soon"}
+ </span>
+ )}
+ </div>
+ <p
+ className={`mt-1 text-[12.5px] leading-relaxed ${
+ isComingSoon
+ ? "text-[var(--muted-foreground)]/70"
+ : "text-[var(--muted-foreground)]"
+ }`}
+ >
+ {hints.short_description || tool.description}
+ </p>
+ </div>
+ <ChevronDown
+ className={`mt-1 h-4 w-4 shrink-0 text-[var(--muted-foreground)] transition-transform ${
+ isOpen ? "rotate-180" : ""
+ }`}
+ />
+ </button>
+ <div className="mt-0.5 flex shrink-0 items-center gap-2">
+ {isComingSoon ? (
+ <ToolToggle
+ checked={false}
+ disabled
+ onChange={() => {
+ /* locked */
+ }}
+ label={
+ language === "zh"
+ ? "敬请期待"
+ : "Coming soon"
+ }
+ />
+ ) : tool.toggleable ? (
+ <ToolToggle
+ checked={isEnabled}
+ disabled={isPending}
+ onChange={() => handleToggleEnabled(tool.name)}
+ label={t(isEnabled ? "On" : "Off")}
+ />
+ ) : (
+ <span
+ className="inline-flex items-center gap-1 rounded-full bg-[var(--muted)]/40 px-2 py-0.5 text-[10.5px] text-[var(--muted-foreground)]"
+ title={t(
+ "Auto-mounted by the agent when needed. Not user-toggleable.",
+ )}
+ >
+ <Lock className="h-3 w-3" />
+ {t("Always on")}
+ </span>
+ )}
+ </div>
+ </div>
+ {isOpen && (
+ <div className="space-y-4 border-t border-[var(--border)]/40 bg-[var(--background)]/40 px-5 py-4 text-[12.5px] leading-relaxed">
+ {hints.when_to_use && (
+ <Field
+ label={t("When to use")}
+ body={hints.when_to_use}
+ />
+ )}
+ {hints.input_format && (
+ <Field
+ label={t("Input format")}
+ body={hints.input_format}
+ mono
+ />
+ )}
+ {hints.guideline && (
+ <Field
+ label={t("Guideline")}
+ body={hints.guideline}
+ />
+ )}
+ {hints.note && (
+ <Field label={t("Note")} body={hints.note} />
+ )}
+ {tool.parameters.length > 0 && (
+ <div>
+ <div className="mb-1 text-[10.5px] font-semibold uppercase tracking-[0.14em] text-[var(--muted-foreground)]/80">
+ {t("Parameters")}
+ </div>
+ <ul className="space-y-1.5">
+ {tool.parameters.map((p) => (
+ <li
+ key={p.name}
+ className="flex items-baseline gap-2"
+ >
+ <span className="font-mono text-[12px] text-[var(--foreground)]">
+ {p.name}
+ </span>
+ <span className="text-[10.5px] text-[var(--muted-foreground)]/70">
+ {p.type}
+ {p.required ? "" : ` · ${t("optional")}`}
+ </span>
+ {p.description && (
+ <span className="text-[12px] text-[var(--muted-foreground)]">
+ — {p.description}
+ </span>
+ )}
+ </li>
+ ))}
+ </ul>
+ </div>
+ )}
+ </div>
+ )}
+ </div>
+ );
+ })}
+ </div>
+ </section>
+ );
+ })}
+ </div>
+ )}
+ </div>
+ );
+}
+
+function ToolToggle({
+ checked,
+ disabled,
+ onChange,
+ label,
+}: {
+ checked: boolean;
+ disabled: boolean;
+ onChange: () => void;
+ label: string;
+}) {
+ return (
+ <button
+ type="button"
+ role="switch"
+ aria-checked={checked}
+ aria-label={label}
+ disabled={disabled}
+ onClick={onChange}
+ className={`relative inline-flex h-[18px] w-[32px] shrink-0 items-center rounded-full border transition-colors ${
+ checked
+ ? "border-[var(--primary)] bg-[var(--primary)]/70"
+ : "border-[var(--border)] bg-[var(--muted)]/50"
+ } ${disabled ? "cursor-not-allowed opacity-60" : "cursor-pointer"}`}
+ >
+ <span
+ className={`inline-block h-[12px] w-[12px] transform rounded-full bg-white shadow transition-transform ${
+ checked ? "translate-x-[16px]" : "translate-x-[2px]"
+ }`}
+ />
+ </button>
+ );
+}
+
+function Field({
+ label,
+ body,
+ mono,
+}: {
+ label: string;
+ body: string;
+ mono?: boolean;
+}) {
+ return (
+ <div>
+ <div className="mb-1 text-[10.5px] font-semibold uppercase tracking-[0.14em] text-[var(--muted-foreground)]/80">
+ {label}
+ </div>
+ <p
+ className={`whitespace-pre-wrap text-[12.5px] leading-relaxed text-[var(--foreground)]/90 ${
+ mono ? "font-mono" : ""
+ }`}
+ >
+ {body}
+ </p>
+ </div>
+ );
+}
diff --git a/web/components/math-animator/MathAnimatorConfigPanel.tsx b/web/components/math-animator/MathAnimatorConfigPanel.tsx
deleted file mode 100644
index d57f6a7a5..000000000
--- a/web/components/math-animator/MathAnimatorConfigPanel.tsx
+++ /dev/null
@@ -1,103 +0,0 @@
-"use client";
-
-import { memo } from "react";
-import { useTranslation } from "react-i18next";
-import {
- summarizeMathAnimatorConfig,
- type MathAnimatorFormConfig,
-} from "@/lib/math-animator-types";
-import {
- CollapsibleConfigSection,
- Field,
- INPUT_CLS,
-} from "@/components/chat/home/composer-field";
-
-interface MathAnimatorConfigPanelProps {
- value: MathAnimatorFormConfig;
- onChange: (next: MathAnimatorFormConfig) => void;
- /**
- * When provided, the panel is wrapped in a `CollapsibleConfigSection`.
- * Omit both to render bare for the chat Activity panel.
- */
- collapsed?: boolean;
- onToggleCollapsed?: () => void;
-}
-
-export default memo(function MathAnimatorConfigPanel({
- value,
- onChange,
- collapsed,
- onToggleCollapsed,
-}: MathAnimatorConfigPanelProps) {
- const { t } = useTranslation();
- const update = <K extends keyof MathAnimatorFormConfig>(
- key: K,
- val: MathAnimatorFormConfig[K],
- ) => onChange({ ...value, [key]: val });
-
- const body = (
- <>
- <Field label={t("Output")} width="w-[100px]">
- <select
- value={value.output_mode}
- onChange={(e) =>
- update(
- "output_mode",
- e.target.value as MathAnimatorFormConfig["output_mode"],
- )
- }
- className={`${INPUT_CLS} w-full`}
- >
- <option value="video">{t("Video")}</option>
- <option value="image">{t("Image")}</option>
- </select>
- </Field>
-
- <Field label={t("Quality")} width="w-[100px]">
- <select
- value={value.quality}
- onChange={(e) =>
- update(
- "quality",
- e.target.value as MathAnimatorFormConfig["quality"],
- )
- }
- className={`${INPUT_CLS} w-full`}
- >
- <option value="low">{t("Low")}</option>
- <option value="medium">{t("Medium")}</option>
- <option value="high">{t("High")}</option>
- </select>
- </Field>
-
- <Field label={t("Style Hint")} width="min-w-[160px] flex-1">
- <input
- type="text"
- value={value.style_hint}
- onChange={(e) => update("style_hint", e.target.value)}
- placeholder={t("Style, pacing, color...")}
- className={`${INPUT_CLS} w-full`}
- />
- </Field>
- </>
- );
-
- if (collapsed === undefined) {
- return (
- <div className="flex flex-wrap items-end gap-x-3 gap-y-2 px-3.5 py-2.5">
- {body}
- </div>
- );
- }
-
- return (
- <CollapsibleConfigSection
- collapsed={collapsed}
- summary={summarizeMathAnimatorConfig(value, t)}
- onToggleCollapsed={onToggleCollapsed ?? (() => undefined)}
- bodyClassName="flex flex-wrap items-end gap-x-3 gap-y-2 px-3.5 pb-2.5"
- >
- {body}
- </CollapsibleConfigSection>
- );
-});
diff --git a/web/components/settings/DimensionField.tsx b/web/components/settings/DimensionField.tsx
new file mode 100644
index 000000000..2abedae79
--- /dev/null
+++ b/web/components/settings/DimensionField.tsx
@@ -0,0 +1,176 @@
+"use client";
+
+import { useState } from "react";
+import { useTranslation } from "react-i18next";
+
+import type {
+ CatalogModel,
+ EmbeddingCapabilities,
+} from "./SettingsContext";
+import { nativeSelectClass, selectOptionClass } from "./shared";
+
+const CUSTOM_DIM_SENTINEL = "__custom__";
+const AUTO_DIM_SENTINEL = "";
+
+function parseSupportedCsv(csv: string | undefined): number[] {
+ if (!csv) return [];
+ return csv
+ .split(",")
+ .map((s) => s.trim())
+ .filter(Boolean)
+ .map((s) => Number(s))
+ .filter((n) => Number.isFinite(n) && n > 0);
+}
+
+function sourceBadge(
+ source: string | undefined,
+ t: (key: string) => string,
+): { label: string; tone: "muted" | "ok" | "warn" } | null {
+ if (source === "detected") {
+ return { label: t("Source: detected from API probe"), tone: "ok" };
+ }
+ return null;
+}
+
+export function DimensionField({
+ activeModel,
+ activeBinding,
+ capabilities,
+ embeddingDefaultDim,
+ inputClass,
+ onChangeDimension,
+}: {
+ activeModel: CatalogModel;
+ activeBinding?: string;
+ capabilities: EmbeddingCapabilities | null;
+ embeddingDefaultDim: (binding?: string) => string;
+ inputClass: string;
+ onChangeDimension: (value: string) => void;
+}) {
+ const { t } = useTranslation();
+ const fallback = embeddingDefaultDim(activeBinding);
+ const rawValue = activeModel.dimension ?? "";
+ const isEmpty = rawValue === "";
+ const currentNum = isEmpty ? NaN : Number(rawValue);
+
+ const liveSupported = capabilities?.supported_dimensions;
+ const cachedSupported = parseSupportedCsv(activeModel.supported_dimensions);
+ const supported =
+ liveSupported && liveSupported.length > 0 ? liveSupported : cachedSupported;
+ const supportsVariable =
+ capabilities?.supports_variable_dimensions ?? supported.length > 1;
+
+ const useDropdown = supported.length > 1 && supportsVariable;
+ const currentInList =
+ Number.isFinite(currentNum) && supported.includes(currentNum);
+ const [customRequested, setCustomRequested] = useState<boolean>(false);
+ const customMode =
+ customRequested || (useDropdown && !isEmpty && !currentInList);
+
+ const detected = capabilities?.detected_dim;
+ const showDetectedBadge =
+ typeof detected === "number" &&
+ detected > 0 &&
+ detected !== currentNum &&
+ !isEmpty;
+
+ const sourceInfo = sourceBadge(capabilities?.active_dim_source, t);
+ const disabled = activeModel.send_dimensions === false;
+
+ const handleSelect = (value: string) => {
+ if (value === CUSTOM_DIM_SENTINEL) {
+ setCustomRequested(true);
+ return;
+ }
+ setCustomRequested(false);
+ onChangeDimension(value);
+ };
+
+ const dropdownValue = isEmpty
+ ? AUTO_DIM_SENTINEL
+ : currentInList
+ ? String(currentNum)
+ : CUSTOM_DIM_SENTINEL;
+
+ return (
+ <div className="space-y-1.5">
+ {useDropdown && !customMode ? (
+ <select
+ className={nativeSelectClass}
+ value={dropdownValue}
+ onChange={(e) => handleSelect(e.target.value)}
+ disabled={disabled}
+ >
+ <option className={selectOptionClass} value={AUTO_DIM_SENTINEL}>
+ {t("Auto (probe on next test)")}
+ </option>
+ {supported.map((dim) => (
+ <option className={selectOptionClass} key={dim} value={String(dim)}>
+ {dim}
+ </option>
+ ))}
+ <option className={selectOptionClass} value={CUSTOM_DIM_SENTINEL}>
+ {t("Custom…")}
+ </option>
+ </select>
+ ) : (
+ <input
+ className={inputClass}
+ value={rawValue}
+ placeholder={fallback}
+ onChange={(e) => onChangeDimension(e.target.value)}
+ disabled={disabled}
+ inputMode="numeric"
+ />
+ )}
+ {useDropdown && customMode && (
+ <button
+ type="button"
+ onClick={() => {
+ setCustomRequested(false);
+ if (isEmpty) {
+ return;
+ }
+ const closest = supported.reduce((acc, dim) =>
+ Math.abs(dim - currentNum) < Math.abs(acc - currentNum)
+ ? dim
+ : acc,
+ );
+ onChangeDimension(String(closest));
+ }}
+ className="text-[11px] text-[var(--muted-foreground)] underline-offset-2 hover:underline"
+ >
+ {t("Use a supported value")}
+ </button>
+ )}
+ {sourceInfo && (
+ <div
+ className={`text-[11px] ${
+ sourceInfo.tone === "warn"
+ ? "text-amber-600 dark:text-amber-400"
+ : sourceInfo.tone === "ok"
+ ? "text-emerald-600 dark:text-emerald-400"
+ : "text-[var(--muted-foreground)]"
+ }`}
+ >
+ {sourceInfo.label}
+ </div>
+ )}
+ {showDetectedBadge && (
+ <div className="flex items-center gap-2 text-[11px] text-[var(--muted-foreground)]">
+ <span>
+ {t("Detected")}: <strong>{detected}d</strong>
+ </span>
+ <button
+ type="button"
+ onClick={() => onChangeDimension(String(detected))}
+ className="rounded-md border border-[var(--border)]/60 px-1.5 py-0.5 text-[10px] text-[var(--foreground)] transition-colors hover:border-[var(--border)]"
+ disabled={disabled}
+ >
+ {t("Use this")}
+ </button>
+ </div>
+ )}
+ </div>
+ );
+}
diff --git a/web/components/settings/ServiceConfigEditor.tsx b/web/components/settings/ServiceConfigEditor.tsx
new file mode 100644
index 000000000..28604e035
--- /dev/null
+++ b/web/components/settings/ServiceConfigEditor.tsx
@@ -0,0 +1,923 @@
+"use client";
+
+import { useState } from "react";
+import {
+ CheckCircle2,
+ ChevronDown,
+ Eye,
+ EyeOff,
+ Info,
+ Loader2,
+ Plus,
+ Terminal,
+ Trash2,
+} from "lucide-react";
+import { useTranslation } from "react-i18next";
+
+import {
+ type CatalogModel,
+ type CatalogProfile,
+ type LlmContextWindowDetection,
+ type ServiceName,
+ getActiveModel,
+ getActiveProfile,
+ useSettings,
+} from "./SettingsContext";
+import { DimensionField } from "./DimensionField";
+import {
+ activeProfileDetail,
+ deprecatedSearchProviders,
+ formatContextWindowSource,
+ inputClass,
+ selectClass,
+ selectOptionClass,
+ stringifyExtraHeaders,
+ supportedSearchProviders,
+} from "./shared";
+
+const SERVICE_LABEL: Record<ServiceName, string> = {
+ llm: "LLM",
+ embedding: "Embedding",
+ search: "Search",
+};
+
+export function ServiceConfigEditor({ service }: { service: ServiceName }) {
+ const { t } = useTranslation();
+ const {
+ draft,
+ catalogEditable,
+ providers,
+ language,
+ embeddingCapabilities,
+ embeddingDefaultDim,
+ logs,
+ testRunning,
+ mutateCatalog,
+ addProfile,
+ removeActiveProfile,
+ addModel,
+ removeActiveModel,
+ updateProfileField,
+ updateModelField,
+ updateModelBoolField,
+ updateContextWindowField,
+ llmContextDetection,
+ applyDetectedContextWindow,
+ runDetailedTest,
+ } = useSettings();
+
+ const activeProfile = getActiveProfile(draft, service);
+ const activeModel = getActiveModel(draft, service);
+
+ const [showApiKey, setShowApiKey] = useState(false);
+ const [diagnosticsOpen, setDiagnosticsOpen] = useState(false);
+ const [editingModelId, setEditingModelId] = useState<string | null>(null);
+ const [editingModelName, setEditingModelName] = useState("");
+ const [editingProfileId, setEditingProfileId] = useState<string | null>(null);
+ const [editingProfileName, setEditingProfileName] = useState("");
+
+ // Reset API-key visibility whenever we land on a different profile or
+ // switch services — same effect the old code had, but using React's
+ // documented "store previous prop in state" pattern so it happens during
+ // render rather than in a useEffect (which the linter forbids).
+ const profileKey = `${service}:${activeProfile?.id ?? "none"}`;
+ const [lastProfileKey, setLastProfileKey] = useState(profileKey);
+ if (lastProfileKey !== profileKey) {
+ setLastProfileKey(profileKey);
+ if (showApiKey) setShowApiKey(false);
+ }
+
+ const searchProviderRaw =
+ service === "search"
+ ? (activeProfile?.provider || "").trim().toLowerCase()
+ : "";
+ const showSearchProviderWarning =
+ service === "search" && Boolean(searchProviderRaw);
+ const isDeprecatedSearchProvider =
+ deprecatedSearchProviders.has(searchProviderRaw);
+ const isSupportedSearchProvider = supportedSearchProviders.includes(
+ searchProviderRaw as (typeof supportedSearchProviders)[number],
+ );
+ const isPerplexityMissingKey =
+ service === "search" &&
+ searchProviderRaw === "perplexity" &&
+ !String(activeProfile?.api_key || "").trim();
+ const activeLlmDetection =
+ service === "llm" &&
+ llmContextDetection?.profileId === draft.services.llm.active_profile_id &&
+ llmContextDetection?.modelId === draft.services.llm.active_model_id
+ ? llmContextDetection
+ : null;
+
+ const startModelRename = (model: CatalogModel) => {
+ setEditingModelId(model.id);
+ setEditingModelName(model.name || model.model || "");
+ };
+
+ const commitModelRename = (modelId: string) => {
+ const fallbackIndex =
+ activeProfile?.models.findIndex((model) => model.id === modelId) ?? -1;
+ const fallbackName = defaultModelLabel(language, fallbackIndex + 1);
+ const nextName = editingModelName.trim() || fallbackName;
+ mutateCatalog((next) => {
+ const profile = getActiveProfile(next, service);
+ const model = profile?.models.find((item) => item.id === modelId);
+ if (model) model.name = nextName;
+ });
+ setEditingModelId(null);
+ setEditingModelName("");
+ };
+
+ const cancelModelRename = () => {
+ setEditingModelId(null);
+ setEditingModelName("");
+ };
+
+ const startProfileRename = (profile: CatalogProfile) => {
+ setEditingProfileId(profile.id);
+ setEditingProfileName(profile.name || "");
+ };
+
+ const commitProfileRename = (profileId: string) => {
+ const nextName = editingProfileName.trim();
+ if (nextName) {
+ mutateCatalog((next) => {
+ const profile = next.services[service].profiles.find(
+ (item) => item.id === profileId,
+ );
+ if (profile) profile.name = nextName;
+ });
+ }
+ setEditingProfileId(null);
+ setEditingProfileName("");
+ };
+
+ const cancelProfileRename = () => {
+ setEditingProfileId(null);
+ setEditingProfileName("");
+ };
+
+ if (!catalogEditable) {
+ return (
+ <div className="rounded-xl border border-dashed border-[var(--border)] px-5 py-10 text-center text-[13px] text-[var(--muted-foreground)]">
+ {t(
+ "Model endpoints are assigned by your administrator. You can still personalize theme and language here.",
+ )}
+ </div>
+ );
+ }
+
+ return (
+ <div data-tour={`tour-${service}`} className="space-y-5">
+ {activeProfile ? (
+ <div className="grid grid-cols-[200px_minmax(0,1fr)] items-start gap-5">
+ {/* ── Profile list (sticky so it stays put while the editor scrolls) ── */}
+ <aside className="sticky top-4 self-start rounded-xl border border-[var(--border)]/60 bg-[var(--card)]/40 p-2">
+ <div className="px-2 pb-2 pt-1 text-[11px] font-medium uppercase tracking-wide text-[var(--muted-foreground)]/70">
+ {t("Profiles")}
+ </div>
+ <div className="space-y-0.5">
+ {draft.services[service].profiles.map((profile) => {
+ const isActive =
+ profile.id === draft.services[service].active_profile_id;
+ const profileDetail = activeProfileDetail(profile, service, t);
+ const isEditing = editingProfileId === profile.id;
+ return (
+ <div
+ key={profile.id}
+ role="button"
+ tabIndex={isEditing ? -1 : 0}
+ onClick={() => {
+ if (isEditing) return;
+ mutateCatalog((next) => {
+ next.services[service].active_profile_id = profile.id;
+ if (service !== "search") {
+ next.services[service].active_model_id =
+ profile.models[0]?.id ?? null;
+ }
+ });
+ }}
+ onDoubleClick={() => startProfileRename(profile)}
+ onKeyDown={(e) => {
+ if (isEditing) return;
+ if (e.key === "Enter" || e.key === " ") {
+ e.preventDefault();
+ mutateCatalog((next) => {
+ next.services[service].active_profile_id = profile.id;
+ if (service !== "search") {
+ next.services[service].active_model_id =
+ profile.models[0]?.id ?? null;
+ }
+ });
+ }
+ }}
+ title={
+ isEditing ? undefined : t("Double-click to rename")
+ }
+ className={`group relative cursor-pointer rounded-lg px-3 py-2 text-left transition-colors ${
+ isActive
+ ? "bg-[var(--muted)]/70 text-[var(--foreground)]"
+ : "text-[var(--muted-foreground)] hover:bg-[var(--muted)]/30"
+ }`}
+ >
+ {isActive && (
+ <span className="absolute inset-y-2 left-0 w-0.5 rounded-r-full bg-[var(--foreground)]/80" />
+ )}
+ {isEditing ? (
+ <input
+ autoFocus
+ className="block w-full rounded border border-[var(--border)] bg-[var(--background)] px-1.5 py-0.5 text-[13px] font-medium text-[var(--foreground)] outline-none focus:border-[var(--ring)]"
+ value={editingProfileName}
+ onChange={(e) => setEditingProfileName(e.target.value)}
+ onBlur={() => commitProfileRename(profile.id)}
+ onClick={(e) => e.stopPropagation()}
+ onKeyDown={(e) => {
+ if (e.key === "Enter") {
+ e.currentTarget.blur();
+ }
+ if (e.key === "Escape") {
+ e.preventDefault();
+ cancelProfileRename();
+ }
+ }}
+ aria-label={t("Rename profile")}
+ />
+ ) : (
+ <div
+ className={`truncate text-[13px] leading-tight ${
+ isActive ? "font-semibold" : "font-medium"
+ }`}
+ >
+ {profile.name}
+ </div>
+ )}
+ <div className="mt-0.5 truncate text-[11px] leading-tight text-[var(--muted-foreground)]/70">
+ {profileDetail}
+ </div>
+ </div>
+ );
+ })}
+ </div>
+ <div className="mt-2 border-t border-[var(--border)]/40 pt-2">
+ <button
+ onClick={() => removeActiveProfile(service)}
+ disabled={!activeProfile}
+ className="flex w-full items-center gap-1.5 rounded-lg px-3 py-1.5 text-left text-[11px] text-[var(--muted-foreground)]/60 transition-colors hover:bg-red-500/5 hover:text-red-500 disabled:opacity-30"
+ title={
+ activeProfile
+ ? t("Permanently remove the currently selected profile.")
+ : undefined
+ }
+ >
+ <Trash2 className="h-3 w-3 shrink-0" />
+ <span className="truncate">
+ {activeProfile
+ ? t("Delete “{{name}}”", { name: activeProfile.name })
+ : t("Delete profile")}
+ </span>
+ </button>
+ </div>
+ </aside>
+
+ {/* ── Editor ── */}
+ <div className="min-w-0 space-y-5">
+ <div className="rounded-xl border border-[var(--border)] p-5">
+ <div className="mb-4 flex items-center justify-between gap-2">
+ <div className="text-[13px] font-medium text-[var(--foreground)]">
+ {t("Provider connection")}
+ </div>
+ <button
+ type="button"
+ onClick={() => addProfile(service)}
+ 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" />
+ {t("Profile")}
+ </button>
+ </div>
+ <ProfileFields
+ service={service}
+ profile={activeProfile}
+ showApiKey={showApiKey}
+ setShowApiKey={setShowApiKey}
+ showSearchProviderWarning={showSearchProviderWarning}
+ isSupportedSearchProvider={isSupportedSearchProvider}
+ isDeprecatedSearchProvider={isDeprecatedSearchProvider}
+ isPerplexityMissingKey={isPerplexityMissingKey}
+ />
+ </div>
+
+ {service !== "search" && (
+ <div className="rounded-xl border border-[var(--border)] p-5">
+ <div className="mb-4 flex items-center justify-between gap-2">
+ <div className="text-[13px] font-medium text-[var(--foreground)]">
+ {t("Models")}
+ </div>
+ <div className="flex items-center gap-2">
+ <button
+ type="button"
+ onClick={() => addModel(service)}
+ 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" />
+ {t("Model")}
+ </button>
+ <button
+ onClick={() => removeActiveModel(service)}
+ 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" />
+ {t("Delete")}
+ </button>
+ </div>
+ </div>
+ {activeProfile.models.length > 0 && (
+ <div className="mb-4 flex flex-wrap items-center gap-1.5">
+ {activeProfile.models.map((model, index) => {
+ const isActive =
+ model.id ===
+ draft.services[service].active_model_id;
+ const label =
+ (model.name || "").trim() ||
+ defaultModelLabel(language, index + 1);
+ const metric =
+ service === "llm"
+ ? formatCompactTokens(model.context_window)
+ : formatDimensionBadge(model.dimension);
+ return (
+ <div key={model.id} className="min-w-0">
+ {editingModelId === model.id ? (
+ <input
+ autoFocus
+ className="h-8 w-60 rounded-lg border border-[var(--border)] bg-[var(--background)] px-2.5 text-[12.5px] text-[var(--foreground)] outline-none focus:border-[var(--ring)]"
+ value={editingModelName}
+ onChange={(e) =>
+ setEditingModelName(e.target.value)
+ }
+ onBlur={() => commitModelRename(model.id)}
+ onKeyDown={(e) => {
+ if (e.key === "Enter") {
+ e.currentTarget.blur();
+ }
+ if (e.key === "Escape") {
+ e.preventDefault();
+ cancelModelRename();
+ }
+ }}
+ aria-label={t("Rename model")}
+ />
+ ) : (
+ <button
+ type="button"
+ onClick={() =>
+ mutateCatalog((next) => {
+ next.services[service].active_model_id =
+ model.id;
+ })
+ }
+ onDoubleClick={() => startModelRename(model)}
+ title={t("Double-click to rename")}
+ className={`inline-flex h-8 items-center gap-1.5 rounded-lg px-2.5 text-[12.5px] transition-colors ${
+ isActive
+ ? "bg-[var(--muted)] text-[var(--foreground)]"
+ : "text-[var(--muted-foreground)] hover:bg-[var(--muted)]/40"
+ }`}
+ >
+ {isActive && (
+ <CheckCircle2 className="h-3 w-3 shrink-0 text-[var(--foreground)]/70" />
+ )}
+ <span
+ className={`max-w-[280px] truncate leading-none ${
+ isActive ? "font-medium" : ""
+ }`}
+ >
+ {label}
+ </span>
+ {metric && (
+ <span className="shrink-0 text-[10.5px] tabular-nums leading-none text-[var(--muted-foreground)]/80">
+ {metric}
+ </span>
+ )}
+ </button>
+ )}
+ </div>
+ );
+ })}
+ </div>
+ )}
+ {activeModel && (
+ <div className="grid gap-4 sm:grid-cols-2">
+ <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(service, "model", e.target.value)
+ }
+ placeholder="gpt-4o"
+ />
+ </div>
+ {service === "llm" && (
+ <>
+ <div>
+ <div className="mb-1.5 text-[12px] text-[var(--muted-foreground)]">
+ {t("Context Window")}
+ </div>
+ <input
+ className={inputClass}
+ inputMode="numeric"
+ value={activeModel.context_window || ""}
+ onChange={(e) =>
+ updateContextWindowField(e.target.value)
+ }
+ placeholder="65536"
+ />
+ <ContextWindowMeta model={activeModel} />
+ </div>
+ <ContextWindowDetectionBanner
+ model={activeModel}
+ detection={activeLlmDetection}
+ onApply={applyDetectedContextWindow}
+ />
+ </>
+ )}
+ {service === "embedding" && (
+ <div>
+ <div className="mb-1.5 flex items-center justify-between gap-2">
+ <span className="text-[12px] text-[var(--muted-foreground)]">
+ {t("Dimension")}
+ </span>
+ <label className="inline-flex cursor-pointer items-center gap-1.5 text-[11px] text-[var(--muted-foreground)] select-none">
+ <input
+ type="checkbox"
+ className="h-3 w-3 cursor-pointer accent-[var(--foreground)]"
+ checked={
+ activeModel.send_dimensions !== false
+ }
+ onChange={(e) =>
+ updateModelBoolField(
+ service,
+ "send_dimensions",
+ e.target.checked,
+ )
+ }
+ />
+ <span>{t("Send dimensions")}</span>
+ <span
+ tabIndex={0}
+ className="group/info relative inline-flex cursor-help focus:outline-none"
+ >
+ <Info className="h-3 w-3 opacity-50 transition-opacity group-hover/info:opacity-100 group-focus/info:opacity-100" />
+ <span
+ role="tooltip"
+ className="pointer-events-none absolute top-full left-1/2 z-20 mt-1.5 w-64 -translate-x-1/2 rounded-lg border border-[var(--border)] bg-[var(--card)] p-2.5 text-[11px] leading-relaxed text-[var(--foreground)] opacity-0 shadow-lg transition-opacity duration-75 group-hover/info:opacity-100 group-focus/info:opacity-100"
+ >
+ {t(
+ "Some embedding models (e.g. Qwen text-embedding-v4) reject the `dimensions` request param. Turn this off if your provider returns HTTP 400.",
+ )}
+ </span>
+ </span>
+ </label>
+ </div>
+ <DimensionField
+ activeModel={activeModel}
+ activeBinding={activeProfile?.binding}
+ capabilities={embeddingCapabilities}
+ embeddingDefaultDim={embeddingDefaultDim}
+ inputClass={inputClass}
+ onChangeDimension={(value) =>
+ updateModelField(service, "dimension", value)
+ }
+ />
+ </div>
+ )}
+ </div>
+ )}
+ </div>
+ )}
+
+ {/* ── Diagnostics — per-service, inline ── */}
+ <div className="rounded-xl border border-[var(--border)]">
+ <div className="flex items-center justify-between px-5 py-3.5">
+ <button
+ type="button"
+ onClick={() => setDiagnosticsOpen((v) => !v)}
+ className="flex min-w-0 flex-1 items-center gap-2 text-left"
+ aria-expanded={diagnosticsOpen}
+ >
+ <Terminal className="h-3.5 w-3.5 text-[var(--muted-foreground)]" />
+ <span className="text-[13px] font-medium text-[var(--foreground)]">
+ {t("Diagnostics")}
+ </span>
+ {testRunning === service && (
+ <Loader2 className="h-3 w-3 animate-spin text-[var(--primary)]" />
+ )}
+ </button>
+ <div className="ml-3 flex items-center gap-3">
+ <button
+ type="button"
+ onClick={() => {
+ if (!diagnosticsOpen) setDiagnosticsOpen(true);
+ runDetailedTest(service);
+ }}
+ disabled={testRunning !== null}
+ 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"
+ >
+ {t("Run test")}
+ </button>
+ <button
+ type="button"
+ onClick={() => setDiagnosticsOpen((v) => !v)}
+ className="text-[var(--muted-foreground)] transition-colors hover:text-[var(--foreground)]"
+ aria-label={
+ diagnosticsOpen
+ ? t("Collapse diagnostics")
+ : t("Expand diagnostics")
+ }
+ aria-expanded={diagnosticsOpen}
+ >
+ <ChevronDown
+ className={`h-4 w-4 transition-transform ${diagnosticsOpen ? "rotate-180" : ""}`}
+ />
+ </button>
+ </div>
+ </div>
+ {diagnosticsOpen && (
+ <div className="border-t border-[var(--border)] px-5 py-4">
+ <p className="mb-3 text-[12px] leading-relaxed text-[var(--muted-foreground)]">
+ {t(
+ "Streams config snapshot, request target, response summary, and service-specific validation for the active {{service}} profile.",
+ { service: t(SERVICE_LABEL[service]) },
+ )}
+ </p>
+ <pre className="max-h-[360px] overflow-auto rounded-lg bg-[#0f0f0f] p-4 font-mono text-[12px] leading-6 text-[#777] whitespace-pre-wrap break-words dark:bg-[#0a0a0a]">
+ {testRunning === service || logs
+ ? logs
+ : t("Waiting for test run...")}
+ </pre>
+ </div>
+ )}
+ </div>
+ </div>
+ </div>
+ ) : (
+ <div className="rounded-xl border border-dashed border-[var(--border)] py-12 text-center text-[13px] text-[var(--muted-foreground)]">
+ {t("No profiles configured. Add a profile to start.")}
+ </div>
+ )}
+ </div>
+ );
+}
+
+function defaultModelLabel(language: "en" | "zh", index: number): string {
+ const safeIndex = index > 0 ? index : 1;
+ return language === "zh" ? `模型${safeIndex}` : `Model ${safeIndex}`;
+}
+
+function formatCompactTokens(value: string | number | undefined): string {
+ if (value === undefined || value === "") return "";
+ const parsed =
+ typeof value === "number"
+ ? value
+ : Number.parseInt(String(value).replace(/[^\d]/g, ""), 10);
+ if (!Number.isFinite(parsed) || parsed <= 0) return "";
+ if (parsed >= 1_000_000) {
+ const m = parsed / 1_000_000;
+ return `${m >= 10 ? m.toFixed(0) : m.toFixed(1).replace(/\.0$/, "")}M`;
+ }
+ if (parsed >= 1_000) {
+ const k = parsed / 1_000;
+ return `${k >= 10 ? k.toFixed(0) : k.toFixed(1).replace(/\.0$/, "")}K`;
+ }
+ return String(parsed);
+}
+
+function formatDimensionBadge(value: string | number | undefined): string {
+ if (value === undefined || value === "") return "";
+ const parsed =
+ typeof value === "number"
+ ? value
+ : Number.parseInt(String(value).replace(/[^\d]/g, ""), 10);
+ if (!Number.isFinite(parsed) || parsed <= 0) return "";
+ return `${parsed}d`;
+}
+
+function formatIsoLocal(value: string | undefined): string {
+ if (!value) return "";
+ const parsed = new Date(value);
+ if (Number.isNaN(parsed.getTime())) return value;
+ const pad = (n: number) => String(n).padStart(2, "0");
+ return (
+ `${parsed.getFullYear()}-${pad(parsed.getMonth() + 1)}-${pad(parsed.getDate())} ` +
+ `${pad(parsed.getHours())}:${pad(parsed.getMinutes())}`
+ );
+}
+
+function ContextWindowMeta({ model }: { model: CatalogModel }) {
+ const { t } = useTranslation();
+ if (!model.context_window) return null;
+ const source = formatContextWindowSource(model.context_window_source, t);
+ const updatedAt = formatIsoLocal(model.context_window_detected_at);
+ return (
+ <div className="mt-1.5 flex flex-wrap items-center gap-x-1.5 gap-y-0.5 text-[11px] text-[var(--muted-foreground)]">
+ <span>{t("Source")}:</span>
+ <span className="text-[var(--foreground)]/80">{source}</span>
+ {updatedAt && (
+ <>
+ <span className="text-[var(--muted-foreground)]/40">·</span>
+ <span title={model.context_window_detected_at}>{updatedAt}</span>
+ </>
+ )}
+ </div>
+ );
+}
+
+function ContextWindowDetectionBanner({
+ model,
+ detection,
+ onApply,
+}: {
+ model: CatalogModel;
+ detection: LlmContextWindowDetection | null;
+ onApply: () => void;
+}) {
+ const { t } = useTranslation();
+ if (!detection) return null;
+ const currentRaw = Number.parseInt(
+ String(model.context_window || "").replace(/[^\d]/g, ""),
+ 10,
+ );
+ const matches =
+ Number.isFinite(currentRaw) && currentRaw === detection.contextWindow;
+ const detectedFormatted = detection.contextWindow.toLocaleString("en-US");
+ const detectedAt = formatIsoLocal(detection.detectedAt);
+ const source = formatContextWindowSource(detection.source, t);
+
+ if (matches) {
+ return (
+ <div className="mt-1 flex flex-wrap items-center gap-x-2 gap-y-1 rounded-lg border border-emerald-500/30 bg-emerald-500/5 px-3 py-2 text-[12px] text-[var(--muted-foreground)] sm:col-span-2">
+ <CheckCircle2 className="h-3.5 w-3.5 text-emerald-500" />
+ <span className="text-[var(--foreground)]/80">
+ {t("Detected value matches your current setting")}
+ </span>
+ <span className="text-[var(--muted-foreground)]/70">
+ ({detectedFormatted} · {source})
+ </span>
+ </div>
+ );
+ }
+
+ return (
+ <div className="mt-1 flex flex-wrap items-center gap-x-3 gap-y-2 rounded-lg border border-[var(--border)] bg-[var(--muted)]/30 px-3 py-2 sm:col-span-2">
+ <div className="flex min-w-0 flex-1 flex-wrap items-baseline gap-x-2 gap-y-0.5 text-[12px]">
+ <span className="text-[var(--muted-foreground)]">
+ {t("Detected")}:
+ </span>
+ <span className="font-mono text-[13px] font-medium text-[var(--foreground)] tabular-nums">
+ {detectedFormatted}
+ </span>
+ <span className="text-[var(--muted-foreground)]/80">· {source}</span>
+ {detectedAt && (
+ <span className="text-[var(--muted-foreground)]/60">
+ · {detectedAt}
+ </span>
+ )}
+ </div>
+ <button
+ type="button"
+ onClick={onApply}
+ className="shrink-0 rounded-md border border-[var(--border)] bg-[var(--background)] px-2.5 py-1 text-[11.5px] font-medium text-[var(--foreground)] transition-colors hover:border-[var(--foreground)]"
+ >
+ {t("Apply")}
+ </button>
+ </div>
+ );
+}
+
+function ProfileFields({
+ service,
+ profile,
+ showApiKey,
+ setShowApiKey,
+ showSearchProviderWarning,
+ isSupportedSearchProvider,
+ isDeprecatedSearchProvider,
+ isPerplexityMissingKey,
+}: {
+ service: ServiceName;
+ profile: CatalogProfile;
+ showApiKey: boolean;
+ setShowApiKey: (next: boolean | ((prev: boolean) => boolean)) => void;
+ showSearchProviderWarning: boolean;
+ isSupportedSearchProvider: boolean;
+ isDeprecatedSearchProvider: boolean;
+ isPerplexityMissingKey: boolean;
+}) {
+ const { t } = useTranslation();
+ const { providers, updateProfileField, updateModelField } = useSettings();
+ const [extraOpen, setExtraOpen] = useState(false);
+
+ return (
+ <div className="grid gap-4 sm:grid-cols-2">
+ <div className="sm:col-span-2">
+ <div className="mb-1.5 text-[12px] text-[var(--muted-foreground)]">
+ {t("Provider")}
+ </div>
+ <div className="relative">
+ <select
+ className={selectClass}
+ value={
+ service === "search"
+ ? profile.provider || ""
+ : profile.binding || ""
+ }
+ onChange={(e) => {
+ const val = e.target.value;
+ const field = service === "search" ? "provider" : "binding";
+ updateProfileField(service, field, val);
+ const match = (providers[service] || []).find(
+ (p) => p.value === val,
+ );
+ if (match?.base_url) {
+ updateProfileField(service, "base_url", match.base_url);
+ }
+ if (service === "embedding" && match?.default_dim) {
+ updateModelField(service, "dimension", match.default_dim);
+ }
+ }}
+ >
+ <option className={selectOptionClass} value="">
+ {t("Select provider...")}
+ </option>
+ {(providers[service] || []).map((p) => (
+ <option
+ className={selectOptionClass}
+ 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>
+ {showSearchProviderWarning && (
+ <p
+ className={`mt-1.5 text-[11px] ${
+ isSupportedSearchProvider
+ ? "text-emerald-600 dark:text-emerald-400"
+ : isDeprecatedSearchProvider
+ ? "text-amber-600 dark:text-amber-400"
+ : "text-red-500"
+ }`}
+ >
+ {isSupportedSearchProvider
+ ? isPerplexityMissingKey
+ ? t(
+ "Perplexity requires API key. It will fail hard without credentials.",
+ )
+ : t("Supported provider.")
+ : isDeprecatedSearchProvider
+ ? 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)]">
+ {service === "embedding" ? t("Endpoint URL") : t("Base URL")}
+ </div>
+ <input
+ className={inputClass}
+ value={profile.base_url}
+ onChange={(e) =>
+ updateProfileField(service, "base_url", e.target.value)
+ }
+ placeholder={
+ service === "embedding"
+ ? "https://api.openai.com/v1/embeddings"
+ : "https://api.openai.com/v1"
+ }
+ />
+ {service === "embedding" && (
+ <p className="mt-1.5 text-[11px] text-[var(--muted-foreground)]">
+ {t(
+ "Embedding requests are sent to this URL exactly; DeepTutor does not append /embeddings or /api/embed at request time.",
+ )}
+ </p>
+ )}
+ </div>
+ <div className="sm:col-span-2">
+ <div className="mb-1.5 text-[12px] text-[var(--muted-foreground)]">
+ {t("API Key")}
+ </div>
+ <div className="relative">
+ <input
+ type={showApiKey ? "text" : "password"}
+ autoComplete="new-password"
+ spellCheck={false}
+ className={`${inputClass} pr-10 font-mono`}
+ value={profile.api_key}
+ onChange={(e) =>
+ updateProfileField(service, "api_key", e.target.value)
+ }
+ placeholder="sk-..."
+ />
+ <button
+ type="button"
+ onClick={() => setShowApiKey((prev) => !prev)}
+ className="absolute right-1 top-1/2 -translate-y-1/2 rounded-md p-1.5 text-[var(--muted-foreground)] hover:bg-[var(--muted)] hover:text-[var(--foreground)]"
+ aria-label={
+ showApiKey ? t("Hide API key") : t("Show API key")
+ }
+ title={showApiKey ? t("Hide API key") : t("Show API key")}
+ >
+ {showApiKey ? (
+ <EyeOff className="h-4 w-4" />
+ ) : (
+ <Eye className="h-4 w-4" />
+ )}
+ </button>
+ </div>
+ </div>
+ <div className="sm:col-span-2 rounded-xl border border-[var(--border)]/60 bg-[var(--muted)]/20">
+ <button
+ type="button"
+ onClick={() => setExtraOpen((value) => !value)}
+ className="flex w-full items-center justify-between gap-3 px-3.5 py-3 text-left"
+ aria-expanded={extraOpen}
+ >
+ <span>
+ <span className="block text-[12px] font-medium text-[var(--foreground)]">
+ {t("Extra (optional)")}
+ </span>
+ <span className="mt-0.5 block text-[11px] text-[var(--muted-foreground)]">
+ {service === "search"
+ ? t("API version and proxy")
+ : t("API version and extra request headers")}
+ </span>
+ </span>
+ <ChevronDown
+ className={`h-4 w-4 text-[var(--muted-foreground)] transition-transform ${
+ extraOpen ? "rotate-180" : ""
+ }`}
+ />
+ </button>
+ {extraOpen && (
+ <div className="grid gap-4 border-t border-[var(--border)]/60 px-3.5 py-4 sm:grid-cols-2">
+ <div>
+ <div className="mb-1.5 text-[12px] text-[var(--muted-foreground)]">
+ {t("API Version")}
+ </div>
+ <input
+ className={inputClass}
+ value={profile.api_version}
+ onChange={(e) =>
+ updateProfileField(service, "api_version", e.target.value)
+ }
+ placeholder={t("Optional")}
+ />
+ </div>
+ {service === "search" ? (
+ <div>
+ <div className="mb-1.5 text-[12px] text-[var(--muted-foreground)]">
+ {t("Proxy")}
+ </div>
+ <input
+ className={inputClass}
+ value={profile.proxy || ""}
+ onChange={(e) =>
+ updateProfileField(service, "proxy", e.target.value)
+ }
+ placeholder={t("http://127.0.0.1:7890 (optional)")}
+ />
+ </div>
+ ) : (
+ <div className="sm:col-span-2">
+ <div className="mb-1.5 text-[12px] text-[var(--muted-foreground)]">
+ {t("Extra Headers (JSON)")}
+ </div>
+ <textarea
+ className={`${inputClass} min-h-[84px] resize-y`}
+ value={stringifyExtraHeaders(profile.extra_headers)}
+ onChange={(e) =>
+ updateProfileField(service, "extra_headers", e.target.value)
+ }
+ placeholder='{"APP-Code":"your-app-code"}'
+ />
+ </div>
+ )}
+ </div>
+ )}
+ </div>
+ </div>
+ );
+}
diff --git a/web/components/settings/SettingsContext.tsx b/web/components/settings/SettingsContext.tsx
new file mode 100644
index 000000000..2c98727d9
--- /dev/null
+++ b/web/components/settings/SettingsContext.tsx
@@ -0,0 +1,1069 @@
+"use client";
+
+import {
+ createContext,
+ useCallback,
+ useContext,
+ useEffect,
+ useMemo,
+ useRef,
+ useState,
+ type ReactNode,
+} from "react";
+import { useRouter } from "next/navigation";
+import { useTranslation } from "react-i18next";
+
+import { writeStoredLanguage } from "@/context/app-shell-storage";
+import type { ModelAccess } from "@/features/multi-user/types";
+import { apiFetch, apiUrl } from "@/lib/api";
+import { setTheme as applyThemePreference } from "@/lib/theme";
+
+// ─── Domain types ─────────────────────────────────────────────────────────
+
+export type ServiceName = "llm" | "embedding" | "search";
+
+export type CatalogModel = {
+ id: string;
+ name: string;
+ model: string;
+ dimension?: string;
+ send_dimensions?: boolean;
+ supported_dimensions?: string;
+ context_window?: string;
+ context_window_source?: string;
+ context_window_detected_at?: string;
+};
+
+export type LlmContextWindowDetection = {
+ profileId: string | null;
+ modelId: string | null;
+ contextWindow: number;
+ source: string;
+ detail?: string;
+ detectedAt?: string;
+};
+
+export type CatalogProfile = {
+ id: string;
+ name: string;
+ binding?: string;
+ provider?: string;
+ base_url: string;
+ api_key: string;
+ api_version: string;
+ extra_headers?: Record<string, string> | string;
+ proxy?: string;
+ max_results?: number;
+ models: CatalogModel[];
+};
+
+export type CatalogService = {
+ active_profile_id: string | null;
+ active_model_id?: string | null;
+ profiles: CatalogProfile[];
+};
+
+export type Catalog = {
+ version: number;
+ services: {
+ llm: CatalogService;
+ embedding: CatalogService;
+ search: CatalogService;
+ };
+};
+
+export type UiSettings = {
+ theme: "light" | "dark" | "glass" | "snow";
+ language: "en" | "zh";
+};
+
+export type ProviderOption = {
+ value: string;
+ label: string;
+ base_url?: string;
+ default_dim?: string;
+};
+
+export type SystemStatus = {
+ backend: { status: string; timestamp: string };
+ llm: { status: string; model?: string; error?: string };
+ embeddings: { status: string; model?: string; error?: string };
+ search: { status: string; provider?: string; error?: string };
+};
+
+export type EmbeddingCapabilities = {
+ detected_dim?: number;
+ default_dim?: number;
+ supported_dimensions?: number[];
+ supports_variable_dimensions?: boolean;
+ model_known?: boolean;
+ active_dim?: number;
+ active_dim_source?: string;
+};
+
+type SettingsPayload = {
+ ui: UiSettings;
+ catalog?: Catalog;
+ model_access?: ModelAccess;
+ providers?: Record<ServiceName, ProviderOption[]>;
+};
+
+// ─── Tour ──────────────────────────────────────────────────────────────────
+//
+// The tour now spans routes — each step names the sub-page it lives on so the
+// controller can navigate there before the spotlight resolves a target. Adding
+// a new step is a matter of pushing onto this list; the overlay reads the
+// target via ``data-tour=""`` after the page has rendered.
+
+export type TourStep = {
+ target: string;
+ route: string;
+ titleKey: string;
+ descKey: string;
+};
+
+// Tour step order MUST match the sidebar order in
+// ``web/lib/settings-items.ts`` so navigating the tour walks the user
+// down the same list they see on the left.
+export const TOUR_STEPS: TourStep[] = [
+ {
+ target: "tour-appearance",
+ route: "/settings/appearance",
+ titleKey: "settingsTour.appearance.title",
+ descKey: "settingsTour.appearance.desc",
+ },
+ {
+ target: "tour-status",
+ route: "/settings/status",
+ titleKey: "settingsTour.status.title",
+ descKey: "settingsTour.status.desc",
+ },
+ {
+ target: "tour-llm",
+ route: "/settings/llm",
+ titleKey: "settingsTour.llm.title",
+ descKey: "settingsTour.llm.desc",
+ },
+ {
+ target: "tour-embedding",
+ route: "/settings/embedding",
+ titleKey: "settingsTour.embedding.title",
+ descKey: "settingsTour.embedding.desc",
+ },
+ {
+ target: "tour-search",
+ route: "/settings/search",
+ titleKey: "settingsTour.search.title",
+ descKey: "settingsTour.search.desc",
+ },
+ {
+ target: "tour-capabilities",
+ route: "/settings/capabilities",
+ titleKey: "settingsTour.capabilities.title",
+ descKey: "settingsTour.capabilities.desc",
+ },
+ {
+ target: "tour-memory",
+ route: "/settings/memory",
+ titleKey: "settingsTour.memory.title",
+ descKey: "settingsTour.memory.desc",
+ },
+ {
+ target: "tour-mcp",
+ route: "/settings/mcp",
+ titleKey: "settingsTour.mcp.title",
+ descKey: "settingsTour.mcp.desc",
+ },
+ {
+ target: "tour-tools",
+ route: "/settings/tools",
+ titleKey: "settingsTour.tools.title",
+ descKey: "settingsTour.tools.desc",
+ },
+ {
+ target: "tour-actions",
+ route: "/settings/llm",
+ titleKey: "settingsTour.apply.title",
+ descKey: "settingsTour.apply.desc",
+ },
+];
+
+// ─── Helpers ───────────────────────────────────────────────────────────────
+
+export function cloneCatalog(catalog: Catalog): Catalog {
+ return JSON.parse(JSON.stringify(catalog)) as Catalog;
+}
+
+export function defaultCatalog(): Catalog {
+ return {
+ version: 1,
+ services: {
+ llm: { active_profile_id: null, active_model_id: null, profiles: [] },
+ embedding: {
+ active_profile_id: null,
+ active_model_id: null,
+ profiles: [],
+ },
+ search: { active_profile_id: null, profiles: [] },
+ },
+ };
+}
+
+export function getActiveProfile(
+ catalog: Catalog,
+ serviceName: ServiceName,
+): CatalogProfile | null {
+ const service = catalog.services[serviceName];
+ return (
+ service.profiles.find(
+ (profile) => profile.id === service.active_profile_id,
+ ) ??
+ service.profiles[0] ??
+ null
+ );
+}
+
+export function getActiveModel(
+ catalog: Catalog,
+ serviceName: ServiceName,
+): CatalogModel | null {
+ if (serviceName === "search") return null;
+ const service = catalog.services[serviceName];
+ const profile = getActiveProfile(catalog, serviceName);
+ if (!profile) return null;
+ return (
+ profile.models.find((model) => model.id === service.active_model_id) ??
+ profile.models[0] ??
+ null
+ );
+}
+
+export function servicePendingApply(
+ catalog: Catalog,
+ draft: Catalog,
+ service: ServiceName,
+): boolean {
+ return (
+ JSON.stringify(catalog.services[service]) !==
+ JSON.stringify(draft.services[service])
+ );
+}
+
+function nextModelName(
+ models: CatalogModel[],
+ language: UiSettings["language"],
+): string {
+ const prefix = language === "zh" ? "模型" : "Model ";
+ const used = new Set(models.map((model) => model.name.trim()));
+ let index = models.length + 1;
+ while (used.has(`${prefix}${index}`)) {
+ index += 1;
+ }
+ return `${prefix}${index}`;
+}
+
+// ─── Context ───────────────────────────────────────────────────────────────
+
+export interface SettingsExtension {
+ dirty: boolean;
+ save: () => Promise<void>;
+}
+
+type SettingsContextValue = {
+ // State
+ catalog: Catalog;
+ draft: Catalog;
+ status: SystemStatus | null;
+ providers: Record<ServiceName, ProviderOption[]>;
+ modelAccess: ModelAccess | null;
+ catalogEditable: boolean | null;
+ settingsLoading: boolean;
+ settingsError: string | null;
+ reloadSettings: () => Promise<void>;
+ hasUnsavedChanges: boolean;
+ theme: UiSettings["theme"];
+ language: UiSettings["language"];
+ toast: string;
+ setToast: (value: string) => void;
+
+ // UI prefs
+ updateTheme: (next: UiSettings["theme"]) => Promise<void>;
+ updateLanguage: (next: UiSettings["language"]) => Promise<void>;
+
+ // Catalog mutation
+ mutateCatalog: (mutator: (next: Catalog) => void) => void;
+ addProfile: (service: ServiceName) => void;
+ removeActiveProfile: (service: ServiceName) => void;
+ addModel: (service: ServiceName) => void;
+ removeActiveModel: (service: ServiceName) => void;
+ updateProfileField: (
+ service: ServiceName,
+ field: keyof CatalogProfile,
+ value: string,
+ ) => void;
+ updateModelField: (
+ service: ServiceName,
+ field: keyof CatalogModel,
+ value: string,
+ ) => void;
+ updateModelBoolField: (
+ service: ServiceName,
+ field: keyof CatalogModel,
+ value: boolean,
+ ) => void;
+ updateContextWindowField: (value: string) => void;
+ llmContextDetection: LlmContextWindowDetection | null;
+ applyDetectedContextWindow: () => void;
+
+ // Save / apply
+ saving: boolean;
+ applying: boolean;
+ saveCatalog: () => Promise<void>;
+ applyCatalog: () => Promise<void>;
+
+ // Sub-page extension hooks. Sub-routes (e.g. /settings/memory) that own
+ // state outside the catalog register a "dirty + save" pair so the global
+ // Apply button can flush them alongside the catalog. Re-register on every
+ // render — the latest closure wins.
+ registerExtension: (key: string, ext: SettingsExtension | null) => void;
+
+ // Diagnostics
+ logs: string;
+ testRunning: ServiceName | null;
+ embeddingCapabilities: EmbeddingCapabilities | null;
+ runDetailedTest: (service: ServiceName) => Promise<void>;
+
+ // Helpers
+ embeddingDefaultDim: (binding?: string) => string;
+
+ // Tour
+ tourStepIndex: number;
+ startTour: () => void;
+ advanceTour: () => void;
+ goBackTour: () => void;
+ skipTour: () => void;
+};
+
+const SettingsContext = createContext<SettingsContextValue | null>(null);
+
+export function useSettings(): SettingsContextValue {
+ const ctx = useContext(SettingsContext);
+ if (!ctx) {
+ throw new Error("useSettings must be used inside <SettingsProvider>");
+ }
+ return ctx;
+}
+
+// ─── Provider ──────────────────────────────────────────────────────────────
+
+export function SettingsProvider({ children }: { children: ReactNode }) {
+ const { t } = useTranslation();
+ const router = useRouter();
+
+ const [status, setStatus] = useState<SystemStatus | null>(null);
+ const [theme, setTheme] = useState<UiSettings["theme"]>("light");
+ const [language, setLanguage] = useState<UiSettings["language"]>("en");
+ const [catalog, setCatalog] = useState<Catalog>(defaultCatalog());
+ const [draft, setDraft] = useState<Catalog>(defaultCatalog());
+ const [modelAccess, setModelAccess] = useState<ModelAccess | null>(null);
+ const [catalogEditable, setCatalogEditable] = useState<boolean | null>(null);
+ const [providers, setProviders] = useState<
+ Record<ServiceName, ProviderOption[]>
+ >({ llm: [], embedding: [], search: [] });
+ const [toast, setToast] = useState("");
+ const [saving, setSaving] = useState(false);
+ const [applying, setApplying] = useState(false);
+ // Empty string is the "no diagnostics yet" sentinel; the editor renders
+ // a localized placeholder when logs is falsy. Don't seed an English
+ // literal here — older code did, then read it back via .startsWith.
+ const [logs, setLogs] = useState<string>("");
+ const [testRunning, setTestRunning] = useState<ServiceName | null>(null);
+ const [llmContextDetection, setLlmContextDetection] =
+ useState<LlmContextWindowDetection | null>(null);
+ const [embeddingCapabilities, setEmbeddingCapabilities] =
+ useState<EmbeddingCapabilities | null>(null);
+ const [tourStepIndex, setTourStepIndex] = useState(-1);
+ const eventSourceRef = useRef<EventSource | null>(null);
+ // Extensions register their latest dirty/save on each render. We track
+ // a "version" counter to trigger re-renders for `hasUnsavedChanges`
+ // when an extension's dirty flag flips.
+ const extensionsRef = useRef<Map<string, SettingsExtension>>(new Map());
+ const [extensionsVersion, setExtensionsVersion] = useState(0);
+ const registerExtension = useCallback(
+ (key: string, ext: SettingsExtension | null) => {
+ const map = extensionsRef.current;
+ const prev = map.get(key);
+ if (ext === null) {
+ if (prev === undefined) return;
+ map.delete(key);
+ setExtensionsVersion((n) => n + 1);
+ return;
+ }
+ if (prev && prev.dirty === ext.dirty && prev.save === ext.save) {
+ return;
+ }
+ map.set(key, ext);
+ // Only bump version when dirty flips — save fn changes every render
+ // are common and should not re-render the toolbar.
+ if (prev?.dirty !== ext.dirty) {
+ setExtensionsVersion((n) => n + 1);
+ }
+ },
+ [],
+ );
+
+ const [settingsError, setSettingsError] = useState<string | null>(null);
+
+ // Single load step. Kept separate from the mount effect so a "Retry" action
+ // can re-run it without remounting the provider.
+ const loadSettings = useCallback(async () => {
+ setSettingsError(null);
+ let settingsLoaded = false;
+ try {
+ const settingsResponse = await apiFetch(apiUrl("/api/v1/settings"));
+ if (!settingsResponse.ok) {
+ throw new Error(
+ `Settings fetch failed: HTTP ${settingsResponse.status}`,
+ );
+ }
+ const payload = (await settingsResponse.json()) as SettingsPayload;
+ if (payload.catalog) {
+ setCatalog(payload.catalog);
+ setDraft(cloneCatalog(payload.catalog));
+ setCatalogEditable(true);
+ setModelAccess(null);
+ } else {
+ setCatalogEditable(false);
+ setModelAccess(payload.model_access ?? null);
+ }
+ setTheme(payload.ui.theme);
+ setLanguage(payload.ui.language);
+ if (payload.providers) setProviders(payload.providers);
+ settingsLoaded = true;
+ } catch (err) {
+ console.error("Failed to load settings:", err);
+ const message = err instanceof Error ? err.message : String(err);
+ setSettingsError(message);
+ // Resolve the loading gate so the page can render the error UI instead
+ // of staying in an infinite skeleton state.
+ setCatalogEditable((current) => (current === null ? false : current));
+ }
+ try {
+ const statusResponse = await apiFetch(apiUrl("/api/v1/system/status"));
+ if (statusResponse.ok) {
+ setStatus((await statusResponse.json()) as SystemStatus);
+ }
+ } catch (err) {
+ console.error("Failed to load system status:", err);
+ // Only surface this when settings itself loaded; otherwise the
+ // settings-fetch error already explains the disconnect.
+ if (settingsLoaded) {
+ setSettingsError((current) =>
+ current ??
+ (err instanceof Error
+ ? t("System status unavailable: {{message}}", {
+ message: err.message,
+ })
+ : t("System status unavailable.")),
+ );
+ }
+ }
+ }, [t]);
+
+ // Load settings + status once on mount. Subsequent navigations between
+ // settings sub-pages share this state via the layout-level provider.
+ useEffect(() => {
+ loadSettings();
+ return () => {
+ if (eventSourceRef.current) eventSourceRef.current.close();
+ };
+ }, [loadSettings]);
+
+ useEffect(() => {
+ if (!toast) return;
+ const timer = setTimeout(() => setToast(""), 3500);
+ return () => clearTimeout(timer);
+ }, [toast]);
+
+ // ── UI preferences ──────────────────────────────────────────────────────
+ const persistUi = useCallback(
+ async (
+ nextTheme: UiSettings["theme"],
+ nextLanguage: UiSettings["language"],
+ ) => {
+ await apiFetch(apiUrl("/api/v1/settings/ui"), {
+ method: "PUT",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ theme: nextTheme, language: nextLanguage }),
+ });
+ },
+ [],
+ );
+
+ const updateTheme = useCallback(
+ async (next: UiSettings["theme"]) => {
+ setTheme(next);
+ applyThemePreference(next);
+ await persistUi(next, language);
+ },
+ [language, persistUi],
+ );
+
+ const updateLanguage = useCallback(
+ async (next: UiSettings["language"]) => {
+ setLanguage(next);
+ writeStoredLanguage(next);
+ await persistUi(theme, next);
+ },
+ [persistUi, theme],
+ );
+
+ // ── Catalog mutators ────────────────────────────────────────────────────
+ const mutateCatalog = useCallback(
+ (mutator: (next: Catalog) => void) => {
+ setDraft((current) => {
+ const next = cloneCatalog(current);
+ mutator(next);
+ return next;
+ });
+ },
+ [],
+ );
+
+ const embeddingDefaultDim = useCallback(
+ (binding?: string) => {
+ const match = (providers.embedding || []).find(
+ (p) => p.value === (binding || "openai"),
+ );
+ return match?.default_dim || "3072";
+ },
+ [providers.embedding],
+ );
+
+ const addProfile = useCallback(
+ (service: ServiceName) => {
+ mutateCatalog((next) => {
+ const target = next.services[service];
+ const profileId = `${service}-profile-${Date.now()}`;
+ const defaultBinding = service === "search" ? undefined : "openai";
+ const defaultProvider = service === "search" ? "brave" : undefined;
+ const providerKey = service === "search" ? defaultProvider : defaultBinding;
+ const providerLabel =
+ (providers[service] || []).find((p) => p.value === providerKey)
+ ?.label ?? providerKey ?? "New Profile";
+ const profile: CatalogProfile = {
+ id: profileId,
+ name: providerLabel,
+ binding: defaultBinding,
+ provider: defaultProvider,
+ base_url: "",
+ api_key: "",
+ api_version: "",
+ extra_headers: service === "search" ? undefined : {},
+ proxy: service === "search" ? "" : undefined,
+ models: [],
+ };
+ if (service !== "search") {
+ const modelId = `${service}-model-${Date.now()}`;
+ const modelName = nextModelName([], language);
+ profile.models.push({
+ id: modelId,
+ name: modelName,
+ model: "",
+ ...(service === "embedding"
+ ? {
+ dimension: embeddingDefaultDim(),
+ send_dimensions: true,
+ }
+ : {}),
+ });
+ target.active_model_id = modelId;
+ }
+ target.profiles.push(profile);
+ target.active_profile_id = profileId;
+ });
+ },
+ [embeddingDefaultDim, language, mutateCatalog, providers],
+ );
+
+ const removeActiveProfile = useCallback(
+ (service: ServiceName) => {
+ mutateCatalog((next) => {
+ const target = next.services[service];
+ target.profiles = target.profiles.filter(
+ (profile) => profile.id !== target.active_profile_id,
+ );
+ target.active_profile_id = target.profiles[0]?.id ?? null;
+ if (service !== "search") {
+ target.active_model_id = target.profiles[0]?.models?.[0]?.id ?? null;
+ }
+ });
+ },
+ [mutateCatalog],
+ );
+
+ const addModel = useCallback(
+ (service: ServiceName) => {
+ if (service === "search") return;
+ mutateCatalog((next) => {
+ const target = next.services[service];
+ const profile =
+ target.profiles.find(
+ (item) => item.id === target.active_profile_id,
+ ) ?? null;
+ if (!profile) return;
+ const modelId = `${service}-model-${Date.now()}`;
+ const modelName = nextModelName(profile.models, language);
+ profile.models.push({
+ id: modelId,
+ name: modelName,
+ model: "",
+ ...(service === "embedding"
+ ? {
+ dimension: embeddingDefaultDim(profile.binding),
+ send_dimensions: true,
+ }
+ : {}),
+ });
+ target.active_model_id = modelId;
+ });
+ },
+ [embeddingDefaultDim, language, mutateCatalog],
+ );
+
+ const removeActiveModel = useCallback(
+ (service: ServiceName) => {
+ if (service === "search") return;
+ mutateCatalog((next) => {
+ const target = next.services[service];
+ const profile =
+ target.profiles.find(
+ (item) => item.id === target.active_profile_id,
+ ) ?? null;
+ if (!profile) return;
+ profile.models = profile.models.filter(
+ (item) => item.id !== target.active_model_id,
+ );
+ target.active_model_id = profile.models[0]?.id ?? null;
+ });
+ },
+ [mutateCatalog],
+ );
+
+ const updateProfileField = useCallback(
+ (service: ServiceName, field: keyof CatalogProfile, value: string) => {
+ mutateCatalog((next) => {
+ const profile = getActiveProfile(next, service);
+ if (!profile) return;
+ (profile[field] as string | undefined) = value;
+ });
+ },
+ [mutateCatalog],
+ );
+
+ const updateModelField = useCallback(
+ (service: ServiceName, field: keyof CatalogModel, value: string) => {
+ if (service === "search") return;
+ mutateCatalog((next) => {
+ const model = getActiveModel(next, service);
+ if (!model) return;
+ (model[field] as string | undefined) = value;
+ });
+ },
+ [mutateCatalog],
+ );
+
+ const updateModelBoolField = useCallback(
+ (service: ServiceName, field: keyof CatalogModel, value: boolean) => {
+ if (service === "search") return;
+ mutateCatalog((next) => {
+ const model = getActiveModel(next, service);
+ if (!model) return;
+ (model[field] as boolean | undefined) = value;
+ });
+ },
+ [mutateCatalog],
+ );
+
+ const updateContextWindowField = useCallback(
+ (value: string) => {
+ const normalized = value.replace(/[^\d]/g, "");
+ mutateCatalog((next) => {
+ const model = getActiveModel(next, "llm");
+ if (!model) return;
+ if (normalized) {
+ model.context_window = normalized;
+ model.context_window_source = "manual";
+ delete model.context_window_detected_at;
+ } else {
+ delete model.context_window;
+ delete model.context_window_source;
+ delete model.context_window_detected_at;
+ }
+ });
+ },
+ [mutateCatalog],
+ );
+
+ const applyDetectedContextWindow = useCallback(() => {
+ if (!llmContextDetection) return;
+ mutateCatalog((next) => {
+ const target = next.services.llm;
+ if (
+ target.active_profile_id !== llmContextDetection.profileId ||
+ target.active_model_id !== llmContextDetection.modelId
+ ) {
+ return;
+ }
+ const model = getActiveModel(next, "llm");
+ if (!model) return;
+ model.context_window = String(llmContextDetection.contextWindow);
+ model.context_window_source = llmContextDetection.source;
+ if (llmContextDetection.detectedAt) {
+ model.context_window_detected_at = llmContextDetection.detectedAt;
+ } else {
+ delete model.context_window_detected_at;
+ }
+ });
+ setToast(t("Detected context window written to draft"));
+ }, [llmContextDetection, mutateCatalog, t]);
+
+ // ── Save / Apply ────────────────────────────────────────────────────────
+ const saveCatalog = useCallback(async () => {
+ if (!catalogEditable) return;
+ setSaving(true);
+ try {
+ const response = await apiFetch(apiUrl("/api/v1/settings/catalog"), {
+ method: "PUT",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ catalog: draft }),
+ });
+ const payload = await response.json();
+ setCatalog(payload.catalog);
+ setDraft(cloneCatalog(payload.catalog));
+ setToast(t("Draft saved"));
+ } finally {
+ setSaving(false);
+ }
+ }, [catalogEditable, draft, t]);
+
+ const applyCatalog = useCallback(async () => {
+ setApplying(true);
+ try {
+ // Flush extensions (e.g. /settings/memory) first so their saved
+ // state is visible to any backend side-effects in /apply below.
+ const exts = Array.from(extensionsRef.current.values()).filter(
+ (e) => e.dirty,
+ );
+ await Promise.all(exts.map((e) => e.save()));
+
+ // The catalog apply is only meaningful when editable; an extension-
+ // only flush should still produce a success toast.
+ if (catalogEditable) {
+ const response = await apiFetch(apiUrl("/api/v1/settings/apply"), {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ catalog: draft }),
+ });
+ const payload = await response.json();
+ setCatalog(payload.catalog);
+ setDraft(cloneCatalog(payload.catalog));
+ const statusResponse = await apiFetch(apiUrl("/api/v1/system/status"));
+ setStatus((await statusResponse.json()) as SystemStatus);
+ }
+ setToast(t("Applied to runtime settings"));
+ } finally {
+ setApplying(false);
+ }
+ }, [catalogEditable, draft, t]);
+
+ // ── Diagnostics ─────────────────────────────────────────────────────────
+ // Reset capability snapshot when switching embedding profile/model so a
+ // stale "Detected: Xd" hint doesn't bleed across profiles.
+ useEffect(() => {
+ setEmbeddingCapabilities(null);
+ }, [
+ draft.services.embedding.active_profile_id,
+ draft.services.embedding.active_model_id,
+ ]);
+
+ useEffect(() => {
+ setLlmContextDetection((current) => {
+ if (!current) return null;
+ const llm = draft.services.llm;
+ if (
+ current.profileId === llm.active_profile_id &&
+ current.modelId === llm.active_model_id
+ ) {
+ return current;
+ }
+ return null;
+ });
+ }, [draft.services.llm.active_profile_id, draft.services.llm.active_model_id]);
+
+ const runDetailedTest = useCallback(
+ async (service: ServiceName) => {
+ if (!catalogEditable) return;
+ if (eventSourceRef.current) {
+ eventSourceRef.current.close();
+ eventSourceRef.current = null;
+ }
+ setLogs(t("Preparing {{service}} diagnostics...", { service }) + "\n");
+ setTestRunning(service);
+ const runProfileId =
+ service === "llm" ? draft.services.llm.active_profile_id : null;
+ const runModelId =
+ service === "llm" ? draft.services.llm.active_model_id ?? null : null;
+ if (service === "llm") setLlmContextDetection(null);
+ if (service === "embedding") setEmbeddingCapabilities(null);
+ try {
+ const response = await apiFetch(
+ apiUrl(`/api/v1/settings/tests/${service}/start`),
+ {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ catalog: draft }),
+ },
+ );
+ const payload = (await response.json()) as {
+ run_id?: string;
+ detail?: string;
+ };
+ if (!response.ok || !payload.run_id) {
+ throw new Error(payload.detail || t("Could not start diagnostics."));
+ }
+ const source = new EventSource(
+ apiUrl(`/api/v1/settings/tests/${service}/${payload.run_id}/events`),
+ { withCredentials: true },
+ );
+ eventSourceRef.current = source;
+ source.onmessage = (event) => {
+ const entry = JSON.parse(event.data) as {
+ type: string;
+ message: string;
+ catalog?: Catalog;
+ detected_dim?: number;
+ default_dim?: number;
+ supported_dimensions?: number[];
+ supports_variable_dimensions?: boolean;
+ model_known?: boolean;
+ active_dim?: number;
+ active_dim_source?: string;
+ context_window?: number;
+ source?: string;
+ detail?: string;
+ detected_at?: string;
+ };
+ setLogs((current) => `${current}[${entry.type}] ${entry.message}\n`);
+ if (service === "llm" && entry.type === "context_window") {
+ const detected =
+ typeof entry.context_window === "number"
+ ? entry.context_window
+ : Number.parseInt(String(entry.context_window ?? ""), 10);
+ if (Number.isFinite(detected) && detected > 0) {
+ setLlmContextDetection({
+ profileId: runProfileId,
+ modelId: runModelId,
+ contextWindow: detected,
+ source: entry.source || "metadata",
+ detail: entry.detail,
+ detectedAt: entry.detected_at,
+ });
+ }
+ }
+ if (entry.type === "capabilities") {
+ setEmbeddingCapabilities({
+ detected_dim: entry.detected_dim,
+ default_dim: entry.default_dim,
+ supported_dimensions: entry.supported_dimensions,
+ supports_variable_dimensions: entry.supports_variable_dimensions,
+ model_known: entry.model_known,
+ active_dim: entry.active_dim,
+ active_dim_source: entry.active_dim_source,
+ });
+ }
+ if (entry.catalog) {
+ setCatalog(entry.catalog);
+ setDraft(cloneCatalog(entry.catalog));
+ }
+ if (entry.type === "completed" || entry.type === "failed") {
+ source.close();
+ eventSourceRef.current = null;
+ setTestRunning(null);
+ setToast(entry.message);
+ }
+ };
+ source.onerror = () => {
+ source.close();
+ eventSourceRef.current = null;
+ setTestRunning(null);
+ setLogs(
+ (current) =>
+ `${current}[failed] ${t("Diagnostics stream disconnected.")}\n`,
+ );
+ setToast(t("Diagnostics stream disconnected"));
+ };
+ } catch (error) {
+ const message =
+ error instanceof Error
+ ? error.message
+ : t("Could not start diagnostics.");
+ setLogs((current) => `${current}[failed] ${message}\n`);
+ setToast(message);
+ setTestRunning(null);
+ }
+ },
+ [catalogEditable, draft, t],
+ );
+
+ // ── Tour ────────────────────────────────────────────────────────────────
+ // The tour drives a SpotlightOverlay rendered by the layout. When the step
+ // changes, we navigate to the step's route; the overlay then resolves the
+ // target via data-tour after the page renders.
+ const startTour = useCallback(() => {
+ if (TOUR_STEPS.length === 0) return;
+ setTourStepIndex(0);
+ // No router.push here — the route-sync effect below handles it,
+ // and doing it in two places would issue a redundant push.
+ }, []);
+
+ // Pure state updaters — DO NOT call router.push inside these. React
+ // may invoke the updater twice in StrictMode, and triggering a
+ // separate component's setState (Router) from inside a setState
+ // callback raises "Cannot update a component while rendering another".
+ // The route is synced via the effect below.
+ const advanceTour = useCallback(() => {
+ setTourStepIndex((idx) => {
+ const nextIdx = idx + 1;
+ return nextIdx >= TOUR_STEPS.length ? -1 : nextIdx;
+ });
+ }, []);
+
+ const goBackTour = useCallback(() => {
+ setTourStepIndex((idx) => (idx > 0 ? idx - 1 : idx));
+ }, []);
+
+ const skipTour = useCallback(() => {
+ setTourStepIndex(-1);
+ }, []);
+
+ // Sync the URL to the current tour step. Runs after render commits
+ // so it never re-enters another component's render.
+ useEffect(() => {
+ if (tourStepIndex < 0 || tourStepIndex >= TOUR_STEPS.length) return;
+ const step = TOUR_STEPS[tourStepIndex];
+ router.push(step.route);
+ }, [tourStepIndex, router]);
+
+ // ── Derived ─────────────────────────────────────────────────────────────
+ const hasUnsavedChanges = useMemo(() => {
+ const catalogDirty =
+ catalogEditable === true &&
+ JSON.stringify(catalog) !== JSON.stringify(draft);
+ if (catalogDirty) return true;
+ // Any registered extension dirty also counts. Reading from the ref is
+ // safe because `extensionsVersion` invalidates this memo on flip.
+ for (const ext of extensionsRef.current.values()) {
+ if (ext.dirty) return true;
+ }
+ return false;
+ }, [catalog, catalogEditable, draft, extensionsVersion]);
+
+ const settingsLoading = catalogEditable === null;
+
+ const value = useMemo<SettingsContextValue>(
+ () => ({
+ catalog,
+ draft,
+ status,
+ providers,
+ modelAccess,
+ catalogEditable,
+ settingsLoading,
+ settingsError,
+ reloadSettings: loadSettings,
+ hasUnsavedChanges,
+ theme,
+ language,
+ toast,
+ setToast,
+ updateTheme,
+ updateLanguage,
+ mutateCatalog,
+ addProfile,
+ removeActiveProfile,
+ addModel,
+ removeActiveModel,
+ updateProfileField,
+ updateModelField,
+ updateModelBoolField,
+ updateContextWindowField,
+ llmContextDetection,
+ applyDetectedContextWindow,
+ saving,
+ applying,
+ saveCatalog,
+ applyCatalog,
+ registerExtension,
+ logs,
+ testRunning,
+ embeddingCapabilities,
+ runDetailedTest,
+ embeddingDefaultDim,
+ tourStepIndex,
+ startTour,
+ advanceTour,
+ goBackTour,
+ skipTour,
+ }),
+ [
+ addModel,
+ addProfile,
+ applyDetectedContextWindow,
+ applyCatalog,
+ applying,
+ catalog,
+ catalogEditable,
+ draft,
+ embeddingCapabilities,
+ embeddingDefaultDim,
+ hasUnsavedChanges,
+ language,
+ llmContextDetection,
+ logs,
+ modelAccess,
+ mutateCatalog,
+ providers,
+ registerExtension,
+ removeActiveModel,
+ removeActiveProfile,
+ runDetailedTest,
+ saveCatalog,
+ saving,
+ settingsError,
+ loadSettings,
+ settingsLoading,
+ skipTour,
+ startTour,
+ advanceTour,
+ goBackTour,
+ status,
+ testRunning,
+ theme,
+ toast,
+ tourStepIndex,
+ updateContextWindowField,
+ updateLanguage,
+ updateModelBoolField,
+ updateModelField,
+ updateProfileField,
+ updateTheme,
+ ],
+ );
+
+ return (
+ <SettingsContext.Provider value={value}>
+ {children}
+ </SettingsContext.Provider>
+ );
+}
diff --git a/web/components/settings/SettingsLoadStatusBanner.tsx b/web/components/settings/SettingsLoadStatusBanner.tsx
new file mode 100644
index 000000000..bed011abd
--- /dev/null
+++ b/web/components/settings/SettingsLoadStatusBanner.tsx
@@ -0,0 +1,70 @@
+"use client";
+
+import { useState } from "react";
+import { AlertTriangle, Loader2, RefreshCw } from "lucide-react";
+import { useTranslation } from "react-i18next";
+
+import { useSettings } from "./SettingsContext";
+
+// Surface the result of the initial /api/v1/settings + /api/v1/system/status
+// load so Docker / first-run users know *why* the page is empty when the
+// backend is unreachable, instead of seeing a blank screen with the failure
+// only in the dev console.
+export function SettingsLoadStatusBanner() {
+ const { t } = useTranslation();
+ const { settingsLoading, settingsError, reloadSettings } = useSettings();
+ const [retrying, setRetrying] = useState(false);
+
+ if (settingsLoading) {
+ return (
+ <div className="mt-3 flex items-center gap-2 rounded-md border border-[var(--border)] bg-[var(--surface-soft)] px-3 py-2 text-sm text-[var(--foreground-soft)]">
+ <Loader2 className="h-4 w-4 animate-spin" />
+ {t("Loading settings...")}
+ </div>
+ );
+ }
+
+ if (!settingsError) return null;
+
+ const handleRetry = async () => {
+ setRetrying(true);
+ try {
+ await reloadSettings();
+ } finally {
+ setRetrying(false);
+ }
+ };
+
+ return (
+ <div
+ role="alert"
+ className="mt-3 flex items-start gap-3 rounded-md border border-amber-300 bg-amber-50 px-3 py-2 text-sm text-amber-900 dark:border-amber-500/40 dark:bg-amber-500/10 dark:text-amber-200"
+ >
+ <AlertTriangle className="mt-0.5 h-4 w-4 shrink-0" />
+ <div className="min-w-0 flex-1">
+ <div className="font-medium">
+ {t("Could not load settings from the backend.")}
+ </div>
+ <div className="mt-1 text-xs opacity-90">
+ {settingsError}
+ </div>
+ <div className="mt-1 text-xs opacity-75">
+ {t(
+ "Verify the backend is running and NEXT_PUBLIC_API_BASE points to a reachable host. For Docker, see data/user/settings/system.json.",
+ )}
+ </div>
+ </div>
+ <button
+ type="button"
+ onClick={handleRetry}
+ disabled={retrying}
+ className="inline-flex items-center gap-1 rounded-md border border-amber-300 bg-amber-100 px-2 py-1 text-xs font-medium text-amber-900 hover:bg-amber-200 disabled:opacity-60 dark:border-amber-500/40 dark:bg-amber-500/20 dark:text-amber-100"
+ >
+ <RefreshCw
+ className={retrying ? "h-3 w-3 animate-spin" : "h-3 w-3"}
+ />
+ {t("Retry")}
+ </button>
+ </div>
+ );
+}
diff --git a/web/components/settings/SettingsMiniNav.tsx b/web/components/settings/SettingsMiniNav.tsx
new file mode 100644
index 000000000..a8f8de043
--- /dev/null
+++ b/web/components/settings/SettingsMiniNav.tsx
@@ -0,0 +1,67 @@
+"use client";
+
+import Link from "next/link";
+import { usePathname } from "next/navigation";
+import { useTranslation } from "react-i18next";
+
+import { SETTINGS_ITEMS } from "@/lib/settings-items";
+
+export default function SettingsMiniNav() {
+ const pathname = usePathname();
+ const { t } = useTranslation();
+
+ return (
+ <aside className="flex h-full w-[248px] shrink-0 flex-col border-r border-[var(--border)] bg-[var(--card)]">
+ <div className="px-5 pb-4 pt-6">
+ <h1 className="text-[19px] font-semibold leading-tight tracking-tight text-[var(--foreground)]">
+ {t("Settings")}
+ </h1>
+ <p className="mt-1.5 text-[12.5px] leading-snug text-[var(--muted-foreground)]/80">
+ {t("Tune the app, configure model services, and inspect built-in tools.")}
+ </p>
+ </div>
+
+ <div
+ aria-hidden
+ className="mx-5 h-px bg-gradient-to-r from-transparent via-[var(--border)] to-transparent"
+ />
+
+ <nav className="flex-1 px-2.5 py-3">
+ {SETTINGS_ITEMS.map(({ href, label, description, icon: Icon }) => {
+ const active = pathname.startsWith(href);
+ return (
+ <Link
+ key={href}
+ href={href}
+ title={t(description)}
+ className={`group relative flex h-11 items-center gap-3 rounded-md px-3 transition-colors ${
+ active
+ ? "bg-[var(--muted)]/70 text-[var(--foreground)]"
+ : "text-[var(--muted-foreground)] hover:bg-[var(--muted)]/40 hover:text-[var(--foreground)]"
+ }`}
+ >
+ {active && (
+ <span
+ aria-hidden
+ className="absolute left-0 top-1/2 h-5 w-[2.5px] -translate-y-1/2 rounded-r-full bg-[var(--foreground)]"
+ />
+ )}
+ <Icon
+ size={17}
+ strokeWidth={active ? 2 : 1.7}
+ className="shrink-0"
+ />
+ <span
+ className={`min-w-0 flex-1 truncate text-[14px] leading-none tracking-tight ${
+ active ? "font-medium" : "font-normal"
+ }`}
+ >
+ {t(label)}
+ </span>
+ </Link>
+ );
+ })}
+ </nav>
+ </aside>
+ );
+}
diff --git a/web/components/settings/SettingsToolbar.tsx b/web/components/settings/SettingsToolbar.tsx
new file mode 100644
index 000000000..0f7213532
--- /dev/null
+++ b/web/components/settings/SettingsToolbar.tsx
@@ -0,0 +1,88 @@
+"use client";
+
+import { Loader2, Rocket, Save, Wand2 } from "lucide-react";
+import { useTranslation } from "react-i18next";
+
+import { useSettings } from "./SettingsContext";
+
+// Sticky toolbar above the sub-page content. Save Draft / Apply only show
+// when there's actually something to save — keeps the bar quiet for the
+// majority of sessions that just visit Appearance.
+export function SettingsToolbar() {
+ const { t } = useTranslation();
+ const {
+ catalogEditable,
+ hasUnsavedChanges,
+ saving,
+ applying,
+ saveCatalog,
+ applyCatalog,
+ startTour,
+ toast,
+ } = useSettings();
+
+ if (catalogEditable !== true) {
+ if (!toast) return null;
+ return (
+ <div className="flex items-center justify-end px-1 py-2">
+ <p className="text-[12px] text-[var(--primary)] animate-fade-in">
+ {toast}
+ </p>
+ </div>
+ );
+ }
+
+ return (
+ <div className="flex items-center justify-between gap-3 px-1 py-2">
+ <p
+ className={`text-[12px] ${
+ toast
+ ? "text-[var(--primary)] animate-fade-in"
+ : hasUnsavedChanges
+ ? "text-amber-600 dark:text-amber-400"
+ : "text-[var(--muted-foreground)]"
+ }`}
+ >
+ {toast
+ ? toast
+ : hasUnsavedChanges
+ ? t("Draft has unsaved changes")
+ : t("All changes saved")}
+ </p>
+ <div className="flex items-center gap-2">
+ <button
+ onClick={startTour}
+ 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)]"
+ >
+ <Rocket className="h-3 w-3" />
+ {t("Tour")}
+ </button>
+ <button
+ onClick={saveCatalog}
+ disabled={saving || !hasUnsavedChanges}
+ 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" />
+ )}
+ {t("Save Draft")}
+ </button>
+ <button
+ data-tour="tour-actions"
+ onClick={applyCatalog}
+ disabled={applying}
+ className="inline-flex items-center gap-1.5 rounded-lg bg-[var(--foreground)] px-3 py-1.5 text-[12px] font-medium text-[var(--background)] transition-opacity hover:opacity-80 disabled:opacity-40"
+ >
+ {applying ? (
+ <Loader2 className="h-3 w-3 animate-spin" />
+ ) : (
+ <Wand2 className="h-3 w-3" />
+ )}
+ {t("Apply")}
+ </button>
+ </div>
+ </div>
+ );
+}
diff --git a/web/components/settings/SettingsTourOverlay.tsx b/web/components/settings/SettingsTourOverlay.tsx
new file mode 100644
index 000000000..005e2ed77
--- /dev/null
+++ b/web/components/settings/SettingsTourOverlay.tsx
@@ -0,0 +1,246 @@
+"use client";
+
+import { useEffect, useState } from "react";
+import { usePathname } from "next/navigation";
+import { ChevronLeft, ChevronRight, Sparkles, X } from "lucide-react";
+import { useTranslation } from "react-i18next";
+
+import { TOUR_STEPS, useSettings } from "./SettingsContext";
+
+// Cross-route guided tour. Mounted in the settings layout so the same
+// instance survives navigation between sub-pages. After each step
+// transition the controller pushes router.push to the step's route;
+// here we wait until the pathname matches AND the target ``data-tour``
+// element exists before painting, so we never spotlight an empty rect
+// mid-transition.
+//
+// Visual design:
+// • Soft full-screen scrim (no harsh cutout) plus a translucent
+// highlight ring around the target — feels less "modal blocker",
+// more "look here".
+// • Tooltip card carries a step pill (3 / 10), a section title +
+// short description, and Back / Next + Skip controls.
+// • Arrow keys + Esc work as keyboard shortcuts so tour-as-orientation
+// doesn't require mousing.
+const TOOLTIP_W = 340;
+const TOOLTIP_H_EST = 200;
+const SCROLL_PADDING = 80;
+const HIGHLIGHT_PAD = 10;
+
+export function SettingsTourOverlay() {
+ const { t } = useTranslation();
+ const pathname = usePathname();
+ const { tourStepIndex, advanceTour, goBackTour, skipTour } = useSettings();
+ const [rect, setRect] = useState<DOMRect | null>(null);
+
+ const guideStep =
+ tourStepIndex >= 0 && tourStepIndex < TOUR_STEPS.length
+ ? TOUR_STEPS[tourStepIndex]
+ : null;
+ const totalSteps = TOUR_STEPS.length;
+ const isFirst = tourStepIndex <= 0;
+ const isLast = tourStepIndex === totalSteps - 1;
+
+ // The "wanted" target identity. When this changes between renders we
+ // drop the previously resolved rect during render (React's "store
+ // info from previous render" pattern), then the effect below resolves
+ // the new one.
+ const wantKey = guideStep
+ ? `${guideStep.target}@${guideStep.route}@${pathname}`
+ : null;
+ const [resolvedFor, setResolvedFor] = useState<string | null>(null);
+ if (resolvedFor !== wantKey) {
+ setResolvedFor(wantKey);
+ if (rect !== null) setRect(null);
+ }
+
+ // Resolve the target element. We retry briefly because the new
+ // sub-page may not have mounted by the time the step changes
+ // (Next.js route transitions are async). 8 attempts × 80ms = 640ms
+ // ceiling; enough for any normal client-side route swap, well below
+ // perceptual budget.
+ useEffect(() => {
+ if (!guideStep) return;
+ if (!pathname.startsWith(guideStep.route)) return;
+ let cancelled = false;
+ let attempt = 0;
+ const tryResolve = () => {
+ if (cancelled) return;
+ const el = document.querySelector(`[data-tour="${guideStep.target}"]`);
+ if (el) {
+ // Scroll the target into view BEFORE measuring so a
+ // far-down target like the toolbar Apply button isn't
+ // painted off-screen.
+ el.scrollIntoView({ behavior: "smooth", block: "center" });
+ // Defer measurement by one frame so the scroll animation
+ // has settled.
+ window.requestAnimationFrame(() => {
+ if (cancelled) return;
+ setRect(el.getBoundingClientRect());
+ });
+ return;
+ }
+ attempt += 1;
+ if (attempt < 8) {
+ window.setTimeout(tryResolve, 80);
+ }
+ };
+ const raf = window.requestAnimationFrame(tryResolve);
+ return () => {
+ cancelled = true;
+ window.cancelAnimationFrame(raf);
+ };
+ }, [guideStep, pathname]);
+
+ // Keep the highlight in sync as the user resizes the window.
+ useEffect(() => {
+ if (!guideStep) return;
+ const onResize = () => {
+ const el = document.querySelector(`[data-tour="${guideStep.target}"]`);
+ if (el) setRect(el.getBoundingClientRect());
+ };
+ window.addEventListener("resize", onResize);
+ return () => window.removeEventListener("resize", onResize);
+ }, [guideStep]);
+
+ // Keyboard shortcuts. Esc skips; ←/→ navigates.
+ useEffect(() => {
+ if (!guideStep) return;
+ const onKey = (e: KeyboardEvent) => {
+ if (e.key === "Escape") {
+ e.preventDefault();
+ skipTour();
+ } else if (e.key === "ArrowRight" || e.key === "Enter") {
+ e.preventDefault();
+ advanceTour();
+ } else if (e.key === "ArrowLeft" && !isFirst) {
+ e.preventDefault();
+ goBackTour();
+ }
+ };
+ window.addEventListener("keydown", onKey);
+ return () => window.removeEventListener("keydown", onKey);
+ }, [guideStep, advanceTour, goBackTour, skipTour, isFirst]);
+
+ if (!guideStep || !rect) return null;
+
+ const holeLeft = rect.left - HIGHLIGHT_PAD;
+ const holeTop = rect.top - HIGHLIGHT_PAD;
+ const holeW = rect.width + HIGHLIGHT_PAD * 2;
+ const holeH = rect.height + HIGHLIGHT_PAD * 2;
+
+ // Tooltip placement: prefer below the highlight; flip above if it
+ // would overflow; clamp horizontally so the card stays on-screen.
+ const wouldOverflowBelow =
+ holeTop + holeH + 16 + TOOLTIP_H_EST > window.innerHeight - SCROLL_PADDING;
+ const tooltipTop = wouldOverflowBelow
+ ? Math.max(16, holeTop - TOOLTIP_H_EST - 16)
+ : Math.min(holeTop + holeH + 16, window.innerHeight - TOOLTIP_H_EST - 16);
+ const tooltipLeft = Math.max(
+ 16,
+ Math.min(holeLeft, window.innerWidth - TOOLTIP_W - 16),
+ );
+
+ return (
+ <div className="fixed inset-0 z-[9999] pointer-events-none">
+ {/* Soft scrim — pointer-events disabled so the user can still
+ click highlighted controls if they want to. The click-through
+ experience is intentional: the tour describes; it does not
+ block. */}
+ <div className="absolute inset-0 bg-[var(--overlay)] backdrop-blur-[1px] transition-opacity duration-200" />
+
+ {/* Highlight ring around the target. A soft outer glow + a crisp
+ inner outline reads more "spotlight" than a hard cut-out. */}
+ <div
+ className="absolute rounded-2xl ring-2 ring-[var(--primary)] ring-offset-2 ring-offset-transparent transition-all duration-300"
+ style={{
+ left: holeLeft,
+ top: holeTop,
+ width: holeW,
+ height: holeH,
+ boxShadow:
+ "0 0 0 9999px rgba(0,0,0,0.35), 0 0 32px rgba(var(--primary-rgb,212,160,90), 0.45)",
+ }}
+ />
+
+ {/* Tooltip */}
+ <div
+ className="pointer-events-auto absolute z-10 w-[340px] overflow-hidden rounded-2xl border border-[var(--border)] bg-[var(--card)] shadow-[0_24px_60px_-12px_rgba(0,0,0,0.3)] animate-fade-in"
+ style={{ top: tooltipTop, left: tooltipLeft }}
+ role="dialog"
+ aria-labelledby="tour-title"
+ >
+ {/* Step progress bar — thin strip across the top of the card. */}
+ <div className="h-1 w-full bg-[var(--muted)]/40">
+ <div
+ className="h-full bg-[var(--foreground)] transition-all duration-500"
+ style={{
+ width: `${((tourStepIndex + 1) / totalSteps) * 100}%`,
+ }}
+ />
+ </div>
+
+ <div className="px-5 pt-4 pb-3">
+ {/* Header row: step pill + skip × */}
+ <div className="mb-3 flex items-center justify-between">
+ <div className="inline-flex items-center gap-1.5 rounded-full bg-[var(--muted)]/50 px-2.5 py-1 text-[11px] font-medium text-[var(--muted-foreground)]">
+ <Sparkles className="h-3 w-3" />
+ <span>
+ {t("Step {{current}} of {{total}}", {
+ current: tourStepIndex + 1,
+ total: totalSteps,
+ })}
+ </span>
+ </div>
+ <button
+ type="button"
+ onClick={skipTour}
+ aria-label={t("Skip tour")}
+ className="rounded-md p-1 text-[var(--muted-foreground)]/60 transition-colors hover:bg-[var(--muted)]/40 hover:text-[var(--foreground)]"
+ >
+ <X className="h-3.5 w-3.5" />
+ </button>
+ </div>
+
+ <h2
+ id="tour-title"
+ className="mb-1.5 text-[14px] font-semibold text-[var(--foreground)]"
+ >
+ {t(guideStep.titleKey)}
+ </h2>
+ <p className="text-[12.5px] leading-relaxed text-[var(--muted-foreground)]">
+ {t(guideStep.descKey)}
+ </p>
+ </div>
+
+ {/* Footer: Back / Next */}
+ <div className="flex items-center justify-between gap-2 border-t border-[var(--border)]/60 bg-[var(--background)]/30 px-5 py-3">
+ <button
+ type="button"
+ onClick={goBackTour}
+ disabled={isFirst}
+ className="inline-flex items-center gap-1 rounded-lg px-2 py-1 text-[12px] font-medium text-[var(--muted-foreground)] transition-colors hover:text-[var(--foreground)] disabled:opacity-40 disabled:cursor-not-allowed"
+ >
+ <ChevronLeft className="h-3 w-3" />
+ {t("Back")}
+ </button>
+ <button
+ type="button"
+ onClick={skipTour}
+ className="text-[12px] text-[var(--muted-foreground)]/60 transition-colors hover:text-[var(--muted-foreground)]"
+ >
+ {t("Skip tour")}
+ </button>
+ <button
+ type="button"
+ onClick={advanceTour}
+ 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"
+ >
+ {isLast ? t("Got it") : t("Next")}
+ <ChevronRight className="h-3 w-3" />
+ </button>
+ </div>
+ </div>
+ </div>
+ );
+}
diff --git a/web/components/settings/ThemePreviewCard.tsx b/web/components/settings/ThemePreviewCard.tsx
new file mode 100644
index 000000000..9ec7a7bc4
--- /dev/null
+++ b/web/components/settings/ThemePreviewCard.tsx
@@ -0,0 +1,185 @@
+"use client";
+
+import { Check } from "lucide-react";
+
+import type { UiSettings } from "./SettingsContext";
+
+type Theme = UiSettings["theme"];
+
+// Explicit palette values lifted from app/globals.css — kept here as plain
+// hex/rgba so each preview tile can render its theme's colours even while
+// the actual document theme is something else. Keep in sync with globals.css
+// when colours change there.
+type Palette = {
+ bg: string;
+ fg: string;
+ card: string;
+ primary: string;
+ muted: string;
+ border: string;
+ // True for translucent themes — adds a soft gradient/backdrop to convey
+ // the "frosted glass" treatment visually.
+ glass?: boolean;
+};
+
+const PALETTES: Record<Theme, Palette> = {
+ // theme id "light" applies no class → :root Cream palette (warm parchment,
+ // the default; renamed from generic "Light" to honestly signal its warmth)
+ light: {
+ bg: "#faf6ec",
+ fg: "#1c1816",
+ card: "#ffffff",
+ primary: "#b0501e",
+ muted: "#ede5d2",
+ border: "#d9ccb2",
+ },
+ // theme id "snow" applies the .theme-snow class → cool blue-tinted palette
+ // with a royal-blue primary (no longer the warm terracotta — Snow now
+ // belongs to a cool family rather than mixing cold bg with warm accent)
+ snow: {
+ bg: "#eef3fa",
+ fg: "#0e1a2e",
+ card: "#ffffff",
+ primary: "#1d4ed8",
+ muted: "#dce6f2",
+ border: "#c2d0e2",
+ },
+ dark: {
+ bg: "#1a1918",
+ fg: "#e8e4de",
+ card: "#242220",
+ primary: "#d4734b",
+ muted: "#2a2725",
+ border: "#3a3634",
+ },
+ glass: {
+ bg: "#0e0d1a",
+ fg: "#ffffff",
+ card: "rgba(255,255,255,0.06)",
+ primary: "#a855f7",
+ muted: "rgba(255,255,255,0.06)",
+ border: "rgba(255,255,255,0.12)",
+ glass: true,
+ },
+};
+
+// Renders a miniature DeepTutor UI mockup in the given theme's palette —
+// a left sidebar with one highlighted nav row, a content area with two
+// text lines and an accent button. Pure SVG so it stays crisp at any
+// device pixel ratio without leaking real interactive controls.
+function MiniPreview({ palette }: { palette: Palette }) {
+ const { bg, fg, card, primary, muted, border, glass } = palette;
+ return (
+ <svg
+ viewBox="0 0 160 96"
+ className="block h-full w-full"
+ aria-hidden
+ >
+ {/* Outer frame */}
+ <rect x="0" y="0" width="160" height="96" rx="6" fill={bg} />
+ {glass && (
+ <>
+ <defs>
+ <radialGradient id="glass-shine" cx="20%" cy="0%" r="80%">
+ <stop offset="0%" stopColor="rgba(168,85,247,0.38)" />
+ <stop offset="100%" stopColor="rgba(168,85,247,0)" />
+ </radialGradient>
+ </defs>
+ <rect x="0" y="0" width="160" height="96" rx="6" fill="url(#glass-shine)" />
+ </>
+ )}
+
+ {/* Sidebar */}
+ <rect x="0" y="0" width="44" height="96" fill={muted} />
+ {/* Sidebar nav rows */}
+ <rect x="8" y="14" width="28" height="3" rx="1.5" fill={fg} opacity="0.45" />
+ <rect x="6" y="26" width="32" height="10" rx="3" fill={card} />
+ <rect x="10" y="30" width="20" height="2.5" rx="1.25" fill={fg} opacity="0.9" />
+ <circle cx="40" cy="31" r="1.5" fill={primary} />
+ <rect x="8" y="44" width="24" height="2.5" rx="1.25" fill={fg} opacity="0.45" />
+ <rect x="8" y="54" width="26" height="2.5" rx="1.25" fill={fg} opacity="0.45" />
+ <rect x="8" y="64" width="22" height="2.5" rx="1.25" fill={fg} opacity="0.45" />
+
+ {/* Sidebar divider */}
+ <line x1="44" y1="0" x2="44" y2="96" stroke={border} strokeWidth="0.5" />
+
+ {/* Content card */}
+ <rect
+ x="54"
+ y="14"
+ width="96"
+ height="68"
+ rx="4"
+ fill={card}
+ stroke={border}
+ strokeWidth="0.5"
+ />
+ {/* Title line */}
+ <rect x="62" y="22" width="40" height="3.5" rx="1.5" fill={fg} opacity="0.85" />
+ {/* Body lines */}
+ <rect x="62" y="34" width="78" height="2.5" rx="1.25" fill={fg} opacity="0.35" />
+ <rect x="62" y="42" width="64" height="2.5" rx="1.25" fill={fg} opacity="0.35" />
+ <rect x="62" y="50" width="72" height="2.5" rx="1.25" fill={fg} opacity="0.35" />
+ {/* Accent button */}
+ <rect x="62" y="64" width="22" height="9" rx="2.5" fill={primary} />
+ </svg>
+ );
+}
+
+export function ThemePreviewCard({
+ theme,
+ label,
+ selected,
+ onSelect,
+}: {
+ theme: Theme;
+ label: string;
+ selected: boolean;
+ onSelect: (theme: Theme) => void;
+}) {
+ const palette = PALETTES[theme];
+ return (
+ <button
+ type="button"
+ onClick={() => onSelect(theme)}
+ aria-pressed={selected}
+ className={`group relative flex flex-col items-stretch gap-2 rounded-xl border p-1.5 text-left transition-all focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--ring)] ${
+ selected
+ ? "border-[var(--foreground)] bg-[var(--card)] shadow-sm"
+ : "border-[var(--border)]/60 bg-transparent hover:border-[var(--border)] hover:bg-[var(--muted)]/25"
+ }`}
+ >
+ <div
+ className="relative overflow-hidden rounded-lg ring-1"
+ style={{ aspectRatio: "5 / 3", boxShadow: `inset 0 0 0 1px ${palette.border}` }}
+ >
+ <MiniPreview palette={palette} />
+ {selected && (
+ <div className="absolute right-1.5 top-1.5 flex h-4 w-4 items-center justify-center rounded-full bg-[var(--foreground)] text-[var(--background)]">
+ <Check className="h-2.5 w-2.5" strokeWidth={3} />
+ </div>
+ )}
+ </div>
+ <div className="flex items-center justify-between px-1 pb-0.5">
+ <span
+ className={`text-[12.5px] tracking-tight ${
+ selected
+ ? "font-medium text-[var(--foreground)]"
+ : "text-[var(--muted-foreground)] group-hover:text-[var(--foreground)]"
+ }`}
+ >
+ {label}
+ </span>
+ <div className="flex -space-x-1">
+ {[palette.primary, palette.fg, palette.muted].map((c, i) => (
+ <span
+ key={i}
+ className="h-2.5 w-2.5 rounded-full ring-1 ring-[var(--background)]"
+ style={{ background: c }}
+ />
+ ))}
+ </div>
+ </div>
+ </button>
+ );
+}
diff --git a/web/components/settings/shared.tsx b/web/components/settings/shared.tsx
new file mode 100644
index 000000000..5d6177e67
--- /dev/null
+++ b/web/components/settings/shared.tsx
@@ -0,0 +1,189 @@
+"use client";
+
+import type { CatalogProfile, ServiceName } from "./SettingsContext";
+
+export const fieldControlClass =
+ "w-full rounded-lg border border-[var(--border)] px-3 py-2 text-[14px] text-[var(--foreground)] outline-none transition-colors focus:border-[var(--ring)]";
+
+export const inputClass = `${fieldControlClass} bg-transparent placeholder:text-[var(--muted-foreground)]/40`;
+
+export const nativeSelectClass = `${fieldControlClass} bg-[var(--background)] cursor-pointer disabled:cursor-not-allowed disabled:opacity-60`;
+
+export const selectClass = `${nativeSelectClass} appearance-none`;
+
+export const selectOptionClass = "bg-[var(--background)] text-[var(--foreground)]";
+
+export const supportedSearchProviders = [
+ "brave",
+ "tavily",
+ "jina",
+ "searxng",
+ "duckduckgo",
+ "perplexity",
+] as const;
+
+export const deprecatedSearchProviders = new Set([
+ "exa",
+ "serper",
+ "baidu",
+ "openrouter",
+]);
+
+export function stringifyExtraHeaders(value: CatalogProfile["extra_headers"]): string {
+ if (!value) return "";
+ if (typeof value === "string") return value;
+ try {
+ return JSON.stringify(value);
+ } catch {
+ return "";
+ }
+}
+
+export function statusDotClass(configured: boolean, hasError: boolean): string {
+ if (hasError) return "bg-red-400";
+ if (configured) return "bg-emerald-500";
+ return "bg-[var(--border)]";
+}
+
+export function formatContextWindowSource(
+ source: string | undefined,
+ t: (key: string) => string,
+): string {
+ if (source === "manual") return t("Manual");
+ if (source === "metadata") return t("Auto");
+ if (source === "known_model") return t("Known");
+ if (source === "default") return t("Default");
+ return t("Unset");
+}
+
+export function formatContextWindowUpdatedAt(
+ value: string | undefined,
+ language: "en" | "zh",
+): string {
+ if (!value) return "";
+ const parsed = new Date(value);
+ if (Number.isNaN(parsed.getTime())) return value;
+ return parsed.toLocaleString(language === "zh" ? "zh-CN" : "en-US", {
+ dateStyle: "medium",
+ timeStyle: "short",
+ });
+}
+
+export function activeProfileDetail(
+ profile: CatalogProfile | null,
+ service: ServiceName,
+ t: (key: string) => string,
+): string {
+ if (!profile) return t("No profile");
+ if (service === "search") return profile.provider || t("No provider");
+ return profile.base_url || t("No endpoint");
+}
+
+export function activeModelDetail(
+ profile: CatalogProfile | null,
+ model: { model?: string; name?: string } | null,
+ service: ServiceName,
+ t: (key: string) => string,
+): string {
+ if (service === "search") return profile?.provider || t("No provider");
+ return model?.model || model?.name || t("No model selected");
+}
+
+// Category-label typography. English looks good with uppercase + wide tracking;
+// CJK glyphs are already square blocks so we drop both and bump size a hair.
+export function labelClass(
+ size: "sm" | "md" | "lg",
+ language: "en" | "zh",
+): string {
+ if (language === "zh") {
+ if (size === "sm") return "text-[10.5px] font-medium";
+ if (size === "lg") return "text-[12px] font-medium";
+ return "text-[11px] font-medium";
+ }
+ if (size === "sm")
+ return "text-[9.5px] font-semibold uppercase tracking-[0.16em]";
+ if (size === "lg") return "text-[11px] uppercase tracking-[0.16em]";
+ return "text-[10px] font-semibold uppercase tracking-[0.16em]";
+}
+
+// One-row settings group used on simple pages (Appearance, Status etc.).
+// Title + optional description on the left, control flushed right. Matches
+// the visual rhythm used on Codex-style preferences pages.
+export function SettingRow({
+ title,
+ description,
+ control,
+}: {
+ title: string;
+ description?: string;
+ control: React.ReactNode;
+}) {
+ return (
+ <div className="flex items-start justify-between gap-6 border-t border-[var(--border)]/50 px-1 py-4 first:border-t-0">
+ <div className="min-w-0 flex-1">
+ <div className="text-[13.5px] font-medium text-[var(--foreground)]">
+ {title}
+ </div>
+ {description && (
+ <p className="mt-1 text-[12px] leading-relaxed text-[var(--muted-foreground)]">
+ {description}
+ </p>
+ )}
+ </div>
+ <div className="shrink-0">{control}</div>
+ </div>
+ );
+}
+
+// Page-level section group. Title + optional description, then children.
+export function SettingSection({
+ title,
+ description,
+ children,
+}: {
+ title: string;
+ description?: string;
+ children: React.ReactNode;
+}) {
+ return (
+ <section className="mb-10">
+ <header className="mb-3">
+ <h2 className="text-[15px] font-semibold tracking-tight text-[var(--foreground)]">
+ {title}
+ </h2>
+ {description && (
+ <p className="mt-1 text-[12.5px] leading-relaxed text-[var(--muted-foreground)]">
+ {description}
+ </p>
+ )}
+ </header>
+ <div className="rounded-xl border border-[var(--border)]/60 bg-[var(--card)]/40 px-5">
+ {children}
+ </div>
+ </section>
+ );
+}
+
+// Page heading shared across settings sub-pages. The Save Draft / Apply
+// buttons live in the layout above this, so each page just owns its title
+// row.
+export function SettingsPageHeader({
+ title,
+ description,
+}: {
+ title: string;
+ description?: string;
+}) {
+ return (
+ <header className="mb-8">
+ <h1 className="text-[22px] font-semibold tracking-tight text-[var(--foreground)]">
+ {title}
+ </h1>
+ {description && (
+ <p className="mt-1.5 text-[13px] leading-relaxed text-[var(--muted-foreground)]">
+ {description}
+ </p>
+ )}
+ </header>
+ );
+}
diff --git a/web/components/visualize/VisualizationViewer.tsx b/web/components/visualize/VisualizationViewer.tsx
index 7d12f418b..122f32971 100644
--- a/web/components/visualize/VisualizationViewer.tsx
+++ b/web/components/visualize/VisualizationViewer.tsx
@@ -1,11 +1,40 @@
"use client";
+import dynamic from "next/dynamic";
import { useEffect, useMemo, useRef, useState } from "react";
import { Code2, Copy, Check, ExternalLink, Maximize2, X } from "lucide-react";
import { useTranslation } from "react-i18next";
import { Mermaid } from "@/components/Mermaid";
import { prepareIframeHtml } from "@/lib/iframe-html";
-import type { VisualizeResult } from "@/lib/visualize-types";
+import { isManimResult, type VisualizeResult } from "@/lib/visualize-types";
+
+const MathAnimatorViewer = dynamic(
+ () => import("@/components/math-animator/MathAnimatorViewer"),
+ { ssr: false },
+);
+
+function stripCodeFence(source: string): string {
+ const trimmed = source.trim();
+ const fenced = trimmed.match(
+ /^```(?:json|javascript|js)?\s*([\s\S]*?)\s*```$/i,
+ );
+ return fenced ? fenced[1].trim() : trimmed;
+}
+
+function parseChartConfig(source: string): unknown {
+ const raw = stripCodeFence(source);
+ try {
+ return JSON.parse(raw);
+ } catch {
+ const jsonish = raw
+ .replace(/([{,]\s*)([A-Za-z_$][\w$]*)\s*:/g, '$1"$2":')
+ .replace(/'([^'\\]*(?:\\.[^'\\]*)*)'/g, (_match, value: string) =>
+ JSON.stringify(value.replace(/\\'/g, "'")),
+ )
+ .replace(/,\s*([}\]])/g, "$1");
+ return JSON.parse(jsonish);
+ }
+}
function ChartJsRenderer({ config }: { config: string }) {
const { t } = useTranslation();
@@ -28,10 +57,9 @@ function ChartJsRenderer({ config }: { config: string }) {
chartRef.current = null;
}
- // eslint-disable-next-line no-new-func
- const parsedConfig = new Function(
- `"use strict"; return (${config});`,
- )();
+ const parsedConfig = parseChartConfig(config) as ConstructorParameters<
+ typeof Chart
+ >[1];
if (cancelled) return;
@@ -78,6 +106,7 @@ function ChartJsRenderer({ config }: { config: string }) {
}
function HtmlRenderer({ html }: { html: string }) {
+ const { t } = useTranslation();
const iframeRef = useRef<HTMLIFrameElement>(null);
const prepared = useMemo(() => prepareIframeHtml(html || ""), [html]);
@@ -90,11 +119,18 @@ function HtmlRenderer({ html }: { html: string }) {
const handleOpenInNewTab = () => {
try {
- const blob = new Blob([prepared], { type: "text/html" });
- const url = URL.createObjectURL(blob);
+ const contentUrl = URL.createObjectURL(
+ new Blob([prepared], { type: "text/html" }),
+ );
+ const wrapper = `<!DOCTYPE html><html><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Visualization</title><style>html,body,iframe{height:100%;width:100%;margin:0;border:0;}</style></head><body><iframe sandbox="allow-scripts" src="${contentUrl}"></iframe></body></html>`;
+ const url = URL.createObjectURL(
+ new Blob([wrapper], { type: "text/html" }),
+ );
window.open(url, "_blank", "noopener,noreferrer");
- // Best-effort cleanup; the new tab keeps its own reference.
- setTimeout(() => URL.revokeObjectURL(url), 60_000);
+ setTimeout(() => {
+ URL.revokeObjectURL(url);
+ URL.revokeObjectURL(contentUrl);
+ }, 60_000);
} catch {
/* no-op */
}
@@ -106,14 +142,14 @@ function HtmlRenderer({ html }: { html: string }) {
type="button"
onClick={handleOpenInNewTab}
className="absolute right-2 top-2 z-10 inline-flex items-center gap-1 rounded-md border border-[var(--border)] bg-[var(--background)]/90 px-2 py-1 text-[10px] font-medium text-[var(--muted-foreground)] backdrop-blur transition-colors hover:text-[var(--foreground)]"
- title="Open in new tab"
+ title={t("Open in new tab")}
>
<ExternalLink size={10} strokeWidth={1.8} />
- Open
+ {t("Open")}
</button>
<iframe
ref={iframeRef}
- title="HTML visualization"
+ title={t("HTML visualization")}
sandbox="allow-scripts"
className="w-full rounded-lg border border-[var(--border)] bg-[var(--card)]"
style={{ minHeight: 480, height: 560 }}
@@ -124,18 +160,17 @@ function HtmlRenderer({ html }: { html: string }) {
function SvgRenderer({ svg }: { svg: string }) {
const { t } = useTranslation();
- const containerRef = useRef<HTMLDivElement>(null);
- const [error, setError] = useState<string | null>(null);
-
- const sanitizedSvg = useMemo(() => {
- const trimmed = svg.trim();
- if (!trimmed.startsWith("<svg")) {
- setError(t("Invalid SVG: does not start with <svg"));
- return "";
- }
- setError(null);
- return trimmed;
- }, [svg, t]);
+ const trimmedSvg = svg.trim();
+ const error = trimmedSvg.startsWith("<svg")
+ ? null
+ : t("Invalid SVG: does not start with <svg");
+ const svgUrl = useMemo(
+ () =>
+ error
+ ? ""
+ : `data:image/svg+xml;charset=utf-8,${encodeURIComponent(trimmedSvg)}`,
+ [error, trimmedSvg],
+ );
if (error) {
return (
@@ -151,15 +186,19 @@ function SvgRenderer({ svg }: { svg: string }) {
}
return (
- <div
- ref={containerRef}
- className="flex justify-center overflow-x-auto"
- dangerouslySetInnerHTML={{ __html: sanitizedSvg }}
- />
+ <div className="flex justify-center overflow-x-auto">
+ {/* eslint-disable-next-line @next/next/no-img-element */}
+ <img src={svgUrl} alt={t("SVG visualization")} className="max-w-full" />
+ </div>
);
}
-function renderVisualization(result: VisualizeResult) {
+type TextResult = Extract<
+ VisualizeResult,
+ { render_type: "svg" | "chartjs" | "mermaid" | "html" }
+>;
+
+function renderTextVisualization(result: TextResult) {
if (result.render_type === "svg") {
return <SvgRenderer svg={result.code.content} />;
}
@@ -178,14 +217,15 @@ export default function VisualizationViewer({
result: VisualizeResult;
}) {
const { t } = useTranslation();
+
+ // All hooks must run unconditionally before any early return — React
+ // requires a stable hook order across renders. The text-path body below
+ // is the only consumer of these states; the manim path returns earlier
+ // and ignores them.
const [showCode, setShowCode] = useState(false);
const [copied, setCopied] = useState(false);
const [fullscreen, setFullscreen] = useState(false);
- // HTML iframe already provides its own "Open in new tab" affordance; the
- // sandboxed iframe also doesn't behave well inside a re-rendered modal.
- const supportsFullscreen = result.render_type !== "html";
-
useEffect(() => {
if (!fullscreen) return;
const onKey = (e: KeyboardEvent) => {
@@ -200,6 +240,15 @@ export default function VisualizationViewer({
};
}, [fullscreen]);
+ if (isManimResult(result)) {
+ return <MathAnimatorViewer result={result.manim} />;
+ }
+
+ // TypeScript narrows ``result`` to the text-only variant from here on.
+ // HTML iframe already provides its own "Open in new tab" affordance; the
+ // sandboxed iframe also doesn't behave well inside a re-rendered modal.
+ const supportsFullscreen = result.render_type !== "html";
+
const handleCopy = async () => {
try {
await navigator.clipboard.writeText(result.code.content);
@@ -231,7 +280,7 @@ export default function VisualizationViewer({
{t("Fullscreen")}
</button>
)}
- {renderVisualization(result)}
+ {renderTextVisualization(result)}
</div>
{/* Toolbar */}
@@ -322,7 +371,7 @@ export default function VisualizationViewer({
onClick={(e) => e.stopPropagation()}
>
<div className="w-full max-w-[1600px]">
- {renderVisualization(result)}
+ {renderTextVisualization(result)}
</div>
</div>
</div>
diff --git a/web/components/visualize/VisualizeConfigPanel.tsx b/web/components/visualize/VisualizeConfigPanel.tsx
index 12574d741..a3c064b34 100644
--- a/web/components/visualize/VisualizeConfigPanel.tsx
+++ b/web/components/visualize/VisualizeConfigPanel.tsx
@@ -30,26 +30,71 @@ export default memo(function VisualizeConfigPanel({
onToggleCollapsed,
}: VisualizeConfigPanelProps) {
const { t } = useTranslation();
+ const update = <K extends keyof VisualizeFormConfig>(
+ key: K,
+ val: VisualizeFormConfig[K],
+ ) => onChange({ ...value, [key]: val });
+
+ // Manim modes need extra knobs (render quality, style hint) — match what
+ // the legacy Animator panel exposed so users don't lose granularity when
+ // they pick "Animation" / "Storyboard" here.
+ const isManim =
+ value.render_mode === "manim_video" || value.render_mode === "manim_image";
const body = (
- <Field label={t("Render Mode")} width="w-[120px]">
- <select
- value={value.render_mode}
- onChange={(e) =>
- onChange({
- ...value,
- render_mode: e.target.value as VisualizeFormConfig["render_mode"],
- })
- }
- className={`${INPUT_CLS} w-full`}
- >
- <option value="auto">{t("Auto")}</option>
- <option value="chartjs">{t("Chart.js")}</option>
- <option value="svg">{t("SVG")}</option>
- <option value="mermaid">{t("Mermaid")}</option>
- <option value="html">{t("HTML")}</option>
- </select>
- </Field>
+ <>
+ <Field label={t("Render Mode")} width="w-[140px]">
+ <select
+ value={value.render_mode}
+ onChange={(e) =>
+ update(
+ "render_mode",
+ e.target.value as VisualizeFormConfig["render_mode"],
+ )
+ }
+ className={`${INPUT_CLS} w-full`}
+ >
+ <option value="auto">{t("Auto")}</option>
+ <option value="chartjs">{t("Chart.js")}</option>
+ <option value="svg">{t("SVG")}</option>
+ <option value="mermaid">{t("Mermaid")}</option>
+ <option value="html">{t("HTML")}</option>
+ <option value="manim_video">{t("Animation")}</option>
+ <option value="manim_image">{t("Storyboard")}</option>
+ </select>
+ </Field>
+
+ {isManim ? (
+ <>
+ <Field label={t("Quality")} width="w-[100px]">
+ <select
+ value={value.quality}
+ onChange={(e) =>
+ update(
+ "quality",
+ e.target.value as VisualizeFormConfig["quality"],
+ )
+ }
+ className={`${INPUT_CLS} w-full`}
+ >
+ <option value="low">{t("Low")}</option>
+ <option value="medium">{t("Medium")}</option>
+ <option value="high">{t("High")}</option>
+ </select>
+ </Field>
+
+ <Field label={t("Style Hint")} width="min-w-[160px] flex-1">
+ <input
+ type="text"
+ value={value.style_hint}
+ onChange={(e) => update("style_hint", e.target.value)}
+ placeholder={t("Style, pacing, color...")}
+ className={`${INPUT_CLS} w-full`}
+ />
+ </Field>
+ </>
+ ) : null}
+ </>
);
if (collapsed === undefined) {
diff --git a/web/lib/math-animator-types.ts b/web/lib/math-animator-types.ts
index 240975550..d8bf88395 100644
--- a/web/lib/math-animator-types.ts
+++ b/web/lib/math-animator-types.ts
@@ -1,17 +1,4 @@
export type MathAnimatorOutputMode = "video" | "image";
-export type MathAnimatorQuality = "low" | "medium" | "high";
-
-export interface MathAnimatorFormConfig {
- output_mode: MathAnimatorOutputMode;
- quality: MathAnimatorQuality;
- style_hint: string;
-}
-
-export const DEFAULT_MATH_ANIMATOR_CONFIG: MathAnimatorFormConfig = {
- output_mode: "video",
- quality: "medium",
- style_hint: "",
-};
export interface MathAnimatorArtifact {
type: "video" | "image";
@@ -51,38 +38,6 @@ export interface MathAnimatorResult {
};
}
-export function buildMathAnimatorWSConfig(
- cfg: MathAnimatorFormConfig,
-): Record<string, unknown> {
- return {
- output_mode: cfg.output_mode,
- quality: cfg.quality,
- style_hint: cfg.style_hint.trim(),
- };
-}
-
-function titleCase(value: string): string {
- if (!value) return "";
- return value.charAt(0).toUpperCase() + value.slice(1);
-}
-
-/**
- * One-line summary of the math-animator form, shown next to the collapsed
- * `Settings` chevron in the composer. Pass `translate` (typically `t` from
- * `react-i18next`) so the summary follows the active UI language.
- */
-export function summarizeMathAnimatorConfig(
- cfg: MathAnimatorFormConfig,
- translate?: (key: string) => string,
-): string {
- const output = titleCase(cfg.output_mode);
- const quality = titleCase(cfg.quality);
- return [
- translate ? translate(output) : output,
- translate ? translate(quality) : quality,
- ].join(" · ");
-}
-
export function extractMathAnimatorResult(
resultMetadata: Record<string, unknown> | undefined,
): MathAnimatorResult | null {
diff --git a/web/lib/settings-items.ts b/web/lib/settings-items.ts
new file mode 100644
index 000000000..a70cca3bf
--- /dev/null
+++ b/web/lib/settings-items.ts
@@ -0,0 +1,101 @@
+"use client";
+
+import {
+ Activity,
+ BookMarked,
+ Brain,
+ Database,
+ Palette,
+ Plug,
+ Search,
+ SlidersHorizontal,
+ Wrench,
+ type LucideIcon,
+} from "lucide-react";
+
+export type SettingsItemKey =
+ | "appearance"
+ | "status"
+ | "tools"
+ | "mcp"
+ | "llm"
+ | "embedding"
+ | "search"
+ | "memory"
+ | "capabilities";
+
+export interface SettingsItem {
+ key: SettingsItemKey;
+ href: string;
+ label: string;
+ description: string;
+ icon: LucideIcon;
+}
+
+export const SETTINGS_ITEMS: SettingsItem[] = [
+ {
+ key: "appearance",
+ href: "/settings/appearance",
+ label: "Appearance",
+ description: "Theme and language preferences.",
+ icon: Palette,
+ },
+ {
+ key: "status",
+ href: "/settings/status",
+ label: "Status",
+ description: "Runtime status for backend and configured services.",
+ icon: Activity,
+ },
+ {
+ key: "llm",
+ href: "/settings/llm",
+ label: "LLM",
+ description: "Language model providers and active profile.",
+ icon: Brain,
+ },
+ {
+ key: "embedding",
+ href: "/settings/embedding",
+ label: "Embedding",
+ description: "Embedding model providers and dimensions.",
+ icon: Database,
+ },
+ {
+ key: "search",
+ href: "/settings/search",
+ label: "Search",
+ description: "Web search providers.",
+ icon: Search,
+ },
+ {
+ key: "capabilities",
+ href: "/settings/capabilities",
+ label: "Capabilities",
+ description: "Per-capability LLM parameters and runtime knobs.",
+ icon: SlidersHorizontal,
+ },
+ {
+ key: "memory",
+ href: "/settings/memory",
+ label: "Memory",
+ description: "Chunking, LLM-budget, dedup, and reference policies.",
+ icon: BookMarked,
+ },
+ {
+ key: "mcp",
+ href: "/settings/mcp",
+ label: "MCP servers",
+ description: "External MCP servers (coming soon).",
+ icon: Plug,
+ },
+ {
+ key: "tools",
+ href: "/settings/tools",
+ label: "Tools",
+ description: "Built-in tools the chat agent can invoke.",
+ icon: Wrench,
+ },
+];
+
+export const SETTINGS_DEFAULT_HREF = "/settings/appearance";
diff --git a/web/lib/tools-settings.ts b/web/lib/tools-settings.ts
new file mode 100644
index 000000000..18825558c
--- /dev/null
+++ b/web/lib/tools-settings.ts
@@ -0,0 +1,35 @@
+import { apiFetch, apiUrl } from "@/lib/api";
+
+export interface ToolSettingsResponse {
+ enabled_optional_tools: string[];
+}
+
+let cached: Promise<string[]> | null = null;
+
+async function fetchEnabledOptionalTools(): Promise<string[]> {
+ const res = await apiFetch(apiUrl("/api/v1/tools"));
+ if (!res.ok) throw new Error(`HTTP ${res.status}`);
+ const payload = (await res.json()) as ToolSettingsResponse;
+ return Array.isArray(payload.enabled_optional_tools)
+ ? payload.enabled_optional_tools.slice()
+ : [];
+}
+
+/** Read the user's saved set of enabled toggleable tools.
+ * Cached at module scope so multiple consumers on the same page share one
+ * network round-trip; call ``refreshEnabledOptionalTools`` to bust. */
+export async function getEnabledOptionalTools(options?: {
+ force?: boolean;
+}): Promise<string[]> {
+ if (options?.force || cached === null) {
+ cached = fetchEnabledOptionalTools().catch((err) => {
+ cached = null;
+ throw err;
+ });
+ }
+ return cached.then((list) => list.slice());
+}
+
+export function invalidateEnabledOptionalToolsCache(): void {
+ cached = null;
+}
diff --git a/web/lib/visualize-types.ts b/web/lib/visualize-types.ts
index 1bbc3cbd0..847336c09 100644
--- a/web/lib/visualize-types.ts
+++ b/web/lib/visualize-types.ts
@@ -1,23 +1,36 @@
-export type VisualizeRenderType = "svg" | "chartjs" | "mermaid" | "html";
-export type VisualizeRenderMode =
- | "auto"
- | "svg"
- | "chartjs"
- | "mermaid"
- | "html";
+import type { MathAnimatorResult } from "@/lib/math-animator-types";
+import { extractMathAnimatorResult } from "@/lib/math-animator-types";
+
+export type VisualizeTextRenderType = "svg" | "chartjs" | "mermaid" | "html";
+export type VisualizeManimRenderType = "manim_video" | "manim_image";
+export type VisualizeRenderType =
+ | VisualizeTextRenderType
+ | VisualizeManimRenderType;
+export type VisualizeRenderMode = "auto" | VisualizeRenderType;
export interface VisualizeFormConfig {
render_mode: VisualizeRenderMode;
+ // Only consumed by the backend when the resolved render_type ends up
+ // being manim_video / manim_image. Ignored on text-only paths but kept
+ // in form state so toggling between modes preserves the user's choice.
+ quality: "low" | "medium" | "high";
+ style_hint: string;
}
export const DEFAULT_VISUALIZE_CONFIG: VisualizeFormConfig = {
render_mode: "auto",
+ quality: "medium",
+ style_hint: "",
};
export function buildVisualizeWSConfig(
cfg: VisualizeFormConfig,
): Record<string, unknown> {
- return { render_mode: cfg.render_mode };
+ return {
+ render_mode: cfg.render_mode,
+ quality: cfg.quality,
+ style_hint: cfg.style_hint.trim(),
+ };
}
const VISUALIZE_RENDER_LABELS: Record<VisualizeRenderMode, string> = {
@@ -26,8 +39,22 @@ const VISUALIZE_RENDER_LABELS: Record<VisualizeRenderMode, string> = {
svg: "SVG",
mermaid: "Mermaid",
html: "HTML",
+ manim_video: "Animation",
+ manim_image: "Storyboard",
};
+export function isManimRenderType(
+ renderType: string,
+): renderType is VisualizeManimRenderType {
+ return renderType === "manim_video" || renderType === "manim_image";
+}
+
+export function isManimResult(
+ result: VisualizeResult,
+): result is VisualizeManimResult {
+ return isManimRenderType(result.render_type);
+}
+
/**
* One-line summary of the visualize form, shown next to the collapsed
* `Settings` chevron in the composer. Pass `translate` (typically the
@@ -39,12 +66,20 @@ export function summarizeVisualizeConfig(
translate?: (key: string) => string,
): string {
const label = VISUALIZE_RENDER_LABELS[cfg.render_mode] ?? cfg.render_mode;
- return translate ? translate(label) : label;
+ const text = translate ? translate(label) : label;
+ // For manim modes, surface the quality tier alongside the format —
+ // matches what users were used to in the old Animator panel.
+ if (cfg.render_mode === "manim_video" || cfg.render_mode === "manim_image") {
+ const qLabel = cfg.quality.charAt(0).toUpperCase() + cfg.quality.slice(1);
+ const q = translate ? translate(qLabel) : qLabel;
+ return `${text} · ${q}`;
+ }
+ return text;
}
-export interface VisualizeResult {
+interface VisualizeTextResult {
response: string;
- render_type: VisualizeRenderType;
+ render_type: VisualizeTextRenderType;
code: {
language: string;
content: string;
@@ -64,12 +99,28 @@ export interface VisualizeResult {
};
}
+interface VisualizeManimResult {
+ render_type: VisualizeManimRenderType;
+ manim: MathAnimatorResult;
+}
+
+export type VisualizeResult = VisualizeTextResult | VisualizeManimResult;
+
export function extractVisualizeResult(
resultMetadata: Record<string, unknown> | undefined,
): VisualizeResult | null {
if (!resultMetadata) return null;
const renderType = resultMetadata.render_type;
+
+ // Manim path: delegate decoding to math-animator-types so the existing
+ // MathAnimatorViewer can render the artefacts unchanged.
+ if (renderType === "manim_video" || renderType === "manim_image") {
+ const manim = extractMathAnimatorResult(resultMetadata);
+ if (!manim) return null;
+ return { render_type: renderType, manim };
+ }
+
if (
renderType !== "svg" &&
renderType !== "chartjs" &&
@@ -94,7 +145,7 @@ export function extractVisualizeResult(
},
analysis:
resultMetadata.analysis && typeof resultMetadata.analysis === "object"
- ? (resultMetadata.analysis as VisualizeResult["analysis"])
+ ? (resultMetadata.analysis as VisualizeTextResult["analysis"])
: {
render_type: renderType,
description: "",
@@ -105,7 +156,7 @@ export function extractVisualizeResult(
},
review:
resultMetadata.review && typeof resultMetadata.review === "object"
- ? (resultMetadata.review as VisualizeResult["review"])
+ ? (resultMetadata.review as VisualizeTextResult["review"])
: { optimized_code: "", changed: false, review_notes: "" },
};
}