DeepSeek Harness Tauri 桌面版 | Only 8mb installer, zero environment setup, preset plugins, Windows / macOS / Linux.
feat: add lightweight built-in appearance settings (#831)
SkanderBotb74f26ee1145
diff --git a/README.en.md b/README.en.mdindex 054b993e..63a618df 100644--- a/README.en.md+++ b/README.en.md@@ -45,6 +45,8 @@- ⌨️ **CLI integration** — Managed `dsh` / `pnpm` shims, not a global npm core installation.- 🐾 **Desktop pets** — Pets / Codex resources, pack imports, and conversation activity; preset media comes from remote hosts.+**Settings → Appearance** offers Default, Nord, Solarized, Forest, Amber, GitHub, GitHub Dimmed, and GitHub High Contrast palettes that follow the existing Light/Dark/System preference. Terminal mode keeps the original fonts and hides the sidebar; the top-left button reveals it. Enable native transparency to show the 20–100% background opacity slider and the option to keep the session area opaque. Text and menus stay opaque. Setting opacity to 100% does not disable native transparency. Enabling or disabling native transparency requires fully quitting and reopening the app, and the effect depends on the window system. Restore defaults resets all appearance settings.+## Built-in pluginsThe 11 first-party plugins distributed with desktop resources:diff --git a/README.es.md b/README.es.mdindex f839b4b9..4a46b1db 100644--- a/README.es.md+++ b/README.es.md@@ -45,6 +45,8 @@- ⌨️ **Integración con la terminal** — Shims administrados de `dsh` / `pnpm`, no una instalación global del núcleo por npm.- 🐾 **Mascotas de escritorio** — Recursos Pets / Codex, importación de paquetes y actividad de conversaciones; los recursos predefinidos son remotos.+**Settings → Appearance** ofrece las paletas Default, Nord, Solarized, Forest, Amber, GitHub, GitHub Dimmed y GitHub High Contrast, que siguen la preferencia de tema claro, oscuro o del sistema. El modo terminal conserva las fuentes originales y oculta la barra lateral; el botón superior izquierdo permite mostrarla. Al activar la transparencia nativa, aparece un deslizador de opacidad del 20 al 100% y una opción para mantener opaca el área de sesión. El texto y los menús permanecen opacos. Elegir el 100% no desactiva la transparencia nativa. Para activar o desactivar la transparencia nativa, cerrá la aplicación por completo y volvé a abrirla; el efecto depende del sistema de ventanas. Restore defaults restablece todos los ajustes de apariencia.+## Plugins integradosLos 11 plugins propios distribuidos con los recursos del escritorio:diff --git a/README.md b/README.mdindex 02801b52..9bff0fa0 100644--- a/README.md+++ b/README.md@@ -45,6 +45,8 @@- ⌨️ **命令行集成** — 通过托管 shim 提供 `dsh` / `pnpm`,不是全局 npm 内核安装。- 🐾 **桌宠** — Pets / Codex 资源管理、资源包导入与会话状态展示;预设素材来自远端。+“设置 → 外观”提供默认、北欧、日光、森林、琥珀、GitHub、GitHub 柔和和 GitHub 高对比度配色,跟随现有浅色/深色/系统主题。终端模式保留原有字体并隐藏侧栏,左上角按钮可重新展开。启用原生透明模式后,可通过滑块将背景不透明度设为 20–100%,也可选择让会话区域保持不透明。文字和菜单保持不透明,100% 不透明度不会关闭原生透明模式;启用或关闭原生透明模式后需完全退出并重新打开应用,效果取决于窗口系统。所有外观设置均可一键恢复默认。+## 内置插件随桌面资源分发的 11 个第一方插件:diff --git a/THIRD_PARTY_NOTICES.md b/THIRD_PARTY_NOTICES.mdindex 110023d8..7c2b149f 100644--- a/THIRD_PARTY_NOTICES.md+++ b/THIRD_PARTY_NOTICES.md@@ -23,3 +23,4 @@| `packages/dsh-tauri-ui` | [deepseek-ai/deepseek-harness](https://github.com/deepseek-ai/deepseek-harness) | `dsh-v0.2.0-rc.2` | `639ed015397290b3745d163aafe02ffee4aa3f84` | `source/deepseek-harness` | [THIRD_PARTY_NOTICES.md](packages/dsh-tauri-ui/THIRD_PARTY_NOTICES.md) || `packages/dsh-tauri-ui-playground` | [deepseek-ai/deepseek-harness](https://github.com/deepseek-ai/deepseek-harness) | `dsh-v0.2.0-rc.2` | `639ed015397290b3745d163aafe02ffee4aa3f84` | `source/deepseek-harness` | [THIRD_PARTY_NOTICES.md](packages/dsh-tauri-ui-playground/THIRD_PARTY_NOTICES.md) || `packages/dsh-tauri-worktree` | [deepseek-ai/deepseek-harness](https://github.com/deepseek-ai/deepseek-harness) | `dsh-v0.2.0-rc.2` | `639ed015397290b3745d163aafe02ffee4aa3f84` | `source/deepseek-harness` | [THIRD_PARTY_NOTICES.md](packages/dsh-tauri-worktree/THIRD_PARTY_NOTICES.md) |+| `packages/dsh-tauri` | [primer/primitives](https://github.com/primer/primitives) | — | `f48bc063f7bc0fb3e447386a8c259650ce46dea8` | — | [THIRD_PARTY_NOTICES.md](packages/dsh-tauri/THIRD_PARTY_NOTICES.md) |diff --git a/packages/dsh-tauri/THIRD_PARTY_NOTICES.md b/packages/dsh-tauri/THIRD_PARTY_NOTICES.mdindex dc725b77..28c3b39d 100644--- a/packages/dsh-tauri/THIRD_PARTY_NOTICES.md+++ b/packages/dsh-tauri/THIRD_PARTY_NOTICES.md@@ -49,3 +49,35 @@ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THESOFTWARE.```++## primer/primitives++- Repository: <https://github.com/primer/primitives>+- Revision: `f48bc063f7bc0fb3e447386a8c259650ce46dea8`+- License: MIT — Copyright (c) 2018 GitHub Inc.+- Derived: GitHub palette constants in `src/shared/appearance.ts`, from `src/tokens/base/color/{dark,light}` and `src/tokens/functional/color/{bgColor,fgColor,borderColor}.json5`.+- Adaptation: GitHub Dimmed uses the standard GitHub light palette in light mode. Its dark link blue is brightened to meet 4.5:1 on all three DSH surfaces. High Contrast text meets 7:1 on opaque palette surfaces; transparency depends on the background behind the window. Only color constants are bundled, with no Primer runtime dependency.++```text+The MIT License (MIT)++Copyright (c) 2018 GitHub Inc.++Permission is hereby granted, free of charge, to any person obtaining a copy+of this software and associated documentation files (the "Software"), to deal+in the Software without restriction, including without limitation the rights+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell+copies of the Software, and to permit persons to whom the Software is+furnished to do so, subject to the following conditions:++The above copyright notice and this permission notice shall be included in all+copies or substantial portions of the Software.++THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE+SOFTWARE.+```diff --git a/packages/dsh-tauri/src/client/apply.test.ts b/packages/dsh-tauri/src/client/apply.test.tsindex 0eb7fae0..2ef24887 100644--- a/packages/dsh-tauri/src/client/apply.test.ts+++ b/packages/dsh-tauri/src/client/apply.test.ts@@ -11,6 +11,7 @@ import { apply } from './apply'// effect 标签是 `ctx.effect` 的卸载日志标识:与 `client/apply.ts` 逐字一致。const EXPECTED_LABELS = [+ 'dsh-tauri: appearance','dsh-tauri: style (sidebar background)','dsh-tauri: sidebar (toggle command + collapsed report)','dsh-tauri: navigation (new session, add workspace)',diff --git a/packages/dsh-tauri/src/client/apply.ts b/packages/dsh-tauri/src/client/apply.tsindex 68aeca16..30d7fe1a 100644--- a/packages/dsh-tauri/src/client/apply.ts+++ b/packages/dsh-tauri/src/client/apply.ts@@ -12,6 +12,7 @@*/import type { ClientContext } from './types'import { accountSignInFeature } from './register/account'+import { registerAppearance } from './register/appearance'import { navigationFeature } from './register/navigation'import { shortcutsFeature } from './register/shortcuts'import { sidebarFeature } from './register/sidebar'@@ -26,6 +27,7 @@ const ZOOM_SHORTCUT_EFFECT = 'dsh-tauri: zoom shortcuts (ctrl/cmd +/-/0)'const SIDEBAR_TWEAKS_EFFECT = 'dsh-tauri: sidebar tweaks (hide collapse toggle, center brand)'const STYLE_EFFECT = 'dsh-tauri: style (sidebar background)'const ACCOUNT_SIGN_IN_EFFECT = 'dsh-tauri: account sign-in (auto-open the authorize url)'+const APPEARANCE_EFFECT = 'dsh-tauri: appearance'const SHORTCUTS_EFFECT = 'dsh-tauri: shortcuts (catalog report + edit commands)'/** 插件体:注册侧边栏桥、导航命令、缩放快捷键、账号登录接管与侧边栏 UI 微调。 */export function apply(ctx: ClientContext): void {@@ -33,6 +35,7 @@ export function apply(ctx: ClientContext): void {if (typeof window === 'undefined' || typeof document === 'undefined' || window.parent === window)return+ ctx.effect(registerAppearance, APPEARANCE_EFFECT)ctx.effect(registerStyle, STYLE_EFFECT)ctx.effect(sidebarFeature, SIDEBAR_TOGGLE_EFFECT)ctx.effect(navigationFeature, NAVIGATION_EFFECT)diff --git a/packages/dsh-tauri/src/client/index.ts b/packages/dsh-tauri/src/client/index.tsindex 5bd32bd3..10919309 100644--- a/packages/dsh-tauri/src/client/index.ts+++ b/packages/dsh-tauri/src/client/index.ts@@ -35,5 +35,4 @@ export type * from './types/tauri'export const name = PLUGIN_ID-/** 客户端服务依赖:layout(侧边栏切换)。 */-export const inject = ['layout']+export const inject = ['layout', 'theme']diff --git a/packages/dsh-tauri/src/client/register/appearance.test.ts b/packages/dsh-tauri/src/client/register/appearance.test.tsnew file mode 100644index 00000000..40469508--- /dev/null+++ b/packages/dsh-tauri/src/client/register/appearance.test.ts@@ -0,0 +1,133 @@+// @vitest-environment jsdom+import type { ClientContext } from '../types'+import { afterEach, describe, expect, it, vi } from 'vitest'+import { registerAppearance } from './appearance'++const disposers: Array<() => void> = []++afterEach(() => {+ disposers.splice(0).forEach(dispose => dispose())+ document.body.replaceChildren()+ document.head.replaceChildren()+ vi.restoreAllMocks()+ vi.unstubAllGlobals()+})++function setup() {+ document.body.innerHTML = '<main style="grid-template-columns:280px minmax(400px, 1fr) minmax(0px, 350px)"><aside data-slot="sidebar"></aside><div></div><aside></aside><div data-shell-overlay></div></main>'+ const frame = document.querySelector('main')!+ const listeners = new Set<() => void>()+ let scheme: 'dark' | 'light' = 'dark'+ const retract = vi.fn()+ const theme = {+ getTheme: () => ({ active: { colorScheme: scheme } }),+ overrideTokens: vi.fn((_source: string, _tokens: Record<string, unknown>) => retract),+ }+ const ctx = {+ get: (name: string) => name === 'theme' ? theme : undefined,+ layout: { toggleSidebar: vi.fn(() => frame.toggleAttribute('data-sidebar-collapsed')) },+ on: (_event: string, callback: () => void) => {+ listeners.add(callback)+ return () => listeners.delete(callback)+ },+ }+ const post = vi.fn()+ vi.stubGlobal('parent', { postMessage: post })+ disposers.push(registerAppearance.call(ctx as unknown as ClientContext))+ function send(appearance: unknown, source: MessageEventSource = window.parent) {+ window.dispatchEvent(new MessageEvent('message', { source, data: { type: 'dsh://appearance', appearance } }))+ }+ return { frame, ctx, theme, retract, post, send, listeners, setScheme(value: 'dark' | 'light') {+ scheme = value+ listeners.forEach(fn => fn())+ } }+}++describe('desktop appearance bridge', () => {+ it('requests initial settings once and leaves defaults and layout untouched', () => {+ const { post, send, ctx, theme } = setup()+ expect(post.mock.calls[0][0]).toMatchObject({ type: 'dsh://appearance:ready' })+ send({})+ expect(theme.overrideTokens).not.toHaveBeenCalled()+ expect(ctx.layout.toggleSidebar).not.toHaveBeenCalled()+ expect(document.querySelector('style')!.textContent).toBe('')+ })++ it('ignores messages from windows other than the desktop parent', () => {+ const { send, theme } = setup()+ send({ palette: 'nord' }, {} as MessageEventSource)+ expect(theme.overrideTokens).not.toHaveBeenCalled()+ })++ it('applies a palette once and retracts it on reset', () => {+ const { send, theme, retract } = setup()+ send({ palette: 'nord' })+ send({ palette: 'nord' })+ expect(theme.overrideTokens).toHaveBeenCalledTimes(1)+ expect(theme.overrideTokens.mock.calls[0]).toEqual(['dsh-tauri:appearance', expect.objectContaining({ '--dsw-alias-label-primary': { dark: '#eceff4', light: '#2e3440' } })])+ send({})+ expect(retract).toHaveBeenCalledOnce()+ expect(document.querySelector('style')!.textContent).toBe('')+ })++ it('puts alpha on the background only and follows light/dark changes', () => {+ const { send, theme, setScheme } = setup()+ send({ palette: 'nord', opacity: 70 })+ expect(document.querySelector('style')!.textContent).toContain('#2e3440 70%')+ expect(document.querySelector('style')!.textContent).not.toMatch(/(?:^|[;{])opacity:/)+ expect(theme.overrideTokens.mock.calls[0]).toEqual(['dsh-tauri:appearance', expect.objectContaining({ '--dsw-alias-bg-base': { dark: 'transparent', light: 'transparent' }, '--dsw-specific-menu': { dark: '#343c4a', light: '#e5e9f0' } })])+ setScheme('light')+ expect(document.querySelector('style')!.textContent).toContain('#eceff4 70%')+ })++ it('keeps the canvas opaque when transparency is explicitly disabled', () => {+ const { send, theme } = setup()+ send({ transparency: false, opacity: 70 })+ expect(document.querySelector('style')!.textContent).toBe('')+ expect(theme.overrideTokens).not.toHaveBeenCalled()+ })++ it('hides the collapsed sidebar while retaining the live right-panel width and restores layout on reset', async () => {+ const { send, frame, ctx } = setup()+ send({ terminal: true })+ expect(document.querySelector('style')!.textContent).not.toMatch(/font-family|monospace/)+ expect(frame.hasAttribute('data-sidebar-collapsed')).toBe(true)+ expect(frame.style.getPropertyValue('--dsh-appearance-columns')).toBe('0px minmax(400px, 1fr) minmax(0px, 350px)')+ frame.style.gridTemplateColumns = '56px minmax(0px, 1fr) minmax(0px, 480px)'+ await vi.waitFor(() => expect(frame.style.getPropertyValue('--dsh-appearance-columns')).toBe('0px minmax(0px, 1fr) minmax(0px, 480px)'))+ ctx.layout.toggleSidebar()+ expect(frame.hasAttribute('data-sidebar-collapsed')).toBe(false)+ ctx.layout.toggleSidebar()+ send({})+ expect(frame.hasAttribute('data-sidebar-collapsed')).toBe(false)+ expect(frame.style.getPropertyValue('--dsh-appearance-columns')).toBe('')+ expect(document.querySelector('style')!.textContent).toBe('')+ })++ it('removes styles, subscriptions and token overrides on unload', () => {+ const { send, theme, retract, listeners } = setup()+ send({ palette: 'forest', terminal: true })+ disposers.pop()!()+ expect(retract).toHaveBeenCalledOnce()+ expect(listeners.size).toBe(0)+ expect(document.querySelector('style')).toBeNull()+ send({ palette: 'amber' })+ expect(theme.overrideTokens).toHaveBeenCalledOnce()+ })++ it('releases terminal observers when disabled instead of retaining them until unload', () => {+ const observe = vi.spyOn(MutationObserver.prototype, 'observe')+ const disconnect = vi.spyOn(MutationObserver.prototype, 'disconnect')+ const { send } = setup()+ send({})+ expect(observe).not.toHaveBeenCalled()+ for (let i = 0; i < 20; i++) {+ send({ terminal: true })+ send({ terminal: false })+ }+ expect(observe).toHaveBeenCalledTimes(20)+ expect(disconnect).toHaveBeenCalledTimes(20)+ disposers.pop()!()+ expect(disconnect).toHaveBeenCalledTimes(20)+ })+})diff --git a/packages/dsh-tauri/src/client/register/appearance.ts b/packages/dsh-tauri/src/client/register/appearance.tsnew file mode 100644index 00000000..5be292f0--- /dev/null+++ b/packages/dsh-tauri/src/client/register/appearance.ts@@ -0,0 +1,103 @@+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 { PLUGIN_ID } from '../../shared/constants'+import { invokeParent } from '../service/invoke-parent'+import { listenParent } from '../service/listen-parent'+import { defineRegister } from './index'++export const registerAppearance = defineRegister<ClientContext>((controller, ctx, adapter) => {+ const theme = adapter.service<ThemeRuntime>('theme')+ if (typeof theme?.overrideTokens !== 'function') {+ console.warn('[appearance] the core theme API is unavailable')+ return+ }+ const style = document.createElement('style')+ style.id = 'dsh-tauri:appearance'+ style.dataset.plugin = PLUGIN_ID+ document.head.append(style)+ let current: Appearance | undefined+ let removeTokens: (() => void) | undefined+ // keep:effect 切换时立即释放观察器,避免 controller.observe 累积断开的实例;卸载由 controller 托管。+ let frameObserver: MutationObserver | undefined+ let waitingObserver: MutationObserver | undefined+ let frame: HTMLElement | null = null+ let restoreSidebar = false++ function updateStyles() {+ if (!current)+ return+ const { canvas } = appearanceColors(current, theme!.getTheme().active.colorScheme)+ const translucent = current.transparency && current.opacity < 100+ 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}` : '',+ 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}' : '',+ ].filter(Boolean).join('\n')+ }++ function syncColumns() {+ if (!frame)+ return+ const columns = frame.style.gridTemplateColumns.replace(/^\S+\s+/, '0px ')+ if (frame.style.getPropertyValue('--dsh-appearance-columns') !== columns)+ frame.style.setProperty('--dsh-appearance-columns', columns)+ }++ function attachFrame(): boolean {+ frame = document.querySelector<HTMLElement>('[data-shell-overlay]')?.parentElement ?? null+ if (!frame)+ return false+ waitingObserver?.disconnect()+ waitingObserver = undefined+ syncColumns()+ frameObserver = new MutationObserver(syncColumns)+ frameObserver.observe(frame, { attributes: true, attributeFilter: ['style'] })+ restoreSidebar = !frame.hasAttribute('data-sidebar-collapsed')+ if (restoreSidebar)+ ctx.layout.toggleSidebar()+ return true+ }++ function stopTerminal() {+ waitingObserver?.disconnect()+ frameObserver?.disconnect()+ waitingObserver = frameObserver = undefined+ frame?.style.removeProperty('--dsh-appearance-columns')+ if (restoreSidebar && frame?.hasAttribute('data-sidebar-collapsed'))+ ctx.layout.toggleSidebar()+ restoreSidebar = false+ frame = null+ }++ controller.add(listenParent<{ type: string, appearance?: unknown }>((message) => {+ const next = normalizeAppearance(message.appearance)+ if (current && JSON.stringify(current) === JSON.stringify(next))+ return+ const terminalChanged = next.terminal !== current?.terminal+ current = next+ removeTokens?.()+ const tokens = appearanceTokens(next)+ if (next.transparency && next.opacity < 100) {+ 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()+ if (terminalChanged) {+ stopTerminal()+ if (next.terminal && !attachFrame()) {+ waitingObserver = new MutationObserver(attachFrame)+ waitingObserver.observe(document.body, { childList: true, subtree: true })+ }+ }+ }, 'dsh://appearance'))+ controller.add(ctx.on('theme/change', updateStyles))+ controller.add(() => {+ stopTerminal()+ removeTokens?.()+ style.remove()+ })+ invokeParent({ type: 'dsh://appearance:ready' })+})diff --git a/packages/dsh-tauri/src/shared/appearance.test.ts b/packages/dsh-tauri/src/shared/appearance.test.tsnew file mode 100644index 00000000..fde47317--- /dev/null+++ b/packages/dsh-tauri/src/shared/appearance.test.ts@@ -0,0 +1,57 @@+import { describe, expect, it } from 'vitest'+import { APPEARANCE_DEFAULTS, APPEARANCE_PALETTES, appearanceColors, appearanceTokens, normalizeAppearance } from './appearance'++describe('appearance preferences', () => {+ it('migrates old transparency settings but respects an explicit disabled switch', () => {+ expect(normalizeAppearance({ opacity: 70 })).toMatchObject({ transparency: true, sidebarOnly: false })+ expect(normalizeAppearance({ opacity: 70, transparency: false })).toMatchObject({ transparency: false, opacity: 70 })+ expect(normalizeAppearance({ opacity: 100, transparency: true, sidebarOnly: true })).toMatchObject({ transparency: true, sidebarOnly: true })+ })++ it.each([undefined, null, {}, 1, 'nord', { palette: 'missing', terminal: 'true', opacity: Number.NaN }])('keeps original defaults for invalid or missing preferences: %j', (value) => {+ expect(normalizeAppearance(value)).toEqual(APPEARANCE_DEFAULTS)+ })++ 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 })+ })++ it.each(['github', 'github-dimmed', 'github-high-contrast'])('preserves the saved %s palette', (palette) => {+ expect(normalizeAppearance({ palette }).palette).toBe(palette)+ })++ it.each(['light', 'dark'] as const)('keeps high-contrast text at 7:1 and borders at 3:1 in %s mode', (scheme) => {+ const tokens = appearanceTokens(normalizeAppearance({ palette: 'github-high-contrast' }))+ for (const background of ['--dsw-alias-bg-base', '--dsw-alias-bg-layer-1', '--dsw-alias-bg-layer-2']) {+ for (const foreground of ['--dsw-alias-label-primary', '--dsw-alias-label-secondary', '--dsw-alias-label-tertiary', '--dsw-alias-label-caption', '--dsw-alias-link', '--dsw-alias-border-l2']) {+ const [dark, light] = [luminance(tokens[background][scheme]), luminance(tokens[foreground][scheme])].sort((a, b) => a - b)+ const minimum = foreground.includes('border') ? 3 : foreground.includes('link') ? 4.5 : 7+ expect((light + 0.05) / (dark + 0.05), `${foreground} on ${background}`).toBeGreaterThanOrEqual(minimum)+ }+ }+ })++ it('does not override core theme tokens under default settings', () => {+ expect(appearanceTokens(APPEARANCE_DEFAULTS)).toEqual({})+ })++ it.each(APPEARANCE_PALETTES)('keeps %s text readable on all opaque palette surfaces in both modes', (palette) => {+ for (const scheme of ['light', 'dark'] as const) {+ const colors = appearanceColors({ ...APPEARANCE_DEFAULTS, palette }, scheme)+ for (const background of [colors.canvas, colors.panel, colors.surface]) {+ for (const foreground of [colors.text, colors.muted, ...(palette.startsWith('github') ? [colors.accent] : [])]) {+ const [dark, light] = [luminance(background), luminance(foreground)].sort((a, b) => a - b)+ expect((light + 0.05) / (dark + 0.05), `${palette}/${scheme}: ${foreground} on ${background}`).toBeGreaterThanOrEqual(4.5)+ }+ }+ }+ })+})++function luminance(hex: string): number {+ const channels = [1, 3, 5].map((offset) => {+ const value = Number.parseInt(hex.slice(offset, offset + 2), 16) / 255+ return value <= 0.04045 ? value / 12.92 : ((value + 0.055) / 1.055) ** 2.4+ })+ return channels[0] * 0.2126 + channels[1] * 0.7152 + channels[2] * 0.0722+}diff --git a/packages/dsh-tauri/src/shared/appearance.ts b/packages/dsh-tauri/src/shared/appearance.tsnew file mode 100644index 00000000..c059ab05--- /dev/null+++ b/packages/dsh-tauri/src/shared/appearance.ts@@ -0,0 +1,79 @@+export const APPEARANCE_DEFAULTS = { palette: 'default', terminal: false, transparency: false, opacity: 100, sidebarOnly: false } as const+export const APPEARANCE_PALETTES = ['default', 'nord', 'solarized', 'forest', 'amber', 'github', 'github-dimmed', 'github-high-contrast'] as const++export interface Appearance {+ palette: typeof APPEARANCE_PALETTES[number]+ terminal: boolean+ transparency: boolean+ opacity: number+ sidebarOnly: boolean+}++export function normalizeAppearance(value: unknown): Appearance {+ const input = value as Partial<Appearance> | null+ const opacity = typeof input?.opacity === 'number' && Number.isFinite(input.opacity)+ ? Math.round(Math.min(100, Math.max(20, input.opacity)))+ : 100+ return {+ palette: APPEARANCE_PALETTES.includes(input?.palette as Appearance['palette']) ? input!.palette! : 'default',+ terminal: input?.terminal === true,+ transparency: input?.transparency === undefined ? opacity < 100 : input.transparency === true,+ opacity,+ sidebarOnly: input?.sidebarOnly === true,+ }+}++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>> = {+ 'default': { dark: ['#151517', '#1b1b1c', '#2c2c2e', '#f9fafb', '#adb2b8', '#7aaaff'], light: ['#ffffff', '#f9fafb', '#f1f3f5', '#0f1115', '#61666b', '#4176e6'] },+ 'nord': { dark: ['#2e3440', '#343c4a', '#434c5e', '#eceff4', '#b8c5d6', '#88c0d0'], light: ['#eceff4', '#e5e9f0', '#d8dee9', '#2e3440', '#4c566a', '#375f85'] },+ 'solarized': { dark: ['#002b36', '#073642', '#164450', '#eee8d5', '#a4b4b3', '#64b5c5'], light: ['#fdf6e3', '#eee8d5', '#e3dcc8', '#073642', '#4a5d62', '#006c82'] },+ 'forest': { dark: ['#15211b', '#1c2d23', '#2b3d31', '#e8f4e9', '#b0c9b6', '#8bcea0'], light: ['#f4f8f0', '#e8efe2', '#d8e4d0', '#203b29', '#49614d', '#276b3d'] },+ 'amber': { dark: ['#211c14', '#2b241a', '#3c3223', '#fff1d6', '#cfbd9d', '#f0bd68'], light: ['#fff8eb', '#f3e8d1', '#e8d8b8', '#3c2c13', '#695638', '#875700'] },+ 'github': { dark: ['#0d1117', '#010409', '#151b23', '#f0f6fc', '#9198a1', '#4493f8', '#3d444d'], light: ['#ffffff', '#f6f8fa', '#f6f8fa', '#1f2328', '#59636e', '#0969da', '#d1d9e0'] },+ 'github-dimmed': { dark: ['#212830', '#151b23', '#262c36', '#d1d7e0', '#9198a1', '#6cb6ff', '#3d444d'], light: ['#ffffff', '#f6f8fa', '#f6f8fa', '#1f2328', '#59636e', '#0969da', '#d1d9e0'] },+ 'github-high-contrast': { dark: ['#010409', '#151b23', '#151b23', '#ffffff', '#b7bdc8', '#74b9ff', '#b7bdc8'], light: ['#ffffff', '#eff2f5', '#e6eaef', '#010409', '#454c54', '#023b95', '#454c54'] },+}++export function appearanceColors(appearance: Appearance, scheme: 'dark' | 'light') {+ const [canvas, panel, surface, text, muted, accent, border] = PALETTES[appearance.palette][scheme]+ return { canvas, panel, surface, text, muted, accent, border }+}++export function appearanceTokens(appearance: Appearance): Record<string, { dark: string, light: string }> {+ if (appearance.palette === 'default' && (!appearance.transparency || appearance.opacity === 100))+ return {}+ function modes(scheme: 'dark' | 'light'): Record<string, string> {+ const { canvas, panel, surface, text, muted, accent, border } = appearanceColors(appearance, scheme)+ const tokens: Record<string, string> = {+ '--dsw-alias-bg-base': canvas,+ '--dsw-specific-sidebar-fill': panel,+ '--dsw-alias-bg-layer-1': panel,+ '--dsw-alias-bg-layer-2': surface,+ '--dsw-alias-bg-layer-3': surface,+ '--dsw-alias-bg-module-platform': surface,+ '--dsw-alias-bg-overlay': panel,+ '--dsw-specific-menu': panel,+ '--dsw-specific-input-major': panel,+ '--dsw-specific-bubble': surface,+ '--dsw-alias-label-primary': text,+ '--dsw-alias-label-secondary': muted,+ '--dsw-alias-label-tertiary': muted,+ '--dsw-alias-label-caption': muted,+ '--dsw-alias-state-business-primary': accent,+ }+ if (border) {+ tokens['--dsw-alias-link'] = accent+ for (const level of ['l1', 'l2', 'l2-darkmode-thin', 'l3', 'l4'])+ tokens[`--dsw-alias-border-${level}`] = border+ }+ return tokens+ }+ const dark = modes('dark')+ const light = modes('light')+ return Object.fromEntries(Object.keys(dark).map(key => [key, {+ dark: dark[key],+ light: light[key],+ }]))+}diff --git a/src-tauri/licenses/INSTALLER-LICENSE.txt b/src-tauri/licenses/INSTALLER-LICENSE.txtindex 23f641be..8ea34de6 100644--- a/src-tauri/licenses/INSTALLER-LICENSE.txt+++ b/src-tauri/licenses/INSTALLER-LICENSE.txt@@ -52,3 +52,29 @@ Copyright (c) 2026 deepseek-harness-desktop contributors=======================================================================In the event of any conflict, the Additional Terms prevail.=======================================================================++=======================================================================+GitHub palette colors — Primer Primitives+=======================================================================++The MIT License (MIT)++Copyright (c) 2018 GitHub Inc.++Permission is hereby granted, free of charge, to any person obtaining a copy+of this software and associated documentation files (the "Software"), to deal+in the Software without restriction, including without limitation the rights+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell+copies of the Software, and to permit persons to whom the Software is+furnished to do so, subject to the following conditions:++The above copyright notice and this permission notice shall be included in all+copies or substantial portions of the Software.++THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE+SOFTWARE.diff --git a/src-tauri/src/bridge/config.rs b/src-tauri/src/bridge/config.rsindex 90d3aa6c..f59b7971 100644--- a/src-tauri/src/bridge/config.rs+++ b/src-tauri/src/bridge/config.rs@@ -36,7 +36,9 @@ pub fn is_dev_build() -> bool {#[allow(clippy::too_many_arguments)]pub async fn update_app_config(app_handle: AppHandle,+ appearance: Option<config::Appearance>,port: Option<u16>,+ zoom_factor: Option<f64>,harness_max_heap_mb: Option<u32>,auto_start: Option<bool>,cli_link_enabled: Option<bool>,@@ -59,12 +61,18 @@ pub async fn update_app_config(}}let setting = config::update_store_dat_setting(&app_handle, |setting| {+ if let Some(appearance) = appearance {+ setting.appearance = appearance;+ }if let Some(port) = port {setting.port = port;// 记住用户手动选择的端口:自动避让递增后仍能回落回用户值,而不是// 一路顶高(issue #91,见 workflow::launch 的端口自愈逻辑)setting.manual_port = Some(port);}+ if let Some(zoom_factor) = zoom_factor {+ setting.zoom_factor = zoom_factor;+ }if let Some(mb) = harness_max_heap_mb {setting.harness_max_heap_mb = (mb != 0).then_some(mb);}diff --git a/src-tauri/src/config/appearance.rs b/src-tauri/src/config/appearance.rsnew file mode 100644index 00000000..1535ece0--- /dev/null+++ b/src-tauri/src/config/appearance.rs@@ -0,0 +1,190 @@+use serde::{Deserialize, Serialize};++#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]+#[serde(rename_all = "camelCase", from = "serde_json::Value")]+pub struct Appearance {+ pub palette: String,+ pub terminal: bool,+ pub transparency: bool,+ pub opacity: u8,+ pub sidebar_only: bool,+}++impl Default for Appearance {+ fn default() -> Self {+ Self {+ palette: "default".into(),+ terminal: false,+ transparency: false,+ opacity: 100,+ sidebar_only: false,+ }+ }+}++impl From<serde_json::Value> for Appearance {+ fn from(value: serde_json::Value) -> Self {+ let opacity = value["opacity"]+ .as_f64()+ .filter(|value| value.is_finite())+ .map(|value| value.round().clamp(20.0, 100.0) as u8)+ .unwrap_or(100);+ let mut appearance = Self {+ palette: value["palette"].as_str().unwrap_or("default").to_owned(),+ terminal: value["terminal"].as_bool().unwrap_or(false),+ transparency: value+ .get("transparency")+ .map_or(opacity < 100, |value| value.as_bool().unwrap_or(false)),+ opacity,+ sidebar_only: value["sidebarOnly"].as_bool().unwrap_or(false),+ };+ appearance.normalize();+ appearance+ }+}++impl Appearance {+ pub fn normalize(&mut self) {+ if !matches!(+ self.palette.as_str(),+ "default"+ | "nord"+ | "solarized"+ | "forest"+ | "amber"+ | "github"+ | "github-dimmed"+ | "github-high-contrast"+ ) {+ self.palette = "default".into();+ }+ self.opacity = self.opacity.clamp(20, 100);+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn missing_appearance_fields_preserve_the_original_window() {+ let appearance: Appearance = serde_json::from_str("{}").unwrap();+ assert_eq!(appearance, Appearance::default());+ assert_eq!(appearance.opacity, 100);+ assert!(!appearance.terminal);+ }++ #[test]+ fn transparency_migrates_once_and_is_independent_of_opacity() {+ for (value, expected) in [+ (serde_json::json!({"opacity": 70}), true),+ (+ serde_json::json!({"opacity": 70, "transparency": false}),+ false,+ ),+ (+ serde_json::json!({"opacity": 100, "transparency": true}),+ true,+ ),+ (+ serde_json::json!({"opacity": 70, "transparency": "true"}),+ false,+ ),+ ] {+ let appearance: Appearance = serde_json::from_value(value.clone()).unwrap();+ assert_eq!(appearance.transparency, expected, "{value}");+ let saved = serde_json::to_value(&appearance).unwrap();+ assert_eq!(saved["transparency"], expected);+ assert_eq!(+ serde_json::from_value::<Appearance>(saved).unwrap(),+ appearance+ );+ }+ let appearance: Appearance =+ serde_json::from_value(serde_json::json!({"sidebarOnly": true})).unwrap();+ assert!(appearance.sidebar_only);+ assert_eq!(+ serde_json::to_value(appearance).unwrap()["sidebarOnly"],+ true+ );+ }++ #[test]+ fn opacity_decoding_rounds_and_clamps_numeric_values() {+ for (value, expected) in [+ (serde_json::json!(77.49), 77),+ (serde_json::json!(77.5), 78),+ (serde_json::json!(20), 20),+ (serde_json::json!(100), 100),+ (serde_json::json!(-300), 20),+ (serde_json::json!(300), 100),+ (serde_json::json!(1e300), 100),+ ] {+ let appearance: Appearance = serde_json::from_value(serde_json::json!({+ "opacity": value+ }))+ .unwrap();+ assert_eq!(appearance.opacity, expected, "{value}");+ }+ }++ #[test]+ fn invalid_opacity_preserves_the_other_appearance_fields() {+ for value in [+ serde_json::json!(null),+ serde_json::json!("70"),+ serde_json::json!(true),+ serde_json::json!([]),+ serde_json::json!({}),+ ] {+ let appearance: Appearance = serde_json::from_value(serde_json::json!({+ "palette": "nord", "terminal": true, "opacity": value+ }))+ .unwrap();+ assert_eq!(+ appearance,+ Appearance {+ palette: "nord".into(),+ terminal: true,+ opacity: 100,+ ..Default::default()+ },+ "{value}"+ );+ }+ }++ #[test]+ fn github_palettes_survive_saving_and_reloading() {+ 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+ }))+ .unwrap();+ assert_eq!(appearance.palette, palette);+ let saved = serde_json::to_value(&appearance).unwrap();+ assert_eq!(+ serde_json::from_value::<Appearance>(saved).unwrap(),+ appearance+ );+ }+ }++ #[test]+ fn invalid_palette_and_opacity_are_normalized() {+ let mut appearance = Appearance {+ palette: "unknown".into(),+ terminal: true,+ opacity: 0,+ ..Default::default()+ };+ appearance.normalize();+ assert_eq!(appearance.palette, "default");+ assert_eq!(appearance.opacity, 20);+ assert!(appearance.terminal);+ appearance.opacity = 255;+ appearance.normalize();+ assert_eq!(appearance.opacity, 100);+ }+}diff --git a/src-tauri/src/config/mod.rs b/src-tauri/src/config/mod.rsindex 0f54e892..ff3ff447 100644--- a/src-tauri/src/config/mod.rs+++ b/src-tauri/src/config/mod.rs@@ -1,3 +1,5 @@+mod appearance;+pub use appearance::Appearance;mod constants;pub mod dependencies;pub mod i18n;diff --git a/src-tauri/src/config/setting.rs b/src-tauri/src/config/setting.rsindex a1b9e412..a3cd56fd 100644--- a/src-tauri/src/config/setting.rs+++ b/src-tauri/src/config/setting.rs@@ -7,6 +7,8 @@ use tauri_plugin_store::StoreExt;#[derive(Debug, Clone, Serialize, Deserialize)]#[serde(rename_all = "snake_case")]pub struct Setting {+ #[serde(default)]+ pub appearance: super::Appearance,pub installed: bool,pub port: u16,#[serde(default)]@@ -158,6 +160,7 @@ pub fn normalize_backup_retention(retention_count: u32) -> u32 {}fn normalize_setting(setting: &mut Setting) {+ setting.appearance.normalize();setting.zoom_factor = normalize_zoom_factor(setting.zoom_factor);setting.harness_max_heap_mb = normalize_harness_max_heap_mb(setting.harness_max_heap_mb);setting.close_action = normalize_close_action(&setting.close_action);@@ -176,6 +179,7 @@ pub fn default_port() -> u16 {impl Default for Setting {fn default() -> Self {Self {+ appearance: super::Appearance::default(),installed: false,port: default_port(),harness_max_heap_mb: None,@@ -338,6 +342,7 @@ fn emit_setting(app_handle: &AppHandle, value: &serde_json::Value) {}fn preserve_persisted_fields(mut replacement: Setting, current: &Setting) -> Setting {+ replacement.appearance.clone_from(¤t.appearance);replacement.zoom_factor = normalize_zoom_factor(current.zoom_factor);replacement.harness_max_heap_mb = normalize_harness_max_heap_mb(current.harness_max_heap_mb);replacement.close_action = normalize_close_action(¤t.close_action);@@ -512,6 +517,71 @@ mod tests {assert_eq!(normalize_zoom_factor(f64::INFINITY), default_zoom_factor());}+ #[test]+ fn malformed_appearance_preserves_operational_settings() {+ for (appearance, expected) in [+ (+ serde_json::json!({ "palette": "nord", "terminal": true, "opacity": 77.5 }),+ ("nord", true, 78),+ ),+ (+ serde_json::json!({ "opacity": 300 }),+ ("default", false, 100),+ ),+ (serde_json::json!({ "opacity": -1 }), ("default", false, 20)),+ (+ serde_json::json!({ "opacity": "70" }),+ ("default", false, 100),+ ),+ (+ serde_json::json!({ "opacity": null }),+ ("default", false, 100),+ ),+ (+ serde_json::json!({ "palette": [], "terminal": "true", "opacity": 64 }),+ ("default", false, 64),+ ),+ (serde_json::json!(null), ("default", false, 100)),+ (serde_json::json!([]), ("default", false, 100)),+ (serde_json::json!("invalid"), ("default", false, 100)),+ ] {+ let mut object = serde_json::json!({+ "installed": true,+ "port": 4099,+ "manual_port": 4099,+ "auto_start": false,+ "language": "en-US",+ "active_profile": "custom-profile",+ "active_core": "app",+ "dsh_pkg_commit": "saved-core",+ "dsh_pkg_tag": "saved-release",+ "preinstall_done": true,+ "dsh_home_migrated": true,+ "desktop_profile_ready": true,+ "cli_link_enabled": false,+ "harness_max_heap_mb": 2048,+ "zoom_factor": 1.2,+ "close_action": "quit"+ });+ object["appearance"] = appearance;+ for value in [+ object.clone(),+ serde_json::Value::String(object.to_string()),+ ] {+ let setting = setting_from_value(Some(&value));+ assert_eq!(setting.appearance.palette, expected.0, "{value}");+ assert_eq!(setting.appearance.terminal, expected.1, "{value}");+ assert_eq!(setting.appearance.opacity, expected.2, "{value}");+ let saved = serde_json::to_value(setting).unwrap();+ for (key, expected) in object.as_object().unwrap() {+ if key != "appearance" {+ assert_eq!(&saved[key], expected, "{key} changed for {value}");+ }+ }+ }+ }+ }+#[test]fn settings_decode_object_and_wrapped_object_with_same_normalization() {let object = serde_json::json!({@@ -636,6 +706,13 @@ mod tests {};let current = Setting {+ appearance: super::super::Appearance {+ palette: "nord".into(),+ terminal: true,+ opacity: 70,+ transparency: true,+ sidebar_only: true,+ },harness_max_heap_mb: Some(4096),zoom_factor: 1.6,close_action: "tray".to_string(),@@ -656,6 +733,7 @@ mod tests {assert_eq!(merged.dsh_pkg_tag.as_deref(), Some("new-tag"));assert_eq!(merged.harness_max_heap_mb, Some(4096));assert_eq!(merged.zoom_factor, 1.6);+ assert_eq!(merged.appearance, current.appearance);assert_eq!(merged.close_action, "tray");assert!(merged.pet_enabled);assert_eq!(merged.active_pet.as_deref(), Some("codex:latest"));diff --git a/src-tauri/src/desktop/builder.rs b/src-tauri/src/desktop/builder.rsindex 48b36184..52ca8f1c 100644--- a/src-tauri/src/desktop/builder.rs+++ b/src-tauri/src/desktop/builder.rs@@ -744,7 +744,13 @@ 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 builder = builder+ .transparent(transparent)+ .initialization_script(format!(+ "window.__DSH_TRANSPARENT__ = {transparent}; window.__DSH_STORE_FILE__ = {};",+ serde_json::json!(crate::config::store_dat_file_name())+ )).inner_size(1280.0, 840.0).min_inner_size(860.0, 620.0).resizable(true);@@ -934,9 +940,12 @@ pub fn build_main_window(app: &tauri::AppHandle<Wry>) -> tauri::Result<tauri::We/// macOS 未实现窗口底色接口,`set_background_color` 会返回错误并被忽略——那里由/// `config::apply_window_theme` 同步原生外观。fn apply_window_background(app: &tauri::AppHandle<Wry>, window: &tauri::WebviewWindow<Wry>) {- let Some(color) =+ let background = if crate::config::get_store_dat_setting(app).appearance.transparency {+ Some(tauri::webview::Color(0, 0, 0, 0))+ } else {crate::config::window_background(crate::config::get_dsh_theme(app), window.theme().ok())- else {+ };+ let Some(color) = background else {return;};if let Err(error) = window.as_ref().set_background_color(Some(color)) {diff --git a/src/config/storage.test.ts b/src/config/storage.test.tsnew file mode 100644index 00000000..41eb0007--- /dev/null+++ b/src/config/storage.test.ts@@ -0,0 +1,25 @@+import { afterEach, describe, expect, it, vi } from 'vitest'++const load = vi.hoisted(() => vi.fn(async () => ({})))+vi.mock('@tauri-apps/plugin-store', () => ({ Store: { load } }))++afterEach(() => {+ vi.unstubAllGlobals()+ vi.clearAllMocks()+})++describe('native store selection', () => {+ it.each(['.store.dat', '.store.dev.dat', '.store.test.dat'])('uses the native window store %s', async (path) => {+ vi.resetModules()+ vi.stubGlobal('__DSH_STORE_FILE__', path)+ await import('./storage')+ expect(load).toHaveBeenCalledWith(path, undefined)+ })++ it('uses the production store when no native window metadata is present', async () => {+ vi.resetModules()+ vi.stubGlobal('__DSH_STORE_FILE__', undefined)+ await import('./storage')+ expect(load).toHaveBeenCalledWith('.store.dat', undefined)+ })+})diff --git a/src/config/storage.ts b/src/config/storage.tsindex f13a0d11..9ad1c0b1 100644--- a/src/config/storage.ts+++ b/src/config/storage.ts@@ -39,5 +39,7 @@ export const tauriStorageDriver = defineDriver<TauriStorageDriverOptions | undef})export const storage = createStorage({- driver: tauriStorageDriver({ path: '.store.dat' }),+ driver: tauriStorageDriver({+ path: (globalThis as typeof globalThis & { __DSH_STORE_FILE__?: string }).__DSH_STORE_FILE__ ?? '.store.dat',+ }),})diff --git a/src/hooks/use-appearance.test.tsx b/src/hooks/use-appearance.test.tsxnew file mode 100644index 00000000..6c6a33f9--- /dev/null+++ b/src/hooks/use-appearance.test.tsx@@ -0,0 +1,99 @@+// @vitest-environment jsdom+import { act, cleanup, renderHook } from '@testing-library/react'+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 }))+vi.mock('@/store', () => ({ store: { get setting() {+ return mocks.setting+} } }))+vi.mock('./use-dsh-style', () => ({ useDshStyle: () => [{ colorScheme: 'dark' }] }))++afterEach(() => {+ cleanup()+ document.body.replaceChildren()+ document.head.replaceChildren()+ delete (window as any).__DSH_TRANSPARENT__+ vi.restoreAllMocks()+})++function setup(transparent: boolean) {+ ;(window as any).__DSH_TRANSPARENT__ = transparent+ mocks.setting = defineStore({ state: () => ({ appearance: { palette: 'nord', terminal: false, opacity: 70 } }) })+ const iframe = document.createElement('iframe')+ iframe.src = 'http://localhost:3080'+ document.body.append(iframe)+ const post = vi.spyOn(iframe.contentWindow!, 'postMessage').mockImplementation(() => {})+ const hook = renderHook(() => useAppearance({ current: iframe }))+ function ready(origin = 'http://localhost:3080') {+ act(() => window.dispatchEvent(new MessageEvent('message', {+ source: iframe.contentWindow!,+ origin,+ data: { type: 'dsh://appearance:ready' },+ })))+ }+ return { post, hook, ready }+}++describe('desktop appearance projection', () => {+ it('keeps the canvas opaque until the native window has restarted with transparency enabled', () => {+ 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%')+ })++ 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%')+ hook.unmount()+ post.mockClear()+ ready()+ expect(post).not.toHaveBeenCalled()+ })++ it('immediately restores an opaque canvas when native transparency is disabled', async () => {+ const { post, ready, hook } = setup(true)+ ready()+ await act(async () => {+ 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%')+ })++ it('applies high-contrast borders to the shell and removes them when switching palettes', async () => {+ const { hook } = setup(false)+ await act(async () => {+ mocks.setting.appearance = { palette: 'github-high-contrast', opacity: 100 }+ })+ expect(hook.result.current).toContain('--color-canvas:#010409')+ expect(hook.result.current).toContain('--field-border:#b7bdc8')+ await act(async () => {+ mocks.setting.appearance = { palette: 'nord', opacity: 100 }+ })+ expect(hook.result.current).not.toContain('--field-border:')+ })++ it('rejects an appearance handshake from the wrong origin', () => {+ const { post, ready } = setup(true)+ ready('https://example.invalid')+ expect(post).not.toHaveBeenCalled()+ })++ it('does no message work on unrelated renders and clears styling on reset', async () => {+ const { post, ready, hook } = setup(true)+ ready()+ post.mockClear()+ hook.rerender()+ expect(post).not.toHaveBeenCalled()+ await act(async () => {+ 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('')+ })+})diff --git a/src/hooks/use-appearance.ts b/src/hooks/use-appearance.tsnew file mode 100644index 00000000..84c77732--- /dev/null+++ b/src/hooks/use-appearance.ts@@ -0,0 +1,47 @@+import type { RefObject } from 'react'+import { useWatch } from '@reause/core'+import { useRef } from 'react'+import { useStore } from 'valtio-define'+import { store } from '@/store'+import { appearanceColors, 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 [dshStyle] = useDshStyle()+ const post = useIframePost(iframeRef)+ const readyRef = useRef(false)+ const transparent = (window as Window & { __DSH_TRANSPARENT__?: boolean }).__DSH_TRANSPARENT__ === true++ function sendAppearance() {+ const value = normalizeAppearance(appearance)+ post({ type: 'dsh://appearance', appearance: { ...value, transparency: transparent && value.transparency, opacity: transparent && value.transparency ? value.opacity : 100 } })+ }++ useIframeMessage<{ type?: string }>(iframeRef, (message) => {+ if (message.type === 'dsh://appearance:ready') {+ readyRef.current = true+ sendAppearance()+ }+ else if (message.type === 'dsh://plugin-boot:leaving') {+ readyRef.current = false+ }+ })+ useWatch([appearance, dshStyle.colorScheme], () => {+ 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'))+ 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}+ `+}diff --git a/src/i18n/locales/en-US.json b/src/i18n/locales/en-US.jsonindex c205f436..8331788d 100644--- a/src/i18n/locales/en-US.json+++ b/src/i18n/locales/en-US.json@@ -174,6 +174,7 @@"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",@@ -474,5 +475,26 @@"remote.connect.retry": "Retry","remote.connect.cancel": "Cancel","buttons.close": "Close",- "remote.loading": "Loading remote interface…"+ "remote.loading": "Loading remote interface…",+ "config.appearance": "Appearance",+ "appearance.description": "Desktop colours and layout. Palettes follow your Light, Dark, or System preference.",+ "appearance.palette": "Colour palette",+ "appearance.palette.default": "Default",+ "appearance.palette.nord": "Nord",+ "appearance.palette.solarized": "Solarized",+ "appearance.palette.forest": "Forest",+ "appearance.palette.amber": "Amber",+ "appearance.palette.github": "GitHub",+ "appearance.palette.github-dimmed": "GitHub Dimmed",+ "appearance.palette.github-high-contrast": "GitHub High Contrast",+ "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.opacity": "Background opacity",+ "appearance.opacity_description": "Text and menus stay opaque. Desktop transparency depends on your window system.",+ "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.jsonindex d6e9a40b..151724a5 100644--- a/src/i18n/locales/zh-CN.json+++ b/src/i18n/locales/zh-CN.json@@ -174,6 +174,7 @@"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": "保存端口失败",@@ -474,5 +475,26 @@"remote.connect.retry": "重试","remote.connect.cancel": "取消连接","buttons.close": "关闭",- "remote.loading": "正在加载远端界面…"+ "remote.loading": "正在加载远端界面…",+ "config.appearance": "外观",+ "appearance.description": "桌面配色与布局。配色跟随浅色、深色或系统主题。",+ "appearance.palette": "配色方案",+ "appearance.palette.default": "默认",+ "appearance.palette.nord": "北欧",+ "appearance.palette.solarized": "日光",+ "appearance.palette.forest": "森林",+ "appearance.palette.amber": "琥珀",+ "appearance.palette.github": "GitHub",+ "appearance.palette.github-dimmed": "GitHub 柔和",+ "appearance.palette.github-high-contrast": "GitHub 高对比度",+ "appearance.terminal": "终端模式",+ "appearance.terminal_description": "隐藏侧栏,保留原有字体。点击左上角侧栏按钮可重新展开。",+ "appearance.transparency": "启用原生透明模式",+ "appearance.transparency_description": "让窗口背景半透明,使桌面颜色透出。",+ "appearance.sidebar_only": "会话区域保持不透明",+ "appearance.opacity": "背景不透明度",+ "appearance.opacity_description": "文字和菜单保持不透明。桌面透明效果取决于窗口系统。",+ "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.tsindex 684017fc..87ab7eb9 100644--- a/src/layout/components/iframe-notification.test.ts+++ b/src/layout/components/iframe-notification.test.ts@@ -29,6 +29,7 @@ vi.mock('@/hooks/use-notification-action', () => ({ useNotificationAction: vi.fnvi.mock('@/hooks/use-notification-clicked', () => ({ useNotificationClicked: vi.fn() }))vi.mock('@/hooks/use-sync-visibility', () => ({ useSyncVisibility: vi.fn() }))vi.mock('@/hooks/use-zoom-factor', () => ({ useZoomFactor: vi.fn() }))+vi.mock('@/hooks/use-appearance', () => ({ useAppearance: () => '' }))vi.mock('./loadable', () => ({ Loadable: () => null }))function notify(tag = 'dsh-notification-session-1') {diff --git a/src/layout/components/iframe.tsx b/src/layout/components/iframe.tsxindex 465c8c51..fb9d41ea 100644--- a/src/layout/components/iframe.tsx+++ b/src/layout/components/iframe.tsx@@ -18,6 +18,7 @@ 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'@@ -209,6 +210,7 @@ export function Iframe({ iframeRef, srcOverride = null, borderTint = null }: Ifrconst [loadedUrl, setLoadedUrl] = useState('')const remoteLoading = remoteMode && loadedUrl !== srcOverride+ const appearanceCss = useAppearance(iframeRef)const post = useIframePost(iframeRef)/** 待合并的按钮动作,按「tag + actionId」索引(见 `handleNotificationAction`)。 */@@ -293,7 +295,7 @@ export function Iframe({ iframeRef, srcOverride = null, borderTint = null }: Ifrif (!action)returnevent.preventDefault()- setting.zoom(action)+ void setting.zoom(action).catch(error => console.error('[Zoom] failed to save zoom:', error))}/**@@ -398,7 +400,7 @@ export function Iframe({ iframeRef, srcOverride = null, borderTint = null }: Ifrfunction handleZoomShortcut(data: IframeBridgeMessage) {const action = zoomActionFromBridgeMessage(data)if (action)- setting.zoom(action)+ void setting.zoom(action).catch(error => console.error('[Zoom] failed to save zoom:', error))}function handleFrameLog(data: IframeBridgeMessage) {@@ -523,6 +525,7 @@ export function Iframe({ iframeRef, srcOverride = null, borderTint = null }: Ifrreturn (<div className="relative min-h-0 flex-1">+ <style>{appearanceCss}</style><Ifcond={remoteMode || harness.serviceHealthy}else={<Loadable subtitle={t(harness.startupStatusKey)} />}diff --git a/src/layout/components/navbar.tsx b/src/layout/components/navbar.tsxindex 0523978e..361021ef 100644--- a/src/layout/components/navbar.tsx+++ b/src/layout/components/navbar.tsx@@ -90,6 +90,7 @@ type HelpAction = 'keyboard-shortcuts' | 'copy-run-logs' | 'check-update' | 'abo/** 「运行」菜单项:直接打开配置对话框并定位到对应面板。 */const CONFIG_TABS: { id: ConfigTab, labelKey: string }[] = [{ id: 'application', labelKey: 'config.application' },+ { id: 'appearance', labelKey: 'config.appearance' },{ id: 'profiles', labelKey: 'config.profiles' },{ id: 'plugins', labelKey: 'config.plugins' },{ id: 'harness', labelKey: 'config.harness' },diff --git a/src/store/modules/harness/store.ts b/src/store/modules/harness/store.tsindex 00079c9a..a14dd2f0 100644--- a/src/store/modules/harness/store.ts+++ b/src/store/modules/harness/store.ts@@ -559,7 +559,7 @@ export const harness = defineStore({// 已安装过则跳过安装界面,避免每次启动都闪现"正在安装依赖..."// 设置由 setting store 持有(与 Rust 共享同一份 .store.dat)。必须先等水合// 完成再读,否则会把默认值当成真实安装状态:多跑一次安装,还漏掉更新检查。- await setting.$persist.rehydrate()+ await setting.refresh()// 取快照:后面的 `install_dependencies` 会把 installed 置位并广播,// 而本次 boot 的判断应当基于「启动开始时是否已安装」const config = { ...setting.$state }diff --git a/src/store/modules/setting/store.test.ts b/src/store/modules/setting/store.test.tsnew file mode 100644index 00000000..b907debe--- /dev/null+++ b/src/store/modules/setting/store.test.ts@@ -0,0 +1,192 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'++const mocks = vi.hoisted(() => ({+ saved: {} as Record<string, unknown>,+ listeners: new Set<(event: { payload: Record<string, unknown> }) => Promise<void>>(),+ invoke: vi.fn(),+ setItem: vi.fn(),+}))++vi.mock('@tauri-apps/api/core', () => ({ invoke: mocks.invoke }))+vi.mock('@tauri-apps/api/event', () => ({+ listen: vi.fn(async (_event, callback) => {+ mocks.listeners.add(callback)+ return () => mocks.listeners.delete(callback)+ }),+}))+vi.mock('@/config/storage', () => ({+ storage: {+ getItem: async () => JSON.stringify(mocks.saved),+ setItem: mocks.setItem,+ },+}))++let setting: (typeof import('./store'))['setting']++beforeEach(async () => {+ vi.resetModules()+ mocks.saved = {+ appearance: { palette: 'default', terminal: false, transparency: false, opacity: 100, sidebarOnly: false },+ zoom_factor: 1,+ backup_include_credentials: true,+ }+ mocks.setItem.mockImplementation(async (_key: string, value: string) => {+ mocks.saved = JSON.parse(value)+ })+ mocks.invoke.mockImplementation(async (command, update) => {+ if (command === 'update_app_config') {+ if (update.appearance !== undefined)+ mocks.saved.appearance = structuredClone(update.appearance)+ if (update.zoomFactor !== undefined)+ mocks.saved.zoom_factor = update.zoomFactor+ }+ else if (command !== 'get_app_config') {+ throw new Error(`Unexpected command: ${command}`)+ }+ return structuredClone(mocks.saved)+ })+ ;({ setting } = await import('./store'))+})++afterEach(() => {+ mocks.listeners.clear()+ vi.resetAllMocks()+})++async function nativeUpdate(value: Record<string, unknown>) {+ mocks.saved = structuredClone(value)+ await Promise.all([...mocks.listeners].map(callback => callback({ payload: structuredClone(value) })))+}++function deferred<T>() {+ let resolve!: (value: T) => void+ const promise = new Promise<T>((done) => {+ resolve = done+ })+ return { promise, resolve }+}++describe('settings synchronization across windows', () => {+ it('applies native settings updates after initial hydration', async () => {+ await nativeUpdate(mocks.saved)+ await nativeUpdate({ ...mocks.saved, appearance: { palette: 'amber', terminal: true, opacity: 80 } })+ expect(setting.appearance).toEqual({ palette: 'amber', terminal: true, opacity: 80 })+ })++ it('keeps another window’s appearance when a local zoom change is saved', async () => {+ await nativeUpdate(mocks.saved)+ await nativeUpdate({ ...mocks.saved, appearance: { palette: 'nord', terminal: false, opacity: 78 } })+ await setting.zoom('increase')+ expect(mocks.invoke).toHaveBeenCalledWith('update_app_config', { zoomFactor: 1.1 })+ expect(mocks.saved.zoom_factor).toBe(1.1)+ expect(mocks.saved.appearance).toEqual({ palette: 'nord', terminal: false, opacity: 78 })+ expect(mocks.setItem).not.toHaveBeenCalled()+ })++ it('preserves a newer credential-backup opt-out after an older appearance response', async () => {+ await nativeUpdate(mocks.saved)+ const olderResponse = deferred<Record<string, unknown>>()+ mocks.invoke.mockImplementationOnce(() => olderResponse.promise)+ const appearance = { ...setting.appearance, palette: 'github-high-contrast' as const }+ const pending = setting.update({ appearance })+ expect(mocks.invoke).toHaveBeenCalledWith('update_app_config', { appearance })+ const olderSnapshot = { ...mocks.saved, appearance }+ await nativeUpdate(olderSnapshot)+ await nativeUpdate({ ...olderSnapshot, backup_include_credentials: false })+ expect(setting.backup_include_credentials).toBe(false)+ olderResponse.resolve(olderSnapshot)+ await pending+ expect(setting.backup_include_credentials).toBe(false)+ expect(mocks.saved.backup_include_credentials).toBe(false)+ expect(setting.appearance.palette).toBe('github-high-contrast')+ expect(mocks.setItem).not.toHaveBeenCalled()+ })++ it('reads current native settings when an older event arrives late', async () => {+ const olderSnapshot = structuredClone(mocks.saved)+ await nativeUpdate({ ...mocks.saved, backup_include_credentials: false })+ await Promise.all([...mocks.listeners].map(callback => callback({ payload: olderSnapshot })))+ expect(setting.backup_include_credentials).toBe(false)+ expect(mocks.saved.backup_include_credentials).toBe(false)+ expect(mocks.setItem).not.toHaveBeenCalled()+ })++ it.each(['older first', 'newer first'])('discards superseded reads when responses arrive %s', async (order) => {+ await nativeUpdate(mocks.saved)+ const older = deferred<Record<string, unknown>>()+ const newer = deferred<Record<string, unknown>>()+ mocks.invoke.mockImplementationOnce(() => older.promise).mockImplementationOnce(() => newer.promise)+ let initialRefreshFinished = false+ const initial = setting.refresh().then(() => {+ initialRefreshFinished = true+ })+ const latest = setting.refresh()+ const latestSnapshot = { ...mocks.saved, installed: true, backup_include_credentials: false }+ if (order === 'older first') {+ older.resolve({ ...mocks.saved, installed: false })+ await Promise.resolve()+ expect(initialRefreshFinished).toBe(false)+ newer.resolve(latestSnapshot)+ }+ else {+ newer.resolve(latestSnapshot)+ await latest+ older.resolve({ ...mocks.saved, installed: false })+ }+ await Promise.all([initial, latest])+ expect(setting.installed).toBe(true)+ expect(setting.backup_include_credentials).toBe(false)+ expect(mocks.setItem).not.toHaveBeenCalled()+ })++ it('refreshes a saved appearance even when no native event is delivered', async () => {+ await nativeUpdate(mocks.saved)+ const appearance = { ...setting.appearance, palette: 'github' as const }+ await setting.update({ appearance })+ expect(setting.appearance.palette).toBe('github')+ expect(mocks.saved.appearance).toEqual(appearance)+ expect(mocks.setItem).not.toHaveBeenCalled()+ })++ it('keeps the last settings when a native read fails', async () => {+ await nativeUpdate({ ...mocks.saved, backup_include_credentials: false })+ mocks.invoke.mockRejectedValueOnce(new Error('native read failed'))+ await expect(setting.refresh()).rejects.toThrow('native read failed')+ expect(setting.backup_include_credentials).toBe(false)+ expect(mocks.setItem).not.toHaveBeenCalled()+ })++ it('rejects a failed save without applying or persisting its proposed appearance', async () => {+ await nativeUpdate(mocks.saved)+ 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.setItem).not.toHaveBeenCalled()+ })++ it('persists consecutive zoom shortcuts without dropping an increment', async () => {+ await nativeUpdate({ ...mocks.saved, backup_include_credentials: false })+ await Promise.all([setting.zoom('increase'), setting.zoom('increase')])+ expect(setting.zoom_factor).toBe(1.2)+ expect(mocks.saved.zoom_factor).toBe(1.2)+ expect(mocks.saved.backup_include_credentials).toBe(false)+ expect(mocks.setItem).not.toHaveBeenCalled()+ })++ it('accepts the next zoom shortcut after a rejected save', async () => {+ await nativeUpdate(mocks.saved)+ mocks.invoke.mockRejectedValueOnce(new Error('native write failed'))+ await expect(setting.zoom('increase')).rejects.toThrow('native write failed')+ await setting.zoom('increase')+ expect(setting.zoom_factor).toBe(1.1)+ expect(mocks.saved.zoom_factor).toBe(1.1)+ })++ it.each([['decrease', 1.4], ['reset', 1]] as const)('persists the %s zoom shortcut', async (action, expected) => {+ await nativeUpdate({ ...mocks.saved, zoom_factor: 1.5 })+ await setting.zoom(action)+ expect(setting.zoom_factor).toBe(expected)+ expect(mocks.saved.zoom_factor).toBe(expected)+ })+})diff --git a/src/store/modules/setting/store.ts b/src/store/modules/setting/store.tsindex ad14ea6a..28f1533b 100644--- a/src/store/modules/setting/store.ts+++ b/src/store/modules/setting/store.ts@@ -2,13 +2,17 @@ import type { AppSettingUpdate, ZoomAction } from './types'import { invoke } from '@tauri-apps/api/core'import { listen } from '@tauri-apps/api/event'import { defineStore } from 'valtio-define'-import { persist } from 'valtio-define/plugins/persist'-import { storage } from '@/config/storage'+import { APPEARANCE_DEFAULTS, normalizeAppearance } from '../../../../packages/dsh-tauri/src/shared/appearance'import { ZOOM_FACTOR_STEP } from './constants'import { normalizeZoomFactor } from './utils'+let refreshRevision = 0+let latestRefresh = Promise.resolve()+let zoomQueue = Promise.resolve()+export const setting = defineStore({state: () => ({+ appearance: normalizeAppearance(APPEARANCE_DEFAULTS),installed: false,port: 3080,harness_max_heap_mb: null as number | null,@@ -21,33 +25,40 @@ export const setting = defineStore({language: null as string | null,}),actions: {- update(update: AppSettingUpdate) {- return invoke('update_app_config', { ...update })+ async update(update: AppSettingUpdate): Promise<void> {+ await invoke('update_app_config', { ...update })+ await setting.refresh()},- zoom(action: ZoomAction) {- if (action === 'reset') {- this.zoom_factor = 1- return- }- const delta = action === 'increase' ? ZOOM_FACTOR_STEP : -ZOOM_FACTOR_STEP- this.zoom_factor = normalizeZoomFactor(this.zoom_factor + delta)+ refresh(): Promise<void> {+ const revision = ++refreshRevision+ latestRefresh = invoke<typeof setting.$state>('get_app_config').then(async (value) => {+ if (revision !== refreshRevision) {+ await latestRefresh+ return+ }+ setting.$patch(value)+ })+ return latestRefresh+ },+ zoom(action: ZoomAction): Promise<void> {+ const pending = zoomQueue.then(async () => {+ const delta = action === 'increase' ? ZOOM_FACTOR_STEP : -ZOOM_FACTOR_STEP+ const zoomFactor = action === 'reset' ? 1 : normalizeZoomFactor(setting.zoom_factor + delta)+ await setting.update({ zoomFactor })+ })+ zoomQueue = pending.catch(() => {})+ return pending},- },- persist: {- key: 'setting',- storage,},})-setting.use(persist({ hydrate: false }))+// keep:effect 原生设置是唯一持久化入口;事件仅触发重读,不能把旧快照写回。+const unlisten = listen('setting_updated', () => setting.refresh().catch((error) => {+ console.error('[Setting] failed to refresh native settings:', error)+}))-const unlisten = listen<typeof setting.$state>('setting_updated', async (event) => {- setting.$patch(event.payload)- await setting.$persist.rehydrate()- unlisten.then(unlisten => unlisten())+import.meta.hot?.dispose(() => {+ unlisten.then(stop => stop()).catch(() => {})})-// 非 Tauri 环境(vitest/jsdom)listen 会 reject(无 invoke/window);这只是-// 跨窗口同步通道,建不起来时设置功能本身不受影响,吞掉 rejection 避免-// unhandled(应用内 listen 失败时同样语义:静默无同步而非崩掉模块加载)。unlisten.catch(() => {})diff --git a/src/store/modules/setting/types/index.ts b/src/store/modules/setting/types/index.tsindex 49439d07..7031c060 100644--- a/src/store/modules/setting/types/index.ts+++ b/src/store/modules/setting/types/index.ts@@ -1,5 +1,9 @@+import type { Appearance } from '../../../../../packages/dsh-tauri/src/shared/appearance'+export interface AppSettingUpdate {+ appearance?: Appearanceport?: number+ zoomFactor?: numberharnessMaxHeapMb?: numberautoStart?: booleancliLinkEnabled?: booleandiff --git a/src/ui/config/appearance.test.tsx b/src/ui/config/appearance.test.tsxnew file mode 100644index 00000000..d2d5e59e--- /dev/null+++ b/src/ui/config/appearance.test.tsx@@ -0,0 +1,101 @@+// @vitest-environment jsdom+import { QueryClient, QueryClientProvider } from '@tanstack/react-query'+import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'+import { defineStore } from 'valtio-define'+import { afterEach, describe, expect, it, vi } from 'vitest'+import { APPEARANCE_DEFAULTS } from '../../../packages/dsh-tauri/src/shared/appearance'+import { ConfigAppearance } from './appearance'++const mocks = vi.hoisted(() => ({ setting: {} as any, toast: vi.fn() }))+vi.mock('@/store', () => ({ store: { get setting() {+ return mocks.setting+} } }))+vi.mock('@/utils/toast', () => ({ toast: mocks.toast }))+vi.mock('react-i18next', () => ({ useTranslation: () => ({ t: (key: string) => key }) }))++afterEach(() => {+ cleanup()+ delete (window as any).__DSH_TRANSPARENT__+ vi.clearAllMocks()+})++function setup(fail = false, opacity = 70) {+ const update = vi.fn(async (value) => {+ if (fail)+ throw new Error('disk write failed')+ mocks.setting.$patch(value)+ })+ mocks.setting = defineStore({+ state: () => ({ appearance: { palette: 'nord', terminal: false, opacity } }),+ actions: { update },+ })+ const client = new QueryClient({ defaultOptions: { mutations: { retry: false } } })+ render(<QueryClientProvider client={client}><ConfigAppearance /></QueryClientProvider>)+ return update+}++describe('appearance settings controls', () => {+ it('keeps native transparency enabled at 100% without requesting a restart', async () => {+ ;(window as any).__DSH_TRANSPARENT__ = true+ const update = setup()+ const slider = screen.getByRole('slider', { name: 'appearance.opacity' })+ fireEvent.keyDown(slider, { key: 'End' })+ fireEvent.keyUp(slider, { key: 'End' })+ await waitFor(() => expect(update).toHaveBeenLastCalledWith({ appearance: expect.objectContaining({ transparency: true, opacity: 100 }) }))+ await waitFor(() => expect(screen.queryByTestId('dsh-appearance-restart')).toBeNull())+ expect((screen.getByRole('switch', { name: 'appearance.transparency' }) as HTMLInputElement).checked).toBe(true)+ })++ it('hides opacity controls when native transparency is switched off and remembers the opacity', async () => {+ const update = setup()+ fireEvent.click(screen.getByRole('switch', { name: 'appearance.transparency' }))+ await waitFor(() => expect(update).toHaveBeenLastCalledWith({ appearance: expect.objectContaining({ transparency: false, opacity: 70 }) }))+ await waitFor(() => expect(screen.queryByRole('slider')).toBeNull())+ expect(screen.queryByRole('switch', { name: 'appearance.sidebar_only' })).toBeNull()+ })++ it('restores the saved slider value when persistence fails', async () => {+ setup(true)+ const slider = screen.getByRole('slider', { name: 'appearance.opacity' })+ fireEvent.keyDown(slider, { key: 'End' })+ fireEvent.keyUp(slider, { key: 'End' })+ await waitFor(() => expect(mocks.toast).toHaveBeenCalledWith('appearance.save_failed', { variant: 'danger' }))+ expect((slider as HTMLInputElement).value).toBe('70')+ })++ it.each([21, 78, 99])('displays saved opacity %i even when it is between preset steps', async (opacity) => {+ setup(false, opacity)+ await waitFor(() => expect(screen.getByTestId('dsh-appearance-opacity').textContent).toContain(`${opacity}%`))+ })++ it('persists the opaque session option', async () => {+ const update = setup()+ fireEvent.click(screen.getByRole('switch', { name: 'appearance.sidebar_only' }))+ await waitFor(() => expect(update).toHaveBeenLastCalledWith({ appearance: expect.objectContaining({ sidebarOnly: true }) }))+ await waitFor(() => expect((screen.getByRole('switch', { name: 'appearance.sidebar_only' }) as HTMLInputElement).checked).toBe(true))+ })++ 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((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(screen.queryByTestId('dsh-appearance-restart')).toBeNull())+ expect((toggle as HTMLInputElement).checked).toBe(false)+ })++ it('reports a failed save and keeps the previously saved preference', async () => {+ setup(true)+ const toggle = screen.getByRole('switch', { name: 'appearance.terminal' })+ fireEvent.click(toggle)+ await waitFor(() => expect(mocks.toast).toHaveBeenCalledWith('appearance.save_failed', { variant: 'danger' }))+ expect((toggle as HTMLInputElement).checked).toBe(false)+ expect(mocks.setting.appearance.terminal).toBe(false)+ })+})diff --git a/src/ui/config/appearance.tsx b/src/ui/config/appearance.tsxnew file mode 100644index 00000000..71ee3bf0--- /dev/null+++ b/src/ui/config/appearance.tsx@@ -0,0 +1,149 @@+import { Alert, Button, Description, Label, ListBox, Select, Slider, Switch, Typography } from '@heroui/react'+import { useMutation } from '@tanstack/react-query'+import { useState } from 'react'+import { useTranslation } from 'react-i18next'+import { If } from 'react-if-lite'+import { useStore } from 'valtio-define'+import { Panel } from '@/components/panel'+import { store } from '@/store'+import { toast } from '@/utils/toast'+import { APPEARANCE_DEFAULTS, APPEARANCE_PALETTES, normalizeAppearance } from '../../../packages/dsh-tauri/src/shared/appearance'++export function ConfigAppearance() {+ const { t } = useTranslation()+ const { appearance: saved } = 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) }),+ onError: () => toast(t('appearance.save_failed'), { variant: 'danger' }),+ })++ return (+ <div className="space-y-3" data-testid="dsh-appearance-settings">+ <Panel.Header title={t('config.appearance')} description={t('appearance.description')} testId="dsh-config-panel-title" />++ <div className="space-y-2">+ <div className="flex items-center justify-between gap-2">+ <Typography type="body-sm" weight="medium">{t('appearance.palette')}</Typography>+ <Select+ variant="secondary"+ aria-label={t('appearance.palette')}+ selectedKey={appearance.palette}+ onSelectionChange={key => save(normalizeAppearance({ ...appearance, palette: key }))}+ isDisabled={isPending}+ className="w-[180px]"+ >+ <Select.Trigger data-testid="dsh-appearance-palette" className="min-h-8! h-8 py-0 items-center">+ <Select.Value />+ <Select.Indicator />+ </Select.Trigger>+ <Select.Popover>+ <ListBox>+ {APPEARANCE_PALETTES.map(palette => (+ <ListBox.Item className="min-h-8!" key={palette} id={palette} textValue={t(`appearance.palette.${palette}`)} data-testid={`dsh-appearance-palette-${palette}`}>+ {t(`appearance.palette.${palette}`)}+ </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>+ <Description>{t('appearance.terminal_description')}</Description>+ </div>+ <Switch+ aria-label={t('appearance.terminal')}+ isSelected={appearance.terminal}+ isDisabled={isPending}+ onChange={terminal => save({ ...appearance, terminal })}+ >+ <Switch.Content data-testid="dsh-appearance-terminal">+ <Switch.Control><Switch.Thumb /></Switch.Control>+ </Switch.Content>+ </Switch>+ </div>+ </div>++ <div className="border-t border-line/30" />++ <div className="space-y-2">+ <div className="flex items-center justify-between gap-2">+ <div>+ <Typography type="body-sm" weight="medium">{t('appearance.transparency')}</Typography>+ <Description>{t('appearance.transparency_description')}</Description>+ </div>+ <Switch+ aria-label={t('appearance.transparency')}+ isSelected={appearance.transparency}+ isDisabled={isPending}+ onChange={transparency => save({ ...appearance, transparency })}+ >+ <Switch.Content data-testid="dsh-appearance-transparency">+ <Switch.Control><Switch.Thumb /></Switch.Control>+ </Switch.Content>+ </Switch>+ </div>+ </div>++ <div className="border-t border-line/30" />++ <If cond={appearance.transparency}>+ <div className="space-y-2">+ <div className="flex items-center justify-between gap-2">+ <Typography type="body-sm" weight="medium">{t('appearance.sidebar_only')}</Typography>+ <Switch+ aria-label={t('appearance.sidebar_only')}+ isSelected={appearance.sidebarOnly}+ isDisabled={isPending}+ onChange={sidebarOnly => save({ ...appearance, sidebarOnly })}+ >+ <Switch.Content data-testid="dsh-appearance-sidebar-only">+ <Switch.Control><Switch.Thumb /></Switch.Control>+ </Switch.Content>+ </Switch>+ </div>+ <div>+ <Slider+ aria-label={t('appearance.opacity')}+ value={opacity ?? appearance.opacity}+ minValue={20}+ maxValue={100}+ step={1}+ isDisabled={isPending}+ onChange={value => setOpacity(Number(value))}+ onChangeEnd={value => save({ ...appearance, opacity: Number(value) }, { onSettled: () => setOpacity(undefined) })}+ data-testid="dsh-appearance-opacity"+ >+ <Label>{t('appearance.opacity')}</Label>+ <Slider.Output>{({ state }) => `${state.values[0]}%`}</Slider.Output>+ <Slider.Track>+ <Slider.Fill />+ <Slider.Thumb />+ </Slider.Track>+ </Slider>+ </div>+ </div>+ <div className="border-t border-line/30" />+ </If>++ <If cond={restartPending}>+ <Alert status="warning" className="gap-2">+ <Alert.Indicator />+ <Alert.Content>+ <Alert.Description data-testid="dsh-appearance-restart">{t('appearance.restart')}</Alert.Description>+ </Alert.Content>+ </Alert>+ </If>++ <Button variant="secondary" isDisabled={isPending} onPress={() => save(normalizeAppearance(APPEARANCE_DEFAULTS))} data-testid="dsh-appearance-reset">+ {t('appearance.reset')}+ </Button>+ </div>+ )+}diff --git a/src/ui/config/debug.tsx b/src/ui/config/debug.tsxindex 8396616a..6bdb2273 100644--- a/src/ui/config/debug.tsx+++ b/src/ui/config/debug.tsx@@ -95,13 +95,10 @@ export function ConfigDebug() {},})- /**- * 缩放真值写进 setting store(persist 写入的 `setting` 键与 Rust 共用同一份 `.store.dat`),- * WebView 上的应用由 `iframe.tsx` 的 `useZoomFactor` 完成,因此这里没有失败分支。- */- function onSetZoom(zoomFactor: number) {- store.setting.zoom_factor = zoomFactor- }+ 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 () => {diff --git a/src/ui/dialog/config.tsx b/src/ui/dialog/config.tsxindex cca0e401..be68b6d8 100644--- a/src/ui/dialog/config.tsx+++ b/src/ui/dialog/config.tsx@@ -1,6 +1,6 @@import type { PropsWithOverlays } from '@overlastic/react'import type { DshPlugin } from '@/types'-import { Cpu, LogoWindows, PersonPencil, Puzzle } from '@gravity-ui/icons'+import { Brush, Cpu, LogoWindows, PersonPencil, Puzzle } from '@gravity-ui/icons'import { cn, Modal } from '@heroui/react'import { useDisclosure } from '@overlastic/react'import { useListener } from '@reause/core'@@ -11,13 +11,14 @@ import { useTranslation } from 'react-i18next'import { Case, If, Switch } from 'react-if-lite'import { hooks } from '@/config/hooks'import { queryKeys } from '@/config/query-keys'+import { ConfigAppearance } from '@/ui/config/appearance'import { ConfigCore } from '@/ui/config/core'import { ConfigDebug } from '@/ui/config/debug'import { ConfigPlugin } from '@/ui/config/plugin'import { ConfigProfile } from '@/ui/config/profile'/** 配置面板标识(左侧导航与顶部「配置」菜单共用同一组值) */-export type ConfigTab = 'application' | 'profiles' | 'plugins' | 'harness'+export type ConfigTab = 'appearance' | 'application' | 'profiles' | 'plugins' | 'harness'export interface ConfigDialogProps extends PropsWithOverlays {/** 打开时定位到的面板;缺省为「应用」 */@@ -37,6 +38,7 @@ export function ConfigDialog(props: ConfigDialogProps) {const navs: { label: string, value: ConfigTab, icon: typeof Cpu }[] = [{ label: t('config.application'), value: 'application', icon: LogoWindows },+ { label: t('config.appearance'), value: 'appearance', icon: Brush },{ label: t('config.profiles'), value: 'profiles', icon: PersonPencil },{ label: t('config.plugins'), value: 'plugins', icon: Puzzle },{ label: t('config.harness'), value: 'harness', icon: Cpu },@@ -91,6 +93,9 @@ export function ConfigDialog(props: ConfigDialogProps) {<Case cond="application"><ConfigDebug /></Case>+ <Case cond="appearance">+ <ConfigAppearance />+ </Case><Case cond="profiles"><ConfigProfile /></Case>diff --git a/test/e2e/desktop/boot.e2e.ts b/test/e2e/desktop/boot.e2e.tsindex ed4b0fd8..1a1c04a5 100644--- a/test/e2e/desktop/boot.e2e.ts+++ b/test/e2e/desktop/boot.e2e.ts@@ -3,6 +3,7 @@ import { existsSync } from 'node:fs'import { join } from 'node:path'import process from 'node:process'import { afterAll, beforeAll, describe, expect, it } from 'vitest'+import { Key } from 'webdriverio'import { startDesktopApp } from '../support/desktop'import { completePreinstall } from '../support/preinstall'import { SETUP_ERROR, SHELL_IFRAME, SHELL_ROOT } from '../support/selectors'@@ -137,4 +138,74 @@ describe.skipIf(process.platform === 'darwin')('桌面端启动冒烟', () => {const shellErrors = await browser.execute(readPageErrors)expect(shellErrors, '壳层出现报错').toEqual([])}, ASSEMBLY_TIMEOUT_MS)++ it('persists appearance through the native bridge and restores defaults', async () => {+ expect(await browser.execute(() => (window as unknown as { __DSH_STORE_FILE__: string }).__DSH_STORE_FILE__), '前端必须使用原生测试配置文件').toBe('.store.test.dat')+ async function click(id: string) {+ const element = await browser.$(`[data-testid="${id}"]`)+ await element.waitForClickable()+ await element.click()+ }+ async function appearance() {+ 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+ })+ }+ await click('dsh-navbar-menu-config')+ await click('dsh-navbar-item-appearance')+ await click('dsh-appearance-palette')+ await click('dsh-appearance-palette-nord')+ await browser.waitUntil(async () => (await appearance()).palette === 'nord', { timeoutMsg: '原生设置未保存 Nord 配色' })+ const terminal = await browser.$('[data-testid="dsh-appearance-terminal"] input[role="switch"]')+ await terminal.waitForEnabled()+ // 内嵌驱动调用 HTMLElement.click;React Aria 的 label 会拦截它,须激活真实 input。+ await terminal.click()+ await browser.waitUntil(async () => (await appearance()).terminal, { timeoutMsg: '终端开关未通过原生桥保存' })+ const transparency = await browser.$('[data-testid="dsh-appearance-transparency"] input[role="switch"]')+ await transparency.waitForEnabled()+ await transparency.click()+ await browser.waitUntil(async () => (await appearance()).transparency)+ 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 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 })+ await click('dsh-config-dialog-close')+ })++ it('persists shell zoom shortcuts without changing other native settings', async () => {+ async function config() {+ return browser.execute(() => {+ const bridge = (window as unknown as { __TAURI_INTERNALS__: { invoke: (command: string) => Promise<{ zoom_factor: number, appearance: unknown, backup_include_credentials: boolean }> } }).__TAURI_INTERNALS__+ return bridge.invoke('get_app_config')+ })+ }+ async function shortcut(key: string) {+ await browser.execute((key) => {+ document.dispatchEvent(new KeyboardEvent('keydown', { key, ctrlKey: true, bubbles: true }))+ }, key)+ }+ const original = await config()+ try {+ await shortcut('0')+ await browser.waitUntil(async () => (await config()).zoom_factor === 1, { timeoutMsg: '缩放重置未写入原生设置' })+ await shortcut('+')+ await shortcut('+')+ await browser.waitUntil(async () => (await config()).zoom_factor === 1.2, { timeoutMsg: '连续缩放快捷键未保存到原生设置' })+ const saved = await config()+ expect(saved.appearance, '缩放不应覆盖原生外观设置').toEqual(original.appearance)+ expect(saved.backup_include_credentials, '缩放不应覆盖凭证备份偏好').toBe(original.backup_include_credentials)+ }+ finally {+ await browser.execute(async (zoomFactor) => {+ const bridge = (window as unknown as { __TAURI_INTERNALS__: { invoke: (command: string, args: unknown) => Promise<unknown> } }).__TAURI_INTERNALS__+ await bridge.invoke('update_app_config', { zoomFactor })+ }, original.zoom_factor)+ }+ })})diff --git a/test/e2e/plugins/dsh-tauri-appearance.e2e.ts b/test/e2e/plugins/dsh-tauri-appearance.e2e.tsnew file mode 100644index 00000000..a6136105--- /dev/null+++ b/test/e2e/plugins/dsh-tauri-appearance.e2e.ts@@ -0,0 +1,92 @@+import type { Browser } from 'playwright'+import { afterAll, beforeAll, describe, expect, it } from 'vitest'+import { launchDshBrowser, newDshPage } from '../support/browser'++let browser: Browser+beforeAll(async () => {+ browser = await launchDshBrowser()+})+afterAll(async () => {+ await browser?.close()+})++describe('built-in desktop appearance', () => {+ it.each([+ ['nord', '#eceff4', '#2e3440'],+ ['github', '#f0f6fc', '#1f2328'],+ ['github-dimmed', '#d1d7e0', '#1f2328'],+ ['github-high-contrast', '#ffffff', '#010409'],+ ])('renders %s tokens in the real core and restores its original colours', async (palette, darkText, lightText) => {+ const app = await newDshPage(browser, { ready: 'style[id="dsh-tauri:appearance"]' })+ try {+ const initial = await app.frame.locator('body').evaluate(el => getComputedStyle(el).getPropertyValue('--dsw-alias-label-primary'))+ await app.page.evaluate(palette => document.querySelector('iframe')!.contentWindow!.postMessage({ type: 'dsh://appearance', appearance: { palette } }, location.origin), palette)+ await expect.poll(() => app.frame.locator('body').evaluate((el, [darkText, lightText]) => {+ const dark = el.hasAttribute('data-ds-dark-theme')+ return getComputedStyle(el).getPropertyValue('--dsw-alias-label-primary') === (dark ? darkText : lightText)+ }, [darkText, lightText]), { message: '配色必须通过真实主题服务应用到页面' }).toBe(true)+ await app.page.evaluate(() => document.querySelector('iframe')!.contentWindow!.postMessage({ type: 'dsh://appearance', appearance: {} }, location.origin))+ await expect.poll(() => app.frame.locator('body').evaluate(el => getComputedStyle(el).getPropertyValue('--dsw-alias-label-primary')), { message: '重置必须恢复原有主题变量' }).toBe(initial)+ expect(app.errors, '外观切换不得产生浏览器错误').toEqual([])+ }+ finally {+ await app.close()+ }+ })++ it('hides the sidebar in terminal mode and permits the existing desktop toggle to reveal it', async () => {+ const app = await newDshPage(browser, { ready: 'style[id="dsh-tauri:appearance"]' })+ try {+ const sidebar = app.frame.locator('[data-slot="sidebar"]')+ const originalFont = await app.frame.locator('body').evaluate(el => getComputedStyle(el).fontFamily)+ await app.page.evaluate(() => document.querySelector('iframe')!.contentWindow!.postMessage({ type: 'dsh://appearance', appearance: { terminal: true } }, location.origin))+ await expect.poll(() => sidebar.evaluate(el => el.parentElement!.getBoundingClientRect().width), { message: '终端模式下侧栏不应占用空白列' }).toBe(0)+ expect(await sidebar.evaluate(el => getComputedStyle(el).visibility), '隐藏侧栏内容不可见').toBe('hidden')+ expect(await app.frame.locator('body').evaluate(el => getComputedStyle(el).fontFamily)).toBe(originalFont)+ await app.page.evaluate(() => document.querySelector('iframe')!.contentWindow!.postMessage({ type: 'dsh://sidebar:toggle' }, location.origin))+ await expect.poll(() => sidebar.evaluate(el => el.parentElement!.getBoundingClientRect().width), { message: '原有侧栏开关必须能恢复侧栏' }).toBeGreaterThanOrEqual(264)+ expect(await sidebar.evaluate(el => getComputedStyle(el).visibility), '展开后侧栏内容可见').toBe('visible')+ expect(app.errors, '终端模式不得产生浏览器错误').toEqual([])+ }+ finally {+ await app.close()+ }+ })++ it('keeps the session opaque while the sidebar is transparent and restores full-window transparency', async () => {+ const app = await newDshPage(browser, { ready: 'style[id="dsh-tauri:appearance"]' })+ try {+ await app.page.evaluate(() => document.querySelector('iframe')!.contentWindow!.postMessage({ type: 'dsh://appearance', appearance: { palette: 'forest', transparency: true, opacity: 70, sidebarOnly: true } }, location.origin))+ const main = app.frame.locator('[data-slot="main"]')+ await expect.poll(() => main.evaluate(el => getComputedStyle(el.parentElement!).backgroundColor), { message: '会话区域必须有不透明背景' }).toMatch(/^rgb\(/)+ expect(await main.evaluate(el => getComputedStyle(el).getPropertyValue('--dsw-alias-bg-base'))).toMatch(/^#[\da-f]{6}$/i)+ expect(await app.frame.locator('[data-slot="sidebar"]').evaluate(el => getComputedStyle(el).getPropertyValue('--dsw-alias-bg-base'))).toBe('transparent')+ expect(await app.frame.locator('body').evaluate(el => getComputedStyle(el).backgroundColor)).toMatch(/(?:0\.7\)|\/ 0\.7\))/)+ await app.page.evaluate(() => document.querySelector('iframe')!.contentWindow!.postMessage({ type: 'dsh://appearance', appearance: { palette: 'forest', transparency: true, opacity: 70, sidebarOnly: false } }, location.origin))+ await expect.poll(() => main.evaluate(el => getComputedStyle(el).getPropertyValue('--dsw-alias-bg-base'))).toBe('transparent')+ expect(app.errors).toEqual([])+ }+ finally {+ await app.close()+ }+ })++ it('applies alpha to the canvas without fading text or menu surfaces', async () => {+ const app = await newDshPage(browser, { ready: 'style[id="dsh-tauri:appearance"]' })+ try {+ await app.page.evaluate(() => document.querySelector('iframe')!.contentWindow!.postMessage({ type: 'dsh://appearance', appearance: { palette: 'forest', opacity: 70 } }, location.origin))+ await expect.poll(() => app.frame.locator('body').evaluate(el => getComputedStyle(el).backgroundColor), { message: '画布背景应保留 70% 不透明度' }).toMatch(/(?:0\.7\)|\/ 0\.7\))/)+ const surface = await app.frame.locator('body').evaluate((el) => {+ const css = getComputedStyle(el)+ return { opacity: css.opacity, menu: css.getPropertyValue('--dsw-specific-menu'), base: css.getPropertyValue('--dsw-alias-bg-base') }+ })+ expect(surface.opacity, '文字不得随背景整体淡化').toBe('1')+ expect(surface.menu, '菜单必须有不透明底色').toMatch(/^#[\da-f]{6}$/i)+ expect(surface.base, '嵌套画布不得叠加不透明背景').toBe('transparent')+ expect(app.errors, '透明模式不得产生浏览器错误').toEqual([])+ }+ finally {+ await app.close()+ }+ })+})