Skip to content

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

refactor(plugins): centralize declarative store persistence (#804)

Mao Mr2c361270357f
diff --git a/packages/dsh-tauri-model/src/client/store/modules/open-in-app.ts b/packages/dsh-tauri-model/src/client/store/modules/open-in-app.ts
new file mode 100644
index 00000000..aef52cad
--- /dev/null
+++ b/packages/dsh-tauri-model/src/client/store/modules/open-in-app.ts
@@ -0,0 +1,12 @@
+import { defineStore } from 'dsh-tauri/client'
+import { PLUGIN_ID } from '../../../shared/constants'
+
+export const openInApp = defineStore({
+ state: () => ({ choice: '' }),
+ persist: { key: `${PLUGIN_ID}.open-in-app.choice` },
+ actions: {
+ setChoice(id: string) {
+ this.choice = id
+ },
+ },
+})
diff --git a/packages/dsh-tauri-model/src/client/ui/model-extras/model-config-toolbar.tsx b/packages/dsh-tauri-model/src/client/ui/model-extras/model-config-toolbar.tsx
index 95cac71c..f7a37e78 100644
--- a/packages/dsh-tauri-model/src/client/ui/model-extras/model-config-toolbar.tsx
+++ b/packages/dsh-tauri-model/src/client/ui/model-extras/model-config-toolbar.tsx
@@ -2,8 +2,10 @@ import type { ReactElement } from 'react'
import type { WorkspacePathApplication } from '../../types/remotes.ts'
import type { Translate } from './types'
import { Action, Select } from 'dsh-tauri-ui/client'
+import { useStore } from 'dsh-tauri/client'
import { useEffect, useState } from 'react'
import { listConfigApplications, openConfigInApp } from '../../service/open-in-app'
+import { openInApp } from '../../store/modules/open-in-app'
export type ModelDraft = Record<string, unknown>
@@ -23,19 +25,14 @@ export interface ModelConfigToolbarProps {
}
const DEFAULT_APPLICATION = ''
-const APPLICATION_CHOICE_KEY = 'dsh-tauri-model.open-in-app.choice'
-/**
- * 模型页工具条:左侧用哪个应用打开(复用 ui 的 `Select`),右侧「打开配置文件」。
- * 候选来自官方 open-in-app 的主机目录,低版本核心或非桌面环境为空,此时只剩右侧按钮。
- */
export function ModelConfigToolbar({
t,
onOpenConfig,
disabled,
}: ModelConfigToolbarProps): ReactElement {
const [applications, setApplications] = useState<readonly WorkspacePathApplication[]>([])
- const [choice, setChoice] = useState<string>(readChoice)
+ const { choice } = useStore(openInApp)
useEffect(() => {
let active = true
@@ -78,10 +75,7 @@ export function ModelConfigToolbar({
]}
value={selected === undefined ? DEFAULT_APPLICATION : choice}
icon={selected === undefined ? undefined : <ApplicationIcon application={selected} />}
- onChange={(id) => {
- setChoice(id)
- writeChoice(id)
- }}
+ onChange={openInApp.setChoice}
/>
)}
<Action className="text-[13px] text-secondary rounded-[14px]" variant="link" disabled={disabled} onClick={openConfig}>
@@ -94,21 +88,3 @@ export function ModelConfigToolbar({
function ApplicationIcon({ application }: { application: WorkspacePathApplication }): ReactElement {
return <img src={application.icon ?? ''} alt="" className="w-[14px] h-[14px] rounded-[3px] flex-none" />
}
-
-function readChoice(): string {
- try {
- return localStorage.getItem(APPLICATION_CHOICE_KEY) ?? DEFAULT_APPLICATION
- }
- catch {
- return DEFAULT_APPLICATION
- }
-}
-
-function writeChoice(id: string): void {
- try {
- localStorage.setItem(APPLICATION_CHOICE_KEY, id)
- }
- catch {
-
- }
-}
diff --git a/packages/dsh-tauri-model/src/client/ui/model-extras/model-extras.test.tsx b/packages/dsh-tauri-model/src/client/ui/model-extras/model-extras.test.tsx
index ce63e28c..30623a46 100644
--- a/packages/dsh-tauri-model/src/client/ui/model-extras/model-extras.test.tsx
+++ b/packages/dsh-tauri-model/src/client/ui/model-extras/model-extras.test.tsx
@@ -13,6 +13,7 @@ const mocks = vi.hoisted(() => ({
vi.mock('dsh-tauri/client', async () => ({
...await import('tailwind-variants'),
+ ...await import('../../../../../dsh-tauri/src/client/modules/valtio-define'),
ofetch: mocks.ofetch,
defineLocale: (_namespace: string, dicts: { zh: Record<string, string>, en: Record<string, string> }) => {
mocks.dicts = dicts
diff --git a/packages/dsh-tauri-notification/src/client/index.ts b/packages/dsh-tauri-notification/src/client/index.ts
index 00df95b6..357253bd 100644
--- a/packages/dsh-tauri-notification/src/client/index.ts
+++ b/packages/dsh-tauri-notification/src/client/index.ts
@@ -4,7 +4,6 @@ import { LOCALE_EFFECT, NOTIFY_EFFECT, SETTINGS_EFFECT } from './constants'
import { locale } from './locales'
import { notifyFeature } from './register/notify'
import { settingsFeature } from './register/settings'
-import { notificationSettings } from './store/modules/settings'
export const name = PLUGIN_ID
@@ -15,9 +14,6 @@ export const name = PLUGIN_ID
export const inject = ['slots', 'locale', 'sessions']
export function apply(ctx: ClientContext): void {
- // 先把本地存储里的设置读回内存:通知运行时与设置面板都直接读 store,
- // 不 hydrate 的话每次启动都从默认值开始,用户改过的选项会被首次写回覆盖。
- void notificationSettings.hydrate()
ctx.effect(locale.registerLocale, LOCALE_EFFECT)
ctx.effect(settingsFeature, SETTINGS_EFFECT)
ctx.effect(notifyFeature, NOTIFY_EFFECT)
diff --git a/packages/dsh-tauri-notification/src/client/service/settings.test.ts b/packages/dsh-tauri-notification/src/client/service/settings.test.ts
deleted file mode 100644
index 8ec93050..00000000
--- a/packages/dsh-tauri-notification/src/client/service/settings.test.ts
+++ /dev/null
@@ -1,108 +0,0 @@
-import { beforeEach, describe, expect, it, vi } from 'vitest'
-
-// `settings.ts` 的模块级 `createStorage(...)` 会走 `dsh-tauri/client` 的运行时模块表,
-// 在 node 下不可求值;这里按仓库既有做法(见 dsh-tauri-ssh 的客户端用例)打桩成内存存储。
-// `vi.hoisted` 保证工厂在 import 之前就能拿到这份 Map。
-const { memory } = vi.hoisted(() => ({ memory: new Map<string, unknown>() }))
-
-vi.mock('dsh-tauri/client', () => ({
- createStorage: () => ({
- getItem: async (key: string) => memory.get(key) ?? null,
- setItem: async (key: string, value: unknown) => { memory.set(key, value) },
- }),
- localStorageDriver: () => ({}),
-}))
-
-const { DEFAULT_SETTINGS, loadSettings, parseSettings, saveSettings } = await import('./settings')
-
-/** 一个合法的自定义提示音(data URL,长度在限制内)。 */
-const SOUND_DATA_URL = `data:audio/wav;base64,${'A'.repeat(64)}`
-
-beforeEach(() => {
- memory.clear()
-})
-
-describe('dEFAULT_SETTINGS', () => {
- it('与参考实现一致:完成提醒仅在未聚焦时、权限与提问开启、默认提示音', () => {
- expect(DEFAULT_SETTINGS).toEqual({
- turnComplete: 'background',
- approval: true,
- question: true,
- sound: 'default',
- customSound: null,
- })
- })
-
- it('被冻结,避免调用方就地改写共享默认值', () => {
- expect(Object.isFrozen(DEFAULT_SETTINGS)).toBe(true)
- })
-})
-
-describe('parseSettings', () => {
- it('完整合法值原样通过', () => {
- const raw = { turnComplete: 'always', approval: false, question: false, sound: 'classic', customSound: SOUND_DATA_URL }
- expect(parseSettings(raw)).toEqual(raw)
- })
-
- it('非对象输入整体退化为默认值', () => {
- expect(parseSettings(undefined)).toEqual(DEFAULT_SETTINGS)
- expect(parseSettings(null)).toEqual(DEFAULT_SETTINGS)
- expect(parseSettings('nope')).toEqual(DEFAULT_SETTINGS)
- expect(parseSettings(42)).toEqual(DEFAULT_SETTINGS)
- })
-
- it('未知枚举值退回默认,而不是透传脏数据', () => {
- expect(parseSettings({ turnComplete: 'sometimes', sound: 'loud' })).toEqual(DEFAULT_SETTINGS)
- })
-
- it('缺字段时逐项补默认值', () => {
- expect(parseSettings({ turnComplete: 'never' })).toEqual({ ...DEFAULT_SETTINGS, turnComplete: 'never' })
- })
-
- it('非布尔开关退回默认开启', () => {
- expect(parseSettings({ approval: 'yes', question: 0 })).toEqual(DEFAULT_SETTINGS)
- expect(parseSettings({ approval: false, question: false })).toEqual({ ...DEFAULT_SETTINGS, approval: false, question: false })
- })
-
- it('自定义提示音必须是 data URL 且在长度上限内', () => {
- expect(parseSettings({ sound: 'custom', customSound: SOUND_DATA_URL }).customSound).toBe(SOUND_DATA_URL)
- expect(parseSettings({ sound: 'custom', customSound: 'https://example.com/a.wav' }).customSound).toBeNull()
- expect(parseSettings({ sound: 'custom', customSound: '' }).customSound).toBeNull()
- expect(parseSettings({ sound: 'custom', customSound: `data:audio/wav;base64,${'A'.repeat(760_001)}` }).customSound).toBeNull()
- })
-
- it('选了自定义却没有可用音频时退回默认音,避免「选了却没声音」', () => {
- expect(parseSettings({ sound: 'custom' }).sound).toBe('default')
- expect(parseSettings({ sound: 'custom', customSound: 'not-a-data-url' }).sound).toBe('default')
- expect(parseSettings({ sound: 'custom', customSound: SOUND_DATA_URL }).sound).toBe('custom')
- })
-
- it('非自定义音时仍保留已存的自定义数据,便于切回自定义', () => {
- expect(parseSettings({ sound: 'none', customSound: SOUND_DATA_URL }).customSound).toBe(SOUND_DATA_URL)
- expect(parseSettings({ sound: 'none' }).sound).toBe('none')
- })
-})
-
-describe('loadSettings', () => {
- it('存储为空时退化为默认值', async () => {
- await expect(loadSettings()).resolves.toEqual(DEFAULT_SETTINGS)
- })
-
- it('读取已存设置时收敛成合法值', async () => {
- memory.set('settings', { turnComplete: 'always', approval: false, sound: 'classic' })
- await expect(loadSettings()).resolves.toEqual({
- turnComplete: 'always',
- approval: false,
- question: true,
- sound: 'classic',
- customSound: null,
- })
- })
-})
-
-describe('saveSettings', () => {
- it('写回不含运行时态(hydrated)的纯设置', async () => {
- await expect(saveSettings({ ...DEFAULT_SETTINGS, turnComplete: 'never' })).resolves.toEqual({ ok: true })
- expect(memory.get('settings')).toEqual({ ...DEFAULT_SETTINGS, turnComplete: 'never' })
- })
-})
diff --git a/packages/dsh-tauri-notification/src/client/service/settings.ts b/packages/dsh-tauri-notification/src/client/service/settings.ts
deleted file mode 100644
index bdec8dab..00000000
--- a/packages/dsh-tauri-notification/src/client/service/settings.ts
+++ /dev/null
@@ -1,81 +0,0 @@
-import type { NotificationSettings } from '../types'
-import { createStorage, localStorageDriver } from 'dsh-tauri/client'
-import { PLUGIN_ID } from '../../shared/constants'
-
-/** 存储键:unstorage 的 base 已隔离到插件自身命名空间。 */
-const SETTINGS_KEY = 'settings'
-
-/** 自定义提示音的 data URL 上限,与 512 KB 的原始文件上限留出 base64 膨胀余量。 */
-const MAX_CUSTOM_SOUND_CHARS = 760_000
-
-const TURN_MODES = ['never', 'background', 'always'] as const
-const SOUNDS = ['default', 'classic', 'none', 'custom'] as const
-
-/** 默认设置:与参考实现(问题/权限开、完成提醒仅在未聚焦时、默认提示音)一致。 */
-export const DEFAULT_SETTINGS: NotificationSettings = Object.freeze({
- turnComplete: 'background',
- approval: true,
- question: true,
- sound: 'default',
- customSound: null,
-})
-
-const storage = createStorage({ driver: localStorageDriver({ base: PLUGIN_ID }) })
-
-function asBoolean(value: unknown, fallback: boolean): boolean {
- return typeof value === 'boolean' ? value : fallback
-}
-
-function asCustomSound(value: unknown): string | null {
- if (typeof value !== 'string' || !value.startsWith('data:') || value.length > MAX_CUSTOM_SOUND_CHARS)
- return null
- return value
-}
-
-/** 把任意来源(本地存储、旧版本写入的残缺值)收敛成合法设置。 */
-export function parseSettings(raw: unknown): NotificationSettings {
- const source: Record<string, unknown> = raw && typeof raw === 'object' ? raw as Record<string, unknown> : {}
- const turnComplete = typeof source.turnComplete === 'string' && (TURN_MODES as readonly string[]).includes(source.turnComplete)
- ? source.turnComplete as NotificationSettings['turnComplete']
- : DEFAULT_SETTINGS.turnComplete
- const customSound = asCustomSound(source.customSound)
- const picked = typeof source.sound === 'string' && (SOUNDS as readonly string[]).includes(source.sound)
- ? source.sound as NotificationSettings['sound']
- : DEFAULT_SETTINGS.sound
- return {
- turnComplete,
- approval: asBoolean(source.approval, DEFAULT_SETTINGS.approval),
- question: asBoolean(source.question, DEFAULT_SETTINGS.question),
- // 选自定义但没有可用的音频数据时退回默认音,避免「选了却没声音」。
- sound: picked === 'custom' && !customSound ? DEFAULT_SETTINGS.sound : picked,
- customSound,
- }
-}
-
-export interface SaveSettingsResult {
- ok: boolean
- error?: string
-}
-
-/** 读取设置;任何异常(无 localStorage、配额、解析失败)都退化为默认值。 */
-export async function loadSettings(): Promise<NotificationSettings> {
- try {
- return parseSettings(await storage.getItem(SETTINGS_KEY))
- }
- catch (error) {
- console.warn(`[${PLUGIN_ID}] failed to read settings`, error)
- return { ...DEFAULT_SETTINGS }
- }
-}
-
-/** 写入设置;失败只记录日志,UI 永远以内存态为准。 */
-export async function saveSettings(settings: NotificationSettings): Promise<SaveSettingsResult> {
- try {
- await storage.setItem(SETTINGS_KEY, { ...settings })
- return { ok: true }
- }
- catch (error) {
- console.warn(`[${PLUGIN_ID}] failed to save settings`, error)
- return { ok: false, error: error instanceof Error ? error.message : String(error) }
- }
-}
diff --git a/packages/dsh-tauri-notification/src/client/store/modules/settings.ts b/packages/dsh-tauri-notification/src/client/store/modules/settings.ts
index 647d7ca1..c17ed3c7 100644
--- a/packages/dsh-tauri-notification/src/client/store/modules/settings.ts
+++ b/packages/dsh-tauri-notification/src/client/store/modules/settings.ts
@@ -1,62 +1,35 @@
-import type { NotificationSettings, NotificationSettingsState, NotificationSound, TurnCompleteMode } from '../../types'
+import type { NotificationSettings, NotificationSound, TurnCompleteMode } from '../../types'
import { defineStore } from 'dsh-tauri/client'
-import { DEFAULT_SETTINGS, loadSettings, saveSettings } from '../../service/settings'
+import { PLUGIN_ID } from '../../../shared/constants'
-/** 抽出要持久化的字段(`hydrated` 是内存态,不入库)。 */
-function persisted(state: NotificationSettings): NotificationSettings {
- return {
- turnComplete: state.turnComplete,
- approval: state.approval,
- question: state.question,
- sound: state.sound,
- customSound: state.customSound,
- }
-}
-
-function persist(state: NotificationSettingsState): void {
- void saveSettings(persisted(state))
-}
-
-/**
- * 通知设置的唯一真源。
- *
- * `hydrate` 幂等:React 严格模式的双调用、设置面板反复挂载都只会读一次本地存储。
- * 所有写操作先落内存态(UI 立即响应)再异步持久化。
- */
export const notificationSettings = defineStore({
- state: (): NotificationSettingsState => ({ ...DEFAULT_SETTINGS, hydrated: false }),
+ state: (): NotificationSettings => ({
+ turnComplete: 'background',
+ approval: true,
+ question: true,
+ sound: 'default',
+ customSound: null,
+ }),
+ persist: { key: `${PLUGIN_ID}.settings` },
actions: {
- async hydrate() {
- if (this.hydrated)
- return
- this.hydrated = true
- const loaded = await loadSettings()
- Object.assign(this, loaded)
- },
setTurnComplete(mode: TurnCompleteMode) {
this.turnComplete = mode
- persist(this)
},
setApproval(enabled: boolean) {
this.approval = enabled
- persist(this)
},
setQuestion(enabled: boolean) {
this.question = enabled
- persist(this)
},
setSound(sound: NotificationSound) {
this.sound = sound
- persist(this)
},
- /** 选中自定义提示音文件;传 `null` 表示移除并(必要时)退回默认音。 */
setCustomSound(dataUrl: string | null) {
this.customSound = dataUrl
if (dataUrl)
this.sound = 'custom'
else if (this.sound === 'custom')
- this.sound = DEFAULT_SETTINGS.sound
- persist(this)
+ this.sound = 'default'
},
},
})
diff --git a/packages/dsh-tauri-notification/src/client/types/index.ts b/packages/dsh-tauri-notification/src/client/types/index.ts
index 5e11d860..e361ad86 100644
--- a/packages/dsh-tauri-notification/src/client/types/index.ts
+++ b/packages/dsh-tauri-notification/src/client/types/index.ts
@@ -159,8 +159,3 @@ export interface NotificationSettings {
sound: NotificationSound
customSound: string | null
}
-
-/** store 状态 = 持久化设置 + 一次性水合标记。 */
-export interface NotificationSettingsState extends NotificationSettings {
- hydrated: boolean
-}
diff --git a/packages/dsh-tauri-scheduler/src/client/store/modules/scheduler.ts b/packages/dsh-tauri-scheduler/src/client/store/modules/scheduler.ts
index bbfb0a12..0ace9d09 100644
--- a/packages/dsh-tauri-scheduler/src/client/store/modules/scheduler.ts
+++ b/packages/dsh-tauri-scheduler/src/client/store/modules/scheduler.ts
@@ -1,44 +1,6 @@
import type { SchedulerUiState } from './scheduler.types'
import { defineStore } from 'dsh-tauri/client'
-
-const READ_AT_KEY = 'dsh.scheduler.readAt'
-const READ_IDS_KEY = 'dsh.scheduler.readIds'
-
-function readRaw(key: string): string | null {
- try {
- return localStorage.getItem(key)
- }
- catch {
- return null
- }
-}
-
-function persist(key: string, value: string): void {
- try {
- localStorage.setItem(key, value)
- }
- catch {
- // 持久化不可用(无 localStorage / 配额)时退化为内存态,本次会话内角标照常工作
- }
-}
-
-function readPersistedAt(): number {
- const parsed = Number(readRaw(READ_AT_KEY))
- return Number.isFinite(parsed) && parsed > 0 ? parsed : 0
-}
-
-function readPersistedIds(): string[] {
- const raw = readRaw(READ_IDS_KEY)
- if (raw === null)
- return []
- try {
- const parsed: unknown = JSON.parse(raw)
- return Array.isArray(parsed) ? parsed.filter((id): id is string => typeof id === 'string') : []
- }
- catch {
- return []
- }
-}
+import { PLUGIN_ID } from '../../../shared/constants'
export const scheduler = defineStore({
state: (): SchedulerUiState => ({
@@ -49,24 +11,21 @@ export const scheduler = defineStore({
error: '',
refreshedAt: 0,
loadToken: 0,
- readAt: readPersistedAt(),
- readIds: readPersistedIds(),
+ readAt: 0,
+ readIds: [],
}),
+ persist: { key: `${PLUGIN_ID}.read`, paths: ['readAt', 'readIds'] },
actions: {
- /** 首次载入播种为「此刻已读」:已有历史不再算未读,之后新增的运行才未读。 */
seedReadAt() {
if (this.readAt !== 0)
return
this.readAt = Date.now()
- persist(READ_AT_KEY, String(this.readAt))
},
markRunRead(id: string) {
if (this.readIds.includes(id))
return
this.readIds = [...this.readIds, id]
- persist(READ_IDS_KEY, JSON.stringify(this.readIds))
},
- /** 会话区里打开了某条运行记录的会话:把它记的未读一并消掉。 */
markSessionRead(sessionId: string) {
const next = [...new Set([
...this.readIds,
@@ -75,13 +34,10 @@ export const scheduler = defineStore({
if (next.length === this.readIds.length)
return
this.readIds = next
- persist(READ_IDS_KEY, JSON.stringify(next))
},
markAllRunsRead() {
this.readAt = Date.now()
this.readIds = []
- persist(READ_AT_KEY, String(this.readAt))
- persist(READ_IDS_KEY, '[]')
},
},
})
diff --git a/packages/dsh-tauri/src/client/index.ts b/packages/dsh-tauri/src/client/index.ts
index 8a80de73..5bd32bd3 100644
--- a/packages/dsh-tauri/src/client/index.ts
+++ b/packages/dsh-tauri/src/client/index.ts
@@ -16,7 +16,6 @@ export * from './modules/hookable'
export * from './modules/lodash-es'
export * from './modules/reause'
export * from './modules/tailwind-variants'
-export * from './modules/unstorage'
export * from './modules/valtio-define'
export * from './panel'
diff --git a/packages/dsh-tauri/src/client/modules/unstorage.ts b/packages/dsh-tauri/src/client/modules/unstorage.ts
deleted file mode 100644
index 5eaa68a7..00000000
--- a/packages/dsh-tauri/src/client/modules/unstorage.ts
+++ /dev/null
@@ -1,2 +0,0 @@
-export { createStorage } from 'unstorage'
-export { default as localStorageDriver } from 'unstorage/drivers/localstorage'
diff --git a/packages/dsh-tauri/src/client/modules/valtio-define.ts b/packages/dsh-tauri/src/client/modules/valtio-define.ts
index 81bc8a16..1d3f5b13 100644
--- a/packages/dsh-tauri/src/client/modules/valtio-define.ts
+++ b/packages/dsh-tauri/src/client/modules/valtio-define.ts
@@ -1 +1,6 @@
+import valtio from 'valtio-define'
+import { persist } from 'valtio-define/plugins/persist'
+
+valtio.use(persist())
+
export { defineStore, useStore } from 'valtio-define'
diff --git a/test/plugin-store-persistence.test.ts b/test/plugin-store-persistence.test.ts
new file mode 100644
index 00000000..e2dbddab
--- /dev/null
+++ b/test/plugin-store-persistence.test.ts
@@ -0,0 +1,219 @@
+import { createRequire } from 'node:module'
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+
+const memory = new Map<string, string>()
+const stores: Array<{ $persist?: { dehydrate: () => void } }> = []
+
+beforeEach(() => {
+ vi.resetModules()
+ memory.clear()
+ for (const plugin of ['notification', 'scheduler', 'model']) {
+ const require = createRequire(new URL(`../packages/dsh-tauri-${plugin}/src/client/index.ts`, import.meta.url))
+ vi.doMock(require.resolve('dsh-tauri/client'), () => import('../packages/dsh-tauri/src/client/modules/valtio-define'))
+ }
+ vi.stubGlobal('localStorage', {
+ getItem: (key: string) => memory.get(key) ?? null,
+ setItem: (key: string, value: string) => memory.set(key, value),
+ })
+})
+
+afterEach(() => {
+ for (const store of stores)
+ store.$persist?.dehydrate()
+ stores.length = 0
+ vi.unstubAllGlobals()
+ vi.restoreAllMocks()
+})
+
+async function loadNotification() {
+ const { notificationSettings } = await import('../packages/dsh-tauri-notification/src/client/store/modules/settings')
+ stores.push(notificationSettings)
+ return notificationSettings
+}
+
+async function loadScheduler() {
+ const { scheduler } = await import('../packages/dsh-tauri-scheduler/src/client/store/modules/scheduler')
+ stores.push(scheduler)
+ return scheduler
+}
+
+describe('global store persistence', () => {
+ it('registers persistence before a consuming store is created', async () => {
+ const { defineStore } = await import('../packages/dsh-tauri/src/client/modules/valtio-define')
+ memory.set('test.preferences', JSON.stringify({ count: 7 }))
+ const preferences = defineStore({ state: () => ({ count: 0 }), persist: { key: 'test.preferences' } })
+ stores.push(preferences)
+ expect(preferences.count).toBe(7)
+ preferences.count = 8
+ await vi.waitFor(() => expect(memory.get('test.preferences')).toBe('{"count":8}'))
+ })
+
+ it('leaves stores without persist in memory', async () => {
+ const { defineStore } = await import('../packages/dsh-tauri/src/client/modules/valtio-define')
+ const runtime = defineStore({ state: () => ({ loading: false }) })
+ runtime.loading = true
+ await Promise.resolve()
+ expect(runtime.$persist).toBeUndefined()
+ expect(memory.size).toBe(0)
+ })
+
+ it('keeps stores usable when localStorage is absent', async () => {
+ vi.stubGlobal('localStorage', undefined)
+ const settings = await loadNotification()
+ settings.setApproval(false)
+ expect(settings.approval).toBe(false)
+ expect(settings.$persist).toBeUndefined()
+ expect(memory.size).toBe(0)
+ })
+})
+
+describe('notification preferences', () => {
+ it('starts with notification defaults when storage is empty', async () => {
+ const settings = await loadNotification()
+ expect(settings.$state).toEqual({
+ turnComplete: 'background',
+ approval: true,
+ question: true,
+ sound: 'default',
+ customSound: null,
+ })
+ })
+
+ it('restores preferences synchronously without a hydrate action', async () => {
+ memory.set('dsh-tauri-notification.settings', JSON.stringify({ turnComplete: 'always', approval: false, sound: 'classic' }))
+ const settings = await loadNotification()
+ expect(settings.$state).toEqual({
+ turnComplete: 'always',
+ approval: false,
+ question: true,
+ sound: 'classic',
+ customSound: null,
+ })
+ expect('hydrate' in settings).toBe(false)
+ })
+
+ it('automatically saves every notification preference', async () => {
+ const settings = await loadNotification()
+ settings.setTurnComplete('never')
+ settings.setApproval(false)
+ settings.setQuestion(false)
+ settings.setSound('none')
+ await vi.waitFor(() => expect(JSON.parse(memory.get('dsh-tauri-notification.settings')!)).toEqual({
+ turnComplete: 'never',
+ approval: false,
+ question: false,
+ sound: 'none',
+ customSound: null,
+ }))
+ })
+
+ it('retains custom audio when changing the selected sound', async () => {
+ const settings = await loadNotification()
+ settings.setCustomSound('data:audio/wav;base64,AAAA')
+ expect(settings.sound).toBe('custom')
+ settings.setSound('none')
+ await vi.waitFor(() => expect(JSON.parse(memory.get('dsh-tauri-notification.settings')!)).toMatchObject({
+ sound: 'none',
+ customSound: 'data:audio/wav;base64,AAAA',
+ }))
+ })
+
+ it('returns to the default sound when selected custom audio is removed', async () => {
+ const settings = await loadNotification()
+ settings.setCustomSound('data:audio/wav;base64,AAAA')
+ settings.setCustomSound(null)
+ await vi.waitFor(() => expect(JSON.parse(memory.get('dsh-tauri-notification.settings')!)).toMatchObject({
+ sound: 'default',
+ customSound: null,
+ }))
+ })
+})
+
+describe('open-in-app preferences', () => {
+ it('uses the default application when storage is empty', async () => {
+ const { openInApp } = await import('../packages/dsh-tauri-model/src/client/store/modules/open-in-app')
+ stores.push(openInApp)
+ expect(openInApp.choice).toBe('')
+ })
+
+ it('restores the selected application synchronously', async () => {
+ memory.set('dsh-tauri-model.open-in-app.choice', JSON.stringify({ choice: 'editor' }))
+ const { openInApp } = await import('../packages/dsh-tauri-model/src/client/store/modules/open-in-app')
+ stores.push(openInApp)
+ expect(openInApp.choice).toBe('editor')
+ })
+
+ it('persists application changes and a return to the default', async () => {
+ const { openInApp } = await import('../packages/dsh-tauri-model/src/client/store/modules/open-in-app')
+ stores.push(openInApp)
+ openInApp.setChoice('editor')
+ await vi.waitFor(() => expect(memory.get('dsh-tauri-model.open-in-app.choice')).toBe('{"choice":"editor"}'))
+ openInApp.setChoice('')
+ await vi.waitFor(() => expect(memory.get('dsh-tauri-model.open-in-app.choice')).toBe('{"choice":""}'))
+ })
+})
+
+describe('scheduler read markers', () => {
+ it('restores read markers without restoring task runtime state', async () => {
+ memory.set('dsh-tauri-scheduler.read', JSON.stringify({ readAt: 123, readIds: ['run-1'] }))
+ const scheduler = await loadScheduler()
+ expect(scheduler.readAt).toBe(123)
+ expect(scheduler.readIds).toEqual(['run-1'])
+ expect(scheduler.tasks).toEqual([])
+ expect(scheduler.runs).toEqual([])
+ expect(scheduler.loading).toBe(false)
+ expect(scheduler.loadToken).toBe(0)
+ })
+
+ it('persists only read markers when runtime state changes', async () => {
+ const scheduler = await loadScheduler()
+ scheduler.loading = true
+ scheduler.error = 'offline'
+ scheduler.loadToken = 9
+ scheduler.markRunRead('run-1')
+ scheduler.markRunRead('run-1')
+ await vi.waitFor(() => expect(JSON.parse(memory.get('dsh-tauri-scheduler.read')!)).toEqual({
+ readAt: 0,
+ readIds: ['run-1'],
+ }))
+ })
+
+ it('marks only runs from the opened session read without duplicate markers', async () => {
+ const scheduler = await loadScheduler()
+ scheduler.runs = [
+ { id: 'run-1', taskId: 'task', taskName: 'Task', trigger: 'manual', status: 'succeeded', scheduledFor: '', startedAt: '', sessionId: 'session-1' },
+ { id: 'run-2', taskId: 'task', taskName: 'Task', trigger: 'manual', status: 'succeeded', scheduledFor: '', startedAt: '', sessionId: 'session-1' },
+ { id: 'run-3', taskId: 'task', taskName: 'Task', trigger: 'manual', status: 'succeeded', scheduledFor: '', startedAt: '', sessionId: 'session-2' },
+ ]
+ scheduler.markRunRead('run-1')
+ scheduler.markSessionRead('session-1')
+ scheduler.markSessionRead('session-1')
+ scheduler.markSessionRead('missing-session')
+ await vi.waitFor(() => expect(JSON.parse(memory.get('dsh-tauri-scheduler.read')!)).toEqual({
+ readAt: 0,
+ readIds: ['run-1', 'run-2'],
+ }))
+ })
+
+ it('seeds the read timestamp only once', async () => {
+ vi.spyOn(Date, 'now').mockReturnValueOnce(100).mockReturnValueOnce(200)
+ const scheduler = await loadScheduler()
+ scheduler.seedReadAt()
+ scheduler.seedReadAt()
+ await vi.waitFor(() => expect(JSON.parse(memory.get('dsh-tauri-scheduler.read')!)).toEqual({
+ readAt: 100,
+ readIds: [],
+ }))
+ })
+
+ it('clears individual read markers when marking all runs read', async () => {
+ vi.spyOn(Date, 'now').mockReturnValue(456)
+ const scheduler = await loadScheduler()
+ scheduler.markRunRead('run-1')
+ scheduler.markAllRunsRead()
+ await vi.waitFor(() => expect(JSON.parse(memory.get('dsh-tauri-scheduler.read')!)).toEqual({
+ readAt: 456,
+ readIds: [],
+ }))
+ })
+})