Skip to content

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

feat(appearance): add local scale and backdrop blur (#924)

SkanderBot85c89a134309
diff --git a/README.md b/README.md
index 566f0b11..7c6c8c68 100644
--- a/README.md
+++ b/README.md
@@ -45,7 +45,7 @@
- 💽 **数据目录** — 安装时(Windows 安装包)可选择数据存放位置;Windows / macOS / Linux 都能在设置里整体迁移与回滚。
- ⌨️ **命令行集成** — 通过托管 shim 提供 `dsh` / `pnpm`,不是全局 npm 内核安装。
- 🐾 **桌宠** — Pets / Codex 资源管理、资源包导入与会话状态展示;预设素材来自远端。
-- 🎨 **个性化** — 8 种配色、终端模式与原生透明,可一键恢复默认。
+- 🎨 **个性化** — 8 种配色、本机界面缩放、终端模式,以及可调不透明度与可选磨砂模糊(Windows / macOS 使用原生背景效果),可一键恢复默认。
## 内置插件
diff --git a/packages/dsh-tauri/src/client/register/appearance.test.ts b/packages/dsh-tauri/src/client/register/appearance.test.ts
index 40469508..902cf6e6 100644
--- a/packages/dsh-tauri/src/client/register/appearance.test.ts
+++ b/packages/dsh-tauri/src/client/register/appearance.test.ts
@@ -80,6 +80,49 @@ describe('desktop appearance bridge', () => {
expect(document.querySelector('style')!.textContent).toContain('#eceff4 70%')
})
+ it('paints the translucent canvas once: a backdrop filter would composite the fill twice', () => {
+ const { send } = setup()
+ send({ palette: 'nord', transparency: true, opacity: 70, blur: true })
+ const css = document.querySelector('style')!.textContent!
+ expect(css).toContain('body{background:color-mix(in srgb,#2e3440 70%,transparent)!important}')
+ expect(css).not.toContain('backdrop-filter')
+ send({ transparency: false, opacity: 70, blur: true })
+ expect(document.querySelector('style')!.textContent).toBe('')
+ })
+
+ it.each([false, true])('fills a still-mounted boot page like the shell bar when sidebarOnly=%s', (sidebarOnly) => {
+ const { send } = setup()
+ document.body.innerHTML = '<div id="root"><div data-dsh-boot><span>HARNESS</span><span>Loading plugins...</span></div></div>'
+ const boot = document.querySelector('[data-dsh-boot]')!
+ const markup = boot.outerHTML
+ send({ palette: 'nord', transparency: true, opacity: 70, sidebarOnly })
+ const css = document.querySelector('style')!.textContent!
+ expect(css).toContain('body[data-ds-dark-theme] > #root > [data-dsh-boot]{background:color-mix(in srgb,#2e3440 70%,transparent)!important}')
+ expect(css).toContain('body:not([data-ds-dark-theme]) > #root > [data-dsh-boot]{background:color-mix(in srgb,#eceff4 70%,transparent)!important}')
+ expect(css).not.toContain('#root > [data-dsh-boot]{background:transparent')
+ expect(boot.outerHTML).toBe(markup)
+ })
+
+ it('keeps the boot page opaque unless transparency is effective', () => {
+ const { send } = setup()
+ document.body.innerHTML = '<div id="root"><div data-dsh-boot></div></div>'
+ send({ palette: 'nord', transparency: false, opacity: 70 })
+ expect(document.querySelector('style')!.textContent).toBe('')
+ send({ palette: 'nord', transparency: true, opacity: 100 })
+ expect(document.querySelector('style')!.textContent).toBe('')
+ })
+
+ it('acknowledges each applied appearance only after its stylesheet and tokens are live', () => {
+ const { send, post, theme } = setup()
+ post.mockClear()
+ send({ palette: 'nord', transparency: true, opacity: 70 })
+ expect(post.mock.calls.at(-1)?.[0]).toMatchObject({ type: 'dsh://appearance:applied' })
+ expect(theme.overrideTokens.mock.invocationCallOrder[0]).toBeLessThan(post.mock.invocationCallOrder.at(-1)!)
+ expect(document.querySelector('style')!.textContent).toContain('#2e3440 70%')
+ send({ palette: 'nord', transparency: true, opacity: 70 })
+ expect(post).toHaveBeenCalledTimes(1)
+ })
+
it('keeps the canvas opaque when transparency is explicitly disabled', () => {
const { send, theme } = setup()
send({ transparency: false, opacity: 70 })
diff --git a/packages/dsh-tauri/src/client/register/appearance.ts b/packages/dsh-tauri/src/client/register/appearance.ts
index 5be292f0..f44c0f2c 100644
--- a/packages/dsh-tauri/src/client/register/appearance.ts
+++ b/packages/dsh-tauri/src/client/register/appearance.ts
@@ -1,7 +1,7 @@
import type { ThemeRuntime } from '@deepseek-ai/dsh-client-ui-theme/client'
import type { Appearance } from '../../shared/appearance'
import type { ClientContext } from '../types'
-import { appearanceColors, appearanceTokens, normalizeAppearance } from '../../shared/appearance'
+import { appearanceBootCss, appearanceColors, appearanceSidebarFill, appearanceTokens, appearanceTranslucent, normalizeAppearance } from '../../shared/appearance'
import { PLUGIN_ID } from '../../shared/constants'
import { invokeParent } from '../service/invoke-parent'
import { listenParent } from '../service/listen-parent'
@@ -28,12 +28,16 @@ export const registerAppearance = defineRegister<ClientContext>((controller, ctx
function updateStyles() {
if (!current)
return
- const { canvas } = appearanceColors(current, theme!.getTheme().active.colorScheme)
- const translucent = current.transparency && current.opacity < 100
+ const { canvas, panel } = appearanceColors(current, theme!.getTheme().active.colorScheme)
+ const translucent = appearanceTranslucent(current)
style.textContent = [
- translucent ? `html{background:transparent!important}body{background:color-mix(in srgb,${canvas} ${current.opacity}%,transparent)!important}` : '',
- translucent && current.sidebarOnly ? `body :has(>[data-slot="main"]),body [data-rightbar-col]{--dsw-alias-bg-base:${canvas};background:${canvas}!important}` : '',
+ translucent ? `html{background:transparent!important}body{background:${appearanceSidebarFill(canvas, panel, translucent, current.opacity)}!important}` : '',
+ translucent && current.sidebarOnly
+ ? `body :has(>[data-slot="main"]),body [data-rightbar-col]{--dsw-alias-bg-base:${canvas};background:${canvas}!important} `
+ + `[data-slot="settings.content"]{--dsw-alias-bg-base:${canvas};background:${canvas}!important}`
+ : '',
current.terminal ? 'body [data-sidebar-collapsed]:has(>[data-shell-overlay]){grid-template-columns:var(--dsh-appearance-columns)!important}body [data-sidebar-collapsed] [data-slot="sidebar"]{visibility:hidden}' : '',
+ appearanceBootCss(current, true),
].filter(Boolean).join('\n')
}
@@ -79,12 +83,13 @@ export const registerAppearance = defineRegister<ClientContext>((controller, ctx
current = next
removeTokens?.()
const tokens = appearanceTokens(next)
- if (next.transparency && next.opacity < 100) {
+ if (appearanceTranslucent(next)) {
tokens['--dsw-alias-bg-base'] = { dark: 'transparent', light: 'transparent' }
tokens['--dsw-specific-sidebar-fill'] = { dark: 'transparent', light: 'transparent' }
}
removeTokens = Object.keys(tokens).length ? theme.overrideTokens('dsh-tauri:appearance', tokens) : undefined
updateStyles()
+ invokeParent({ type: 'dsh://appearance:applied' })
if (terminalChanged) {
stopTerminal()
if (next.terminal && !attachFrame()) {
diff --git a/packages/dsh-tauri/src/shared/appearance.test.ts b/packages/dsh-tauri/src/shared/appearance.test.ts
index fde47317..91b82b40 100644
--- a/packages/dsh-tauri/src/shared/appearance.test.ts
+++ b/packages/dsh-tauri/src/shared/appearance.test.ts
@@ -1,5 +1,5 @@
import { describe, expect, it } from 'vitest'
-import { APPEARANCE_DEFAULTS, APPEARANCE_PALETTES, appearanceColors, appearanceTokens, normalizeAppearance } from './appearance'
+import { APPEARANCE_DEFAULTS, APPEARANCE_PALETTES, appearanceBootCss, appearanceColors, appearanceSidebarFill, appearanceStartupFill, appearanceTokens, normalizeAppearance } from './appearance'
describe('appearance preferences', () => {
it('migrates old transparency settings but respects an explicit disabled switch', () => {
@@ -13,7 +13,43 @@ describe('appearance preferences', () => {
})
it.each([[0, 20], [255, 100], [77.4, 77], [80, 80]])('normalizes opacity %s to %s', (input, opacity) => {
- expect(normalizeAppearance({ palette: 'nord', terminal: true, opacity: input })).toEqual({ palette: 'nord', terminal: true, transparency: opacity < 100, opacity, sidebarOnly: false })
+ expect(normalizeAppearance({ palette: 'nord', terminal: true, opacity: input })).toEqual({ palette: 'nord', terminal: true, transparency: opacity < 100, opacity, blur: false, sidebarOnly: false })
+ })
+
+ it.each([[false, false], [true, true], [0, false], [1, true], [40, true]])('normalizes blur %s to %s', (input, expected) => {
+ expect(normalizeAppearance({ transparency: true, opacity: 70, blur: input }).blur).toBe(expected)
+ })
+
+ it.each([
+ [true, 70, 'color-mix(in srgb,#2e3440 70%,transparent)'],
+ [true, 100, 'color-mix(in srgb,#2e3440 100%,transparent)'],
+ [false, 70, '#343c4a'],
+ ])('gives the shell bar the sidebar column fill for translucent=%s at %s%%', (translucent, percent, expected) => {
+ expect(appearanceSidebarFill('#2e3440', '#343c4a', translucent, percent)).toBe(expected)
+ })
+
+ it.each([
+ [{ transparency: true, opacity: 70 }, 'color-mix(in srgb,#2e3440 70%,transparent)'],
+ [{ transparency: true, opacity: 70, sidebarOnly: true }, 'color-mix(in srgb,#2e3440 70%,transparent)'],
+ [{ transparency: true, opacity: 100 }, '#2e3440'],
+ [{ transparency: false, opacity: 70 }, '#2e3440'],
+ ])('fills startup surfaces like the shell bar for preferences=%j', (preferences, expected) => {
+ expect(appearanceStartupFill(normalizeAppearance({ palette: 'nord', ...preferences }), '#2e3440')).toBe(expected)
+ })
+
+ it('projects the boot page onto the window behind it without doubling the alpha', () => {
+ const css = appearanceBootCss(normalizeAppearance({ palette: 'nord', transparency: true, opacity: 70 }))
+ expect(css).toContain('html,body,#root{background:transparent!important}')
+ expect(css).toContain('body[data-ds-dark-theme] > #root > [data-dsh-boot]{background:color-mix(in srgb,#2e3440 70%,transparent)!important}')
+ expect(css).toContain('body:not([data-ds-dark-theme]) > #root > [data-dsh-boot]{background:color-mix(in srgb,#eceff4 70%,transparent)!important}')
+ expect(css).not.toContain('data-dsh-boot]{background:#2e3440')
+ })
+
+ it.each([
+ [{ palette: 'nord', transparency: false, opacity: 70 }],
+ [{ palette: 'nord', transparency: true, opacity: 100 }],
+ ])('leaves the boot page opaque for preferences=%j', (preferences) => {
+ expect(appearanceBootCss(normalizeAppearance(preferences))).toBe('')
})
it.each(['github', 'github-dimmed', 'github-high-contrast'])('preserves the saved %s palette', (palette) => {
diff --git a/packages/dsh-tauri/src/shared/appearance.ts b/packages/dsh-tauri/src/shared/appearance.ts
index c059ab05..edb96b9d 100644
--- a/packages/dsh-tauri/src/shared/appearance.ts
+++ b/packages/dsh-tauri/src/shared/appearance.ts
@@ -1,4 +1,4 @@
-export const APPEARANCE_DEFAULTS = { palette: 'default', terminal: false, transparency: false, opacity: 100, sidebarOnly: false } as const
+export const APPEARANCE_DEFAULTS = { palette: 'default', terminal: false, transparency: false, opacity: 100, blur: false, sidebarOnly: false } as const
export const APPEARANCE_PALETTES = ['default', 'nord', 'solarized', 'forest', 'amber', 'github', 'github-dimmed', 'github-high-contrast'] as const
export interface Appearance {
@@ -6,11 +6,12 @@ export interface Appearance {
terminal: boolean
transparency: boolean
opacity: number
+ blur: boolean
sidebarOnly: boolean
}
export function normalizeAppearance(value: unknown): Appearance {
- const input = value as Partial<Appearance> | null
+ const input = value as (Omit<Partial<Appearance>, 'blur'> & { blur?: unknown }) | null
const opacity = typeof input?.opacity === 'number' && Number.isFinite(input.opacity)
? Math.round(Math.min(100, Math.max(20, input.opacity)))
: 100
@@ -19,10 +20,56 @@ export function normalizeAppearance(value: unknown): Appearance {
terminal: input?.terminal === true,
transparency: input?.transparency === undefined ? opacity < 100 : input.transparency === true,
opacity,
+ blur: input?.blur === true || (typeof input?.blur === 'number' && input.blur > 0),
sidebarOnly: input?.sidebarOnly === true,
}
}
+export function appearanceSidebarFill(canvas: string, panel: string, translucent: boolean, percent: number): string {
+ return translucent ? `color-mix(in srgb,${canvas} ${percent}%,transparent)` : panel
+}
+
+/** 「背景真的半透明」只有一个定义:窗口开了透明且 alpha 未满。 */
+export function appearanceTranslucent(appearance: Appearance): boolean {
+ return appearance.transparency && appearance.opacity < 100
+}
+
+/** 启动页填充色:与 navbar / 侧边栏同源同 alpha,100% 或不透明时回到实心 canvas。 */
+export function appearanceStartupFill(appearance: Appearance, canvas: string): string {
+ return appearanceSidebarFill(canvas, canvas, appearanceTranslucent(appearance), appearance.opacity)
+}
+
+/**
+ * 官方 web shell boot 页(`[data-dsh-boot]`)的透明投影。
+ *
+ * 该页由内核在**插件加载之前**绘出,此刻外观插件还没激活,所以只能用与宿主同源的
+ * CSS 表达:`html`/`body`/`#root` 全透明,由 boot 节点自身承载与 navbar 一致的 alpha。
+ * 只绘制一层 alpha——boot 节点铺底后 `body` 再叠加会得到 0.7×0.7≈0.91 的错误浓度。
+ *
+ * 背景必须落在与 boot 页同优先级的规则上:官方 `.boot` 的背景表达式是
+ * `var(--dsw-alias-bg-base, var(--dsh-boot-bg, Canvas))`,只要 theme 的
+ * `--dsw-alias-bg-base` 存在,仅设 `--dsh-boot-bg` 就会被它压掉。选择器保持结构性
+ * 且 boot-only,boot 一被 React 交接替换,整套规则自动失效(不污染正常页面,也不需要
+ * 给 `[data-dsh-boot]` 注入 inline style,避免 BootHandoff hydration 额外属性告警)。
+ *
+ * `bodyOnly` 供「自己已经画了 body alpha」的调用方(外观插件)使用:此时只取 boot
+ * 节点本体的填充规则,避免与它后写的 `body{background:…}` 争同一层 alpha。
+ */
+export function appearanceBootCss(appearance: Appearance, bodyOnly = false): string {
+ if (!appearanceTranslucent(appearance))
+ return ''
+ const blocks = (['dark', 'light'] as const).map((scheme) => {
+ const { canvas } = appearanceColors(appearance, scheme)
+ const selector = scheme === 'dark' ? 'body[data-ds-dark-theme]' : 'body:not([data-ds-dark-theme])'
+ const fill = appearanceStartupFill(appearance, canvas)
+ return `html:has(${selector} > #root > [data-dsh-boot]),${selector} > #root > [data-dsh-boot]{background:${fill}!important}`
+ })
+ return [
+ ...bodyOnly ? [] : ['html,body,#root{background:transparent!important}'],
+ ...blocks,
+ ].join('\n')
+}
+
type Palette = readonly [canvas: string, panel: string, surface: string, text: string, muted: string, accent: string, border?: string]
const PALETTES: Record<Appearance['palette'], Record<'dark' | 'light', Palette>> = {
diff --git a/src-tauri/capabilities/appearance-effects.json b/src-tauri/capabilities/appearance-effects.json
new file mode 100644
index 00000000..f4b7d36b
--- /dev/null
+++ b/src-tauri/capabilities/appearance-effects.json
@@ -0,0 +1,18 @@
+{
+ "$schema": "../gen/schemas/desktop-schema.json",
+ "identifier": "appearance-effects",
+ "description": "Allows only local shell pages to update native window backdrop effects. Embedded loopback Harness pages do not receive this permission.",
+ "local": true,
+ "windows": [
+ "main",
+ "remote-*",
+ "window-*"
+ ],
+ "permissions": [
+ "core:window:allow-set-effects"
+ ],
+ "platforms": [
+ "windows",
+ "macOS"
+ ]
+}
diff --git a/src-tauri/src/config/appearance.rs b/src-tauri/src/config/appearance.rs
index 1535ece0..6d2af62d 100644
--- a/src-tauri/src/config/appearance.rs
+++ b/src-tauri/src/config/appearance.rs
@@ -7,6 +7,7 @@ pub struct Appearance {
pub terminal: bool,
pub transparency: bool,
pub opacity: u8,
+ pub blur: bool,
pub sidebar_only: bool,
}
@@ -17,6 +18,7 @@ impl Default for Appearance {
terminal: false,
transparency: false,
opacity: 100,
+ blur: false,
sidebar_only: false,
}
}
@@ -36,6 +38,11 @@ impl From<serde_json::Value> for Appearance {
.get("transparency")
.map_or(opacity < 100, |value| value.as_bool().unwrap_or(false)),
opacity,
+ blur: value["blur"].as_bool().unwrap_or_else(|| {
+ value["blur"]
+ .as_f64()
+ .is_some_and(|value| value.is_finite() && value > 0.0)
+ }),
sidebar_only: value["sidebarOnly"].as_bool().unwrap_or(false),
};
appearance.normalize();
@@ -44,6 +51,10 @@ impl From<serde_json::Value> for Appearance {
}
impl Appearance {
+ pub fn native_blur_enabled(&self) -> bool {
+ self.transparency && self.blur
+ }
+
pub fn normalize(&mut self) {
if !matches!(
self.palette.as_str(),
@@ -128,6 +139,41 @@ mod tests {
}
}
+ #[test]
+ fn blur_decoding_accepts_the_switch_and_migrates_positive_preview_values() {
+ for (value, expected) in [
+ (serde_json::json!(false), false),
+ (serde_json::json!(true), true),
+ (serde_json::json!(-1), false),
+ (serde_json::json!(0), false),
+ (serde_json::json!(1), true),
+ (serde_json::json!(40), true),
+ ] {
+ let appearance: Appearance = serde_json::from_value(serde_json::json!({
+ "blur": value
+ }))
+ .unwrap();
+ assert_eq!(appearance.blur, expected, "{value}");
+ }
+ }
+
+ #[test]
+ fn native_blur_requires_both_window_transparency_and_the_blur_switch() {
+ for (transparency, blur, expected) in [
+ (false, false, false),
+ (false, true, false),
+ (true, false, false),
+ (true, true, true),
+ ] {
+ let appearance = Appearance {
+ transparency,
+ blur,
+ ..Default::default()
+ };
+ assert_eq!(appearance.native_blur_enabled(), expected);
+ }
+ }
+
#[test]
fn invalid_opacity_preserves_the_other_appearance_fields() {
for value in [
@@ -159,7 +205,7 @@ mod tests {
for palette in ["github", "github-dimmed", "github-high-contrast"] {
let appearance: Appearance = serde_json::from_value(serde_json::json!({
"palette": palette, "terminal": true, "transparency": true,
- "opacity": 78, "sidebarOnly": true
+ "opacity": 78, "blur": true, "sidebarOnly": true
}))
.unwrap();
assert_eq!(appearance.palette, palette);
@@ -182,6 +228,7 @@ mod tests {
appearance.normalize();
assert_eq!(appearance.palette, "default");
assert_eq!(appearance.opacity, 20);
+ assert!(!appearance.blur);
assert!(appearance.terminal);
appearance.opacity = 255;
appearance.normalize();
diff --git a/src-tauri/src/config/setting.rs b/src-tauri/src/config/setting.rs
index ee69b4fc..f07e01ac 100644
--- a/src-tauri/src/config/setting.rs
+++ b/src-tauri/src/config/setting.rs
@@ -720,6 +720,7 @@ mod tests {
palette: "nord".into(),
terminal: true,
opacity: 70,
+ blur: true,
transparency: true,
sidebar_only: true,
},
diff --git a/src-tauri/src/desktop/appearance.js.inc b/src-tauri/src/desktop/appearance.js.inc
new file mode 100644
index 00000000..1d97921b
--- /dev/null
+++ b/src-tauri/src/desktop/appearance.js.inc
@@ -0,0 +1,61 @@
+(function () {
+ if (window.__dsh_appearance_bootstrap__) return
+ window.__dsh_appearance_bootstrap__ = true
+ // 只有宿主直接内嵌的那一层 frame 参与握手:dsh 应用内部嵌套的 frame 父窗口是 dsh
+ // 页面而不是宿主,自报/应答都不该走这套协议(直达宿主的帧里 parent === top)。
+ if (window.parent !== window.top) return
+
+ var STYLE_ID = 'dsh-tauri:boot-appearance'
+ var acknowledged = false
+
+ // head/documentElement 在 document-start 可能还不存在,等它们出现再补挂。
+ function bootStyle() {
+ var style = document.getElementById(STYLE_ID)
+ if (style) return style
+ var target = document.head || document.documentElement
+ if (!target) return null
+ style = document.createElement('style')
+ style.id = STYLE_ID
+ target.appendChild(style)
+ return style
+ }
+
+ // 宿主是 tauri://localhost / http://tauri.localhost,帧内是 http://127.0.0.1:<port>,
+ // 跨源回发只能用 '*'(消息可信度由两端的 source 校验保证,请求不含敏感数据)。
+ function request() {
+ parent.postMessage({ source: 'dsh-desktop', type: 'dsh://appearance:request' }, '*')
+ }
+
+ window.addEventListener('message', function (event) {
+ if (event.source !== window.parent) return
+ var data = event.data
+ if (!data || typeof data !== 'object') return
+ if (data.source !== 'dsh-desktop') return
+ if (data.type !== 'dsh://appearance') return
+ // boot 页由内核在插件加载之前绘出,宿主下发的 CSS 是它唯一的透明来源;样式始终挂在
+ // 独立 head style 上,绝不改 boot 节点的 DOM(BootHandoff 只交接 className/innerHTML,
+ // 额外 inline style 会被判成 hydration 不匹配)。
+ var style = bootStyle()
+ if (!style) return
+ var css = typeof data.bootCss === 'string' ? data.bootCss : ''
+ if (style.textContent !== css) style.textContent = css
+ if (acknowledged) return
+ acknowledged = true
+ parent.postMessage({ source: 'dsh-desktop', type: 'dsh://appearance:applied' }, '*')
+ })
+
+ // 帧内导航离开:旧文档的 boot 样式立即失效,别让它短暂作用在新文档上;新文档自己
+ // 重新握手(同文档 bfcache 还原走下面的 pageshow,宿主据 leaving 重新隐蔽 iframe)。
+ window.addEventListener('pagehide', function () {
+ var style = document.getElementById(STYLE_ID)
+ if (style) style.remove()
+ acknowledged = false
+ })
+
+ window.addEventListener('pageshow', function () {
+ acknowledged = false
+ request()
+ })
+
+ request()
+})()
diff --git a/src-tauri/src/desktop/appearance.rs b/src-tauri/src/desktop/appearance.rs
new file mode 100644
index 00000000..4f30d952
--- /dev/null
+++ b/src-tauri/src/desktop/appearance.rs
@@ -0,0 +1,2 @@
+/// iframe 内:启动期外观请求/应用/确认(document-start 注入,幂等)。
+pub(crate) const APPEARANCE_BOOTSTRAP_JS: &str = include_str!("appearance.js.inc");
diff --git a/src-tauri/src/desktop/builder.rs b/src-tauri/src/desktop/builder.rs
index 862dca41..694c67b3 100644
--- a/src-tauri/src/desktop/builder.rs
+++ b/src-tauri/src/desktop/builder.rs
@@ -840,17 +840,37 @@ fn with_shell_chrome<'a>(
app: &'a tauri::AppHandle<Wry>,
builder: WebviewWindowBuilder<'a, Wry, tauri::AppHandle<Wry>>,
) -> tauri::Result<WebviewWindowBuilder<'a, Wry, tauri::AppHandle<Wry>>> {
- let transparent = crate::config::get_store_dat_setting(app).appearance.transparency;
+ let appearance = crate::config::get_store_dat_setting(app).appearance;
+ let transparent = appearance.transparency;
let builder = builder
.transparent(transparent)
.initialization_script(format!(
"window.__DSH_TRANSPARENT__ = {transparent}; window.__DSH_STORE_FILE__ = {};",
serde_json::json!(crate::config::store_dat_file_name())
))
+ // 启动期外观引导必须落在 document-start 且覆盖所有 frame:内嵌 dsh 的 boot 页
+ // (HARNESS + Loading plugins…)由内核在插件加载之前绘出,晚于首绘的帧桥改不动它。
+ .initialization_script_for_all_frames(crate::desktop::appearance::APPEARANCE_BOOTSTRAP_JS)
.inner_size(1280.0, 840.0)
.min_inner_size(860.0, 620.0)
.resizable(true);
+ #[cfg(any(windows, target_os = "macos"))]
+ let builder = if appearance.native_blur_enabled() {
+ builder.effects(
+ tauri::window::EffectsBuilder::new()
+ .effects([
+ tauri::window::Effect::Acrylic,
+ tauri::window::Effect::Mica,
+ tauri::window::Effect::UnderWindowBackground,
+ ])
+ .state(tauri::window::EffectState::FollowsWindowActiveState)
+ .build(),
+ )
+ } else {
+ builder
+ };
+
#[cfg(windows)]
let builder = builder
.data_directory(webview_data_directory(app))
@@ -1073,7 +1093,8 @@ pub fn build_main_window(app: &tauri::AppHandle<Wry>) -> tauri::Result<tauri::We
// 非 Windows(macOS/Linux)没有 WebView2 的 FrameCreated/ContentLoading 流程,
// 直接用 Tauri 的 initialization_script_for_all_frames 把兼容桥、通知桥、
- // 剪贴板图片桥、帧内日志桥与 boot 探测桥注入所有 frame(脚本均带幂等守卫,重复注入安全)。
+ // 剪贴板图片桥、帧内日志桥、启动期外观引导与 boot 探测桥注入所有 frame
+ // (脚本均带幂等守卫,重复注入安全)。
// 导航桥(侧边栏)、缩放快捷键与 iframe 全局样式已分别由 dsh-tauri /
// dsh-tauri-ui 插件在 iframe 内实现,不再注入对应脚本。
#[cfg(not(windows))]
@@ -1378,6 +1399,22 @@ mod security_tests {
}
}
+ #[test]
+ fn native_appearance_effects_are_local_shell_only() {
+ let appearance: Value =
+ serde_json::from_str(include_str!("../../capabilities/appearance-effects.json")).unwrap();
+ // 这个能力一旦带上 remote,就会把窗口级 setEffects 暴露给回环承载的 Harness 页面。
+ assert!(appearance.get("remote").is_none());
+
+ let default_permissions = capability()["permissions"]
+ .as_array()
+ .expect("permissions must be an array")
+ .clone();
+ assert!(!default_permissions.iter().any(|permission| {
+ permission.as_str() == Some("core:window:allow-set-effects")
+ }));
+ }
+
#[test]
fn pet_http_scope_is_limited_to_remote_asset_hosts() {
// 桌宠窗口经插件版 fetch 直连远端素材(绕开 githubusercontent 的 CORS),
diff --git a/src-tauri/src/desktop/mod.rs b/src-tauri/src/desktop/mod.rs
index ce4e4a36..03b7e7b4 100644
--- a/src-tauri/src/desktop/mod.rs
+++ b/src-tauri/src/desktop/mod.rs
@@ -1,4 +1,5 @@
pub mod activation;
+pub mod appearance;
pub mod autostart;
pub mod builder;
pub mod compat;
diff --git a/src/hooks/use-appearance.test.tsx b/src/hooks/use-appearance.test.tsx
index 6c6a33f9..4490fa93 100644
--- a/src/hooks/use-appearance.test.tsx
+++ b/src/hooks/use-appearance.test.tsx
@@ -4,36 +4,58 @@ import { defineStore } from 'valtio-define'
import { afterEach, describe, expect, it, vi } from 'vitest'
import { useAppearance } from './use-appearance'
-const mocks = vi.hoisted(() => ({ setting: {} as any }))
+const mocks = vi.hoisted(() => ({
+ setting: {} as any,
+ platform: 'linux',
+ setEffects: vi.fn(() => Promise.resolve()),
+ clearEffects: vi.fn(() => Promise.resolve()),
+}))
vi.mock('@/store', () => ({ store: { get setting() {
return mocks.setting
} } }))
+vi.mock('@tauri-apps/api/window', () => ({
+ Effect: { Acrylic: 'acrylic', Mica: 'mica', UnderWindowBackground: 'underWindowBackground' },
+ EffectState: { FollowsWindowActiveState: 'followsWindowActiveState' },
+ getCurrentWindow: () => ({ setEffects: mocks.setEffects, clearEffects: mocks.clearEffects }),
+}))
+vi.mock('@tauri-apps/plugin-os', () => ({ type: () => mocks.platform }))
vi.mock('./use-dsh-style', () => ({ useDshStyle: () => [{ colorScheme: 'dark' }] }))
+const IFRAME_ORIGIN = 'http://localhost:3080'
+
afterEach(() => {
cleanup()
document.body.replaceChildren()
document.head.replaceChildren()
delete (window as any).__DSH_TRANSPARENT__
+ mocks.platform = 'linux'
+ vi.clearAllMocks()
vi.restoreAllMocks()
})
-function setup(transparent: boolean) {
+function setup(transparent: boolean, hydrated = true) {
;(window as any).__DSH_TRANSPARENT__ = transparent
- mocks.setting = defineStore({ state: () => ({ appearance: { palette: 'nord', terminal: false, opacity: 70 } }) })
+ mocks.setting = defineStore({ state: () => ({ appearance: { palette: 'nord', terminal: false, opacity: 70 }, hydrated }) })
const iframe = document.createElement('iframe')
- iframe.src = 'http://localhost:3080'
+ iframe.src = IFRAME_ORIGIN
document.body.append(iframe)
const post = vi.spyOn(iframe.contentWindow!, 'postMessage').mockImplementation(() => {})
const hook = renderHook(() => useAppearance({ current: iframe }))
- function ready(origin = 'http://localhost:3080') {
+ function dispatch(type: string, origin = IFRAME_ORIGIN) {
act(() => window.dispatchEvent(new MessageEvent('message', {
source: iframe.contentWindow!,
origin,
- data: { type: 'dsh://appearance:ready' },
+ data: { type },
})))
}
- return { post, hook, ready }
+ return {
+ post,
+ hook,
+ // 帧内 document-start 的启动期请求(壳层据此下发 boot 投影)
+ request: (origin?: string) => dispatch('dsh://appearance:request', origin),
+ // 外观插件激活后的既有握手
+ ready: (origin?: string) => dispatch('dsh://appearance:ready', origin),
+ }
}
describe('desktop appearance projection', () => {
@@ -41,20 +63,96 @@ describe('desktop appearance projection', () => {
const { post, ready, hook } = setup(false)
ready()
expect(post.mock.calls.at(-1)?.[0]).toMatchObject({ type: 'dsh://appearance', appearance: { opacity: 100 } })
- expect(hook.result.current).toContain('#343c4a 100%')
+ expect(hook.result.current).toContain('[data-testid="dsh-navbar-root"]{background:#343c4a!important')
})
it('sends the saved opacity to a transparent window and removes the bridge listener on unmount', () => {
const { post, ready, hook } = setup(true)
ready()
expect(post.mock.calls.at(-1)?.[0]).toMatchObject({ appearance: { palette: 'nord', opacity: 70 } })
- expect(hook.result.current).toContain('#343c4a 70%')
+ expect(hook.result.current).toContain('color-mix(in srgb,#2e3440 70%,transparent)')
hook.unmount()
post.mockClear()
ready()
expect(post).not.toHaveBeenCalled()
})
+ it('projects the same blur into the shell and embedded appearance message', async () => {
+ const { post, ready, hook } = setup(true)
+ ready()
+ await act(async () => {
+ mocks.setting.appearance = { palette: 'nord', terminal: false, transparency: true, opacity: 70, blur: true }
+ })
+ expect(post.mock.calls.at(-1)?.[0]).toMatchObject({ appearance: { blur: true } })
+ expect(hook.result.current).toContain('backdrop-filter:blur(16px)')
+ expect(hook.result.current).toContain('-webkit-backdrop-filter:blur(16px)')
+ })
+
+ it('paints the shell bar with the fill the embedded sidebar column shows', async () => {
+ const { hook } = setup(true)
+ await act(async () => {
+ mocks.setting.appearance = { palette: 'nord', terminal: false, transparency: true, opacity: 70, blur: true }
+ })
+ expect(hook.result.current).toContain('--color-canvas:#2e3440')
+ expect(hook.result.current).toContain('[data-testid="dsh-navbar-root"]{background:color-mix(in srgb,#2e3440 70%,transparent)!important')
+ await act(async () => {
+ mocks.setting.appearance = { palette: 'nord', terminal: false, transparency: false, opacity: 70 }
+ })
+ expect(hook.result.current).toContain('[data-testid="dsh-navbar-root"]{background:#343c4a!important')
+ })
+
+ it.each([
+ [{ transparency: true, opacity: 70 }, true],
+ [{ transparency: true, opacity: 70, sidebarOnly: true }, true],
+ [{ transparency: false, opacity: 70 }, false],
+ [{ transparency: true, opacity: 100 }, false],
+ ])('fills startup pages with the same alpha the shell bar uses for %j', async (preferences, translucent) => {
+ const { hook } = setup(true)
+ await act(async () => {
+ mocks.setting.appearance = { palette: 'nord', terminal: false, ...preferences }
+ })
+ if (translucent)
+ expect(hook.result.current).toContain('--color-startup:color-mix(in srgb,#2e3440 70%,transparent)')
+ else
+ expect(hook.result.current).toContain('--color-startup:#2e3440')
+ })
+
+ it('serializes native window effects on supported transparent desktops', async () => {
+ mocks.platform = 'windows'
+ const { hook } = setup(true)
+ await act(async () => {
+ mocks.setting.appearance = { palette: 'nord', terminal: false, transparency: true, opacity: 70, blur: true }
+ })
+ await vi.waitFor(() => expect(mocks.setEffects).toHaveBeenLastCalledWith({
+ effects: ['acrylic', 'mica', 'underWindowBackground'],
+ state: 'followsWindowActiveState',
+ }))
+
+ mocks.clearEffects.mockClear()
+ await act(async () => {
+ mocks.setting.appearance = { palette: 'nord', terminal: false, transparency: true, opacity: 100, blur: true }
+ })
+ await vi.waitFor(() => expect(mocks.setEffects).toHaveBeenCalledTimes(2))
+ expect(mocks.clearEffects).not.toHaveBeenCalled()
+
+ await act(async () => {
+ mocks.setting.appearance = { palette: 'nord', terminal: false, transparency: true, opacity: 70, blur: false }
+ })
+ await vi.waitFor(() => expect(mocks.clearEffects).toHaveBeenCalled())
+ expect(mocks.setEffects.mock.invocationCallOrder.at(-1)).toBeLessThan(mocks.clearEffects.mock.invocationCallOrder.at(-1)!)
+ hook.unmount()
+ })
+
+ it('does not request unsupported Linux window effects', async () => {
+ mocks.platform = 'linux'
+ setup(true)
+ await act(async () => {
+ mocks.setting.appearance = { palette: 'nord', terminal: false, transparency: true, opacity: 70, blur: true }
+ })
+ expect(mocks.setEffects).not.toHaveBeenCalled()
+ expect(mocks.clearEffects).not.toHaveBeenCalled()
+ })
+
it('immediately restores an opaque canvas when native transparency is disabled', async () => {
const { post, ready, hook } = setup(true)
ready()
@@ -62,7 +160,40 @@ describe('desktop appearance projection', () => {
mocks.setting.appearance = { palette: 'nord', terminal: false, opacity: 70, transparency: false }
})
expect(post.mock.calls.at(-1)?.[0]).toMatchObject({ appearance: { transparency: false, opacity: 100 } })
- expect(hook.result.current).toContain('#343c4a 100%')
+ expect(hook.result.current).toContain('[data-testid="dsh-navbar-root"]{background:#343c4a!important')
+ })
+
+ it('keeps a transparent default palette opaque at 100 percent', async () => {
+ const { hook, request, post } = setup(true)
+ request()
+ expect(post.mock.calls.at(-1)?.[0].bootCss).toContain('[data-dsh-boot]')
+ await act(async () => {
+ mocks.setting.appearance = { palette: 'default', terminal: false, transparency: true, opacity: 100, blur: true }
+ })
+ expect(hook.result.current).toContain('[data-testid="dsh-navbar-root"]{background:#1b1b1c!important')
+ expect(hook.result.current).not.toContain('backdrop-filter:blur')
+ request()
+ expect(post.mock.calls.at(-1)?.[0]).toMatchObject({ bootCss: '' })
+ })
+
+ it('keeps the settings dialog opaque with the content-area option', async () => {
+ const { hook } = setup(true)
+ await act(async () => {
+ mocks.setting.appearance = { palette: 'nord', terminal: false, transparency: true, opacity: 70, blur: true, sidebarOnly: true }
+ })
+ expect(hook.result.current).toContain('[data-testid="dsh-config-dialog"]{background:#343c4a!important}')
+ })
+
+ it('does not clear the startup effect before native settings hydrate', async () => {
+ mocks.platform = 'windows'
+ setup(true, false)
+ expect(mocks.setEffects).not.toHaveBeenCalled()
+ expect(mocks.clearEffects).not.toHaveBeenCalled()
+ await act(async () => {
+ mocks.setting.appearance = { palette: 'nord', terminal: false, transparency: true, opacity: 70, blur: true }
+ mocks.setting.hydrated = true
+ })
+ await vi.waitFor(() => expect(mocks.setEffects).toHaveBeenCalledOnce())
})
it('applies high-contrast borders to the shell and removes them when switching palettes', async () => {
@@ -84,7 +215,16 @@ describe('desktop appearance projection', () => {
expect(post).not.toHaveBeenCalled()
})
- it('does no message work on unrelated renders and clears styling on reset', async () => {
+ it('answers a document-start boot request with the boot projection alongside the runtime appearance', () => {
+ const { post, request } = setup(true)
+ request()
+ const message = post.mock.calls.at(-1)?.[0]
+ expect(message).toMatchObject({ type: 'dsh://appearance', appearance: { palette: 'nord' } })
+ expect(message.bootCss).toContain('#root > [data-dsh-boot]')
+ expect(message.bootCss).toContain('color-mix(in srgb,#2e3440 70%,transparent)')
+ })
+
+ it('does no message work on unrelated renders and restores opaque styling on reset', async () => {
const { post, ready, hook } = setup(true)
ready()
post.mockClear()
@@ -94,6 +234,6 @@ describe('desktop appearance projection', () => {
mocks.setting.appearance = { palette: 'default', terminal: false, opacity: 100 }
})
expect(post.mock.calls.at(-1)?.[0]).toMatchObject({ appearance: { palette: 'default', opacity: 100 } })
- expect(hook.result.current).toBe('')
+ expect(hook.result.current).toContain('[data-testid="dsh-navbar-root"]{background:#1b1b1c!important')
})
})
diff --git a/src/hooks/use-appearance.ts b/src/hooks/use-appearance.ts
index 84c77732..b75f02aa 100644
--- a/src/hooks/use-appearance.ts
+++ b/src/hooks/use-appearance.ts
@@ -1,27 +1,35 @@
import type { RefObject } from 'react'
import { useWatch } from '@reause/core'
+import { Effect, EffectState, getCurrentWindow } from '@tauri-apps/api/window'
+import { type } from '@tauri-apps/plugin-os'
import { useRef } from 'react'
import { useStore } from 'valtio-define'
import { store } from '@/store'
-import { appearanceColors, normalizeAppearance } from '../../packages/dsh-tauri/src/shared/appearance'
+import { appearanceBootCss, appearanceColors, appearanceSidebarFill, appearanceStartupFill, appearanceTranslucent, normalizeAppearance } from '../../packages/dsh-tauri/src/shared/appearance'
import { useDshStyle } from './use-dsh-style'
import { useIframeMessage } from './use-iframe-message'
import { useIframePost } from './use-iframe-post'
export function useAppearance(iframeRef: RefObject<HTMLIFrameElement | null>) {
- const { appearance } = useStore(store.setting)
+ const { appearance, hydrated } = useStore(store.setting)
const [dshStyle] = useDshStyle()
const post = useIframePost(iframeRef)
const readyRef = useRef(false)
+ const nativeEffectQueueRef = useRef(Promise.resolve())
const transparent = (window as Window & { __DSH_TRANSPARENT__?: boolean }).__DSH_TRANSPARENT__ === true
+ const value = normalizeAppearance(appearance)
+ const payload = { ...value, transparency: transparent && value.transparency, opacity: transparent && value.transparency ? value.opacity : 100 }
+ const bootCss = appearanceBootCss(payload)
+ const scheme = dshStyle.colorScheme ?? (document.documentElement.dataset.theme === 'light' ? 'light' : 'dark')
function sendAppearance() {
- const value = normalizeAppearance(appearance)
- post({ type: 'dsh://appearance', appearance: { ...value, transparency: transparent && value.transparency, opacity: transparent && value.transparency ? value.opacity : 100 } })
+ post({ type: 'dsh://appearance', appearance: payload, bootCss })
}
+ // 帧内在 document-start 就请求一次(那时壳层可能还没挂载监听器),激活后还会按既有协议
+ // 自报 ready;两条通路都回同一份投影,重复下发由帧内幂等处理。
useIframeMessage<{ type?: string }>(iframeRef, (message) => {
- if (message.type === 'dsh://appearance:ready') {
+ if (message.type === 'dsh://appearance:ready' || message.type === 'dsh://appearance:request' || message.type === 'dsh://plugin-boot:frame') {
readyRef.current = true
sendAppearance()
}
@@ -33,15 +41,44 @@ export function useAppearance(iframeRef: RefObject<HTMLIFrameElement | null>) {
if (readyRef.current)
sendAppearance()
}, { immediate: true })
- const value = normalizeAppearance(appearance)
- const { canvas, panel, surface, text, muted, accent, border } = appearanceColors(value, dshStyle.colorScheme ?? (document.documentElement.dataset.theme === 'light' ? 'light' : 'dark'))
+ // 原生背景效果只在窗口真透明且平台支持时才设:设置错了会让窗口内容被系统合成器
+ // 换成不透明底,比不设更糟;调用是异步窗口 API,串行化避免快速切换时后发先至。
+ useWatch([appearance, hydrated], () => {
+ if (!hydrated)
+ return
+ let platform: ReturnType<typeof type>
+ try {
+ platform = type()
+ }
+ catch {
+ return
+ }
+ if (!transparent || (platform !== 'windows' && platform !== 'macos'))
+ return
+
+ const appWindow = getCurrentWindow()
+ nativeEffectQueueRef.current = nativeEffectQueueRef.current
+ .then(() => value.transparency && value.blur
+ ? appWindow.setEffects({
+ effects: [Effect.Acrylic, Effect.Mica, Effect.UnderWindowBackground],
+ state: EffectState.FollowsWindowActiveState,
+ })
+ : appWindow.clearEffects())
+ .catch(error => console.warn('[useAppearance] native backdrop effect failed:', error))
+ }, { immediate: true })
+
const alpha = transparent && value.transparency ? value.opacity : 100
- return value.palette === 'default' && alpha === 100
- ? ''
- : `
- ${alpha < 100 ? 'html,body{background:transparent!important}' : ''}
- html[data-theme]{--color-canvas:${canvas};--color-panel:${panel};--color-panel-2:${surface};--color-ink:${text};--color-info:${accent};--foreground:${text};--muted:${muted};--background:${canvas};--surface:${panel};--surface-secondary:${surface};--surface-tertiary:${surface};${border ? `--color-line:${border};--color-line-strong:${border};--color-btn-border:${border};--border:${border};--separator:${border};--field-border:${border}` : ''}}
- [data-testid="dsh-navbar-root"]{background:color-mix(in srgb,${panel} ${alpha}%,transparent)!important}
- [data-testid="dsh-shell-root"]>main{background:transparent!important}
- `
+ const backdropFilter = transparent && appearanceTranslucent(value) && value.blur ? 'blur(16px)' : 'none'
+ if (value.palette === 'default' && alpha === 100 && !transparent)
+ return ''
+ const { canvas, panel, surface, text, muted, accent, border } = appearanceColors(value, scheme)
+ return [
+ alpha < 100 ? 'html,body{background:transparent!important}' : '',
+ `html[data-theme]{--color-canvas:${canvas};--color-startup:${appearanceStartupFill(value, canvas)};--color-panel:${panel};--color-panel-2:${surface};--color-ink:${text};--color-info:${accent};--foreground:${text};--muted:${muted};--background:${canvas};--surface:${panel};--surface-secondary:${surface};--surface-tertiary:${surface};${border ? `--color-line:${border};--color-line-strong:${border};--color-btn-border:${border};--border:${border};--separator:${border};--field-border:${border};` : ''}}`,
+ `[data-testid="dsh-navbar-root"]{background:${appearanceSidebarFill(canvas, panel, alpha < 100, alpha)}!important;${backdropFilter === 'none' ? '' : `backdrop-filter:${backdropFilter};-webkit-backdrop-filter:${backdropFilter};`}}`,
+ alpha < 100 && value.sidebarOnly ? `[data-testid="dsh-config-dialog"]{background:${panel}!important}` : '',
+ // 启动页(Loadable / 全屏恢复页 / 预装引导)不属于内容区,但必须跟 navbar、侧边栏
+ // 用同一层 alpha,否则窗口背后只透出一半。
+ '[data-testid="dsh-shell-root"]>main{background:transparent!important}',
+ ].filter(Boolean).join('\n')
}
diff --git a/src/i18n/locales/en-US.json b/src/i18n/locales/en-US.json
index a1ee7530..deb0b282 100644
--- a/src/i18n/locales/en-US.json
+++ b/src/i18n/locales/en-US.json
@@ -131,7 +131,6 @@
"ui.port": "Port",
"ui.heap_limit": "Service memory limit",
"ui.heap_limit_auto": "Auto",
- "ui.zoom": "Zoom",
"ui.launch_on_login": "Launch app at login",
"ui.launch_on_login_hint": "Starts the desktop app after you sign in. Harness service startup is configured separately.",
"ui.close_action": "Close action",
@@ -181,7 +180,6 @@
"messages.port_restart_hint": "It takes effect after the service restarts. Restart now?",
"messages.launch_on_login_failed": "Failed to update launch at login",
"messages.close_action_failed": "Failed to update close action",
- "messages.zoom_save_failed": "Failed to save zoom",
"messages.cli_link_failed": "Failed to update CLI integration",
"messages.port_invalid": "Port must be an integer between 1 and 65535",
"messages.port_save_failed": "Failed to save port",
@@ -556,7 +554,7 @@
"buttons.close": "Close",
"remote.loading": "Loading remote interface…",
"config.appearance": "Appearance",
- "appearance.description": "Desktop colours and layout. Palettes follow your Light, Dark, or System preference.",
+ "appearance.description": "Device-local desktop colours, text scale, and layout. These settings are not synced to other Harness clients.",
"appearance.palette": "Colour palette",
"appearance.palette.default": "Default",
"appearance.palette.nord": "Nord",
@@ -566,13 +564,17 @@
"appearance.palette.github": "GitHub",
"appearance.palette.github-dimmed": "GitHub Dimmed",
"appearance.palette.github-high-contrast": "GitHub High Contrast",
+ "appearance.zoom": "Interface scale",
+ "appearance.zoom_description": "Adjust text and controls on this device without changing the server or phone display.",
"appearance.terminal": "Terminal mode",
"appearance.terminal_description": "Hide the sidebar while keeping the original fonts. Use the top-left sidebar button to reveal it.",
"appearance.transparency": "Enable native transparency",
"appearance.transparency_description": "Make the window background translucent so the desktop colours show through.",
- "appearance.sidebar_only": "Keep session area opaque",
+ "appearance.sidebar_only": "Keep content area opaque",
"appearance.opacity": "Background opacity",
"appearance.opacity_description": "Text and menus stay opaque. Desktop transparency depends on your window system.",
+ "appearance.blur": "Background blur",
+ "appearance.blur_description": "Use the system backdrop effect on Windows and macOS. Linux support depends on the compositor.",
"appearance.restart": "Quit Harness completely and reopen it to change the native transparency mode. Closing to the tray does not restart the app.",
"appearance.reset": "Restore defaults",
"appearance.save_failed": "Could not save appearance settings.",
diff --git a/src/i18n/locales/zh-CN.json b/src/i18n/locales/zh-CN.json
index 36d77332..4186941a 100644
--- a/src/i18n/locales/zh-CN.json
+++ b/src/i18n/locales/zh-CN.json
@@ -131,7 +131,6 @@
"ui.port": "服务端口",
"ui.heap_limit": "服务内存上限",
"ui.heap_limit_auto": "自动",
- "ui.zoom": "界面缩放",
"ui.launch_on_login": "开机自启动",
"ui.launch_on_login_hint": "登录系统后启动桌面应用;Harness 服务的自动运行配置与此项相互独立。",
"ui.close_action": "关闭行为",
@@ -181,7 +180,6 @@
"messages.port_restart_hint": "重启服务后生效,是否立即重启?",
"messages.launch_on_login_failed": "更新开机自启动设置失败",
"messages.close_action_failed": "更新关闭行为设置失败",
- "messages.zoom_save_failed": "保存缩放比例失败",
"messages.cli_link_failed": "更新命令行集成设置失败",
"messages.port_invalid": "端口必须是 1 到 65535 之间的整数",
"messages.port_save_failed": "保存端口失败",
@@ -556,7 +554,7 @@
"buttons.close": "关闭",
"remote.loading": "正在加载远端界面…",
"config.appearance": "外观",
- "appearance.description": "桌面配色与布局。配色跟随浅色、深色或系统主题。",
+ "appearance.description": "仅保存在本机的桌面配色、字号与布局,不会同步到其他 Harness 客户端。",
"appearance.palette": "配色方案",
"appearance.palette.default": "默认",
"appearance.palette.nord": "北欧",
@@ -566,13 +564,17 @@
"appearance.palette.github": "GitHub",
"appearance.palette.github-dimmed": "GitHub 柔和",
"appearance.palette.github-high-contrast": "GitHub 高对比度",
+ "appearance.zoom": "界面缩放",
+ "appearance.zoom_description": "只调整本机的文字和控件大小,不改变服务器或手机端显示。",
"appearance.terminal": "终端模式",
"appearance.terminal_description": "隐藏侧栏,保留原有字体。点击左上角侧栏按钮可重新展开。",
"appearance.transparency": "启用原生透明模式",
"appearance.transparency_description": "让窗口背景半透明,使桌面颜色透出。",
- "appearance.sidebar_only": "会话区域保持不透明",
+ "appearance.sidebar_only": "内容区域保持不透明",
"appearance.opacity": "背景不透明度",
"appearance.opacity_description": "文字和菜单保持不透明。桌面透明效果取决于窗口系统。",
+ "appearance.blur": "背景模糊",
+ "appearance.blur_description": "在 Windows 和 macOS 使用系统背景效果;Linux 效果取决于合成器。",
"appearance.restart": "请完全退出 Harness 后重新打开,以切换原生窗口透明模式。关闭到托盘不会重启应用。",
"appearance.reset": "恢复默认设置",
"appearance.save_failed": "无法保存外观设置。",
diff --git a/src/layout/components/iframe-notification.test.ts b/src/layout/components/iframe-notification.test.ts
index 87ab7eb9..5f43b517 100644
--- a/src/layout/components/iframe-notification.test.ts
+++ b/src/layout/components/iframe-notification.test.ts
@@ -13,7 +13,11 @@ const mocks = vi.hoisted(() => ({
}))
vi.mock('@choochmeque/tauri-plugin-notifications-api', () => mocks)
-vi.mock('@reause/core', () => ({ useEventListener: vi.fn() }))
+vi.mock('@reause/core', () => ({
+ useEventListener: vi.fn(),
+ useWatch: vi.fn(),
+ useTimeoutFn: () => ({ start: vi.fn(), stop: vi.fn() }),
+}))
vi.mock('react-i18next', () => ({ useTranslation: () => ({ t: (key: string) => key }) }))
vi.mock('valtio-define', () => ({ useStore: (value: unknown) => value }))
vi.mock('@/config/client', () => ({ queryClient: {} }))
diff --git a/src/layout/components/iframe.tsx b/src/layout/components/iframe.tsx
index fb9d41ea..17439491 100644
--- a/src/layout/components/iframe.tsx
+++ b/src/layout/components/iframe.tsx
@@ -9,7 +9,7 @@ import {
sendNotification,
} from '@choochmeque/tauri-plugin-notifications-api'
import { CircleExclamation } from '@gravity-ui/icons'
-import { useEventListener } from '@reause/core'
+import { useEventListener, useTimeoutFn, useWatch } from '@reause/core'
import { invoke } from '@tauri-apps/api/core'
import { getCurrentWindow } from '@tauri-apps/api/window'
import { useRef, useState } from 'react'
@@ -18,7 +18,6 @@ import { If } from 'react-if-lite'
import { useStore } from 'valtio-define'
import { queryClient } from '@/config/client'
import { queryKeys } from '@/config/query-keys'
-import { useAppearance } from '@/hooks/use-appearance'
import { useDshStyle } from '@/hooks/use-dsh-style'
import { useIframeMessage } from '@/hooks/use-iframe-message'
import { useIframePost } from '@/hooks/use-iframe-post'
@@ -29,7 +28,12 @@ import { useSyncVisibility } from '@/hooks/use-sync-visibility'
import { useZoomFactor } from '@/hooks/use-zoom-factor'
import { store } from '@/store'
import { zoomActionFromBridgeMessage, zoomActionFromShortcut } from '@/utils/zoom'
+import { appearanceBootCss, appearanceTranslucent, normalizeAppearance } from '../../../packages/dsh-tauri/src/shared/appearance'
import { Loadable } from './loadable'
+
+/** 启动期外观握手兜底:帧内接收器异常时也不让 iframe 永久藏住(远超正常握手耗时)。 */
+const APPEARANCE_HANDSHAKE_TIMEOUT = 4000
+
/** 可见性兜底轮询间隔:主路径是窗口 focus/resize 事件,5s 足以覆盖任务栏切换等场景 */
/**
@@ -209,9 +213,39 @@ export function Iframe({ iframeRef, srcOverride = null, borderTint = null }: Ifr
const remoteMode = srcOverride !== null && srcOverride !== ''
const [loadedUrl, setLoadedUrl] = useState('')
const remoteLoading = remoteMode && loadedUrl !== srcOverride
-
- const appearanceCss = useAppearance(iframeRef)
+ // 换帧(本地重挂 / 换远端隧道 / 重载)即视为新一代文档:旧文档的外观确认不能替它背书。
+ const frameKey = `${remoteMode ? srcOverride : 'local'}#${harness.iframeKey}`
+ const [bootFrame, setBootFrame] = useState<string | null>(null)
+ const appearance = normalizeAppearance(setting.appearance)
+ const translucent = (window as Window & { __DSH_TRANSPARENT__?: boolean }).__DSH_TRANSPARENT__ === true
+ && appearanceTranslucent(appearance)
+ const bootCss = translucent ? appearanceBootCss(appearance) : ''
const post = useIframePost(iframeRef)
+ // 握手兜底:帧内接收器异常时不能让 iframe 永久藏住,超时后按「未确认」直接揭开。
+ const appearancePending = translucent && bootFrame !== frameKey
+ const { start: armAppearanceFallback, stop: stopAppearanceFallback } = useTimeoutFn(
+ () => setBootFrame(frameKey),
+ APPEARANCE_HANDSHAKE_TIMEOUT,
+ { immediate: false },
+ )
+ useWatch([frameKey, remoteMode || harness.serviceHealthy], ([, mounted]) => {
+ setBootFrame(null)
+ if (mounted)
+ armAppearanceFallback()
+ else
+ stopAppearanceFallback()
+ }, { immediate: true })
+ // iframe 与外观投影同一次提交挂载:src 落定后立刻把启动期 CSS 交给帧内接收器
+ // (帧内自己也会 document-start 主动请求一次,两条通路互为兜底)。
+ useWatch(
+ [remoteMode ? srcOverride : harness.iframeSrc, bootCss],
+ ([src, css]) => {
+ if (!src)
+ return
+ post({ type: 'dsh://appearance', bootCss: css })
+ },
+ { immediate: true },
+ )
/** 待合并的按钮动作,按「tag + actionId」索引(见 `handleNotificationAction`)。 */
const pendingActionsRef = useRef(new Map<string, { payload: NotificationClickedPayload, timer: ReturnType<typeof setTimeout> }>())
@@ -239,11 +273,20 @@ export function Iframe({ iframeRef, srcOverride = null, borderTint = null }: Ifr
// iframe → 宿主:iframe 自身的桥共用一个监听器,按 `data.type` 分发
useIframeMessage<IframeBridgeMessage>(iframeRef, (data) => {
- // 帧内文档离开(帧内导航):旧确认立刻作废,等新文档自己重新自报(issue #705)
+ // 帧内文档离开(帧内导航):旧确认立刻作废,等新文档自己重新自报(issue #705);
+ // 外观确认同样作废,并重新隐蔽 iframe + 重挂兜底,避免旧样式作用在新文档上。
if (data.type === 'dsh://plugin-boot:leaving') {
+ setBootFrame(null)
+ armAppearanceFallback()
store.harness.markIframeLeaving()
return
}
+ // 帧内确认启动期外观已落盘:此刻可以安全揭开 iframe,不会闪出不透明 boot 页。
+ // (确认本身已由 `useAppearance` 记录,这里只负责把这一代标记为已确认。)
+ if (data.type === 'dsh://appearance:applied') {
+ setBootFrame(frameKey)
+ return
+ }
// 能走到这里说明帧内确实跑着 dsh 页面(来源与 origin 已由 hook 校验过),
// 与具体桥无关——据此确认 iframe 不是一张浏览器内部错误页(issue #705)。
store.harness.markIframeAlive()
@@ -525,7 +568,6 @@ export function Iframe({ iframeRef, srcOverride = null, borderTint = null }: Ifr
return (
<div className="relative min-h-0 flex-1">
- <style>{appearanceCss}</style>
<If
cond={remoteMode || harness.serviceHealthy}
else={<Loadable subtitle={t(harness.startupStatusKey)} />}
@@ -535,6 +577,10 @@ export function Iframe({ iframeRef, srcOverride = null, borderTint = null }: Ifr
ref={iframeRef}
data-testid="dsh-shell-iframe"
className="h-full w-full"
+ // 未确认收到启动期外观前先藏起来:帧内 boot 页(HARNESS + Loading plugins…)
+ // 会先按不透明画一帧,露出那一下比等待更刺眼。上面的 Loadable 与之逐项同构,
+ // 揭开时视觉无跳变,且有 4s 兜底不会永久藏住。
+ style={{ visibility: appearancePending || remoteLoading || harness.showIframeError ? 'hidden' : 'visible' }}
src={remoteMode ? srcOverride : harness.iframeSrc}
allow="accelerometer; ambient-light-sensor; autoplay; battery; camera; clipboard-read; clipboard-write; display-capture; document-domain; encrypted-media; fullscreen; gamepad; geolocation; gyroscope; hid; idle-detection; keyboard-map; magnetometer; microphone; midi; payment; picture-in-picture; publickey-credentials-get; screen-wake-lock; serial; speaker-selection; usb; web-share; xr-spatial-tracking"
sandbox="allow-same-origin allow-scripts allow-popups allow-forms allow-modals allow-downloads allow-storage-access-by-user-activation"
diff --git a/src/layout/components/loadable.tsx b/src/layout/components/loadable.tsx
index 6a19f2f4..5c64811e 100644
--- a/src/layout/components/loadable.tsx
+++ b/src/layout/components/loadable.tsx
@@ -59,7 +59,7 @@ export function Loadable({
const showPanel = hasLogs || percentage != null
return (
- <div className="flex h-full items-center justify-center bg-load-bg w-full" data-testid={testId}>
+ <div className="flex h-full items-center justify-center bg-startup w-full" data-testid={testId}>
<div className="flex w-[min(460px,88vw)] flex-col items-center gap-4 text-center -mt-[1px]">
{/* 加载态显示 spinner 时隐藏图标(官方 boot 页即无图标),避免与 spinner 重复突兀;仅失败态显示 */}
{/* 加载态显示 spinner 时隐藏图标(官方 boot 页即无图标),避免与 spinner 重复突兀;仅失败态显示 */}
diff --git a/src/layout/components/setup-preinstall.tsx b/src/layout/components/setup-preinstall.tsx
index fe2ca894..7142da96 100644
--- a/src/layout/components/setup-preinstall.tsx
+++ b/src/layout/components/setup-preinstall.tsx
@@ -332,7 +332,7 @@ export function PreinstallSetup() {
const failing = failures.length > 0
return (
- <div className="flex h-full w-full items-center justify-center bg-canvas">
+ <div className="flex h-full w-full items-center justify-center bg-startup">
<div className="flex w-[min(880px,92vw)] flex-col gap-4">
<header className="flex flex-col items-center gap-1 text-center">
<Typography type="h4" className="!text-ink">{t('preinstall.title')}</Typography>
diff --git a/src/layout/components/webview.tsx b/src/layout/components/webview.tsx
index c80c92ff..d3ac58b6 100644
--- a/src/layout/components/webview.tsx
+++ b/src/layout/components/webview.tsx
@@ -6,6 +6,7 @@ import { type } from '@tauri-apps/plugin-os'
import { useRef, useState } from 'react'
import { If } from 'react-if-lite'
import { useStore } from 'valtio-define'
+import { useAppearance } from '@/hooks/use-appearance'
import { DSH_VIEW_COMMANDS, shortcutHint, useDshShortcuts } from '@/hooks/use-dsh-shortcuts'
import { useDshStyle } from '@/hooks/use-dsh-style'
import { useIframeMessage } from '@/hooks/use-iframe-message'
@@ -27,6 +28,7 @@ interface NavBridgeMessage {
export function Webview() {
const [sidebarCollapsed, setSidebarCollapsed] = useState(false)
const iframeRef = useRef<HTMLIFrameElement>(null)
+ const appearanceCss = useAppearance(iframeRef)
const post = useIframePost(iframeRef)
const [dshStyle] = useDshStyle()
@@ -108,6 +110,8 @@ export function Webview() {
return (
<main className="relative flex flex-col min-h-0 flex-1" style={dshStyle.frame || {}}>
+ {/* 挂在 Iframe 外:启动页/预装引导/恢复页先于 Iframe 渲染,否则拿不到透明与调色板 token */}
+ <style>{appearanceCss}</style>
<Navbar onRemoteChange={handleRemoteChange} sidebarCollapsed={sidebarCollapsed} {...bridge} />
<div className="flex min-h-0 flex-1">
{renderContent()}
diff --git a/src/store/modules/setting/constants.ts b/src/store/modules/setting/constants.ts
index 036dbdeb..18de15e0 100644
--- a/src/store/modules/setting/constants.ts
+++ b/src/store/modules/setting/constants.ts
@@ -6,6 +6,10 @@ export const ZOOM_FACTOR_STEP = 0.1
export const ZOOM_FACTOR_MIN = 0.5
/** 缩放上限,与 Rust `ZOOM_FACTOR_MAX` 一致 */
export const ZOOM_FACTOR_MAX = 2
+export const ZOOM_FACTOR_OPTIONS = Array.from(
+ { length: Math.round((ZOOM_FACTOR_MAX - ZOOM_FACTOR_MIN) / ZOOM_FACTOR_STEP) + 1 },
+ (_, index) => Number((ZOOM_FACTOR_MIN + index * ZOOM_FACTOR_STEP).toFixed(1)),
+)
/** 服务内存上限下限(MB),与 Rust `HARNESS_HEAP_MIN_MB` 一致 */
export const HARNESS_HEAP_MIN_MB = 1024
/** 服务内存上限上限(MB),与 Rust `HARNESS_HEAP_MAX_MB` 一致 */
diff --git a/src/store/modules/setting/index.ts b/src/store/modules/setting/index.ts
index 5092c51c..8f146d40 100644
--- a/src/store/modules/setting/index.ts
+++ b/src/store/modules/setting/index.ts
@@ -1,2 +1,2 @@
-export { HARNESS_HEAP_MAX_MB, HARNESS_HEAP_MIN_MB } from './constants'
+export { HARNESS_HEAP_MAX_MB, HARNESS_HEAP_MIN_MB, ZOOM_FACTOR_DEFAULT, ZOOM_FACTOR_OPTIONS } from './constants'
export { setting } from './store'
diff --git a/src/store/modules/setting/store.test.ts b/src/store/modules/setting/store.test.ts
index b907debe..0350854f 100644
--- a/src/store/modules/setting/store.test.ts
+++ b/src/store/modules/setting/store.test.ts
@@ -26,7 +26,7 @@ let setting: (typeof import('./store'))['setting']
beforeEach(async () => {
vi.resetModules()
mocks.saved = {
- appearance: { palette: 'default', terminal: false, transparency: false, opacity: 100, sidebarOnly: false },
+ appearance: { palette: 'default', terminal: false, transparency: false, opacity: 100, blur: false, sidebarOnly: false },
zoom_factor: 1,
backup_include_credentials: true,
}
@@ -161,7 +161,7 @@ describe('settings synchronization across windows', () => {
mocks.invoke.mockRejectedValueOnce(new Error('native write failed'))
await expect(setting.update({ appearance: { ...setting.appearance, palette: 'github' } })).rejects.toThrow('native write failed')
expect(setting.appearance.palette).toBe('default')
- expect(mocks.saved.appearance).toEqual({ palette: 'default', terminal: false, transparency: false, opacity: 100, sidebarOnly: false })
+ expect(mocks.saved.appearance).toEqual({ palette: 'default', terminal: false, transparency: false, opacity: 100, blur: false, sidebarOnly: false })
expect(mocks.setItem).not.toHaveBeenCalled()
})
diff --git a/src/store/modules/setting/store.ts b/src/store/modules/setting/store.ts
index e1591006..1bdc98e5 100644
--- a/src/store/modules/setting/store.ts
+++ b/src/store/modules/setting/store.ts
@@ -24,6 +24,7 @@ export const setting = defineStore({
backup_retention_count: 10,
backup_include_credentials: false,
language: null as string | null,
+ hydrated: false,
}),
actions: {
async update(update: AppSettingUpdate): Promise<void> {
@@ -37,7 +38,7 @@ export const setting = defineStore({
await latestRefresh
return
}
- setting.$patch(value)
+ setting.$patch({ ...value, hydrated: true })
})
return latestRefresh
},
diff --git a/src/styles/main.css b/src/styles/main.css
index 429dba07..c835f3e8 100644
--- a/src/styles/main.css
+++ b/src/styles/main.css
@@ -72,6 +72,7 @@
--backdrop: rgba(0, 0, 0, 0.5);
/* === 壳层自有 token === */
--color-canvas: #151517; /* bg-base (bluish-950) */
+ --color-startup: #151517; /* 启动页底色:默认与画布同色,开启透明度时由外观投影接管 */
--color-panel: #1b1b1c; /* specific-sidebar-fill (bluish-900) */
--color-panel-2: #2c2c2e; /* bg-layer-2 (bluish-850) */
--color-panel-hover: #2c2c2e; /* sidebar-nav-item-hover (bluish-850) */
@@ -87,7 +88,6 @@
--color-scroll-thumb: rgba(84, 85, 87, 0.45); /* neutral-600 */
--color-scroll-thumb-strong: rgba(60, 60, 61, 0.6); /* neutral-700 */
/* 加载页 token:取值与官方 web shell boot 页(dsw alias token)逐项一致 */
- --color-load-bg: #151517;
--color-load-ink: #f9fafb;
--color-load-muted: #adb2b8;
--color-load-ring: rgba(255, 255, 255, 0.12);
@@ -112,6 +112,7 @@
html[data-theme="light"] {
--backdrop: rgba(0, 0, 0, 0.24);
--color-canvas: #ffffff; /* bg-base (bluish-00) */
+ --color-startup: #ffffff; /* 启动页底色:默认与画布同色 */
--color-panel: #f9fafb; /* specific-sidebar-fill (bluish-50) */
--color-panel-2: #f5f6f7; /* bg-module-platform / selector (bluish-60) */
--color-panel-hover: #f1f3f5; /* sidebar-nav-item-hover (bluish-75) */
@@ -126,7 +127,6 @@ html[data-theme="light"] {
--color-scroll-thumb: rgba(212, 212, 212, 0.8); /* neutral-300 */
--color-scroll-thumb-strong: rgba(229, 229, 229, 0.9); /* neutral-200 */
/* 加载页 token:light 主题对应官方 alias 值 */
- --color-load-bg: #ffffff;
--color-load-ink: #0f1115;
--color-load-muted: #81858c;
--color-load-ring: rgba(0, 0, 0, 0.1);
diff --git a/src/ui/config/appearance.test.tsx b/src/ui/config/appearance.test.tsx
index d2d5e59e..7b6c691b 100644
--- a/src/ui/config/appearance.test.tsx
+++ b/src/ui/config/appearance.test.tsx
@@ -26,7 +26,7 @@ function setup(fail = false, opacity = 70) {
mocks.setting.$patch(value)
})
mocks.setting = defineStore({
- state: () => ({ appearance: { palette: 'nord', terminal: false, opacity } }),
+ state: () => ({ appearance: { palette: 'nord', terminal: false, opacity }, zoom_factor: 1 }),
actions: { update },
})
const client = new QueryClient({ defaultOptions: { mutations: { retry: false } } })
@@ -54,6 +54,16 @@ describe('appearance settings controls', () => {
expect(screen.queryByRole('switch', { name: 'appearance.sidebar_only' })).toBeNull()
})
+ it('applies the transparent-mode defaults when native transparency is switched on', async () => {
+ const update = setup()
+ const toggle = screen.getByRole('switch', { name: 'appearance.transparency' })
+ fireEvent.click(toggle)
+ await waitFor(() => expect((toggle as HTMLInputElement).checked).toBe(false))
+ fireEvent.click(toggle)
+ await waitFor(() => expect(update).toHaveBeenLastCalledWith({ appearance: expect.objectContaining({ transparency: true, opacity: 80, blur: true, sidebarOnly: true }) }))
+ await waitFor(() => expect((screen.getByRole('switch', { name: 'appearance.sidebar_only' }) as HTMLInputElement).checked).toBe(true))
+ })
+
it('restores the saved slider value when persistence fails', async () => {
setup(true)
const slider = screen.getByRole('slider', { name: 'appearance.opacity' })
@@ -75,17 +85,31 @@ describe('appearance settings controls', () => {
await waitFor(() => expect((screen.getByRole('switch', { name: 'appearance.sidebar_only' }) as HTMLInputElement).checked).toBe(true))
})
+ it('persists blur in the same native appearance setting', async () => {
+ const update = setup()
+ fireEvent.click(screen.getByRole('switch', { name: 'appearance.blur' }))
+ await waitFor(() => expect(update).toHaveBeenLastCalledWith({ appearance: expect.objectContaining({ blur: true }) }))
+ })
+
+ it('exposes the existing device-local zoom in Appearance', async () => {
+ const update = setup()
+ const select = screen.getByTestId('dsh-appearance-zoom').closest('[data-slot="select"]')!.querySelector('select')!
+ fireEvent.change(select, { target: { value: '1.2' } })
+ await waitFor(() => expect(update).toHaveBeenLastCalledWith({ zoomFactor: 1.2 }))
+ expect(screen.getByText('appearance.zoom_description')).toBeTruthy()
+ })
+
it('provides an operable terminal switch and resets all preferences', async () => {
const update = setup()
const toggle = screen.getByRole('switch', { name: 'appearance.terminal' })
fireEvent.click(toggle)
- await waitFor(() => expect(update).toHaveBeenCalledWith({ appearance: { palette: 'nord', terminal: true, transparency: true, opacity: 70, sidebarOnly: false } }))
+ await waitFor(() => expect(update).toHaveBeenCalledWith({ appearance: { palette: 'nord', terminal: true, transparency: true, opacity: 70, blur: false, sidebarOnly: false } }))
await waitFor(() => expect((toggle as HTMLInputElement).checked).toBe(true))
expect(screen.getByTestId('dsh-appearance-restart').textContent).toBe('appearance.restart')
const reset = screen.getByRole('button', { name: 'appearance.reset' }) as HTMLButtonElement
await waitFor(() => expect(reset.disabled).toBe(false))
fireEvent.click(reset)
- await waitFor(() => expect(update).toHaveBeenLastCalledWith({ appearance: APPEARANCE_DEFAULTS }))
+ await waitFor(() => expect(update).toHaveBeenLastCalledWith({ appearance: APPEARANCE_DEFAULTS, zoomFactor: 1 }))
await waitFor(() => expect(screen.queryByTestId('dsh-appearance-restart')).toBeNull())
expect((toggle as HTMLInputElement).checked).toBe(false)
})
diff --git a/src/ui/config/appearance.tsx b/src/ui/config/appearance.tsx
index 71ee3bf0..3cf7ab57 100644
--- a/src/ui/config/appearance.tsx
+++ b/src/ui/config/appearance.tsx
@@ -1,3 +1,4 @@
+import type { AppSettingUpdate } from '@/store/modules/setting/types'
import { Alert, Button, Description, Label, ListBox, Select, Slider, Switch, Typography } from '@heroui/react'
import { useMutation } from '@tanstack/react-query'
import { useState } from 'react'
@@ -6,18 +7,22 @@ import { If } from 'react-if-lite'
import { useStore } from 'valtio-define'
import { Panel } from '@/components/panel'
import { store } from '@/store'
+import { ZOOM_FACTOR_DEFAULT, ZOOM_FACTOR_OPTIONS } from '@/store/modules/setting'
import { toast } from '@/utils/toast'
import { APPEARANCE_DEFAULTS, APPEARANCE_PALETTES, normalizeAppearance } from '../../../packages/dsh-tauri/src/shared/appearance'
+/** 打开「原生透明」时一并给出的初始组合:内容区保持不透明、背景 80%、开启模糊。 */
+const TRANSPARENCY_DEFAULTS = { opacity: 80, blur: true, sidebarOnly: true }
+
export function ConfigAppearance() {
const { t } = useTranslation()
- const { appearance: saved } = useStore(store.setting)
+ const { appearance: saved, zoom_factor: zoomFactor } = useStore(store.setting)
const appearance = normalizeAppearance(saved)
const [opacity, setOpacity] = useState<number>()
const transparent = (window as Window & { __DSH_TRANSPARENT__?: boolean }).__DSH_TRANSPARENT__ === true
const restartPending = appearance.transparency !== transparent
const { mutate: save, isPending } = useMutation({
- mutationFn: (value: typeof appearance) => store.setting.update({ appearance: normalizeAppearance(value) }),
+ mutationFn: (update: AppSettingUpdate) => store.setting.update(update),
onError: () => toast(t('appearance.save_failed'), { variant: 'danger' }),
})
@@ -32,7 +37,7 @@ export function ConfigAppearance() {
variant="secondary"
aria-label={t('appearance.palette')}
selectedKey={appearance.palette}
- onSelectionChange={key => save(normalizeAppearance({ ...appearance, palette: key }))}
+ onSelectionChange={key => save({ appearance: normalizeAppearance({ ...appearance, palette: key }) })}
isDisabled={isPending}
className="w-[180px]"
>
@@ -52,6 +57,35 @@ export function ConfigAppearance() {
</Select>
</div>
+ <div className="flex items-center justify-between gap-2">
+ <div>
+ <Typography type="body-sm" weight="medium">{t('appearance.zoom')}</Typography>
+ <Description>{t('appearance.zoom_description')}</Description>
+ </div>
+ <Select
+ variant="secondary"
+ aria-label={t('appearance.zoom')}
+ selectedKey={String(zoomFactor)}
+ onSelectionChange={key => save({ zoomFactor: Number(key) })}
+ isDisabled={isPending}
+ className="w-[80px]"
+ >
+ <Select.Trigger data-testid="dsh-appearance-zoom" className="min-h-8! h-8 py-0 items-center">
+ <Select.Value />
+ <Select.Indicator />
+ </Select.Trigger>
+ <Select.Popover>
+ <ListBox>
+ {ZOOM_FACTOR_OPTIONS.map(factor => (
+ <ListBox.Item className="min-h-8!" id={String(factor)} key={factor} textValue={`${Math.round(factor * 100)}%`} data-testid={`dsh-appearance-zoom-${factor}`}>
+ {`${Math.round(factor * 100)}%`}
+ </ListBox.Item>
+ ))}
+ </ListBox>
+ </Select.Popover>
+ </Select>
+ </div>
+
<div className="flex items-center justify-between gap-2">
<div>
<Typography type="body-sm" weight="medium">{t('appearance.terminal')}</Typography>
@@ -61,7 +95,7 @@ export function ConfigAppearance() {
aria-label={t('appearance.terminal')}
isSelected={appearance.terminal}
isDisabled={isPending}
- onChange={terminal => save({ ...appearance, terminal })}
+ onChange={terminal => save({ appearance: { ...appearance, terminal } })}
>
<Switch.Content data-testid="dsh-appearance-terminal">
<Switch.Control><Switch.Thumb /></Switch.Control>
@@ -82,7 +116,7 @@ export function ConfigAppearance() {
aria-label={t('appearance.transparency')}
isSelected={appearance.transparency}
isDisabled={isPending}
- onChange={transparency => save({ ...appearance, transparency })}
+ onChange={transparency => save({ appearance: { ...appearance, transparency, ...(transparency ? TRANSPARENCY_DEFAULTS : {}) } })}
>
<Switch.Content data-testid="dsh-appearance-transparency">
<Switch.Control><Switch.Thumb /></Switch.Control>
@@ -101,7 +135,7 @@ export function ConfigAppearance() {
aria-label={t('appearance.sidebar_only')}
isSelected={appearance.sidebarOnly}
isDisabled={isPending}
- onChange={sidebarOnly => save({ ...appearance, sidebarOnly })}
+ onChange={sidebarOnly => save({ appearance: { ...appearance, sidebarOnly } })}
>
<Switch.Content data-testid="dsh-appearance-sidebar-only">
<Switch.Control><Switch.Thumb /></Switch.Control>
@@ -117,7 +151,7 @@ export function ConfigAppearance() {
step={1}
isDisabled={isPending}
onChange={value => setOpacity(Number(value))}
- onChangeEnd={value => save({ ...appearance, opacity: Number(value) }, { onSettled: () => setOpacity(undefined) })}
+ onChangeEnd={value => save({ appearance: { ...appearance, opacity: Number(value) } }, { onSettled: () => setOpacity(undefined) })}
data-testid="dsh-appearance-opacity"
>
<Label>{t('appearance.opacity')}</Label>
@@ -128,6 +162,22 @@ export function ConfigAppearance() {
</Slider.Track>
</Slider>
</div>
+ <div className="flex items-center justify-between gap-2">
+ <div>
+ <Typography type="body-sm" weight="medium">{t('appearance.blur')}</Typography>
+ <Description>{t('appearance.blur_description')}</Description>
+ </div>
+ <Switch
+ aria-label={t('appearance.blur')}
+ isSelected={appearance.blur}
+ isDisabled={isPending}
+ onChange={blur => save({ appearance: { ...appearance, blur } })}
+ >
+ <Switch.Content data-testid="dsh-appearance-blur">
+ <Switch.Control><Switch.Thumb /></Switch.Control>
+ </Switch.Content>
+ </Switch>
+ </div>
</div>
<div className="border-t border-line/30" />
</If>
@@ -141,7 +191,7 @@ export function ConfigAppearance() {
</Alert>
</If>
- <Button variant="secondary" isDisabled={isPending} onPress={() => save(normalizeAppearance(APPEARANCE_DEFAULTS))} data-testid="dsh-appearance-reset">
+ <Button variant="secondary" isDisabled={isPending} onPress={() => save({ appearance: normalizeAppearance(APPEARANCE_DEFAULTS), zoomFactor: ZOOM_FACTOR_DEFAULT })} data-testid="dsh-appearance-reset">
{t('appearance.reset')}
</Button>
</div>
diff --git a/src/ui/config/debug.tsx b/src/ui/config/debug.tsx
index 902dd9ce..f8fdda18 100644
--- a/src/ui/config/debug.tsx
+++ b/src/ui/config/debug.tsx
@@ -20,8 +20,6 @@ import { useCoreProfileSwitch } from '@/ui/config/hooks/use-core-profile-switch'
import { writeClipboardText } from '@/utils/clipboard'
import { toast } from '@/utils/toast'
-const ZOOM_OPTIONS = Array.from({ length: 16 }, (_, index) => Number((0.5 + index * 0.1).toFixed(1)))
-
export interface CliLinkStatus {
enabled: boolean
shim_exists: boolean
@@ -67,7 +65,7 @@ export function ConfigDebug() {
void refreshInfo()
})
- const { port: savedPort, proxy_url: savedProxy, zoom_factor: zoomFactor, harness_max_heap_mb: savedHeapMb } = useStore(store.setting)
+ const { port: savedPort, proxy_url: savedProxy, harness_max_heap_mb: savedHeapMb } = useStore(store.setting)
const port = portInput ?? savedPort
const proxy = proxyInput ?? savedProxy
const heapValue = heapInput ?? String(savedHeapMb ?? '')
@@ -111,11 +109,6 @@ export function ConfigDebug() {
},
})
- const { mutate: onSetZoom } = useMutation({
- mutationFn: (zoomFactor: number) => store.setting.update({ zoomFactor }),
- onError: () => toast(t('messages.zoom_save_failed'), { variant: 'danger' }),
- })
-
const { mutate: onCopyServiceUrl } = useMutation({
mutationFn: async () => {
await invoke('copy_service_url')
@@ -387,36 +380,6 @@ export function ConfigDebug() {
</Select.Popover>
</Select>
</div>
- <div className="flex items-center justify-between">
- <span className="text-xs font-medium text-ink">{t('ui.zoom')}</span>
- <Select
- variant="secondary"
- selectedKey={String(zoomFactor)}
- onSelectionChange={key => onSetZoom(Number(key))}
- className="w-[80px]"
- aria-label={t('ui.zoom')}
- >
- <Select.Trigger className="min-h-8! h-8 py-0 items-center">
- <Select.Value />
- <Select.Indicator />
- </Select.Trigger>
- <Select.Popover>
- <ListBox>
- {ZOOM_OPTIONS.map(zoomFactor => (
- <ListBox.Item
- className="min-h-8!"
- id={String(zoomFactor)}
- key={zoomFactor}
- textValue={`${Math.round(zoomFactor * 100)}%`}
- >
- {`${Math.round(zoomFactor * 100)}%`}
- </ListBox.Item>
- ))}
- </ListBox>
- </Select.Popover>
- </Select>
- </div>
-
<div className="border-t border-line/30" />
<div className="flex items-center justify-between gap-2">
diff --git a/src/ui/plugin/recovery.tsx b/src/ui/plugin/recovery.tsx
index d93479e0..8a4fd25b 100644
--- a/src/ui/plugin/recovery.tsx
+++ b/src/ui/plugin/recovery.tsx
@@ -86,13 +86,13 @@ export function Recovery({ fullScreen = false }: { fullScreen?: boolean }) {
return (
<div
className={fullScreen
- ? 'flex h-full w-full items-center justify-center overflow-auto bg-canvas p-6'
+ ? 'flex h-full w-full items-center justify-center overflow-auto bg-startup p-6'
: 'fixed inset-0 z-50 flex items-center justify-center bg-backdrop p-4'}
>
<div className={`w-full ${fullScreen ? 'max-w-[640px]' : 'max-w-[560px]'}`}>
{/* 运行期弹窗必须是**不透明**面板:`bg-panel2/40` 只有 40% 不透明度,页面内容会直接
- 透出来(表现为「弹窗透明、与页面内容重叠」);全屏恢复页底下是实心 `bg-canvas`,
- 半透明面板才是想要的层次感,故只在非 fullScreen 分支换成实心 `bg-panel`。 */}
+ 透出来(表现为「弹窗透明、与页面内容重叠」);全屏恢复页底下是与 navbar 同 alpha
+ 的启动底色,半透明面板才是想要的层次感,故只在非 fullScreen 分支换成实心 `bg-panel`。 */}
<div className={fullScreen
? 'rounded-xl border border-line bg-panel2/40 p-6'
: 'rounded-xl border border-line bg-panel p-6 shadow-lg'}
diff --git a/tailwind.config.js b/tailwind.config.js
index d1e5f147..b193b4b9 100644
--- a/tailwind.config.js
+++ b/tailwind.config.js
@@ -25,10 +25,12 @@ export default {
'log-ink': 'var(--color-log-ink)',
// 加载页 token:与主色不同,必须在此注册才会生成对应工具类
// (漏掉会整条回退 currentColor,spinner 变成同色整圈、看不出旋转)
- 'load-bg': 'var(--color-load-bg)',
'load-ink': 'var(--color-load-ink)',
'load-muted': 'var(--color-load-muted)',
'load-ring': 'var(--color-load-ring)',
+ // 启动页底色:默认等于画布色,开启透明度时由外观投影换成与 navbar 同 alpha 的
+ // 启动填充(见 src/hooks/use-appearance.ts 的 --color-startup)
+ 'startup': 'var(--color-startup)',
// 按钮 token:官方 dsw alias 中性色(非蓝色),同样需注册才能生成工具类
'btn-fill': 'var(--color-btn-fill)',
'btn-fill-hover': 'var(--color-btn-fill-hover)',
diff --git a/test/appearance-boot.test.ts b/test/appearance-boot.test.ts
new file mode 100644
index 00000000..3577d497
--- /dev/null
+++ b/test/appearance-boot.test.ts
@@ -0,0 +1,207 @@
+import { readFileSync } from 'node:fs'
+import { createContext, runInContext } from 'node:vm'
+import { describe, expect, it, vi } from 'vitest'
+
+/**
+ * 真实执行 `src-tauri/src/desktop/appearance.js.inc`(document-start 注入的启动期外观
+ * 接收器),在受控的帧内上下文里验证三件事:
+ *
+ * 1. 跨源回发:宿主是 `tauri://localhost` / `http://tauri.localhost`,帧内是
+ * `http://127.0.0.1:<port>`,回发一律 `'*'`——用帧内 `location.origin` 会让请求静默
+ * 丢失(表现为 boot 页永远收不到 CSS、宿主一直等不到 ack)。
+ * 2. 只写独立 head `<style>`:boot 节点由官方 React 树持有(BootHandoff 只交接
+ * className/innerHTML,额外 inline style 会触发 hydration 不匹配),脚本不得碰它。
+ * 3. 同一份 CSS 只 ack 一次;离开的文档由 pagehide 撤销,新文档自己重新请求。
+ */
+const SOURCE = readFileSync(new URL('../src-tauri/src/desktop/appearance.js.inc', import.meta.url), 'utf8')
+
+interface FakeNode {
+ id: string
+ textContent: string
+ children: FakeNode[]
+ removed: boolean
+ appendChild: (child: FakeNode) => void
+ remove: () => void
+}
+
+function fakeNode(): FakeNode {
+ return {
+ id: '',
+ textContent: '',
+ children: [],
+ removed: false,
+ appendChild(child: FakeNode) {
+ this.children.push(child)
+ },
+ remove() {
+ this.removed = true
+ },
+ }
+}
+
+interface HarnessOptions {
+ /** parent === top:壳层自己的顶层文档,脚本必须立刻退出。 */
+ nestedFrame?: boolean
+}
+
+function harness(options: HarnessOptions = {}) {
+ const states: Array<Record<string, unknown>> = []
+ const created: FakeNode[] = []
+ const listeners = new Map<string, (event: unknown) => void>()
+ const head = fakeNode()
+ const documentElement = fakeNode()
+
+ const document = {
+ get head() {
+ return head
+ },
+ get documentElement() {
+ return documentElement
+ },
+ getElementById(id: string) {
+ return created.find(node => node.id === id && !node.removed) ?? null
+ },
+ createElement() {
+ const node = fakeNode()
+ created.push(node)
+ return node
+ },
+ }
+
+ const parentWindow = {
+ postMessage: vi.fn((message: Record<string, unknown>, targetOrigin?: string) => {
+ states.push({ ...message, targetOrigin })
+ }),
+ }
+
+ // 帧内脚本同时引用裸 `parent`、裸 `window` 与 `window.parent`,三者必须是同一个对象。
+ // 直达宿主的帧里 `parent === top`(真实浏览器同样如此:宿主就是顶层窗口);顶层壳层
+ // 文档与嵌套帧的 parent/top 关系不同,脚本据此退出。
+ const context: Record<string, unknown> = {
+ document,
+ location: { origin: 'http://127.0.0.1:3081' },
+ addEventListener(type: string, handler: (event: unknown) => void) {
+ listeners.set(type, handler)
+ },
+ parent: parentWindow,
+ }
+ context.top = parentWindow
+ context.window = context
+ context.self = context
+ if (options.nestedFrame) {
+ context.parent = { __dshPage: true }
+ context.top = parentWindow
+ }
+
+ runInContext(SOURCE, createContext(context), { filename: 'appearance.js.inc' })
+
+ function bootStyle() {
+ return created.find(node => node.id === 'dsh-tauri:boot-appearance' && !node.removed) ?? null
+ }
+ function deliver(data: unknown, source: unknown = parentWindow, origin = 'tauri://localhost') {
+ const handler = listeners.get('message')
+ if (!handler)
+ throw new Error('message listener was not registered')
+ handler({ source, origin, data })
+ }
+ function fire(type: string) {
+ const handler = listeners.get(type)
+ if (!handler)
+ throw new Error(`${type} listener was not registered`)
+ handler({})
+ }
+ return { states, created, context, parentWindow, bootStyle, deliver, fire, listenerCount: () => listeners.size }
+}
+
+describe('appearance boot bootstrap (in-frame receiver)', () => {
+ it('asks the host once for the boot projection through the cross-origin-safe wildcard target', () => {
+ const frame = harness()
+ expect(frame.states).toEqual([{ source: 'dsh-desktop', type: 'dsh://appearance:request', targetOrigin: '*' }])
+ })
+
+ it('stays out of frames that are not the host’s own embedded layer', () => {
+ // 直达宿主的帧就是 `parent === top` 的那一层(VM 里两端都指向宿主代理对象),
+ // 它必须开口说话;dsh 应用内部再嵌套的 frame(parent 是 dsh 页面、top 是宿主)
+ // 必须完全静默,否则会把宿主外观消息当成自己该处理的东西。
+ const embedded = harness()
+ expect(embedded.states).toHaveLength(1)
+ embedded.deliver({ source: 'dsh-desktop', type: 'dsh://appearance', bootCss: 'x' })
+ expect(embedded.bootStyle()?.textContent).toBe('x')
+
+ const nested = harness({ nestedFrame: true })
+ expect(nested.states).toHaveLength(0)
+ expect(nested.context.__dsh_appearance_bootstrap__).toBe(true)
+ // 完全静默:连消息/生命周期监听器都不注册,宿主外观消息不会被它处理。
+ expect(nested.listenerCount()).toBe(0)
+ expect(nested.bootStyle()).toBeNull()
+ expect(nested.parentWindow.postMessage).not.toHaveBeenCalled()
+ })
+
+ it('is idempotent when the host injects the script twice', () => {
+ const frame = harness()
+ expect(() => runInContext(SOURCE, createContext(frame.context), { filename: 'appearance.js.inc' })).not.toThrow()
+ expect(frame.states).toHaveLength(1)
+ })
+
+ it('applies the delivered CSS to an isolated head style and acknowledges exactly once', () => {
+ const frame = harness()
+ const css = 'html,body{background:transparent!important}'
+ frame.deliver({ source: 'dsh-desktop', type: 'dsh://appearance', bootCss: css })
+ expect(frame.bootStyle()?.textContent).toBe(css)
+ expect(frame.bootStyle()?.id).toBe('dsh-tauri:boot-appearance')
+ expect(frame.parentWindow.postMessage).toHaveBeenLastCalledWith({ source: 'dsh-desktop', type: 'dsh://appearance:applied' }, '*')
+ const calls = frame.parentWindow.postMessage.mock.calls.length
+ frame.deliver({ source: 'dsh-desktop', type: 'dsh://appearance', bootCss: css })
+ expect(frame.parentWindow.postMessage.mock.calls.length).toBe(calls)
+ })
+
+ it('clears the frame stylesheet when the host projects an empty boot CSS', () => {
+ const frame = harness()
+ frame.deliver({ source: 'dsh-desktop', type: 'dsh://appearance', bootCss: 'x{color:red}' })
+ frame.deliver({ source: 'dsh-desktop', type: 'dsh://appearance', bootCss: '' })
+ expect(frame.bootStyle()?.textContent).toBe('')
+ })
+
+ it.each([
+ ['a non-parent window', { source: 'dsh-desktop', type: 'dsh://appearance', bootCss: 'x' }, { __sibling: true }],
+ ['a message without the host marker', { type: 'dsh://appearance', bootCss: 'x' }, undefined],
+ ['an unrelated bridge message', { source: 'dsh-desktop', type: 'dsh://sidebar:toggle' }, undefined],
+ ['a non-object payload', 'dsh://appearance', undefined],
+ ])('ignores %s', (_label, data, source) => {
+ const frame = harness()
+ frame.deliver(data, source ?? frame.parentWindow)
+ expect(frame.bootStyle()).toBeNull()
+ expect(frame.parentWindow.postMessage).not.toHaveBeenCalledWith(expect.objectContaining({ type: 'dsh://appearance:applied' }), expect.anything())
+ })
+
+ it('drops the frame stylesheet on pagehide so a navigated document starts clean', () => {
+ const frame = harness()
+ frame.deliver({ source: 'dsh-desktop', type: 'dsh://appearance', bootCss: 'x{color:red}' })
+ expect(frame.bootStyle()?.textContent).toBe('x{color:red}')
+ const before = frame.states.length
+ frame.fire('pagehide')
+ expect(frame.bootStyle()).toBeNull()
+ // pagehide 只负责撤销:不再重试,新文档自己会重新请求(bfcache 还原走 pageshow)。
+ expect(frame.states.length).toBe(before)
+ // 新文档的握手必须被重新接受:旧文档的确认不替它背书。
+ frame.deliver({ source: 'dsh-desktop', type: 'dsh://appearance', bootCss: 'y{color:blue}' })
+ expect(frame.bootStyle()?.textContent).toBe('y{color:blue}')
+ expect(frame.created.filter(node => node.id === 'dsh-tauri:boot-appearance')).toHaveLength(2)
+ })
+
+ it('re-handshakes after a bfcache restore so a re-mounted boot page is styled again', () => {
+ const frame = harness()
+ frame.deliver({ source: 'dsh-desktop', type: 'dsh://appearance', bootCss: 'x' })
+ const before = frame.states.length
+ frame.fire('pageshow')
+ expect(frame.states.length).toBeGreaterThan(before)
+ expect(frame.states.at(-1)).toEqual({ source: 'dsh-desktop', type: 'dsh://appearance:request', targetOrigin: '*' })
+ })
+
+ it('never touches the boot node itself (hydration safety)', () => {
+ expect(SOURCE).not.toContain('data-dsh-boot')
+ expect(SOURCE).not.toContain('style.background')
+ expect(SOURCE).not.toContain('window.location.origin')
+ expect(SOURCE).not.toContain('location.reload')
+ })
+})
diff --git a/test/e2e/desktop/boot.e2e.ts b/test/e2e/desktop/boot.e2e.ts
index 1a1c04a5..0c40fb0f 100644
--- a/test/e2e/desktop/boot.e2e.ts
+++ b/test/e2e/desktop/boot.e2e.ts
@@ -146,12 +146,15 @@ describe.skipIf(process.platform === 'darwin')('桌面端启动冒烟', () => {
await element.waitForClickable()
await element.click()
}
- async function appearance() {
+ async function config() {
return browser.execute(async () => {
- const bridge = (window as unknown as { __TAURI_INTERNALS__: { invoke: (command: string) => Promise<{ appearance: { palette: string, terminal: boolean, transparency: boolean, opacity: number, sidebarOnly: boolean } }> } }).__TAURI_INTERNALS__
- return (await bridge.invoke('get_app_config')).appearance
+ const bridge = (window as unknown as { __TAURI_INTERNALS__: { invoke: (command: string) => Promise<{ zoom_factor: number, appearance: { palette: string, terminal: boolean, transparency: boolean, opacity: number, blur: boolean, sidebarOnly: boolean } }> } }).__TAURI_INTERNALS__
+ return bridge.invoke('get_app_config')
})
}
+ async function appearance() {
+ return (await config()).appearance
+ }
await click('dsh-navbar-menu-config')
await click('dsh-navbar-item-appearance')
await click('dsh-appearance-palette')
@@ -166,15 +169,24 @@ describe.skipIf(process.platform === 'darwin')('桌面端启动冒烟', () => {
await transparency.waitForEnabled()
await transparency.click()
await browser.waitUntil(async () => (await appearance()).transparency)
+ expect(await appearance(), '开启原生透明未应用默认组合').toEqual({ palette: 'nord', terminal: true, transparency: true, opacity: 80, blur: true, sidebarOnly: true })
const opacity = await browser.$('[data-testid="dsh-appearance-opacity"] input[type="range"]')
await opacity.waitForEnabled()
await browser.execute(() => document.querySelector<HTMLInputElement>('[data-testid="dsh-appearance-opacity"] input[type="range"]')!.focus())
await browser.keys(Key.ArrowLeft)
- await browser.waitUntil(async () => (await appearance()).opacity === 99, { timeoutMsg: '原生设置未保存滑块的 99% 不透明度' })
- expect(await appearance(), '原生设置与所选外观不一致').toEqual({ palette: 'nord', terminal: true, transparency: true, opacity: 99, sidebarOnly: false })
+ await browser.waitUntil(async () => (await appearance()).opacity === 79, { timeoutMsg: '原生设置未保存滑块的 79% 不透明度' })
+ const sidebarOnly = await browser.$('[data-testid="dsh-appearance-sidebar-only"] input[role="switch"]')
+ await sidebarOnly.waitForEnabled()
+ await sidebarOnly.click()
+ await browser.waitUntil(async () => !(await appearance()).sidebarOnly, { timeoutMsg: '原生设置未保存内容区不透明开关' })
+ await click('dsh-appearance-zoom')
+ await click('dsh-appearance-zoom-1.2')
+ await browser.waitUntil(async () => (await config()).zoom_factor === 1.2, { timeoutMsg: '本机界面缩放未从外观面板保存' })
+ expect(await appearance(), '原生设置与所选外观不一致').toEqual({ palette: 'nord', terminal: true, transparency: true, opacity: 79, blur: true, sidebarOnly: false })
await click('dsh-appearance-reset')
await browser.waitUntil(async () => (await appearance()).palette === 'default', { timeoutMsg: '原生外观设置未恢复默认值' })
- expect(await appearance(), '重置未还原完整原生外观设置').toEqual({ palette: 'default', terminal: false, transparency: false, opacity: 100, sidebarOnly: false })
+ expect(await appearance(), '重置未还原完整原生外观设置').toEqual({ palette: 'default', terminal: false, transparency: false, opacity: 100, blur: false, sidebarOnly: false })
+ expect((await config()).zoom_factor, '重置未还原本机界面缩放').toBe(1)
await click('dsh-config-dialog-close')
})