Skip to content

DeepSeek Harness Tauri 桌面版 | Only 8mb installer, zero environment setup, preset plugins, Windows / macOS / Linux.

fix(theme): 主题偏好改读当前档案,并以窗口底色消除首帧闪变

hairyfb1eec3cdd636
diff --git a/src-tauri/src/config/theme.rs b/src-tauri/src/config/theme.rs
index d19cbd33..38675bd5 100644
--- a/src-tauri/src/config/theme.rs
+++ b/src-tauri/src/config/theme.rs
@@ -1,4 +1,5 @@
use std::fs;
+use std::path::Path;
use std::sync::{Mutex, OnceLock};
#[cfg(target_os = "macos")]
use tauri::Manager;
@@ -6,7 +7,8 @@ use tauri::{AppHandle, Emitter};
use super::runtime::get_dsh_data_path;
-/// dsh 主题偏好(对应 `$DSH_HOME/settings.yaml` 的 `ui-theme.preference`)
+/// dsh 主题偏好(0.1.7 起是当前档案 `cordis.patch.yml` 里 `ui-theme` 条目的
+/// `config.preference`;更早的核心是 `$DSH_HOME/settings.yaml`)
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum DshTheme {
@@ -17,23 +19,90 @@ pub enum DshTheme {
/// 未设置过主题偏好时的回退值:跟随系统外观。
///
-/// 首次进入(`settings.yaml` 不存在)或偏好值缺失/非法时都走这里;回退成固定
+/// 首次进入(两代设置文件都不存在)或偏好值缺失/非法时都走这里;回退成固定
/// 深色会让「跟随系统」的默认体验失效(浅色系统上启动即深色)。
const DEFAULT_THEME: DshTheme = DshTheme::System;
static LAST_EMITTED: OnceLock<Mutex<Option<DshTheme>>> = OnceLock::new();
-/// 读取 dsh 主题偏好;settings.yaml 缺失或解析失败时回退为跟随系统
+/// 读取 dsh 主题偏好;两代存放位置都缺失或解析失败时回退为跟随系统。
pub fn get_dsh_theme(app_handle: &AppHandle) -> DshTheme {
- let settings_path = get_dsh_data_path(app_handle).join("settings.yaml");
- let content = match fs::read_to_string(&settings_path) {
- Ok(content) => content,
- Err(err) => {
- log::debug!("failed to read dsh settings.yaml: {}", err);
- return DEFAULT_THEME;
+ let home = get_dsh_data_path(app_handle);
+ let profile = crate::service::profile::profile_dir_of(
+ app_handle,
+ &crate::service::profile::active_profile(app_handle),
+ );
+ read_dsh_theme(&home, &profile)
+}
+
+/// 依次尝试当前档案的补丁层、旧 `settings.yaml`、导入后的 `settings.yaml.imported`。
+///
+/// 0.1.7 把设置收进当前 Profile 的插件配置,`settings.yaml` 只在首次导入时读一次、
+/// 随后改名为 `settings.yaml.imported`。档案层是唯一的活配置;后两者只是旧核心与
+/// 「导入完、档案里还没写过主题」的兜底。
+fn read_dsh_theme(home: &Path, profile_dir: &Path) -> DshTheme {
+ if let Ok(content) = fs::read_to_string(profile_dir.join("cordis.patch.yml")) {
+ if let Some(theme) = parse_profile_theme(&content) {
+ return theme;
}
- };
- parse_theme_preference(&content).unwrap_or(DEFAULT_THEME)
+ }
+ for name in [LEGACY_SETTINGS_FILE, IMPORTED_SETTINGS_FILE] {
+ if let Ok(content) = fs::read_to_string(home.join(name)) {
+ if let Some(theme) = parse_theme_preference(&content) {
+ return theme;
+ }
+ }
+ }
+ log::debug!("no dsh theme preference found; following the system appearance");
+ DEFAULT_THEME
+}
+
+/// 0.1.5 / 0.1.6 的设置文件。
+const LEGACY_SETTINGS_FILE: &str = "settings.yaml";
+
+/// 0.1.7 首次导入后留下的快照,此后不再更新。
+const IMPORTED_SETTINGS_FILE: &str = "settings.yaml.imported";
+
+/// 官方 web-app bundle 给主题插件的补丁条目 id(`packages/bundle/web-app/cordis.patch.yml`);
+/// 设置页把偏好写进同 id 的条目,因此这是跨版本稳定的锚点。
+const UI_THEME_ENTRY_ID: &str = "ui-theme";
+
+/// 从档案补丁层 `cordis.patch.yml` 提取 `ui-theme` 条目的 `config.preference`。
+///
+/// 必须按条目分段读取:`locale` 条目也有 `preference` 键(界面语言),越界匹配会把
+/// 语言值当成主题值。
+fn parse_profile_theme(content: &str) -> Option<DshTheme> {
+ let mut in_theme_entry = false;
+ for line in content.lines() {
+ let trimmed = line.trim();
+ if trimmed.is_empty() || trimmed.starts_with('#') {
+ continue;
+ }
+ // 顶层 `- ` 开启新条目;`config:` 下的嵌套列表有缩进,不会误判为边界。
+ if line.starts_with('-') {
+ in_theme_entry = false;
+ if let Some(value) = trimmed.strip_prefix("- id:") {
+ in_theme_entry = value.trim().trim_matches(['"', '\'']) == UI_THEME_ENTRY_ID;
+ }
+ continue;
+ }
+ if !in_theme_entry {
+ continue;
+ }
+ if let Some(value) = trimmed.strip_prefix("preference:") {
+ return parse_theme_name(value.trim().trim_matches(['"', '\'']));
+ }
+ }
+ None
+}
+
+fn parse_theme_name(value: &str) -> Option<DshTheme> {
+ match value {
+ "light" => Some(DshTheme::Light),
+ "dark" => Some(DshTheme::Dark),
+ "system" => Some(DshTheme::System),
+ _ => None,
+ }
}
/// 从 settings.yaml 文本中提取 `ui-theme.preference`(light/dark/system)
@@ -54,12 +123,7 @@ fn parse_theme_preference(content: &str) -> Option<DshTheme> {
}
if !trimmed.is_empty() && !trimmed.starts_with('#') {
if let Some(value) = trimmed.strip_prefix("preference:") {
- return match value.trim() {
- "light" => Some(DshTheme::Light),
- "dark" => Some(DshTheme::Dark),
- "system" => Some(DshTheme::System),
- _ => None,
- };
+ return parse_theme_name(value.trim());
}
}
}
@@ -110,6 +174,34 @@ pub fn check_and_emit_theme(app_handle: &AppHandle) {
apply_window_theme(app_handle, theme);
}
+/// 壳层画布色,与 `src/styles/main.css` 的 `--color-canvas` 同值。
+const CANVAS_DARK: tauri::webview::Color = tauri::webview::Color(0x15, 0x15, 0x17, 0xFF);
+const CANVAS_LIGHT: tauri::webview::Color = tauri::webview::Color(0xFF, 0xFF, 0xFF, 0xFF);
+
+/// 窗口底色:显式偏好直接取画布色,`system` 按当前系统外观折算。
+///
+/// 壳层 CSS 以深色为默认(`src/styles/main.css` 的 `:root`),而偏好要等前端
+/// `use-theme-adaptive` 的 IPC 回来才生效;窗口底色不对,这段间隙就会闪一次错色。
+/// 底色由原生 webview 直接承担,不需要往页面注入脚本;此后偏好变化仍由
+/// `check_and_emit_theme` 的 `dsh-theme-updated` 事件同步。
+///
+/// macOS 未实现该接口(`WebviewWindowBuilder::background_color` 的平台说明),
+/// 那里由 [`apply_window_theme`] 同步原生外观。
+pub fn window_background(
+ theme: DshTheme,
+ system: Option<tauri::Theme>,
+) -> Option<tauri::webview::Color> {
+ match theme {
+ DshTheme::Light => Some(CANVAS_LIGHT),
+ DshTheme::Dark => Some(CANVAS_DARK),
+ DshTheme::System => match system {
+ Some(tauri::Theme::Light) => Some(CANVAS_LIGHT),
+ Some(tauri::Theme::Dark) => Some(CANVAS_DARK),
+ _ => None,
+ },
+ }
+}
+
#[cfg(test)]
mod tests {
use super::*;
@@ -121,6 +213,79 @@ mod tests {
assert_eq!(DEFAULT_THEME, DshTheme::System);
}
+ /// 0.1.7 起主题偏好落在当前 Profile 的 `cordis.patch.yml`。必须按条目分段:
+ /// `locale` 条目同样有 `preference` 键(界面语言),越界匹配会取到 `zh`。
+ #[test]
+ fn parses_profile_patch_theme_entry() {
+ let content = "- id: ui-theme\n name: \"@deepseek-ai/dsh-client-ui-theme\"\n config:\n preference: light\n- id: locale\n name: \"@deepseek-ai/dsh-client-locale\"\n config:\n preference: zh\n";
+ assert_eq!(parse_profile_theme(content), Some(DshTheme::Light));
+ }
+
+ /// 只有 `locale` 条目时不得把界面语言当成主题。
+ #[test]
+ fn profile_patch_ignores_other_entries() {
+ assert_eq!(
+ parse_profile_theme("- id: locale\n config:\n preference: dark\n"),
+ None
+ );
+ }
+
+ /// `ui-theme` 条目缺失、取值非法或整段不存在都返回 `None`。
+ #[test]
+ fn profile_patch_rejects_missing_and_unknown() {
+ assert_eq!(parse_profile_theme("[]\n"), None);
+ assert_eq!(
+ parse_profile_theme("- id: ui-theme\n config:\n preference: blue\n"),
+ None
+ );
+ assert_eq!(
+ parse_profile_theme("- id: ui-theme\n config:\n density: compact\n"),
+ None
+ );
+ }
+
+ /// 档案层优先于旧 `settings.yaml`:后者在 0.1.7 首次导入后就被弃用。
+ #[test]
+ fn profile_patch_wins_over_legacy_settings() {
+ let home = std::env::temp_dir().join("dsh-theme-test-home");
+ let profile = std::env::temp_dir().join("dsh-theme-test-profile");
+ fs::create_dir_all(&home).unwrap();
+ fs::create_dir_all(&profile).unwrap();
+ fs::write(
+ home.join("settings.yaml"),
+ "ui-theme:\n preference: light\n",
+ )
+ .unwrap();
+ fs::write(
+ profile.join("cordis.patch.yml"),
+ "- id: ui-theme\n config:\n preference: dark\n",
+ )
+ .unwrap();
+ assert_eq!(read_dsh_theme(&home, &profile), DshTheme::Dark);
+ let _ = fs::remove_file(profile.join("cordis.patch.yml"));
+ assert_eq!(read_dsh_theme(&home, &profile), DshTheme::Light);
+ let _ = fs::remove_dir_all(&home);
+ let _ = fs::remove_dir_all(&profile);
+ }
+
+ /// 窗口底色跟随偏好;`system` 按系统外观折算,取不到外观时不设(保留 webview
+ /// 默认),避免凭空猜一个可能错的底色。
+ #[test]
+ fn window_background_follows_preference() {
+ let rgba = |c: Option<tauri::webview::Color>| c.map(|c| (c.0, c.1, c.2, c.3));
+ assert_eq!(rgba(window_background(DshTheme::Light, None)), Some((0xFF, 0xFF, 0xFF, 0xFF)));
+ assert_eq!(rgba(window_background(DshTheme::Dark, None)), Some((0x15, 0x15, 0x17, 0xFF)));
+ assert_eq!(
+ rgba(window_background(DshTheme::System, Some(tauri::Theme::Dark))),
+ Some((0x15, 0x15, 0x17, 0xFF))
+ );
+ assert_eq!(
+ rgba(window_background(DshTheme::System, Some(tauri::Theme::Light))),
+ Some((0xFF, 0xFF, 0xFF, 0xFF))
+ );
+ assert_eq!(window_background(DshTheme::System, None), None);
+ }
+
#[test]
fn parses_known_preference_values() {
let cases = [
diff --git a/src-tauri/src/desktop/builder.rs b/src-tauri/src/desktop/builder.rs
index caa19c1a..593b237d 100644
--- a/src-tauri/src/desktop/builder.rs
+++ b/src-tauri/src/desktop/builder.rs
@@ -583,6 +583,9 @@ pub fn build_main_window(app: &tauri::AppHandle<Wry>) -> tauri::Result<tauri::We
.initialization_script_for_all_frames(crate::desktop::plugin_boot::PLUGIN_BOOT_RELOAD_JS);
let webview_window = webview_builder.build()?;
+ // 首帧前把窗口底色设成主题画布色(见 `config::window_background`),否则
+ // 「窗口可见 → 前端取回偏好」之间会闪一次错色。
+ apply_window_background(app, &webview_window);
let zoom_factor = crate::config::get_store_dat_setting(app).zoom_factor;
if zoom_factor != crate::config::default_zoom_factor() {
if let Err(error) = crate::desktop::zoom::apply_native_zoom(&webview_window, zoom_factor) {
@@ -617,6 +620,21 @@ pub fn build_main_window(app: &tauri::AppHandle<Wry>) -> tauri::Result<tauri::We
Ok(webview_window)
}
+/// 把窗口底色设成主题画布色;`system` 按窗口当前外观折算。
+///
+/// macOS 未实现窗口底色接口,`set_background_color` 会返回错误并被忽略——那里由
+/// `config::apply_window_theme` 同步原生外观。
+fn apply_window_background(app: &tauri::AppHandle<Wry>, window: &tauri::WebviewWindow<Wry>) {
+ let Some(color) =
+ crate::config::window_background(crate::config::get_dsh_theme(app), window.theme().ok())
+ else {
+ return;
+ };
+ if let Err(error) = window.as_ref().set_background_color(Some(color)) {
+ log::debug!("[theme] window background color not applied: {error}");
+ }
+}
+
/// 「文件 → 新建窗口」:以同一 `index.html` 再开一个独立 webview 窗口。
///
/// 与主窗口共用同一份平台 chrome、外链/下载接管与(Windows)WebView2 用户数据
@@ -694,6 +712,7 @@ pub fn build_extra_window(app: &tauri::AppHandle<Wry>) -> tauri::Result<tauri::W
};
let window = webview_builder.build()?;
+ apply_window_background(app, &window);
// 启动/真值变化时由主窗口应用缩放;新窗口需要自己应用一次当前真值。
let zoom_factor = crate::config::get_store_dat_setting(app).zoom_factor;
diff --git a/src/hooks/use-theme-adaptive.ts b/src/hooks/use-theme-adaptive.ts
index 657bb74c..dd335b43 100644
--- a/src/hooks/use-theme-adaptive.ts
+++ b/src/hooks/use-theme-adaptive.ts
@@ -2,15 +2,22 @@ import { usePreferredDark, useWatch } from '@reause/core'
import { useDshStyle } from './use-dsh-style'
import { useInvoke } from './use-invoke'
+export function resolveTheme(
+ preference: 'dark' | 'light' | 'system' | null | undefined,
+ systemDark: boolean,
+): 'dark' | 'light' {
+ return preference === 'light' || preference === 'dark'
+ ? preference
+ : (systemDark ? 'dark' : 'light')
+}
+
export function useThemeAdaptive() {
const themePreference = useInvoke<'dark' | 'light' | 'system'>('get_dsh_theme')
const [dshStyle] = useDshStyle()
const systemDark = usePreferredDark()
// 显式偏好优先;`system` 与尚未取到偏好(useInvoke 首次返回 undefined)都按系统
- // 偏好折算——首次进入(settings.yaml 不存在)时后端回退 `system`,这里不能先落深色。
- const theme = themePreference === 'light' || themePreference === 'dark'
- ? themePreference
- : (systemDark ? 'dark' : 'light')
+ // 偏好折算——首次进入(没有偏好配置)时后端回退 `system`,这里不能先落深色。
+ const theme = resolveTheme(themePreference, systemDark)
useWatch(
dshStyle.colorScheme || theme,
value => document.documentElement.dataset.theme = value,
diff --git a/src/main.tsx b/src/main.tsx
index 9380151b..5dbd0257 100644
--- a/src/main.tsx
+++ b/src/main.tsx
@@ -1,21 +1,37 @@
import { OverlaysProvider } from '@overlastic/react'
import { QueryClientProvider } from '@tanstack/react-query'
+import { invoke } from '@tauri-apps/api/core'
import React from 'react'
import ReactDOM from 'react-dom/client'
import { ToastProvider } from './components/toast-provider'
import { queryClient } from './config/client'
+import { resolveTheme } from './hooks/use-theme-adaptive'
import { App } from './layout'
import '@/utils/logger'
import './styles/main.css'
-ReactDOM.createRoot(document.getElementById('root') as HTMLElement).render(
- <React.StrictMode>
- <QueryClientProvider client={queryClient}>
- <ToastProvider>
- <OverlaysProvider>
- <App />
- </OverlaysProvider>
- </ToastProvider>
- </QueryClientProvider>
- </React.StrictMode>,
-)
+// 先取回 dsh 主题偏好再挂载:`main.css` 以深色为默认值,等 IPC 回来才切会让首帧
+// 闪一次错色。挂载前的窗口底色由 Rust 侧 `config::window_background` 兜住,此后
+// 的偏好变化仍由 `useThemeAdaptive` 订阅 `dsh-theme-updated` 跟进。
+async function bootstrap() {
+ const preference = await invoke<'dark' | 'light' | 'system'>('get_dsh_theme')
+ .catch(() => undefined)
+ document.documentElement.dataset.theme = resolveTheme(
+ preference,
+ window.matchMedia('(prefers-color-scheme: dark)').matches,
+ )
+
+ ReactDOM.createRoot(document.getElementById('root') as HTMLElement).render(
+ <React.StrictMode>
+ <QueryClientProvider client={queryClient}>
+ <ToastProvider>
+ <OverlaysProvider>
+ <App />
+ </OverlaysProvider>
+ </ToastProvider>
+ </QueryClientProvider>
+ </React.StrictMode>,
+ )
+}
+
+void bootstrap()