fix(web): persist theme preference in settings

This commit is contained in:
Yichen Jiang
2026-08-06 20:27:31 +08:00
parent 6a32047e77
commit dd473870dd
30 changed files with 692 additions and 121 deletions

View File

@@ -2,11 +2,13 @@
* locale service, declaration-aware Appearance row registration, snapshot
* projection into the row store, and HMR collapse recovery. */
import { Context } from 'cordis'
import { describe, expect, it } from 'vitest'
import { describe, expect, it, vi } from 'vitest'
import { SlotsService } from '@deepseek-ai/dsh-client-runtime/client'
import { LocaleService } from '@deepseek-ai/dsh-client-locale/client'
import { usePinnedBrowserLanguages } from '@deepseek-ai/dsh-client-test-runtime'
import { apply, inject, SETTINGS_NS } from '@deepseek-ai/dsh-client-ui-theme/client'
import {
apply, inject, SETTINGS_NS, THEME_SETTINGS_NAMESPACE,
} from '@deepseek-ai/dsh-client-ui-theme/client'
import type { AppearanceRowInjected, ThemeService } from '@deepseek-ai/dsh-client-ui-theme/client'
import { AppearanceRow } from '../src/client/AppearanceRow.tsx'
import type { createAppearanceRowStore } from '../src/client/settings-store.ts'
@@ -17,12 +19,39 @@ usePinnedBrowserLanguages('zh-CN')
const SLOT = 'settings.general.item'
async function bench() {
async function bench(isLoopback = true) {
const ctx = new Context()
await ctx.plugin(SlotsService).await()
const locale = new LocaleService(ctx)
ctx.provide('locale', locale)
return { ctx, slots: ctx.get('slots') as SlotsService, locale }
let preference = 'system'
const namespace = () => ({
ns: THEME_SETTINGS_NAMESPACE,
schema: {},
value: { preference },
applies: 'live' as const,
secrets: [],
revision: 0,
})
const describe = vi.fn(() => Promise.resolve({
rpcId: 'theme-describe' as never,
result: {
ok: true as const,
value: { writable: true, hasDocument: true, namespaces: [namespace()] },
},
}))
const mutate = vi.fn((request: { ops: { value: string }[] }) => {
preference = request.ops[0]!.value
return Promise.resolve({
rpcId: 'theme-mutate' as never,
result: { ok: true as const, value: namespace() },
})
})
ctx.provide('connection', { api: { settings: { describe, mutate } }, isLoopback } as never)
return {
ctx, slots: ctx.get('slots') as SlotsService, locale, describe, mutate,
setHostPreference: (next: string) => { preference = next },
}
}
/** Stand in for the settings shell: declare the General item slot from root. */
@@ -45,7 +74,7 @@ function faceOf(slots: SlotsService) {
describe('ui-theme apply', () => {
it('declares the slot and locale services', () => {
expect(inject).toEqual(['slots', 'locale'])
expect(inject).toEqual(['slots', 'locale', 'connection'])
})
it('provides the service, registers localized copy, and registers the row (declaration before or after apply)', async () => {
@@ -84,6 +113,33 @@ describe('ui-theme apply', () => {
face.setTheme('system')
expect(theme.getTheme().preference).toBe('system')
expect(instance.getSnapshot().preference).toBe('system')
await vi.waitFor(() => { expect(b.mutate).toHaveBeenCalledTimes(2) })
})
it('loads Host settings at boot, refreshes its namespace, and keeps remote browsers process-local', async () => {
const b = await bench()
b.setHostPreference('dark')
declareItems(b.slots)
await b.ctx.plugin({ inject: [...inject], apply }).await()
const theme = b.ctx.get('theme') as ThemeService
expect(theme.getTheme().preference).toBe('dark')
b.ctx.emit('settings/changed', 'unrelated')
expect(b.describe).toHaveBeenCalledOnce()
b.setHostPreference('light')
b.ctx.emit('settings/changed', THEME_SETTINGS_NAMESPACE)
await vi.waitFor(() => { expect(theme.getTheme().preference).toBe('light') })
b.setHostPreference('dark')
b.ctx.emit('connection/reset')
await vi.waitFor(() => { expect(theme.getTheme().preference).toBe('dark') })
const remote = await bench(false)
declareItems(remote.slots)
await remote.ctx.plugin({ inject: [...inject], apply }).await()
const remoteTheme = remote.ctx.get('theme') as ThemeService
remoteTheme.setTheme('dark')
await Promise.resolve()
expect(remote.describe).not.toHaveBeenCalled()
expect(remote.mutate).not.toHaveBeenCalled()
})
it('recovers after an HMR collapse of the declaring entry (stale disposer must not block)', async () => {

View File

@@ -0,0 +1,30 @@
import { Context } from 'cordis'
import { describe, expect, it } from 'vitest'
import { Settings, settingsNamespace, type SettingsNamespace } from '@deepseek-ai/dsh-settings'
import {
DEFAULT_PREFERENCE, THEME_SETTINGS_NAMESPACE, apply,
} from '@deepseek-ai/dsh-client-ui-theme'
class MemorySettings extends Settings {
readonly writable = true
protected load(): Promise<Record<string, unknown>> { return Promise.resolve({}) }
protected persist(_ns: SettingsNamespace, _section: Record<string, unknown>): Promise<void> {
return Promise.resolve()
}
}
describe('ui-theme host', () => {
it('registers, validates, and disposes the durable theme namespace with its fiber', async () => {
const ctx = new Context()
await ctx.plugin(MemorySettings).await()
const fiber = ctx.plugin({ apply })
await fiber.await()
const ns = settingsNamespace(THEME_SETTINGS_NAMESPACE)
expect(ctx.settings.get(ns)).toEqual({ preference: DEFAULT_PREFERENCE })
await ctx.settings.update(ns, { preference: 'dark' })
expect(ctx.settings.get(ns)).toEqual({ preference: 'dark' })
await expect(ctx.settings.update(ns, { preference: 'sepia' })).rejects.toThrow()
await fiber.dispose()
expect(ctx.settings.describe().map(row => row.ns)).not.toContain(ns)
})
})

View File

@@ -15,18 +15,25 @@ describe('invariant companion', () => {
await expect(ctx.plugin(ThemeInvariant).await()).resolves.toBeDefined()
})
it('node-half apply is a no-op host placeholder', () => {
nodeApply()
expect(true).toBe(true) // reaching here without throw is the contract
it('node-half waits for an optional settings provider', () => {
nodeApply(new Context())
expect(true).toBe(true)
})
it('client apply provides ctx.theme over the slots/locale edges', async () => {
// The feature registers its own Appearance settings row with localized
// copy, hence the slots + locale edges.
expect(inject).toEqual(['slots', 'locale'])
expect(inject).toEqual(['slots', 'locale', 'connection'])
const ctx = new Context()
new SlotsService(ctx)
await ctx.plugin({ inject: ['slots'], apply: localeApply }).await()
ctx.provide('connection', {
api: { settings: { describe: () => Promise.resolve({
rpcId: 'theme-invariant' as never,
result: { ok: true, value: { writable: true, hasDocument: false, namespaces: [] } },
}) } },
isLoopback: true,
} as never)
await ctx.plugin({ inject, apply: clientApply }).await()
expect(ctx.get('theme')).toBeInstanceOf(ThemeService)
})

View File

@@ -0,0 +1,149 @@
import { describe, expect, it, vi } from 'vitest'
import type { RpcResponse, SettingsNamespaceView } from '@deepseek-ai/dsh-client-connection/client'
import {
THEME_PREFERENCE_FIELD, THEME_SETTINGS_NAMESPACE, ThemeSettingsController,
type ThemePreference,
} from '@deepseek-ai/dsh-client-ui-theme/client'
let rpc = 0
function ok<T>(value: T): RpcResponse<T> {
return { rpcId: `theme-${rpc++}` as never, result: { ok: true, value } }
}
function view(preference: unknown = 'system'): SettingsNamespaceView {
return {
ns: THEME_SETTINGS_NAMESPACE,
schema: {},
value: { [THEME_PREFERENCE_FIELD]: preference },
applies: 'live',
secrets: [],
revision: 0,
}
}
function described(preference: unknown = 'system') {
return ok({ writable: true, hasDocument: true, namespaces: [view(preference)] })
}
function deferred<T>() {
let resolve!: (value: T) => void
let reject!: (reason: unknown) => void
const promise = new Promise<T>((res, rej) => { resolve = res; reject = rej })
return { promise, resolve, reject }
}
function target() {
const values: ThemePreference[] = []
return { values, syncPreference: (preference: ThemePreference) => { values.push(preference) } }
}
describe('ThemeSettingsController', () => {
it('loads a valid Host value and ignores unavailable or malformed namespaces', async () => {
const receiver = target()
const describe = vi.fn()
.mockResolvedValueOnce(described('dark'))
.mockResolvedValueOnce(ok({ writable: true, hasDocument: true, namespaces: [] }))
.mockResolvedValueOnce(described('sepia'))
.mockResolvedValueOnce(ok({ writable: true, hasDocument: true, namespaces: [{ ...view(), value: null }] }))
.mockResolvedValueOnce({
rpcId: 'failed' as never,
result: { ok: false as const, error: { code: 'internal' as const, message: 'offline', details: {} } },
})
.mockRejectedValueOnce(new Error('transport offline'))
const controller = new ThemeSettingsController({ settings: { describe } } as never, receiver)
for (let i = 0; i < 6; i++) await controller.load()
expect(receiver.values).toEqual(['dark'])
})
it('persists ordered rapid selections and publishes only the latest settlement', async () => {
const first = deferred<ReturnType<typeof ok<SettingsNamespaceView>>>()
const calls: string[] = []
const mutate = vi.fn(async (request: { ops: { value: string }[] }) => {
const preference = request.ops[0]!.value
calls.push(preference)
if (preference === 'dark') return first.promise
return ok(view(preference))
})
const receiver = target()
const controller = new ThemeSettingsController({ settings: { mutate } } as never, receiver)
const dark = controller.persist('dark')
const light = controller.persist('light')
await Promise.resolve()
expect(calls).toEqual(['dark'])
first.resolve(ok(view('dark')))
await Promise.all([dark, light])
expect(calls).toEqual(['dark', 'light'])
expect(receiver.values).toEqual(['light'])
expect(mutate).toHaveBeenNthCalledWith(1, {
ns: THEME_SETTINGS_NAMESPACE,
ops: [{ op: 'set', path: [THEME_PREFERENCE_FIELD], value: 'dark' }],
})
})
it('reloads after a rejected latest write and contains stale reads and disposal', async () => {
const stale = deferred<ReturnType<typeof described>>()
const describe = vi.fn()
.mockImplementationOnce(() => stale.promise)
.mockResolvedValueOnce(described('system'))
const mutate = vi.fn().mockResolvedValue({
rpcId: 'rejected' as never,
result: { ok: false as const, error: { code: 'settings-rejected' as const, message: 'disk full', details: {} } },
})
const receiver = target()
const controller = new ThemeSettingsController({ settings: { describe, mutate } } as never, receiver)
const oldLoad = controller.load()
await vi.waitFor(() => { expect(describe).toHaveBeenCalledOnce() })
await controller.persist('dark')
stale.resolve(described('light'))
await oldLoad
expect(receiver.values).toEqual(['system'])
const disposedRead = deferred<ReturnType<typeof described>>()
describe.mockImplementationOnce(() => disposedRead.promise)
const pending = controller.load()
controller.dispose()
disposedRead.resolve(described('dark'))
await pending
expect(receiver.values).toEqual(['system'])
})
it('keeps remote-browser persistence in memory without calling Host settings', async () => {
const describe = vi.fn()
const mutate = vi.fn()
const receiver = target()
const controller = new ThemeSettingsController({ settings: { describe, mutate } } as never, receiver, 'memory')
await controller.load()
await controller.persist('dark')
expect(describe).not.toHaveBeenCalled()
expect(mutate).not.toHaveBeenCalled()
expect(receiver.values).toEqual([])
})
it('reloads after a thrown write and ignores a malformed success response', async () => {
const receiver = target()
const describe = vi.fn().mockResolvedValue(described('light'))
const mutate = vi.fn()
.mockRejectedValueOnce(new Error('offline'))
.mockResolvedValueOnce(ok(view('sepia')))
const controller = new ThemeSettingsController({ settings: { describe, mutate } } as never, receiver)
await controller.persist('dark')
await controller.persist('system')
expect(receiver.values).toEqual(['light'])
})
it('lets an explicit refresh supersede a stale rejected write', async () => {
const rejected = deferred<never>()
const receiver = target()
const describe = vi.fn().mockResolvedValue(described('system'))
const mutate = vi.fn().mockReturnValue(rejected.promise)
const controller = new ThemeSettingsController({ settings: { describe, mutate } } as never, receiver)
const write = controller.persist('dark')
await vi.waitFor(() => { expect(mutate).toHaveBeenCalledOnce() })
const refresh = controller.load()
rejected.reject(new Error('stale rejection'))
await Promise.all([write, refresh])
expect(receiver.values).toEqual(['system'])
expect(describe).toHaveBeenCalledOnce()
})
})

View File

@@ -1,21 +1,22 @@
// @vitest-environment jsdom
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { afterEach, describe, expect, it, vi } from 'vitest'
import { Context } from 'cordis'
import type { ThemeSnapshot } from '@deepseek-ai/dsh-client-ui-theme/client'
import { STORAGE_KEY, ThemeService } from '@deepseek-ai/dsh-client-ui-theme/client'
import { ThemeService } from '@deepseek-ai/dsh-client-ui-theme/client'
const make = (): { ctx: Context; theme: ThemeService; events: ThemeSnapshot[] } => {
const make = (persist = vi.fn()): {
ctx: Context
theme: ThemeService
events: ThemeSnapshot[]
persist: typeof persist
} => {
const ctx = new Context()
const events: ThemeSnapshot[] = []
ctx.on('theme/change', (snapshot) => { events.push(snapshot) })
return { ctx, theme: new ThemeService(ctx), events }
return { ctx, theme: new ThemeService(ctx, persist), events, persist }
}
describe('ThemeService', () => {
beforeEach(() => {
localStorage.clear()
})
it('defaults to the system preference resolved against prefers-color-scheme', () => {
const { theme } = make()
const snapshot = theme.getTheme()
@@ -26,12 +27,12 @@ describe('ThemeService', () => {
expect(snapshot.themes.map(t => t.id)).toEqual(['light', 'dark'])
})
it('setTheme switches, persists, republishes, and keeps DOM untouched', () => {
const { theme, events } = make()
it('setTheme switches, requests persistence, republishes, and keeps DOM untouched', () => {
const { theme, events, persist } = make()
theme.setTheme('dark')
expect(theme.getTheme().preference).toBe('dark')
expect(theme.getTheme().active.colorScheme).toBe('dark')
expect(localStorage.getItem(STORAGE_KEY)).toBe('dark')
expect(persist).toHaveBeenCalledWith('dark')
expect(events).toHaveLength(1)
expect(events[0]).toBe(theme.getTheme())
// The service never touches presentation state.
@@ -39,13 +40,17 @@ describe('ThemeService', () => {
// Same-value set is a no-op (no extra event).
theme.setTheme('dark')
expect(events).toHaveLength(1)
expect(persist).toHaveBeenCalledOnce()
})
it('restores a persisted preference and falls back on garbage', () => {
localStorage.setItem(STORAGE_KEY, 'dark')
expect(make().theme.getTheme().preference).toBe('dark')
localStorage.setItem(STORAGE_KEY, 'sepia')
expect(make().theme.getTheme().preference).toBe('system')
it('syncs a Host preference without writing it back', () => {
const { theme, events, persist } = make()
theme.syncPreference('dark')
expect(theme.getTheme().preference).toBe('dark')
expect(events).toHaveLength(1)
expect(persist).not.toHaveBeenCalled()
theme.syncPreference('dark')
expect(events).toHaveLength(1)
})
it('throws on unknown setTheme ids, duplicate registration, and the system id', () => {
@@ -56,7 +61,7 @@ describe('ThemeService', () => {
})
it('registered themes join the snapshot; disposing the active one resets to default', () => {
const { theme, events } = make()
const { theme, events, persist } = make()
const dispose = theme.register({ id: 'sepia', colorScheme: 'light', tokens: { '--dsw-alias-bg-base': 'red' } })
expect(theme.getTheme().themes.map(t => t.id)).toEqual(['light', 'dark', 'sepia'])
theme.setTheme('sepia')
@@ -64,7 +69,10 @@ describe('ThemeService', () => {
dispose()
expect(theme.getTheme().preference).toBe('system')
expect(theme.getTheme().themes.map(t => t.id)).toEqual(['light', 'dark'])
expect(localStorage.getItem(STORAGE_KEY)).toBe('system')
// Custom ids are in-process extension themes; only the built-in product
// preferences cross the Host settings schema.
expect(persist).toHaveBeenCalledTimes(1)
expect(persist).toHaveBeenCalledWith('system')
// register + set + dispose = three publishes; disposer is idempotent.
expect(events.length).toBe(3)
dispose()
@@ -88,16 +96,11 @@ describe('ThemeService', () => {
expect(events.map(e => e.revision)).toEqual([1, 2, 3, 4])
})
it('runs without localStorage (node boots): defaults on read, no-op on write', () => {
vi.stubGlobal('localStorage', undefined)
try {
const { theme } = make()
expect(theme.getTheme().preference).toBe('system')
theme.setTheme('dark')
expect(theme.getTheme().preference).toBe('dark')
} finally {
vi.unstubAllGlobals()
}
it('uses a no-op persistence callback when constructed directly', () => {
const ctx = new Context()
const theme = new ThemeService(ctx)
theme.setTheme('dark')
expect(theme.getTheme().preference).toBe('dark')
})
describe('prefers-color-scheme resolution (stubbed matchMedia)', () => {