From 13c3f8205ccd945a06881f3c9f80eeb2cd0c4bf3 Mon Sep 17 00:00:00 2001 From: t8y2 <1156263951@qq.com> Date: Tue, 29 Sep 2026 18:30:09 +0000 Subject: [PATCH] fix(settings): persist appearance preferences Closes #10524 --- apps/desktop/src/composables/useTheme.ts | 5 + apps/desktop/src/i18n/index.ts | 19 +- .../lib/app/__tests__/appAppearance.spec.ts | 72 +++++++ apps/desktop/src/lib/app/appAppearance.ts | 175 ++++++++++++++++++ apps/desktop/src/main.ts | 5 + crates/dbx-core/src/persistence/storage.rs | 121 +++++++++++- src-tauri/src/commands/app_settings.rs | 35 +++- src-tauri/src/lib.rs | 2 + src-tauri/src/migration_gate.rs | 2 + 9 files changed, 416 insertions(+), 20 deletions(-) create mode 100644 apps/desktop/src/lib/app/__tests__/appAppearance.spec.ts create mode 100644 apps/desktop/src/lib/app/appAppearance.ts diff --git a/apps/desktop/src/composables/useTheme.ts b/apps/desktop/src/composables/useTheme.ts index c5acba7f17..c6cd237370 100644 --- a/apps/desktop/src/composables/useTheme.ts +++ b/apps/desktop/src/composables/useTheme.ts @@ -27,6 +27,7 @@ import { } from "@/lib/app/appTheme"; import { safeLocalStorageGet, safeLocalStorageSet } from "@/lib/backend/safeStorage"; import { isTauriRuntime } from "@/lib/backend/tauriRuntime"; +import { persistAppAppearancePatch } from "@/lib/app/appAppearance"; function isLinuxTauriRuntime() { return isTauriRuntime() && typeof navigator !== "undefined" && /linux/i.test(navigator.userAgent); @@ -169,6 +170,7 @@ function applyTheme() { function setThemeMode(mode: AppThemeMode) { themeMode.value = mode; safeLocalStorageSet(APP_THEME_STORAGE_KEY, mode); + persistAppAppearancePatch({ themeMode: mode }); applyTheme(); } @@ -176,6 +178,7 @@ function setThemePalette(palette: AppThemePalette) { savedThemePaletteValue.value = palette; previewedThemePalette.value = null; safeLocalStorageSet(APP_THEME_PALETTE_STORAGE_KEY, palette); + persistAppAppearancePatch({ themePalette: palette }); applyTheme(); } @@ -225,6 +228,7 @@ function setCustomUiColors(colors: AppCustomUiColors) { customUiColors.value = next; safeLocalStorageSet(APP_CUSTOM_UI_STORAGE_KEY, JSON.stringify(next)); } + persistAppAppearancePatch({ [isDark.value ? "customUiColorsDark" : "customUiColors"]: next }); applyCustomUiColors(); } @@ -235,6 +239,7 @@ function resetCustomUiColors() { function setCornerStyle(style: AppCornerStyle) { cornerStyle.value = normalizeAppCornerStyle(style); safeLocalStorageSet(APP_CORNER_STYLE_STORAGE_KEY, cornerStyle.value); + persistAppAppearancePatch({ cornerStyle: cornerStyle.value }); applyTheme(); } diff --git a/apps/desktop/src/i18n/index.ts b/apps/desktop/src/i18n/index.ts index f59ebea8de..32a65bf21d 100644 --- a/apps/desktop/src/i18n/index.ts +++ b/apps/desktop/src/i18n/index.ts @@ -1,7 +1,7 @@ import { createI18n } from "vue-i18n"; import en from "./locales/en"; -import { safeLocalStorageGet, safeLocalStorageSet } from "@/lib/backend/safeStorage"; -import { isTauriRuntime } from "@/lib/backend/tauriRuntime"; +import { safeLocalStorageGet } from "@/lib/backend/safeStorage"; +import { persistAppLocale } from "@/lib/app/appAppearance"; export type Locale = "az" | "en" | "es" | "it" | "ja" | "ko" | "pt-BR" | "ru" | "tr" | "zh-CN" | "zh-TW"; type LocaleMessages = Record; @@ -98,19 +98,9 @@ export async function loadLocaleMessages(locale: Locale) { loadedLocales.add(locale); } -async function syncLocaleToBackend(locale: Locale) { - if (!isTauriRuntime()) return; - try { - const { invoke } = await import("@tauri-apps/api/core"); - await invoke("set_app_locale", { locale }); - } catch (error) { - console.warn("[DBX][i18n] failed to sync locale to backend", error); - } -} - export async function loadSavedLocale() { await loadLocaleMessages(initialLocale); - void syncLocaleToBackend(initialLocale); + persistAppLocale(initialLocale); } async function applyTransientLocale(locale: Locale) { @@ -138,8 +128,7 @@ export async function setLocale(locale: Locale) { ++localeRequestId; // An explicit selection is durable immediately; only the visible locale // waits for its lazy message bundle. Preview paths never reach this branch. - safeLocalStorageSet("dbx-locale", locale); - void syncLocaleToBackend(locale); + persistAppLocale(locale); await loadLocaleMessages(locale); // A later explicit selection wins; hover/restore requests must not undo it. if (persistedLocale !== locale) return; diff --git a/apps/desktop/src/lib/app/__tests__/appAppearance.spec.ts b/apps/desktop/src/lib/app/__tests__/appAppearance.spec.ts new file mode 100644 index 0000000000..e81f19f11c --- /dev/null +++ b/apps/desktop/src/lib/app/__tests__/appAppearance.spec.ts @@ -0,0 +1,72 @@ +// @vitest-environment happy-dom + +import { beforeEach, describe, expect, it, vi } from "vitest"; + +const invoke = vi.hoisted(() => vi.fn()); + +vi.mock("@/lib/backend/tauriRuntime", () => ({ isTauriRuntime: () => true })); +vi.mock("@tauri-apps/api/core", () => ({ invoke })); + +async function loadAppearance() { + vi.resetModules(); + return import("@/lib/app/appAppearance"); +} + +beforeEach(() => { + invoke.mockReset(); + window.localStorage.clear(); +}); + +describe("Tauri appearance persistence", () => { + it("gives durable backend values precedence over stale WebView storage", async () => { + window.localStorage.setItem("dbx-locale", "en"); + window.localStorage.setItem("dbx-theme", "light"); + window.localStorage.setItem("dbx-theme-palette", "pearl"); + invoke.mockResolvedValueOnce({ locale: "zh-CN", themeMode: "dark", themePalette: "cobalt", cornerStyle: "small" }); + + const { hydrateAppAppearance } = await loadAppearance(); + await hydrateAppAppearance(); + + expect(window.localStorage.getItem("dbx-locale")).toBe("zh-CN"); + expect(window.localStorage.getItem("dbx-theme")).toBe("dark"); + expect(window.localStorage.getItem("dbx-theme-palette")).toBe("cobalt"); + expect(window.localStorage.getItem("dbx-corner-style")).toBe("small"); + expect(invoke).toHaveBeenCalledWith("load_app_appearance_settings", undefined); + expect(invoke).toHaveBeenCalledTimes(1); + }); + + it("migrates legacy WebView values when the durable record is empty", async () => { + window.localStorage.setItem("dbx-locale", "ja"); + window.localStorage.setItem("dbx-theme", "system"); + window.localStorage.setItem("dbx-theme-palette", "sage"); + invoke.mockResolvedValueOnce({}); + invoke.mockResolvedValueOnce(undefined); + + const { hydrateAppAppearance } = await loadAppearance(); + await hydrateAppAppearance(); + + expect(invoke).toHaveBeenNthCalledWith(1, "load_app_appearance_settings", undefined); + expect(invoke).toHaveBeenNthCalledWith(2, "update_app_appearance_settings", { + patch: { locale: "ja", themeMode: "system", themePalette: "sage" }, + }); + expect(window.localStorage.getItem("dbx-theme-palette")).toBe("sage"); + }); + + it("persists explicit choices while leaving the caller synchronous", async () => { + invoke.mockResolvedValue(undefined); + const { persistAppAppearancePatch, persistAppLocale } = await loadAppearance(); + + persistAppAppearancePatch({ themeMode: "dark", themePalette: "graphite" }); + persistAppLocale("ko"); + await new Promise((resolve) => setTimeout(resolve, 0)); + await new Promise((resolve) => setTimeout(resolve, 0)); + + expect(window.localStorage.getItem("dbx-theme")).toBe("dark"); + expect(window.localStorage.getItem("dbx-theme-palette")).toBe("graphite"); + expect(window.localStorage.getItem("dbx-locale")).toBe("ko"); + expect(invoke).toHaveBeenNthCalledWith(1, "update_app_appearance_settings", { + patch: { themeMode: "dark", themePalette: "graphite" }, + }); + expect(invoke).toHaveBeenNthCalledWith(2, "set_app_locale", { locale: "ko" }); + }); +}); diff --git a/apps/desktop/src/lib/app/appAppearance.ts b/apps/desktop/src/lib/app/appAppearance.ts new file mode 100644 index 0000000000..34f006b116 --- /dev/null +++ b/apps/desktop/src/lib/app/appAppearance.ts @@ -0,0 +1,175 @@ +import { safeLocalStorageGet, safeLocalStorageSet } from "@/lib/backend/safeStorage"; +import { isTauriRuntime } from "@/lib/backend/tauriRuntime"; +import { APP_CORNER_STYLE_STORAGE_KEY, APP_CUSTOM_UI_DARK_STORAGE_KEY, APP_CUSTOM_UI_STORAGE_KEY, APP_THEME_PALETTE_STORAGE_KEY, APP_THEME_STORAGE_KEY, type AppCustomUiColors, type AppCornerStyle, type AppThemeMode, type AppThemePalette } from "@/lib/app/appTheme"; + +export interface AppAppearanceSettings { + locale?: string | null; + themeMode?: AppThemeMode | string | null; + themePalette?: AppThemePalette | string | null; + customUiColors?: AppCustomUiColors | null; + customUiColorsDark?: AppCustomUiColors | null; + cornerStyle?: AppCornerStyle | string | null; +} + +export type AppAppearanceSettingsPatch = Partial; + +type TauriInvoke = (command: string, args?: Record) => Promise; + +let hydrationPromise: Promise | null = null; +let persistenceQueue: Promise = Promise.resolve(); + +function warn(action: string, error: unknown) { + console.warn(`[DBX][appearance:${action}]`, error); +} + +async function invokeTauri(command: string, args?: Record): Promise { + const { invoke } = (await import("@tauri-apps/api/core")) as { invoke: TauriInvoke }; + return invoke(command, args); +} + +function nonEmptyString(value: unknown): value is string { + return typeof value === "string" && value.trim().length > 0; +} + +function validThemeMode(value: unknown): value is AppThemeMode { + return value === "light" || value === "dark" || value === "system" || value === "soft-light" || value === "soft-dark" || value === "soft-system"; +} + +function validThemePalette(value: unknown): value is AppThemePalette { + return ( + value === "pearl" || + value === "mist" || + value === "graphite" || + value === "cobalt" || + value === "sage" || + value === "amber" || + value === "blush" || + value === "vscode" || + value === "idea" || + value === "xcode" || + value === "jetbrains" || + value === "cursor" || + value === "claude" || + value === "custom" + ); +} + +function validCornerStyle(value: unknown): value is AppCornerStyle { + return value === "none" || value === "small" || value === "large"; +} + +function parseColorObject(raw: string | null): AppCustomUiColors | undefined { + if (!raw) return undefined; + try { + const parsed = JSON.parse(raw); + return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? (parsed as AppCustomUiColors) : undefined; + } catch { + return undefined; + } +} + +function localAppearance(): AppAppearanceSettings { + return { + locale: safeLocalStorageGet("dbx-locale"), + themeMode: safeLocalStorageGet(APP_THEME_STORAGE_KEY), + themePalette: safeLocalStorageGet(APP_THEME_PALETTE_STORAGE_KEY), + customUiColors: parseColorObject(safeLocalStorageGet(APP_CUSTOM_UI_STORAGE_KEY)), + customUiColorsDark: parseColorObject(safeLocalStorageGet(APP_CUSTOM_UI_DARK_STORAGE_KEY)), + cornerStyle: safeLocalStorageGet(APP_CORNER_STYLE_STORAGE_KEY), + }; +} + +function backendField(settings: Record, camelCase: string, snakeCase: string): T | undefined { + const value = settings[camelCase] ?? settings[snakeCase]; + return value as T | undefined; +} + +function setLocalAppearance(patch: AppAppearanceSettingsPatch) { + if (nonEmptyString(patch.locale)) safeLocalStorageSet("dbx-locale", patch.locale); + if (validThemeMode(patch.themeMode)) safeLocalStorageSet(APP_THEME_STORAGE_KEY, patch.themeMode); + if (validThemePalette(patch.themePalette)) safeLocalStorageSet(APP_THEME_PALETTE_STORAGE_KEY, patch.themePalette); + if (patch.customUiColors && typeof patch.customUiColors === "object") { + safeLocalStorageSet(APP_CUSTOM_UI_STORAGE_KEY, JSON.stringify(patch.customUiColors)); + } + if (patch.customUiColorsDark && typeof patch.customUiColorsDark === "object") { + safeLocalStorageSet(APP_CUSTOM_UI_DARK_STORAGE_KEY, JSON.stringify(patch.customUiColorsDark)); + } + if (validCornerStyle(patch.cornerStyle)) safeLocalStorageSet(APP_CORNER_STYLE_STORAGE_KEY, patch.cornerStyle); +} + +function enqueuePersistence(operation: () => Promise, action: string) { + persistenceQueue = persistenceQueue + .catch(() => {}) + .then(operation) + .catch((error) => warn(action, error)); +} + +/** + * Hydrate the renderer's legacy storage keys from the durable Tauri app + * settings record before i18n and the theme composable are imported. Backend + * values win; existing localStorage values are migrated when a field is new. + */ +export async function hydrateAppAppearance(): Promise { + if (!isTauriRuntime()) return; + if (!hydrationPromise) { + hydrationPromise = (async () => { + let raw: unknown; + try { + raw = await invokeTauri("load_app_appearance_settings"); + } catch (error) { + warn("load", error); + return; + } + const backend = raw && typeof raw === "object" && !Array.isArray(raw) ? (raw as Record) : {}; + const local = localAppearance(); + const migrate: AppAppearanceSettingsPatch = {}; + + const locale = backendField(backend, "locale", "locale"); + if (nonEmptyString(locale)) setLocalAppearance({ locale }); + else if (nonEmptyString(local.locale)) migrate.locale = local.locale; + + const themeMode = backendField(backend, "themeMode", "theme_mode"); + if (validThemeMode(themeMode)) setLocalAppearance({ themeMode }); + else if (validThemeMode(local.themeMode)) migrate.themeMode = local.themeMode; + + const themePalette = backendField(backend, "themePalette", "theme_palette"); + if (validThemePalette(themePalette)) setLocalAppearance({ themePalette }); + else if (validThemePalette(local.themePalette)) migrate.themePalette = local.themePalette; + + const customUiColors = backendField(backend, "customUiColors", "custom_ui_colors"); + if (customUiColors && typeof customUiColors === "object" && !Array.isArray(customUiColors)) setLocalAppearance({ customUiColors }); + else if (local.customUiColors) migrate.customUiColors = local.customUiColors; + + const customUiColorsDark = backendField(backend, "customUiColorsDark", "custom_ui_colors_dark"); + if (customUiColorsDark && typeof customUiColorsDark === "object" && !Array.isArray(customUiColorsDark)) setLocalAppearance({ customUiColorsDark }); + else if (local.customUiColorsDark) migrate.customUiColorsDark = local.customUiColorsDark; + + const cornerStyle = backendField(backend, "cornerStyle", "corner_style"); + if (validCornerStyle(cornerStyle)) setLocalAppearance({ cornerStyle }); + else if (validCornerStyle(local.cornerStyle)) migrate.cornerStyle = local.cornerStyle; + + if (Object.keys(migrate).length > 0) { + try { + await invokeTauri("update_app_appearance_settings", { patch: migrate }); + } catch (error) { + warn("migrate", error); + } + } + })().finally(() => { + hydrationPromise = null; + }); + } + await hydrationPromise; +} + +export function persistAppAppearancePatch(patch: AppAppearanceSettingsPatch) { + setLocalAppearance(patch); + if (!isTauriRuntime()) return; + enqueuePersistence(() => invokeTauri("update_app_appearance_settings", { patch }), "save"); +} + +export function persistAppLocale(locale: string) { + setLocalAppearance({ locale }); + if (!isTauriRuntime()) return; + enqueuePersistence(() => invokeTauri("set_app_locale", { locale }), "locale"); +} diff --git a/apps/desktop/src/main.ts b/apps/desktop/src/main.ts index 7e41931288..9e23e15e20 100644 --- a/apps/desktop/src/main.ts +++ b/apps/desktop/src/main.ts @@ -5,6 +5,7 @@ import { installDebugLogCapture } from "@/lib/backend/debugLog"; import { retryStartupAfterPreloadFailure } from "@/lib/startup/startupPreloadRecovery"; import { markStartupPhase } from "@/lib/startup/startupTiming"; import { applyLegacyWebViewClass, isBlockingCompatFailure } from "@/lib/ui/legacyWebView"; +import { hydrateAppAppearance } from "@/lib/app/appAppearance"; function startupErrorMessage(error: unknown): string { if (error instanceof Error) { @@ -87,6 +88,10 @@ async function bootstrap() { window.dispatchEvent(new Event("dbx:startup-ready")); return; } + // Tauri WebViews may not retain localStorage across macOS restarts. Load the + // durable appearance record before importing i18n and the theme composable; + // those modules synchronously read the compatibility keys during evaluation. + await hydrateAppAppearance(); const [{ default: i18n, loadSavedLocale }, { default: App }] = await Promise.all([import("./i18n"), import("./StartupGate.vue")]); console.log("[STARTUP] frontend modules loaded"); const localeReady = loadSavedLocale(); diff --git a/crates/dbx-core/src/persistence/storage.rs b/crates/dbx-core/src/persistence/storage.rs index 2984e26200..436045f9f1 100644 --- a/crates/dbx-core/src/persistence/storage.rs +++ b/crates/dbx-core/src/persistence/storage.rs @@ -53,6 +53,7 @@ const APP_STATE_EDITOR_SETTINGS_KEY: &str = "editor_settings"; const APP_STATE_OPEN_TABS_KEY: &str = "open_tabs"; const APP_STATE_SAVED_SQL_EDITOR_POSITIONS_KEY: &str = "saved_sql_editor_positions"; const APP_STATE_TRANSFER_TASK_LIBRARY_KEY: &str = "transfer_task_library"; +const APP_APPEARANCE_SETTINGS_KEY: &str = "app_appearance"; const MCP_GLOBAL_POLICY_KEY: &str = "mcp_global_policy"; const MCP_HTTP_SERVER_SETTINGS_KEY: &str = "mcp_http_server_settings"; const WEB_MCP_SETTINGS_KEY: &str = "web_mcp_settings"; @@ -431,6 +432,47 @@ pub struct DesktopSettings { pub sidebar_table_page_size: usize, } +/// Appearance preferences are kept separately from device-specific desktop +/// settings because they are renderer-owned and must be available before the +/// frontend modules initialize. The optional fields also keep older databases +/// compatible: an absent value means the frontend may use its legacy storage +/// fallback and migrate it on first startup. +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct AppAppearanceSettings { + #[serde(default, skip_serializing_if = "Option::is_none")] + pub locale: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub theme_mode: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub theme_palette: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub custom_ui_colors: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub custom_ui_colors_dark: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub corner_style: Option, +} + +/// A partial appearance update. Patches are applied in one SQLite transaction +/// so rapid controls cannot overwrite a value changed by another control. +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct AppAppearanceSettingsPatch { + #[serde(default, skip_serializing_if = "Option::is_none")] + pub locale: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub theme_mode: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub theme_palette: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub custom_ui_colors: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub custom_ui_colors_dark: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub corner_style: Option, +} + #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)] #[serde(rename_all = "camelCase")] pub struct McpGlobalPolicy { @@ -4228,6 +4270,7 @@ impl Storage { .optional() .map_err(|e| e.to_string())?; let dedicated_keys = [ + APP_APPEARANCE_SETTINGS_KEY, MCP_GLOBAL_POLICY_KEY, WEB_MCP_SETTINGS_KEY, MAX_RETRIES_KEY, @@ -4507,6 +4550,37 @@ impl Storage { .await } + pub async fn load_app_appearance_settings(&self) -> Result { + let settings = self.load_app_settings_json().await?; + match settings.get(APP_APPEARANCE_SETTINGS_KEY) { + Some(value) if !value.is_null() => serde_json::from_value(value.clone()) + .map_err(|error| format!("invalid app appearance settings: {error}")), + _ => Ok(AppAppearanceSettings::default()), + } + } + + pub async fn update_app_appearance_settings(&self, patch: &AppAppearanceSettingsPatch) -> Result<(), String> { + let patch = serde_json::to_value(patch).map_err(|error| error.to_string())?; + let patch = patch.as_object().cloned().ok_or_else(|| "app appearance patch must be an object".to_string())?; + self.with_conn(move |conn| { + let tx = + conn.transaction_with_behavior(TransactionBehavior::Immediate).map_err(|error| error.to_string())?; + let mut settings = app_settings_map_from_conn(&tx)?; + let mut appearance = match settings.remove(APP_APPEARANCE_SETTINGS_KEY) { + Some(value) if !value.is_null() => { + serde_json::from_value::>(value) + .map_err(|error| format!("invalid app appearance settings: {error}"))? + } + _ => serde_json::Map::new(), + }; + appearance.extend(patch); + settings.insert(APP_APPEARANCE_SETTINGS_KEY.to_string(), serde_json::Value::Object(appearance)); + write_app_settings_map(&tx, &settings)?; + tx.commit().map_err(|error| error.to_string()) + }) + .await + } + pub async fn save_desktop_settings(&self, desktop_settings: &DesktopSettings) -> Result<(), String> { let mut settings = self.load_app_settings_json().await?; settings.remove("run_in_background"); @@ -8794,8 +8868,9 @@ fn map_from_sql_err(err: serde_json::Error) -> rusqlite::Error { #[cfg(test)] mod tests { use super::{ - maybe_import_user_data_db, DataDbImportResult, DesktopIconTheme, DesktopSettings, McpGlobalPolicy, - McpGlobalPolicyState, Storage, SyncImportPlan, KEEP_TERMINAL_AI_RUNS_PER_CONVERSATION, MCP_GLOBAL_POLICY_KEY, + maybe_import_user_data_db, AppAppearanceSettingsPatch, DataDbImportResult, DesktopIconTheme, DesktopSettings, + McpGlobalPolicy, McpGlobalPolicyState, Storage, SyncImportPlan, KEEP_TERMINAL_AI_RUNS_PER_CONVERSATION, + MCP_GLOBAL_POLICY_KEY, }; use crate::ai::{ AiActiveModelSelection, AiAssistantMode, AiChatMessage, AiChatSelectionState, AiConversation, @@ -11451,6 +11526,48 @@ mod tests { assert_eq!(storage.load_desktop_settings().await.unwrap(), DesktopSettings::default()); } + #[tokio::test] + async fn app_appearance_settings_patch_roundtrips_and_survives_desktop_saves() { + let path = temp_db_path("app-appearance-settings"); + let storage = crate::persistence::test_storage::open(&path).await.unwrap(); + + storage + .update_app_appearance_settings(&AppAppearanceSettingsPatch { + locale: Some("zh-CN".to_string()), + theme_mode: Some("dark".to_string()), + theme_palette: Some("cobalt".to_string()), + custom_ui_colors: Some(serde_json::json!({ "background": "#123456" })), + ..Default::default() + }) + .await + .unwrap(); + + assert_eq!( + storage.load_app_appearance_settings().await.unwrap(), + super::AppAppearanceSettings { + locale: Some("zh-CN".to_string()), + theme_mode: Some("dark".to_string()), + theme_palette: Some("cobalt".to_string()), + custom_ui_colors: Some(serde_json::json!({ "background": "#123456" })), + ..Default::default() + } + ); + + storage.save_desktop_settings(&DesktopSettings::default()).await.unwrap(); + assert_eq!(storage.load_app_appearance_settings().await.unwrap().theme_palette.as_deref(), Some("cobalt")); + + storage + .update_app_appearance_settings(&AppAppearanceSettingsPatch { + corner_style: Some("small".to_string()), + ..Default::default() + }) + .await + .unwrap(); + let updated = storage.load_app_appearance_settings().await.unwrap(); + assert_eq!(updated.locale.as_deref(), Some("zh-CN")); + assert_eq!(updated.corner_style.as_deref(), Some("small")); + } + #[tokio::test] async fn mcp_global_policy_defaults_unconfigured_and_roundtrips_atomically() { let path = temp_db_path("mcp-global-policy"); diff --git a/src-tauri/src/commands/app_settings.rs b/src-tauri/src/commands/app_settings.rs index baea300174..8083e969c4 100644 --- a/src-tauri/src/commands/app_settings.rs +++ b/src-tauri/src/commands/app_settings.rs @@ -4,7 +4,9 @@ use std::{ sync::{Arc, Mutex, OnceLock}, }; -use dbx_core::storage::{DesktopSettings, McpGlobalPolicy, McpGlobalPolicyState}; +use dbx_core::storage::{ + AppAppearanceSettings, AppAppearanceSettingsPatch, DesktopSettings, McpGlobalPolicy, McpGlobalPolicyState, +}; use tauri::{AppHandle, Manager, State, Window}; use super::connection::AppState; @@ -84,9 +86,36 @@ pub async fn load_max_agent_turns(state: State<'_, Arc>) -> Result, locale: String) -> Result<(), String> { +pub async fn load_app_appearance_settings(state: State<'_, Arc>) -> Result { + state.storage.load_app_appearance_settings().await +} + +#[tauri::command] +pub async fn update_app_appearance_settings( + state: State<'_, Arc>, + patch: AppAppearanceSettingsPatch, +) -> Result<(), String> { + state.storage.update_app_appearance_settings(&patch).await +} + +#[tauri::command] +pub async fn set_app_locale( + app: AppHandle, + state: State<'_, Arc>, + locale_state: State<'_, AppLocaleState>, + locale: String, +) -> Result<(), String> { locale_state.set(locale); - refresh_native_menus(&app).map_err(|err| format!("failed to refresh native menus: {err}")) + let persistence = state + .storage + .update_app_appearance_settings(&AppAppearanceSettingsPatch { + locale: Some(locale_state.get()), + ..Default::default() + }) + .await; + let refresh = refresh_native_menus(&app).map_err(|err| format!("failed to refresh native menus: {err}")); + persistence?; + refresh } #[tauri::command] diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index c445dfabcd..c74470bd6a 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -1873,6 +1873,8 @@ pub fn run() { commands::app_settings::save_mcp_history_retention_limit, commands::app_settings::load_max_retries, commands::app_settings::save_max_retries, + commands::app_settings::load_app_appearance_settings, + commands::app_settings::update_app_appearance_settings, commands::app_settings::set_app_locale, commands::app_settings::complete_app_close, commands::app_settings::mark_frontend_ready, diff --git a/src-tauri/src/migration_gate.rs b/src-tauri/src/migration_gate.rs index 051be0a537..2313799ba6 100644 --- a/src-tauri/src/migration_gate.rs +++ b/src-tauri/src/migration_gate.rs @@ -44,6 +44,8 @@ pub fn allowed_command(command: &str) -> bool { | "complete_app_close" | "reveal_path_in_file_manager" | "get_platform" + | "load_app_appearance_settings" + | "update_app_appearance_settings" | "set_app_locale" ) }