Skip to content

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

fix(web): honour the saved interface language on first load (#730)

Dongyubf76ccfd83f9
diff --git a/deeptutor/api/routers/settings.py b/deeptutor/api/routers/settings.py
index 25f3a2bb4..4e3ede79d 100644
--- a/deeptutor/api/routers/settings.py
+++ b/deeptutor/api/routers/settings.py
@@ -1104,6 +1104,18 @@ async def update_chat_response_timeout(update: ChatResponseTimeoutUpdate):
return {"chat_response_timeout": update.chat_response_timeout}
+async def get_ui_settings():
+ """Return the saved UI settings blob.
+
+ The full ``ui`` payload (sidebar_nav_order, enabled_optional_tools,
+ voice_autoplay, …), same as the ``ui`` key of GET /settings. The app shell
+ reads it during bootstrap for the interface language, which nothing outside
+ the settings route used to see.
+ """
+ return load_ui_settings()
+
+
@router.put("/ui")
async def update_ui_settings(update: UISettingsUpdate):
"""Merge frontend partial update into current UI settings.
diff --git a/tests/api/test_settings_router.py b/tests/api/test_settings_router.py
index 69ebf4eb7..54f6dcbac 100644
--- a/tests/api/test_settings_router.py
+++ b/tests/api/test_settings_router.py
@@ -774,6 +774,26 @@ async def test_update_ui_settings_preserves_theme_and_language_when_code_block_u
assert persisted["code_block_theme"] == "dracula"
+async def test_get_ui_settings_returns_persisted_interface_preferences(
+ monkeypatch: pytest.MonkeyPatch, tmp_path
+) -> None:
+ settings_file = tmp_path / "interface.json"
+ monkeypatch.setattr(settings_router, "_settings_file", lambda: settings_file)
+ settings_router.save_ui_settings(
+ {
+ **settings_router.DEFAULT_UI_SETTINGS,
+ "theme": "dark",
+ "language": "zh",
+ }
+ )
+
+ response = await settings_router.get_ui_settings()
+
+ assert response["theme"] == "dark"
+ assert response["language"] == "zh"
+
+
def test_codex_provider_choice_is_advertised_as_oauth() -> None:
llm = {item["value"]: item for item in settings_router._provider_choices()["llm"]}
diff --git a/web/app/(workspace)/home/[[...sessionId]]/page.tsx b/web/app/(workspace)/home/[[...sessionId]]/page.tsx
index 45451eeb4..74c119ea1 100644
--- a/web/app/(workspace)/home/[[...sessionId]]/page.tsx
+++ b/web/app/(workspace)/home/[[...sessionId]]/page.tsx
@@ -103,6 +103,7 @@ import {
} from "@/lib/tools-settings";
import { downloadChatMarkdown } from "@/lib/chat-export";
import { buildChatOutline } from "@/lib/chat-outline";
+import { isPlaceholderSessionTitle } from "@/lib/session-title";
import type { SpaceMemoryFile } from "@/lib/space-items";
import {
selectedBooksToPayload,
@@ -694,8 +695,9 @@ export default function ChatPage() {
[state.messages],
);
const persistedSessionTitle = state.sessionTitle.trim();
- const displaySessionTitle =
- persistedSessionTitle || firstUserTitle || t("New chat");
+ const displaySessionTitle = isPlaceholderSessionTitle(persistedSessionTitle)
+ ? firstUserTitle || t("New chat")
+ : persistedSessionTitle;
const canRenameSession = Boolean(state.sessionId);
const titleInputRef = useRef<HTMLInputElement | null>(null);
const skipTitleCommitRef = useRef(false);
diff --git a/web/components/SessionList.tsx b/web/components/SessionList.tsx
index 83a79d70e..c63f9cd46 100644
--- a/web/components/SessionList.tsx
+++ b/web/components/SessionList.tsx
@@ -11,6 +11,7 @@ import {
getDayGroupKey,
type DayGroupKey,
} from "@/lib/relative-time";
+import { isPlaceholderSessionTitle } from "@/lib/session-title";
type SessionRuntimeStatus =
| "idle"
@@ -87,10 +88,6 @@ export default function SessionList({
// "New chat" string with a breathing animation so the sidebar shows
// something "alive" while the title is being generated in the
// background instead of a literal English sentinel.
- const isPlaceholderTitle = (raw: string | null | undefined): boolean => {
- const value = (raw ?? "").trim();
- return value === "" || value === "New conversation";
- };
const placeholderLabel = t("New chat");
// The group-key tokens stay stable; only the translated labels change.
@@ -221,7 +218,7 @@ export default function SessionList({
onClick={(event) => event.stopPropagation()}
className="min-w-0 flex-1 rounded border border-[var(--border)] bg-[var(--background)] px-1.5 py-px text-[12px] text-[var(--foreground)] outline-none focus:ring-1 focus:ring-[var(--primary)]/40"
/>
- ) : isPlaceholderTitle(session.title) ? (
+ ) : isPlaceholderSessionTitle(session.title) ? (
<span
className={`dt-breathing-text min-w-0 flex-1 truncate text-[13px] italic text-[var(--muted-foreground)] ${active ? "font-medium" : ""}`}
>
@@ -331,7 +328,7 @@ export default function SessionList({
/>
) : (
<div className="flex items-center">
- {isPlaceholderTitle(session.title) ? (
+ {isPlaceholderSessionTitle(session.title) ? (
<span
className={`dt-breathing-text line-clamp-1 min-w-0 flex-1 text-[12px] italic leading-snug text-[var(--muted-foreground)] ${
active ? "font-medium" : "font-normal"
diff --git a/web/context/AppShellContext.tsx b/web/context/AppShellContext.tsx
index fda2c06e9..ae2d7bee0 100644
--- a/web/context/AppShellContext.tsx
+++ b/web/context/AppShellContext.tsx
@@ -8,6 +8,7 @@ import {
useMemo,
useState,
} from "react";
+import { apiFetch, apiUrl } from "@/lib/api";
import {
getStoredTheme,
getSystemTheme,
@@ -24,6 +25,7 @@ import {
CODE_BLOCK_WRAP_LONG_LINES_STORAGE_KEY,
LANGUAGE_EVENT,
LANGUAGE_STORAGE_KEY,
+ hasStoredLanguage,
SIDEBAR_COLLAPSED_EVENT,
SIDEBAR_COLLAPSED_STORAGE_KEY,
normalizeCodeBlockShowLineNumbers,
@@ -94,6 +96,32 @@ export function AppShellProvider({ children }: { children: React.ReactNode }) {
setCodeBlockWrapLongLinesState(readStoredCodeBlockWrapLongLines());
}, []);
+ 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.
+ if (hasStoredLanguage()) return;
+ const controller = new AbortController();
+ void (async () => {
+ try {
+ const response = await apiFetch(apiUrl("/api/v1/settings/ui"), {
+ signal: controller.signal,
+ skipAuthRedirect: true,
+ });
+ if (!response.ok) return;
+ const payload = (await response.json()) as { language?: unknown };
+ if (payload.language !== "zh" && payload.language !== "en") return;
+ writeStoredLanguage(payload.language);
+ setLanguageState(payload.language);
+ } catch {
+ // Offline or unauthenticated: keep the local default.
+ }
+ })();
+ return () => controller.abort();
+ }, []);
+
useEffect(() => {
return subscribeToThemeChanges((nextTheme) => {
setThemeState(nextTheme);
diff --git a/web/context/app-shell-storage.ts b/web/context/app-shell-storage.ts
index 44c6b0d5b..81b3bf0d4 100644
--- a/web/context/app-shell-storage.ts
+++ b/web/context/app-shell-storage.ts
@@ -74,6 +74,22 @@ export function readStoredLanguage(): AppLanguage {
}
}
+/** Whether this browser has ever recorded a choice.
+ *
+ * ``readStoredLanguage`` cannot answer this: it normalizes a missing value to
+ * "en", which is indistinguishable from an explicit English selection. The
+ * bootstrap needs the difference — it may only consult the server-side
+ * preference when the browser has no choice of its own to honour.
+ */
+export function hasStoredLanguage(): boolean {
+ if (typeof window === "undefined") return false;
+ try {
+ return window.localStorage.getItem(LANGUAGE_STORAGE_KEY) !== null;
+ } catch {
+ return false;
+ }
+}
+
export function writeStoredLanguage(language: AppLanguage): void {
if (typeof window === "undefined") return;
try {
diff --git a/web/lib/session-title.ts b/web/lib/session-title.ts
new file mode 100644
index 000000000..8946dab51
--- /dev/null
+++ b/web/lib/session-title.ts
@@ -0,0 +1,8 @@
+const DEFAULT_SESSION_TITLE = "New conversation";
+
+export function isPlaceholderSessionTitle(
+ title: string | null | undefined,
+): boolean {
+ const value = (title ?? "").trim();
+ return value === "" || value === DEFAULT_SESSION_TITLE;
+}
diff --git a/web/locales/en/app.json b/web/locales/en/app.json
index 515c3de9a..c78e248c7 100644
--- a/web/locales/en/app.json
+++ b/web/locales/en/app.json
@@ -935,6 +935,9 @@
"Try": "Try",
"No conversations yet": "No conversations yet",
"New conversation": "New conversation",
+ "Add files & context": "Add files & context",
+ "Select persona": "Select persona",
+ "Record voice": "Record voice",
"Archived": "Archived",
"Archived conversation": "Archived conversation",
"Continue this conversation": "Continue this conversation",
diff --git a/web/locales/zh/app.json b/web/locales/zh/app.json
index 910832194..879f4d3d5 100644
--- a/web/locales/zh/app.json
+++ b/web/locales/zh/app.json
@@ -952,6 +952,9 @@
"Try": "试试",
"No conversations yet": "暂无对话",
"New conversation": "新对话",
+ "Add files & context": "添加文件和上下文",
+ "Select persona": "选择 Persona",
+ "Record voice": "录制语音",
"Archived": "已归档",
"Archived conversation": "已归档对话",
"Continue this conversation": "继续这个对话",
diff --git a/web/tests/app-shell-language-bootstrap.test.ts b/web/tests/app-shell-language-bootstrap.test.ts
new file mode 100644
index 000000000..f28bf729b
--- /dev/null
+++ b/web/tests/app-shell-language-bootstrap.test.ts
@@ -0,0 +1,65 @@
+import test from "node:test";
+import assert from "node:assert/strict";
+
+import {
+ LANGUAGE_STORAGE_KEY,
+ hasStoredLanguage,
+ readStoredLanguage,
+} from "../context/app-shell-storage";
+
+/** Minimal localStorage stand-in — the helpers only need get/set. */
+function withLocalStorage(entries: Record<string, string>, run: () => void) {
+ const store = new Map(Object.entries(entries));
+ const original = (globalThis as { window?: unknown }).window;
+ (globalThis as { window?: unknown }).window = {
+ localStorage: {
+ getItem: (key: string) => store.get(key) ?? null,
+ setItem: (key: string, value: string) => void store.set(key, value),
+ },
+ dispatchEvent: () => true,
+ };
+ try {
+ run();
+ } finally {
+ (globalThis as { window?: unknown }).window = original;
+ }
+}
+
+test("an absent choice is distinguishable from an explicit English one", () => {
+ // readStoredLanguage normalizes both to "en", so the bootstrap cannot use it
+ // to decide whether the server-side preference may be adopted.
+ withLocalStorage({}, () => {
+ assert.equal(hasStoredLanguage(), false);
+ assert.equal(readStoredLanguage(), "en");
+ });
+
+ withLocalStorage({ [LANGUAGE_STORAGE_KEY]: "en" }, () => {
+ assert.equal(hasStoredLanguage(), true);
+ assert.equal(readStoredLanguage(), "en");
+ });
+});
+
+test("a stored choice is reported for either language", () => {
+ withLocalStorage({ [LANGUAGE_STORAGE_KEY]: "zh" }, () => {
+ assert.equal(hasStoredLanguage(), true);
+ assert.equal(readStoredLanguage(), "zh");
+ });
+});
+
+test("an unusable value still counts as a choice and normalizes to English", () => {
+ withLocalStorage({ [LANGUAGE_STORAGE_KEY]: "fr" }, () => {
+ assert.equal(hasStoredLanguage(), true);
+ assert.equal(readStoredLanguage(), "en");
+ });
+});
+
+test("server-side rendering reports no stored choice instead of throwing", () => {
+ const original = (globalThis as { window?: unknown }).window;
+ (globalThis as { window?: unknown }).window = undefined;
+ try {
+ assert.equal(hasStoredLanguage(), false);
+ assert.equal(readStoredLanguage(), "en");
+ } finally {
+ (globalThis as { window?: unknown }).window = original;
+ }
+});
diff --git a/web/tests/session-title.test.ts b/web/tests/session-title.test.ts
new file mode 100644
index 000000000..fb9f8f4db
--- /dev/null
+++ b/web/tests/session-title.test.ts
@@ -0,0 +1,14 @@
+import test from "node:test";
+import assert from "node:assert/strict";
+
+import { isPlaceholderSessionTitle } from "../lib/session-title";
+
+test("empty and backend-default session titles are placeholders", () => {
+ assert.equal(isPlaceholderSessionTitle(""), true);
+ assert.equal(isPlaceholderSessionTitle(" New conversation "), true);
+});
+
+test("user and generated session titles remain business data", () => {
+ assert.equal(isPlaceholderSessionTitle("New Conversation"), false);
+ assert.equal(isPlaceholderSessionTitle("傅里叶变换"), false);
+});