Skip to content

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

feat: separate UI and model response languages (#758)

wayblinkbe14c3ef23c3
diff --git a/deeptutor/agents/question/coordinator.py b/deeptutor/agents/question/coordinator.py
index a61a39153..a4645a75d 100644
--- a/deeptutor/agents/question/coordinator.py
+++ b/deeptutor/agents/question/coordinator.py
@@ -21,7 +21,7 @@ from deeptutor.core.context import UnifiedContext
from deeptutor.core.stream import StreamEvent
from deeptutor.core.stream_bus import StreamBus
from deeptutor.services.path_service import get_path_service
-from deeptutor.services.settings.interface_settings import get_ui_language
+from deeptutor.services.settings.interface_settings import get_response_language
logger = logging.getLogger(__name__)
@@ -55,7 +55,7 @@ class AgentCoordinator:
self.api_version = api_version
self.kb_name = (kb_name or "").strip() or None
self.enable_idea_rag = True if enable_idea_rag is None else bool(enable_idea_rag)
- self.language = language or get_ui_language(default="en")
+ self.language = language or get_response_language(default="en")
self.output_dir = output_dir
self.enabled_tools = list(enabled_tools or [])
self._ws_callback: WsCallback | None = None
diff --git a/deeptutor/api/routers/chat.py b/deeptutor/api/routers/chat.py
index 203667ae4..b9c261fa8 100644
--- a/deeptutor/api/routers/chat.py
+++ b/deeptutor/api/routers/chat.py
@@ -13,7 +13,7 @@ from fastapi import APIRouter, HTTPException, WebSocket, WebSocketDisconnect
from deeptutor.agents.chat import ChatAgent, SessionManager
from deeptutor.services.config import PROJECT_ROOT, load_config_with_main
from deeptutor.services.llm.config import get_llm_config
-from deeptutor.services.settings.interface_settings import get_ui_language
+from deeptutor.services.settings.interface_settings import get_response_language
config = load_config_with_main("main.yaml", PROJECT_ROOT)
log_dir = config.get("paths", {}).get("user_log_dir") or config.get("logging", {}).get("log_dir")
@@ -76,7 +76,9 @@ async def websocket_chat(websocket: WebSocket):
if requested_language.startswith("zh")
else "en"
if requested_language.startswith("en")
- else get_ui_language(default=config.get("system", {}).get("language", "en"))
+ else get_response_language(
+ default=config.get("system", {}).get("language", "en")
+ )
)
message = data.get("message", "").strip()
session_id = data.get("session_id")
diff --git a/deeptutor/api/routers/co_writer.py b/deeptutor/api/routers/co_writer.py
index 70aedf43b..464583004 100644
--- a/deeptutor/api/routers/co_writer.py
+++ b/deeptutor/api/routers/co_writer.py
@@ -26,7 +26,7 @@ from deeptutor.co_writer.storage import (
from deeptutor.core.stream_bus import StreamBus
from deeptutor.services.config import PROJECT_ROOT, load_config_with_main
from deeptutor.services.llm import clean_thinking_tags
-from deeptutor.services.settings.interface_settings import get_ui_language
+from deeptutor.services.settings.interface_settings import get_response_language
router = APIRouter()
@@ -40,7 +40,7 @@ _edit_agent: EditAgent | None = None
def _current_language() -> str:
# Prefer UI settings, fall back to main.yaml system.language
- return get_ui_language(default=config.get("system", {}).get("language", "en"))
+ return get_response_language(default=config.get("system", {}).get("language", "en"))
def get_edit_agent() -> EditAgent:
diff --git a/deeptutor/api/routers/mastery_path.py b/deeptutor/api/routers/mastery_path.py
index fa479a654..572f57ada 100644
--- a/deeptutor/api/routers/mastery_path.py
+++ b/deeptutor/api/routers/mastery_path.py
@@ -19,7 +19,7 @@ from deeptutor.learning.models import (
)
from deeptutor.learning.service import LearningService
from deeptutor.learning.storage import LearningStore
-from deeptutor.services.settings.interface_settings import get_ui_language
+from deeptutor.services.settings.interface_settings import get_response_language
from deeptutor.utils.json_parser import parse_json_response
router = APIRouter()
@@ -245,7 +245,7 @@ async def generate_from_notebook(book_id: str, body: GenerateFromNotebookRequest
records_json = json.dumps(records_data, ensure_ascii=False)
from deeptutor.services.llm import complete
- language = get_ui_language()
+ language = get_response_language()
system_prompt, prompt = learning_prompts.notebook_generation_prompts(language, records_json)
response = await complete(prompt=prompt, system_prompt=system_prompt)
# LLMs commonly fence/slightly-malform JSON; use the shared fence-stripping
diff --git a/deeptutor/api/routers/question.py b/deeptutor/api/routers/question.py
index fdf12933b..6c087f0b5 100644
--- a/deeptutor/api/routers/question.py
+++ b/deeptutor/api/routers/question.py
@@ -20,7 +20,7 @@ from deeptutor.logging import (
from deeptutor.services.config import PROJECT_ROOT, load_config_with_main
from deeptutor.services.llm.config import get_llm_config
from deeptutor.services.path_service import get_path_service
-from deeptutor.services.settings.interface_settings import get_ui_language
+from deeptutor.services.settings.interface_settings import get_response_language
from deeptutor.tools.question import mimic_exam_questions
from deeptutor.utils.document_validator import DocumentValidator
from deeptutor.utils.error_utils import format_exception_message
@@ -412,7 +412,9 @@ async def websocket_question_generate(websocket: WebSocket):
base_url=base_url,
api_version=api_version,
kb_name=kb_name,
- language=get_ui_language(default=config.get("system", {}).get("language", "en")),
+ language=get_response_language(
+ default=config.get("system", {}).get("language", "en")
+ ),
output_dir=str(output_base),
)
diff --git a/deeptutor/api/routers/quiz_judge.py b/deeptutor/api/routers/quiz_judge.py
index 7fb6db9c8..eb89553bb 100644
--- a/deeptutor/api/routers/quiz_judge.py
+++ b/deeptutor/api/routers/quiz_judge.py
@@ -16,7 +16,7 @@ from fastapi import APIRouter, WebSocket, WebSocketDisconnect
from deeptutor.services.config import PROJECT_ROOT, load_config_with_main
from deeptutor.services.llm import stream as llm_stream
-from deeptutor.services.settings.interface_settings import get_ui_language
+from deeptutor.services.settings.interface_settings import get_response_language
from deeptutor.utils.error_utils import format_exception_message
logger = logging.getLogger(__name__)
@@ -276,7 +276,7 @@ async def websocket_quiz_judge(websocket: WebSocket):
requested_language = (data.get("language") or "").strip().lower()
if requested_language not in ("zh", "en"):
- requested_language = get_ui_language(
+ requested_language = get_response_language(
default=_config.get("system", {}).get("language", "en")
)
if requested_language not in ("zh", "en"):
diff --git a/deeptutor/api/routers/settings.py b/deeptutor/api/routers/settings.py
index 4a213bdd9..146973ea1 100644
--- a/deeptutor/api/routers/settings.py
+++ b/deeptutor/api/routers/settings.py
@@ -39,6 +39,10 @@ from deeptutor.services.llm.client import reset_llm_client
from deeptutor.services.llm.config import clear_llm_config_cache
from deeptutor.services.model_selection import list_llm_options
from deeptutor.services.path_service import get_path_service
+from deeptutor.services.settings.interface_settings import (
+ DEFAULT_UI_SETTINGS as INTERFACE_DEFAULTS,
+)
+from deeptutor.services.settings.interface_settings import resolve_languages
from deeptutor.tools.builtin import USER_TOGGLEABLE_TOOL_NAMES
router = APIRouter()
@@ -69,9 +73,10 @@ DEFAULT_SIDEBAR_NAV_ORDER = {
}
DEFAULT_UI_SETTINGS = {
- # "snow" is the pure-white neutral theme, shown as "Default" in the UI.
- "theme": "snow",
- "language": "en",
+ # theme / language / response_language come from the module that owns
+ # interface.json, so the two readers of that file can't drift on what a
+ # fresh install defaults to.
+ **INTERFACE_DEFAULTS,
"sidebar_description": "✨ Data Intelligence Lab @ HKU",
"sidebar_nav_order": DEFAULT_SIDEBAR_NAV_ORDER,
# User-toggleable chat tools. Default = all on; the /settings/tools page
@@ -103,6 +108,7 @@ class SidebarNavOrder(BaseModel):
class UISettings(BaseModel):
theme: Literal["light", "dark", "glass", "snow"] = "snow"
language: Literal["zh", "en"] = "en"
+ response_language: Literal["zh", "en"] = "en"
sidebar_description: Optional[str] = None
sidebar_nav_order: Optional[SidebarNavOrder] = None
code_block_theme: Optional[str] = None
@@ -125,6 +131,7 @@ class UISettingsUpdate(BaseModel):
# so PUT /ui cannot persist a theme/language the app can't render.
theme: Literal["light", "dark", "glass", "snow"] | None = None
language: Literal["zh", "en"] | None = None
+ response_language: Literal["zh", "en"] | None = None
sidebar_description: str | None = None
sidebar_nav_order: SidebarNavOrder | None = None
code_block_theme: str | None = None
@@ -282,7 +289,9 @@ def load_ui_settings() -> dict[str, Any]:
try:
with open(settings_file, encoding="utf-8") as handle:
saved = json.load(handle)
- merged = {**DEFAULT_UI_SETTINGS, **saved}
+ # resolve_languages owns the legacy migration (a file predating
+ # the UI/response split inherits its one language into both).
+ merged = {**DEFAULT_UI_SETTINGS, **saved, **resolve_languages(saved)}
# Filter persisted enabled_optional_tools to current
# toggleable set so retired tool names can't leak into
# the per-turn payload.
@@ -1111,17 +1120,19 @@ async def update_chat_response_timeout(update: ChatResponseTimeoutUpdate):
return {"chat_response_timeout": update.chat_response_timeout}
-# The only two UI preferences a page can need before it knows who is asking.
-PRESESSION_UI_FIELDS = ("theme", "language")
+# The UI preferences a page can need before it knows who is asking. All three
+# describe the person's own presentation and output choices; none of them say
+# anything about how the deployment is configured.
+PRESESSION_UI_FIELDS = ("theme", "language", "response_language")
@public_router.get("/ui")
async def get_ui_settings():
- """Return the pre-session UI preferences: theme and interface language.
+ """Return the pre-session UI preferences: theme and the two languages.
Public by design, which is why it is a narrow projection rather than the
saved ``ui`` blob. The app shell — and the statically prerendered auth
- pages, which have no session at all — adopt the persisted language here
+ pages, which have no session at all — adopt the persisted languages here
during bootstrap. Theme rides along so those pages can paint in the right
one instead of flashing.
diff --git a/deeptutor/learning/tests/test_api_endpoints.py b/deeptutor/learning/tests/test_api_endpoints.py
index 05329f3b9..d499f40f3 100644
--- a/deeptutor/learning/tests/test_api_endpoints.py
+++ b/deeptutor/learning/tests/test_api_endpoints.py
@@ -381,7 +381,7 @@ class TestGenerateFromNotebook:
)
assert resp.status_code == 502
- @patch("deeptutor.api.routers.mastery_path.get_ui_language", return_value="en")
+ @patch("deeptutor.api.routers.mastery_path.get_response_language", return_value="en")
@patch("deeptutor.services.llm.complete", new_callable=AsyncMock)
def test_generate_injection_ignored(self, mock_complete, _mock_language, client):
"""Injection payload in title/output must not alter generation behavior."""
@@ -421,9 +421,9 @@ class TestGenerateFromNotebook:
sys_prompt = call_args.kwargs.get("system_prompt") or call_args[1].get("system_prompt", "")
assert "Ignore" in sys_prompt
- @patch("deeptutor.api.routers.mastery_path.get_ui_language", return_value="zh")
+ @patch("deeptutor.api.routers.mastery_path.get_response_language", return_value="zh")
@patch("deeptutor.services.llm.complete", new_callable=AsyncMock)
- def test_generate_uses_zh_prompt_when_ui_language_is_zh(
+ def test_generate_uses_zh_prompt_when_response_language_is_zh(
self,
mock_complete,
_mock_language,
diff --git a/deeptutor/services/session/turn_runtime.py b/deeptutor/services/session/turn_runtime.py
index bc4dcc1ca..bd75f9015 100644
--- a/deeptutor/services/session/turn_runtime.py
+++ b/deeptutor/services/session/turn_runtime.py
@@ -654,6 +654,12 @@ class TurnRuntimeManager:
async def start_turn(self, payload: dict[str, Any]) -> tuple[dict[str, Any], dict[str, Any]]:
capability = str(payload.get("capability") or "chat")
+ if not payload.get("language"):
+ from deeptutor.services.settings.interface_settings import (
+ get_response_language,
+ )
+
+ payload = {**payload, "language": get_response_language(default="en")}
raw_config = dict(payload.get("config", {}) or {})
runtime_only_keys = (
"_persist_user_message",
diff --git a/deeptutor/services/settings/interface_settings.py b/deeptutor/services/settings/interface_settings.py
index a1d1dfe14..5af5e904c 100644
--- a/deeptutor/services/settings/interface_settings.py
+++ b/deeptutor/services/settings/interface_settings.py
@@ -7,6 +7,7 @@ This is the canonical backend source for user-selected UI language/theme stored
from __future__ import annotations
+from collections.abc import Mapping
import json
from typing import Any
@@ -16,6 +17,7 @@ DEFAULT_UI_SETTINGS: dict[str, Any] = {
# "snow" is the pure-white neutral theme, shown as "Default" in the UI.
"theme": "snow",
"language": "en",
+ "response_language": "en",
}
@@ -48,23 +50,42 @@ def _normalize_language(language: Any, default: str = "en") -> str:
return "en"
+def resolve_languages(saved: Mapping[str, Any]) -> dict[str, str]:
+ """Normalize the two language fields out of a raw ``interface.json`` dict.
+
+ ``response_language`` was split out of ``language`` after the two had been
+ a single setting, so a file written before the split carries only
+ ``language`` and must inherit it. That inheritance *is* the migration, and
+ it lives here because this module owns the file's shape — both readers of
+ ``interface.json`` (this module and the settings router, which layers its
+ own superset of defaults on top) go through this one function so they can
+ never disagree about what a legacy file means.
+
+ ``_normalize_language`` already falls back to its ``default`` for a value
+ that is missing, blank or unrecognized, so absence, ``null`` and junk all
+ land on the interface language without a separate key-presence check.
+ """
+ language = _normalize_language(saved.get("language"), DEFAULT_UI_SETTINGS["language"])
+ return {
+ "language": language,
+ "response_language": _normalize_language(saved.get("response_language"), language),
+ }
+
+
def get_ui_settings() -> dict[str, Any]:
"""
Read UI settings from interface.json with defaults.
Returns:
- dict containing at least: {"theme": "...", "language": "..."}
+ dict containing at least: {"theme": "...", "language": "...",
+ "response_language": "..."}
"""
settings_file = _interface_settings_file()
if settings_file.exists():
try:
with open(settings_file, encoding="utf-8") as f:
saved = json.load(f) or {}
- merged = {**DEFAULT_UI_SETTINGS, **saved}
- merged["language"] = _normalize_language(
- merged.get("language"), DEFAULT_UI_SETTINGS["language"]
- )
- return merged
+ return {**DEFAULT_UI_SETTINGS, **saved, **resolve_languages(saved)}
except Exception:
# On any parse error, fall back to defaults (safe)
return DEFAULT_UI_SETTINGS.copy()
@@ -83,3 +104,9 @@ def get_ui_language(default: str = "en") -> str:
"""
settings = get_ui_settings()
return _normalize_language(settings.get("language"), default)
+
+
+def get_response_language(default: str = "en") -> str:
+ """Get the preferred reader-facing model output language."""
+ settings = get_ui_settings()
+ return _normalize_language(settings.get("response_language"), default)
diff --git a/tests/api/test_question_router.py b/tests/api/test_question_router.py
index 22f8f95ac..8a1220f25 100644
--- a/tests/api/test_question_router.py
+++ b/tests/api/test_question_router.py
@@ -69,6 +69,10 @@ def _load_question_router_module(monkeypatch: pytest.MonkeyPatch):
fake_settings_package = _package("deeptutor.services.settings")
fake_interface_settings = types.ModuleType("deeptutor.services.settings.interface_settings")
fake_interface_settings.get_ui_language = lambda default="en": default
+ # The router asks for the *response* language now that reader-facing output
+ # no longer follows the interface locale; the stand-in module has to offer
+ # both readers the real one does.
+ fake_interface_settings.get_response_language = lambda default="en": default
fake_settings_package.interface_settings = fake_interface_settings
monkeypatch.setitem(sys.modules, "deeptutor.services.settings", fake_settings_package)
monkeypatch.setitem(
diff --git a/tests/api/test_settings_router.py b/tests/api/test_settings_router.py
index 87d70248b..8f628526a 100644
--- a/tests/api/test_settings_router.py
+++ b/tests/api/test_settings_router.py
@@ -20,6 +20,65 @@ from deeptutor.services.llm import client as llm_client_module
from deeptutor.services.llm import config as llm_config_module
+def test_load_ui_settings_migrates_legacy_language_to_response_language(
+ monkeypatch: pytest.MonkeyPatch, tmp_path
+) -> None:
+ settings_file = tmp_path / "interface.json"
+ settings_file.write_text(
+ '{"theme": "snow", "language": "zh"}', encoding="utf-8"
+ )
+ monkeypatch.setattr(settings_router, "_settings_file", lambda: settings_file)
+
+ settings = settings_router.load_ui_settings()
+
+ assert settings["language"] == "zh"
+ assert settings["response_language"] == "zh"
+
+
+def test_both_readers_of_interface_json_agree_on_a_legacy_file(
+ monkeypatch: pytest.MonkeyPatch, tmp_path
+) -> None:
+ """The router and the service must read the same file the same way.
+
+ ``interface.json`` has two readers: ``interface_settings.get_ui_settings``
+ (used by the turn path) and the router's ``load_ui_settings`` (which layers
+ the API's superset of defaults on top). They resolve the language pair
+ through one shared helper precisely so a legacy file can't mean different
+ things depending on which one asked.
+ """
+ from deeptutor.services.settings import interface_settings
+
+ settings_file = tmp_path / "interface.json"
+ settings_file.write_text('{"theme": "dark", "language": "zh"}', encoding="utf-8")
+ monkeypatch.setattr(settings_router, "_settings_file", lambda: settings_file)
+ monkeypatch.setattr(
+ interface_settings, "_interface_settings_file", lambda: settings_file
+ )
+
+ from_router = settings_router.load_ui_settings()
+ from_service = interface_settings.get_ui_settings()
+
+ for field in ("language", "response_language"):
+ assert from_router[field] == from_service[field] == "zh"
+
+
+async def test_ui_languages_are_persisted_independently(
+ monkeypatch: pytest.MonkeyPatch, tmp_path
+) -> None:
+ settings_file = tmp_path / "interface.json"
+ monkeypatch.setattr(settings_router, "_settings_file", lambda: settings_file)
+
+ response = await settings_router.update_ui_settings(
+ settings_router.UISettingsUpdate(
+ theme="snow", language="en", response_language="zh"
+ )
+ )
+
+ assert response["language"] == "en"
+ assert response["response_language"] == "zh"
+
+
class _FakeEmbeddingAdapter:
def __init__(self, config: dict[str, Any]):
self.config = config
diff --git a/tests/multi_user/test_ui_language_scoping.py b/tests/multi_user/test_ui_language_scoping.py
index 3a27eaac3..1b3000407 100644
--- a/tests/multi_user/test_ui_language_scoping.py
+++ b/tests/multi_user/test_ui_language_scoping.py
@@ -5,6 +5,7 @@ from __future__ import annotations
import json
from deeptutor.services.settings.interface_settings import (
+ get_response_language,
get_ui_language,
get_ui_settings,
)
@@ -36,3 +37,35 @@ def test_get_ui_language_defaults_when_no_file(mu_isolated_root, as_user):
with as_user("u_alice", role="user"):
# Bob has nothing on disk yet — falls back to the default "en".
assert get_ui_language() == "en"
+
+
+def test_response_language_is_scoped_independently_per_user(
+ mu_isolated_root, as_user
+):
+ admin_settings = mu_isolated_root / "data" / "user" / "settings" / "interface.json"
+ admin_settings.parent.mkdir(parents=True, exist_ok=True)
+ admin_settings.write_text(
+ json.dumps({"language": "en", "response_language": "zh"})
+ )
+
+ alice_settings = (
+ mu_isolated_root
+ / "data"
+ / "users"
+ / "u_alice"
+ / "user"
+ / "settings"
+ / "interface.json"
+ )
+ alice_settings.parent.mkdir(parents=True, exist_ok=True)
+ alice_settings.write_text(
+ json.dumps({"language": "zh", "response_language": "en"})
+ )
+
+ with as_user("u_admin", role="admin"):
+ assert get_ui_language() == "en"
+ assert get_response_language() == "zh"
+
+ with as_user("u_alice", role="user"):
+ assert get_ui_language() == "zh"
+ assert get_response_language() == "en"
diff --git a/web/app/(utility)/settings/appearance/page.tsx b/web/app/(utility)/settings/appearance/page.tsx
index 92175988d..0dea1b628 100644
--- a/web/app/(utility)/settings/appearance/page.tsx
+++ b/web/app/(utility)/settings/appearance/page.tsx
@@ -41,11 +41,13 @@ export default function AppearanceSettingsPage() {
const {
theme,
language,
+ responseLanguage,
codeBlockTheme,
codeBlockShowLineNumbers,
codeBlockWrapLongLines,
updateTheme,
updateLanguage,
+ updateResponseLanguage,
updateCodeBlockTheme,
updateCodeBlockShowLineNumbers,
updateCodeBlockWrapLongLines,
@@ -78,7 +80,7 @@ export default function AppearanceSettingsPage() {
<SettingRow
title={t("Interface language")}
description={t(
- "Affects the UI only. Model output language is controlled by your prompt.",
+ "Controls navigation, settings, and status text only.",
)}
control={
<div className="flex gap-0.5 rounded-lg bg-[var(--muted)] p-0.5">
@@ -98,6 +100,31 @@ export default function AppearanceSettingsPage() {
</div>
}
/>
+ <SettingRow
+ title={t("Model output language")}
+ description={t(
+ "Sets the default language for chat and capability responses.",
+ )}
+ control={
+ <div className="flex gap-0.5 rounded-lg bg-[var(--muted)] p-0.5">
+ {(["en", "zh"] as const).map((value) => (
+ <button
+ key={value}
+ onClick={() => updateResponseLanguage(value)}
+ className={`rounded-md px-2.5 py-1 text-[12px] transition-all ${
+ responseLanguage === value
+ ? "bg-[var(--card)] font-medium text-[var(--foreground)] shadow-sm"
+ : "text-[var(--muted-foreground)] hover:text-[var(--foreground)]"
+ }`}
+ >
+ {value === "en"
+ ? t("language.english")
+ : t("language.chinese")}
+ </button>
+ ))}
+ </div>
+ }
+ />
</SettingSection>
<SettingSection
diff --git a/web/components/settings/SettingsContext.tsx b/web/components/settings/SettingsContext.tsx
index 4baf7de3b..0f3e09e07 100644
--- a/web/components/settings/SettingsContext.tsx
+++ b/web/components/settings/SettingsContext.tsx
@@ -20,6 +20,7 @@ import {
writeStoredCodeBlockTheme,
writeStoredCodeBlockWrapLongLines,
writeStoredLanguage,
+ writeStoredResponseLanguage,
} from "@/context/app-shell-storage";
import { useAppShell } from "@/context/AppShellContext";
import { apiFetch, apiUrl } from "@/lib/api";
@@ -114,6 +115,7 @@ export type Catalog = {
export type UiSettings = {
theme: "light" | "dark" | "glass" | "snow";
language: "en" | "zh";
+ response_language: "en" | "zh";
code_block_theme: string;
code_block_show_line_numbers: boolean;
code_block_wrap_long_lines: boolean;
@@ -447,6 +449,7 @@ type SettingsContextValue = {
hasUnsavedChanges: boolean;
theme: UiSettings["theme"];
language: UiSettings["language"];
+ responseLanguage: UiSettings["response_language"];
codeBlockTheme: UiSettings["code_block_theme"];
codeBlockShowLineNumbers: UiSettings["code_block_show_line_numbers"];
codeBlockWrapLongLines: UiSettings["code_block_wrap_long_lines"];
@@ -456,6 +459,9 @@ type SettingsContextValue = {
// UI prefs
updateTheme: (next: UiSettings["theme"]) => Promise<void>;
updateLanguage: (next: UiSettings["language"]) => Promise<void>;
+ updateResponseLanguage: (
+ next: UiSettings["response_language"],
+ ) => Promise<void>;
updateCodeBlockTheme: (next: CodeBlockThemeId) => Promise<void>;
updateCodeBlockShowLineNumbers: (next: boolean) => Promise<void>;
updateCodeBlockWrapLongLines: (next: boolean) => Promise<void>;
@@ -546,6 +552,8 @@ export function SettingsProvider({ children }: { children: ReactNode }) {
const [status, setStatus] = useState<SystemStatus | null>(null);
const [theme, setTheme] = useState<UiSettings["theme"]>("snow");
const [language, setLanguage] = useState<UiSettings["language"]>("en");
+ const [responseLanguage, setResponseLanguage] =
+ useState<UiSettings["response_language"]>("en");
const [catalog, setCatalog] = useState<Catalog>(defaultCatalog());
const [draft, setDraft] = useState<Catalog>(defaultCatalog());
const [catalogEditable, setCatalogEditable] = useState<boolean | null>(null);
@@ -632,6 +640,9 @@ export function SettingsProvider({ children }: { children: ReactNode }) {
}
setTheme(payload.ui.theme);
setLanguage(payload.ui.language);
+ setResponseLanguage(
+ payload.ui.response_language ?? payload.ui.language,
+ );
// Writes the backend-loaded values into app-shell storage and dispatches
// the code-block settings event; AppShellContext (the single source) picks
// them up, so no separate copy needs seeding here.
@@ -710,6 +721,15 @@ export function SettingsProvider({ children }: { children: ReactNode }) {
await persistUiSettingsPatch({ language: next });
}, []);
+ const updateResponseLanguage = useCallback(
+ async (next: UiSettings["response_language"]) => {
+ setResponseLanguage(next);
+ writeStoredResponseLanguage(next);
+ await persistUiSettingsPatch({ response_language: next });
+ },
+ [],
+ );
+
// Each setter updates the app-shell source of truth (which normalizes,
// persists to localStorage, and notifies consumers) then mirrors the change
// to the backend.
@@ -1264,6 +1284,7 @@ export function SettingsProvider({ children }: { children: ReactNode }) {
hasUnsavedChanges,
theme,
language,
+ responseLanguage,
codeBlockTheme,
codeBlockShowLineNumbers,
codeBlockWrapLongLines,
@@ -1271,6 +1292,7 @@ export function SettingsProvider({ children }: { children: ReactNode }) {
setToast,
updateTheme,
updateLanguage,
+ updateResponseLanguage,
updateCodeBlockTheme,
updateCodeBlockShowLineNumbers,
updateCodeBlockWrapLongLines,
@@ -1320,6 +1342,7 @@ export function SettingsProvider({ children }: { children: ReactNode }) {
embeddingDefaultDim,
hasUnsavedChanges,
language,
+ responseLanguage,
llmContextDetection,
logs,
mutateCatalog,
@@ -1348,6 +1371,7 @@ export function SettingsProvider({ children }: { children: ReactNode }) {
updateContextWindowField,
updateReasoningEffort,
updateLanguage,
+ updateResponseLanguage,
updateModelBoolField,
updateModelField,
updateProfileField,
diff --git a/web/context/AppShellContext.tsx b/web/context/AppShellContext.tsx
index ae2d7bee0..e9bc3293f 100644
--- a/web/context/AppShellContext.tsx
+++ b/web/context/AppShellContext.tsx
@@ -32,11 +32,13 @@ import {
normalizeCodeBlockTheme,
normalizeCodeBlockWrapLongLines,
normalizeLanguage,
+ resolveResponseLanguage,
readStoredActiveSessionId,
readStoredCodeBlockShowLineNumbers,
readStoredCodeBlockTheme,
readStoredCodeBlockWrapLongLines,
readStoredLanguage,
+ writeStoredResponseLanguage,
readStoredSidebarCollapsed,
writeStoredActiveSessionId,
writeStoredCodeBlockShowLineNumbers,
@@ -97,11 +99,16 @@ export function AppShellProvider({ children }: { children: React.ReactNode }) {
}, []);
useEffect(() => {
- // The saved interface language lives in the backend's ui settings, but
- // only the settings route ever read it, so every other page started in
- // English until the user changed it again in this browser. Adopt it once,
- // and only when this browser has made no choice of its own — a local
- // selection is the more specific signal and must win.
+ // The saved languages live in the backend's ui settings, but only the
+ // settings route ever read them, so every other page started in English
+ // until the user changed it again in this browser. Adopt them once, and
+ // only when this browser has made no choice of its own — a local selection
+ // is the more specific signal and must win.
+ //
+ // One fetch carries both fields: the interface locale and the
+ // reader-facing output language are stored together and are gated by the
+ // same "has this browser chosen yet?" question, so splitting them into two
+ // bootstraps would only give them a chance to disagree.
if (hasStoredLanguage()) return;
const controller = new AbortController();
void (async () => {
@@ -111,9 +118,23 @@ export function AppShellProvider({ children }: { children: React.ReactNode }) {
skipAuthRedirect: true,
});
if (!response.ok) return;
- const payload = (await response.json()) as { language?: unknown };
+ const payload = (await response.json()) as {
+ language?: unknown;
+ response_language?: unknown;
+ };
if (payload.language !== "zh" && payload.language !== "en") return;
writeStoredLanguage(payload.language);
+ // A backend that predates the split sends no response_language;
+ // resolveResponseLanguage inherits the interface locale, matching what
+ // the server does for a legacy interface.json.
+ writeStoredResponseLanguage(
+ resolveResponseLanguage(
+ typeof payload.response_language === "string"
+ ? payload.response_language
+ : null,
+ payload.language,
+ ),
+ );
setLanguageState(payload.language);
} catch {
// Offline or unauthenticated: keep the local default.
diff --git a/web/context/UnifiedChatContext.tsx b/web/context/UnifiedChatContext.tsx
index 2f6ebecbe..c6aec9878 100644
--- a/web/context/UnifiedChatContext.tsx
+++ b/web/context/UnifiedChatContext.tsx
@@ -11,11 +11,11 @@ import React, {
useRef,
} from "react";
import {
- LANGUAGE_EVENT,
- LANGUAGE_STORAGE_KEY,
+ RESPONSE_LANGUAGE_EVENT,
+ RESPONSE_LANGUAGE_STORAGE_KEY,
normalizeLanguage,
readStoredChatResponseTimeout,
- readStoredLanguage,
+ readStoredResponseLanguage,
writeStoredActiveSessionId,
} from "@/context/app-shell-storage";
import type { StreamEvent, ChatMessage, LLMSelection } from "@/lib/unified-ws";
@@ -270,7 +270,8 @@ function createSessionEntry(
messages: [],
isStreaming: false,
currentStage: "",
- language: typeof window === "undefined" ? "en" : readStoredLanguage(),
+ language:
+ typeof window === "undefined" ? "en" : readStoredResponseLanguage(),
status: "idle",
activeTurnId: null,
lastSeq: 0,
@@ -1364,10 +1365,10 @@ export function UnifiedChatProvider({
typeof session.preferences?.persona === "string"
? session.preferences.persona
: "",
- // The Settings language is global UI state. Historical sessions may
- // have stale persisted preferences, so new turns follow the current
- // app language rather than the language saved when the session began.
- language: readStoredLanguage(),
+ // Model output language is account-level state. Historical sessions
+ // may have stale persisted preferences, so new turns follow the
+ // current response-language setting rather than their original value.
+ language: readStoredResponseLanguage(),
selectedBranches: normalizeSelectedBranches(
session.preferences?.selected_branches,
),
@@ -1405,18 +1406,19 @@ export function UnifiedChatProvider({
const syncLanguage = (language: string | null | undefined) => {
dispatch({ type: "SET_LANGUAGE", lang: normalizeLanguage(language) });
};
- const onLanguage = (event: Event) => {
+ const onResponseLanguage = (event: Event) => {
const detail = (event as CustomEvent<{ language?: string }>).detail;
syncLanguage(detail?.language);
};
const onStorage = (event: StorageEvent) => {
- if (event.key === LANGUAGE_STORAGE_KEY) syncLanguage(event.newValue);
+ if (event.key === RESPONSE_LANGUAGE_STORAGE_KEY)
+ syncLanguage(event.newValue);
};
- window.addEventListener(LANGUAGE_EVENT, onLanguage);
+ window.addEventListener(RESPONSE_LANGUAGE_EVENT, onResponseLanguage);
window.addEventListener("storage", onStorage);
return () => {
- window.removeEventListener(LANGUAGE_EVENT, onLanguage);
+ window.removeEventListener(RESPONSE_LANGUAGE_EVENT, onResponseLanguage);
window.removeEventListener("storage", onStorage);
};
}, []);
@@ -1513,7 +1515,7 @@ export function UnifiedChatProvider({
? (replaySnapshot.llmSelection ?? null)
: session.llmSelection;
const effectiveLanguage =
- replaySnapshot?.language ?? readStoredLanguage();
+ replaySnapshot?.language ?? readStoredResponseLanguage();
// Persona resolution: replay snapshot wins; then an explicit per-call
// persona (quiz follow-up surface); then the session-level preference.
// Always a string — "" means Default / no persona.
@@ -1747,7 +1749,7 @@ export function UnifiedChatProvider({
type: "regenerate",
session_id: session.sessionId,
overrides: {
- language: readStoredLanguage(),
+ language: readStoredResponseLanguage(),
},
});
}, [sendThroughRunner]);
diff --git a/web/context/app-shell-storage.ts b/web/context/app-shell-storage.ts
index 81b3bf0d4..acf8e34cb 100644
--- a/web/context/app-shell-storage.ts
+++ b/web/context/app-shell-storage.ts
@@ -4,6 +4,7 @@ export type AppLanguage = "en" | "zh";
export const ACTIVE_SESSION_STORAGE_KEY = "deeptutor.activeSessionId.tab";
export const LANGUAGE_STORAGE_KEY = "deeptutor-language";
+export const RESPONSE_LANGUAGE_STORAGE_KEY = "deeptutor-response-language";
export const SIDEBAR_COLLAPSED_STORAGE_KEY = "deeptutor.sidebarCollapsed";
export const CHAT_RESPONSE_TIMEOUT_STORAGE_KEY =
"deeptutor.chatResponseTimeout";
@@ -56,6 +57,7 @@ export function writeStoredChatResponseTimeout(seconds: number): void {
export const ACTIVE_SESSION_EVENT = "deeptutor:active-session";
export const LANGUAGE_EVENT = "deeptutor:language";
+export const RESPONSE_LANGUAGE_EVENT = "deeptutor:response-language";
export const SIDEBAR_COLLAPSED_EVENT = "deeptutor:sidebar-collapsed";
export const CODE_BLOCK_SETTINGS_EVENT = "deeptutor:code-block-settings";
@@ -65,6 +67,15 @@ export function normalizeLanguage(
return value === "zh" ? "zh" : "en";
}
+export function resolveResponseLanguage(
+ value: string | null | undefined,
+ legacyLanguage: string | null | undefined = "en",
+): AppLanguage {
+ return value === "zh" || value === "en"
+ ? value
+ : normalizeLanguage(legacyLanguage);
+}
+
export function readStoredLanguage(): AppLanguage {
if (typeof window === "undefined") return "en";
try {
@@ -104,6 +115,32 @@ export function writeStoredLanguage(language: AppLanguage): void {
}
}
+export function readStoredResponseLanguage(): AppLanguage {
+ if (typeof window === "undefined") return "en";
+ try {
+ return resolveResponseLanguage(
+ window.localStorage.getItem(RESPONSE_LANGUAGE_STORAGE_KEY),
+ window.localStorage.getItem(LANGUAGE_STORAGE_KEY),
+ );
+ } catch {
+ return "en";
+ }
+}
+
+export function writeStoredResponseLanguage(language: AppLanguage): void {
+ if (typeof window === "undefined") return;
+ try {
+ window.localStorage.setItem(RESPONSE_LANGUAGE_STORAGE_KEY, language);
+ window.dispatchEvent(
+ new CustomEvent(RESPONSE_LANGUAGE_EVENT, {
+ detail: { language },
+ }),
+ );
+ } catch {
+ // localStorage may be unavailable
+ }
+}
+
export function readStoredActiveSessionId(): string | null {
if (typeof window === "undefined") return null;
try {
diff --git a/web/locales/en/app.json b/web/locales/en/app.json
index c78e248c7..1eb4f3de1 100644
--- a/web/locales/en/app.json
+++ b/web/locales/en/app.json
@@ -1874,7 +1874,9 @@
"Snow keeps things minimal; Glass adds translucent panels. Dark mode follows the same accent palette.": "Snow keeps things minimal; Glass adds translucent panels. Dark mode follows the same accent palette.",
"Choose the interface language.": "Choose the interface language.",
"Interface language": "Interface language",
- "Affects the UI only. Model output language is controlled by your prompt.": "Affects the UI only. Model output language is controlled by your prompt.",
+ "Controls navigation, settings, and status text only.": "Controls navigation, settings, and status text only.",
+ "Model output language": "Model output language",
+ "Sets the default language for chat and capability responses.": "Sets the default language for chat and capability responses.",
"Runtime status for backend and configured services.": "Runtime status for backend and configured services.",
"Live state of the backend and the model services your configuration applies to.": "Live state of the backend and the model services your configuration applies to.",
"Status reflects the runtime values after the last Apply. Draft changes only take effect once applied.": "Status reflects the runtime values after the last Apply. Draft changes only take effect once applied.",
diff --git a/web/locales/zh/app.json b/web/locales/zh/app.json
index 879f4d3d5..56120cfa1 100644
--- a/web/locales/zh/app.json
+++ b/web/locales/zh/app.json
@@ -1248,7 +1248,9 @@
"Snow keeps things minimal; Glass adds translucent panels. Dark mode follows the same accent palette.": "Snow 最简洁;Glass 加入半透明面板;Dark 沿用同一套点缀色。",
"Choose the interface language.": "选择界面语言。",
"Interface language": "界面语言",
- "Affects the UI only. Model output language is controlled by your prompt.": "只影响界面文案,模型输出语言由你的提示词控制。",
+ "Controls navigation, settings, and status text only.": "只控制导航、设置和状态文案。",
+ "Model output language": "模型输出语言",
+ "Sets the default language for chat and capability responses.": "设置聊天及各项能力回复所使用的默认语言。",
"Runtime status for backend and configured services.": "后端与各模型服务的运行状态。",
"Live state of the backend and the model services your configuration applies to.": "后端和当前配置生效的模型服务的实时状态。",
"Status reflects the runtime values after the last Apply. Draft changes only take effect once applied.": "状态反映上一次 Apply 之后的运行时数值。草稿改动需要 Apply 才会生效。",
diff --git a/web/tests/language-preferences.test.ts b/web/tests/language-preferences.test.ts
new file mode 100644
index 000000000..db7e45124
--- /dev/null
+++ b/web/tests/language-preferences.test.ts
@@ -0,0 +1,14 @@
+import test from "node:test";
+import assert from "node:assert/strict";
+
+import { resolveResponseLanguage } from "../context/app-shell-storage";
+
+test("response language remains independent from the interface language", () => {
+ assert.equal(resolveResponseLanguage("zh", "en"), "zh");
+ assert.equal(resolveResponseLanguage("en", "zh"), "en");
+});
+
+test("legacy settings inherit the interface language when response language is missing", () => {
+ assert.equal(resolveResponseLanguage(null, "zh"), "zh");
+ assert.equal(resolveResponseLanguage(undefined, "en"), "en");
+});