DeepSeek Harness Tauri 桌面版 | Only 8mb installer, zero environment setup, preset plugins, Windows / macOS / Linux.
chore(plugins): simplify worktree archive and pet internals (#820)
Mao Mr589149c90782
diff --git a/docs/audit/pkg-worktree-archive-pet.md b/docs/audit/pkg-worktree-archive-pet.mdindex 3ce3d517..a5523649 100644--- a/docs/audit/pkg-worktree-archive-pet.md+++ b/docs/audit/pkg-worktree-archive-pet.md@@ -57,3 +57,13 @@## net: -490 lines, -4 deps possible.> Lead 复核修正:原 net 的 -5 deps 含 pet 的 `@deepseek-ai/dsh-skill-filesystem`(实为 `cordis.patch.yml:3` 字符串通道引用,已降级 `keep:`)。当前 -4 deps = worktree `hookable` + worktree/archive 的 `lodash-es` 原生化 + worktree `simple-git` → `node:child_process`。++## 执行复核(2026-10-01)++- **已实施**:handoff 仅共享创建 agent 的步骤,保留 pending 捕获的 sourceAgent、不同 workspace 挂接路径、标题登记与 followup/失败清理;复用 prompt provider、loadJobStatus(两个导出路径均保留)、textBlock、worktreeKey 与包内 session 快照类型;删除重复 cwd 判空及未发布的 Ledger/CheckoutContexts 内部类型。+- **已实施**:worktree Git 调用改用原生 execFile,保留参数数组、stdout trim、无小容量输出限制、Windows 隐藏窗口及取消/超时选项。预取消信号不启动命令,运行中取消必须等待子进程 close 后返回,避免回滚与仍在执行的 Git 并发。静默非零退出现在明确返回失败,而非 simple-git 的空输出成功;调用方已复核并由真实临时仓库回归覆盖。+- **已实施**:archive 六个 handler 共享运行时校验,readBody 泛型、400 状态、错误文本与原先 String 转换/重复项/顺序均保留;删除确认合为一个 Modal;三处宿主 lodash 使用改原生集合操作。pet 合并同语义动作错误处理、内联私有 invoke 层、共享设置 busy 流程与 Chat/Codex 卡片映射,仅删除内部 firstSeqAt。+- **不实施**:cleaner 退避并不等同每五分钟巡检,删除会延迟失败恢复;hydration 节流还负责末次请求补发和取消,时间戳 Map 不等价;三个 JSON loader 的非缺失 I/O 错误处理不同;session 重试的刷新/探测时序不同;filesystem 的依赖注入用于隔离故障回归,均保留。+- **协议保留**:WorktreeParams 两种拼写、link 选项、pet toolActivity/activity/liveActivity 字段、archive delete/deleteSelected 服务与 DTO、已有公开类型/常量/方法、所有路由与生命周期注册;store 聚合入口是客户端规范要求,不删除。不同插件的快照类型不引入跨插件依赖。+- **依赖实绩**:移除 worktree simple-git、archive lodash-es 及其 @types/lodash-es 三个声明;worktree 仍需 lodash 的 isPlainObject/isString/uniqBy 等非简单等价语义。hookable 已在先前依赖 PR 删除,不重复计数;simple-git 的孤立 catalog 条目同步移除,pet skill provider 与仍被其他包使用的 catalog/锁文件依赖保留。+- **验证**:三包真实源码别名回归五轮乱序各 350 项通过,取消时序补强后另五轮各 29 文件 / 352 项通过;完整根 TypeScript、三包源码 TypeScript 与 ESLint 通过(仅三条既有 warning);冻结锁文件校验通过。Git 失败吞掉、取消提前返回、archive 400→200、pet enable 条件反转的变异均被回归捕获,随后恢复实现。未执行本地插件构建。diff --git a/packages/dsh-tauri-archive/package.json b/packages/dsh-tauri-archive/package.jsonindex 038960ac..2ca04b62 100644--- a/packages/dsh-tauri-archive/package.json+++ b/packages/dsh-tauri-archive/package.json@@ -58,11 +58,9 @@"dependencies": {"dsh-tauri": "workspace:*","hookable": "catalog:utils",- "lodash-es": "catalog:utils","pathe": "catalog:utils"},"devDependencies": {- "@types/lodash-es": "catalog:types","dsh-tauri-tsdown": "workspace:*","dsh-tauri-ui": "workspace:*","tsdown": "catalog:cli"diff --git a/packages/dsh-tauri-archive/src/client/components/archive-panel.test.tsx b/packages/dsh-tauri-archive/src/client/components/archive-panel.test.tsxnew file mode 100644index 00000000..657a6fde--- /dev/null+++ b/packages/dsh-tauri-archive/src/client/components/archive-panel.test.tsx@@ -0,0 +1,206 @@+// @vitest-environment jsdom+import type { ChangeEventHandler, ReactNode } from 'react'+import type { ArchiveState } from '../store/modules/archive.types'+import type { ArchivePanelProps } from './archive-panel.types'+import { cleanup, fireEvent, render, screen, waitFor, within } from '@testing-library/react'+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+import * as api from '../apis'+import { store } from '../store'+import { ArchivePanel } from './archive-panel'++vi.mock('dsh-tauri/client', async () => {+ const lodash = await import('../../../../dsh-tauri/src/client/modules/lodash-es')+ const valtio = await import('valtio-define')+ const reause = await import('@reause/core')+ const dates = await import('../../../../dsh-tauri/src/client/modules/date-fns')+ return {+ ...lodash,+ defineStore: valtio.defineStore,+ useStore: valtio.useStore,+ useWatchImmediate: reause.useWatchImmediate,+ format: dates.format,+ defineLocale: (_id: string, languages: Record<string, Record<string, string>>) => ({+ useLocale: () => {},+ isEnglishLocale: () => true,+ text: (key: string, values: Record<string, unknown> = {}) => Object.entries(values).reduce((text, [name, value]) => text.replace(`{${name}}`, String(value)), languages.en![key]!),+ }),+ }+})++vi.mock('dsh-tauri-ui/client', async () => {+ const Button = ({ children, onClick, disabled, 'aria-label': label }: { 'children'?: ReactNode, 'onClick'?: () => void, 'disabled'?: boolean, 'aria-label'?: string }) => (+ <button type="button" onClick={onClick} disabled={disabled} aria-label={label}>{children}</button>+ )+ return {+ Action: Button,+ Button,+ Icon: () => null,+ Ellipsis: () => null,+ FolderOpen: () => null,+ Magnifier: () => null,+ TrashBin: () => null,+ Input: ({ value, onChange, 'aria-label': label }: { 'value': string, 'onChange': ChangeEventHandler<HTMLInputElement>, 'aria-label': string }) => <input value={value} onChange={onChange} aria-label={label} />,+ Select: () => null,+ Text: ({ children }: { children: ReactNode }) => <span>{children}</span>,+ Toast: () => null,+ Menu: ({ open, anchor, onSelect }: { open: boolean, anchor: ReactNode, onSelect: (id: string) => void }) => (+ <>+ {anchor}+ {open && <button type="button" onClick={() => onSelect('delete')}>Delete project</button>}+ </>+ ),+ Modal: ({ open, onClose, title, description, footer, closeLabel }: { open: boolean, onClose: () => void, title: string, description: string, footer: ReactNode, closeLabel: string }) => open+ ? (+ <div role="dialog" aria-label={title}>+ <p>{description}</p>+ <button type="button" onClick={onClose}>{closeLabel}</button>+ {footer}+ </div>+ )+ : null,+ }+})++vi.mock('../apis', () => ({+ getSessionArchive: vi.fn(),+ deleteSessionArchive: vi.fn(),+ deleteSessionWorkspaceArchive: vi.fn(),+ postSessionArchiveClear: vi.fn(),+ postSessionArchive: vi.fn(),+ postSessionArchiveRestore: vi.fn(),+ postSessionOpenPath: vi.fn(),+ postSessionWorkspaceArchive: vi.fn(),+}))++function mount() {+ const sessions = { ids: [], byId: {} }+ const workspaces = { items: [{ workspaceId: 'project', title: 'Project', path: '/project', sessionIds: ['a', 'b'] }], archivedSessionIds: ['a', 'b', 'c'] }+ const props = {+ sessionsRuntime: { list: { subscribe: () => () => {}, getSnapshot: () => sessions }, refresh: vi.fn(async () => {}) },+ workspacesRuntime: { list: { subscribe: () => () => {}, getSnapshot: () => workspaces }, manager: { refresh: vi.fn(async () => {}) } },+ } as unknown as ArchivePanelProps+ const view = render(<ArchivePanel {...props} />)+ return { ...view, props }+}++function expectNoDelete() {+ expect(api.deleteSessionArchive).not.toHaveBeenCalled()+ expect(api.deleteSessionWorkspaceArchive).not.toHaveBeenCalled()+ expect(api.postSessionArchiveClear).not.toHaveBeenCalled()+}++beforeEach(() => {+ vi.clearAllMocks()+ const state: ArchiveState = {+ archived: { archivedSessionIds: [], meta: {} },+ sort: 'updatedAt',+ query: '',+ workspaceId: 'all',+ loading: false,+ pending: false,+ error: '',+ suppressedSessionIds: [],+ titleById: {},+ refreshGeneration: 0,+ }+ Object.assign(store.archive, state)+ vi.mocked(api.getSessionArchive).mockResolvedValue({+ archivedSessionIds: ['a', 'b', 'c'],+ meta: { a: { title: 'Alpha', cwd: '/project' }, b: { title: 'Beta', cwd: '/project' }, c: { title: 'Other', cwd: '/other' } },+ })+ vi.mocked(api.deleteSessionArchive).mockResolvedValue(undefined)+ vi.mocked(api.deleteSessionWorkspaceArchive).mockResolvedValue(undefined)+ vi.mocked(api.postSessionArchiveClear).mockResolvedValue(undefined)+})++afterEach(() => {+ cleanup()+ vi.restoreAllMocks()+})++describe('archive deletion confirmation', () => {+ it('single mode preserves title, body, close/cancel and single-session action with runtime resync', async () => {+ const { props } = mount()+ await screen.findByRole('button', { name: 'Open directory: Alpha' })+ fireEvent.click(screen.getAllByRole('button', { name: 'Delete this session' })[0]!)+ let dialog = screen.getByRole('dialog', { name: 'Delete archived chat?' })+ expect(within(dialog).getByText('This will permanently delete the archived chat.')).toBeTruthy()+ fireEvent.click(within(dialog).getByRole('button', { name: 'Close' }))+ expect(screen.queryByRole('dialog')).toBeNull()+ expectNoDelete()+ fireEvent.click(screen.getAllByRole('button', { name: 'Delete this session' })[0]!)+ dialog = screen.getByRole('dialog')+ fireEvent.click(within(dialog).getByRole('button', { name: 'Cancel' }))+ expect(screen.queryByRole('dialog')).toBeNull()+ expectNoDelete()+ fireEvent.click(screen.getAllByRole('button', { name: 'Delete this session' })[0]!)+ fireEvent.click(within(screen.getByRole('dialog')).getByRole('button', { name: 'Delete' }))+ expect(screen.queryByRole('dialog')).toBeNull()+ await waitFor(() => expect(api.deleteSessionArchive).toHaveBeenCalledExactlyOnceWith({ sessionId: 'a' }))+ await waitFor(() => expect(store.archive.pending).toBe(false))+ expect(props.sessionsRuntime.refresh).toHaveBeenCalledOnce()+ expect(props.workspacesRuntime.manager?.refresh).toHaveBeenCalledOnce()+ expect(api.deleteSessionWorkspaceArchive).not.toHaveBeenCalled()+ expect(api.postSessionArchiveClear).not.toHaveBeenCalled()+ })++ it('all mode preserves title and description and calls only clear', async () => {+ mount()+ await screen.findByRole('button', { name: 'Open directory: Alpha' })+ fireEvent.click(screen.getByRole('button', { name: 'Delete all' }))+ const dialog = screen.getByRole('dialog', { name: 'Delete all archived chats?' })+ expect(within(dialog).getByText('This will permanently delete all locally archived chat records.')).toBeTruthy()+ fireEvent.click(within(dialog).getByRole('button', { name: 'Delete' }))+ await waitFor(() => expect(api.postSessionArchiveClear).toHaveBeenCalledExactlyOnceWith())+ await waitFor(() => expect(store.archive.pending).toBe(false))+ expect(api.deleteSessionArchive).not.toHaveBeenCalled()+ expect(api.deleteSessionWorkspaceArchive).not.toHaveBeenCalled()+ })++ it('workspace mode includes all project sessions even when search hides members', async () => {+ mount()+ await screen.findByRole('button', { name: 'Open directory: Alpha' })+ fireEvent.change(screen.getByRole('textbox', { name: 'Search archived chats' }), { target: { value: 'Alpha' } })+ await waitFor(() => expect(screen.queryByRole('button', { name: 'Open directory: Beta' })).toBeNull())+ fireEvent.click(screen.getByRole('button', { name: 'Project actions' }))+ fireEvent.click(screen.getByRole('button', { name: 'Delete project' }))+ const dialog = screen.getByRole('dialog', { name: 'Delete all chats in this project?' })+ expect(within(dialog).getByText('This will permanently delete 2 locally archived chats in "Project".')).toBeTruthy()+ fireEvent.click(within(dialog).getByRole('button', { name: 'Delete' }))+ await waitFor(() => expect(api.deleteSessionWorkspaceArchive).toHaveBeenCalledExactlyOnceWith({ sessionIds: ['a', 'b'] }))+ await waitFor(() => expect(store.archive.pending).toBe(false))+ expect(api.deleteSessionArchive).not.toHaveBeenCalled()+ expect(api.postSessionArchiveClear).not.toHaveBeenCalled()+ })++ it('ungrouped workspace deletion keeps the ungrouped label and ids', async () => {+ mount()+ await screen.findByRole('button', { name: 'Open directory: Other' })+ fireEvent.change(screen.getByRole('textbox', { name: 'Search archived chats' }), { target: { value: 'Other' } })+ await waitFor(() => expect(screen.getAllByRole('button', { name: 'Project actions' })).toHaveLength(1))+ fireEvent.click(screen.getByRole('button', { name: 'Project actions' }))+ fireEvent.click(screen.getByRole('button', { name: 'Delete project' }))+ const dialog = screen.getByRole('dialog')+ expect(within(dialog).getByText('This will permanently delete 1 locally archived chats in "Ungrouped".')).toBeTruthy()+ fireEvent.click(within(dialog).getByRole('button', { name: 'Delete' }))+ await waitFor(() => expect(api.deleteSessionWorkspaceArchive).toHaveBeenCalledExactlyOnceWith({ sessionIds: ['c'] }))+ await waitFor(() => expect(store.archive.pending).toBe(false))+ })++ it('pending disables confirmation without changing an already opened dialog', async () => {+ let resolveClear!: () => void+ vi.mocked(api.postSessionArchiveClear).mockImplementation(() => new Promise((resolve) => {+ resolveClear = resolve+ }))+ mount()+ await screen.findByRole('button', { name: 'Open directory: Alpha' })+ fireEvent.click(screen.getByRole('button', { name: 'Delete all' }))+ const { clearArchive } = await import('../service/archive')+ const pending = clearArchive()+ await waitFor(() => expect((within(screen.getByRole('dialog')).getByRole('button', { name: 'Delete' }) as HTMLButtonElement).disabled).toBe(true))+ fireEvent.click(within(screen.getByRole('dialog')).getByRole('button', { name: 'Delete' }))+ expect(api.postSessionArchiveClear).toHaveBeenCalledOnce()+ resolveClear()+ await pending+ })+})diff --git a/packages/dsh-tauri-archive/src/client/components/archive-panel.tsx b/packages/dsh-tauri-archive/src/client/components/archive-panel.tsxindex 93f3f34d..36433fa3 100644--- a/packages/dsh-tauri-archive/src/client/components/archive-panel.tsx+++ b/packages/dsh-tauri-archive/src/client/components/archive-panel.tsx@@ -210,26 +210,12 @@ export function ArchivePanel(props: ArchivePanelProps): ReactElement | null {</div><Modal- open={confirm?.kind === 'single'}+ open={confirm !== null}onClose={() => setConfirm(null)}- title={locale.text('deleteSingleTitle')}- description={locale.text('deleteSingleBody')}- footer={footer}- closeLabel={locale.text('close')}- />- <Modal- open={confirm?.kind === 'all'}- onClose={() => setConfirm(null)}- title={locale.text('deleteAllTitle')}- description={locale.text('deleteAllBody')}- footer={footer}- closeLabel={locale.text('close')}- />- <Modal- open={confirm?.kind === 'workspace'}- onClose={() => setConfirm(null)}- title={locale.text('deleteProjectTitle')}- description={confirm?.kind === 'workspace' ? locale.text('deleteProjectBody', { count: confirm.sessionIds.length, workspace: confirm.workspaceTitle }) : ''}+ title={locale.text(confirm?.kind === 'single' ? 'deleteSingleTitle' : confirm?.kind === 'all' ? 'deleteAllTitle' : 'deleteProjectTitle')}+ description={confirm?.kind === 'workspace'+ ? locale.text('deleteProjectBody', { count: confirm.sessionIds.length, workspace: confirm.workspaceTitle })+ : locale.text(confirm?.kind === 'single' ? 'deleteSingleBody' : 'deleteAllBody')}footer={footer}closeLabel={locale.text('close')}/>diff --git a/packages/dsh-tauri-archive/src/host/routes/index.test.ts b/packages/dsh-tauri-archive/src/host/routes/index.test.tsindex e2b38aad..7683fbef 100644--- a/packages/dsh-tauri-archive/src/host/routes/index.test.ts+++ b/packages/dsh-tauri-archive/src/host/routes/index.test.ts@@ -22,6 +22,8 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'import { routes } from '.'import { resetTestDshHome, testDshHome } from '../../../../.test/test-utils'import { setCurrentHostInstance } from '../config/runtime'+import { archive } from '../service/archive'+import { session } from '../service/session'vi.mock('dsh-tauri', async (importOriginal) => {const actual = await importOriginal<typeof import('dsh-tauri')>()@@ -151,6 +153,75 @@ afterEach(async () => {})describe('归档路由声明', () => {+ it.each([+ ['POST', '/session/archive', 'single'],+ ['DELETE', '/session/archive', 'single'],+ ['POST', '/session/archive/restore', 'single'],+ ['POST', '/session/open/path', 'single'],+ ['POST', '/session/workspace/archive', 'many'],+ ['DELETE', '/session/workspace/archive', 'many'],+ ] as const)('%s %s preserves invalid body status and error without calling services', async (method, path, kind) => {+ const calls = [+ vi.spyOn(archive, 'archive'),+ vi.spyOn(archive, 'delete'),+ vi.spyOn(archive, 'unarchive'),+ vi.spyOn(archive, 'archiveWorkspace'),+ vi.spyOn(archive, 'deleteSelected'),+ vi.spyOn(session, 'openDir'),+ ]+ const harness = createHarness()+ const dispose = mount(harness)+ const base = await listen(harness.registered)+ const invalid = kind === 'single'+ ? [{}, { sessionId: '' }, { sessionId: 1 }, { sessionId: [] }, { sessionId: null }, null, [], 'id']+ : [{}, { sessionIds: [] }, { sessionIds: [''] }, { sessionIds: 'id' }, { sessionIds: null }, null, [], 'id']+ for (const body of invalid) {+ const response = await postJson(base, `${P}${path}`, method, JSON.stringify(body))+ expect(response.status).toBe(400)+ expect(await response.json()).toEqual({ ok: false, error: kind === 'single' ? 'invalid-session-id' : 'invalid-session-ids' })+ }+ for (const call of calls)+ expect(call).not.toHaveBeenCalled()+ dispose()+ })++ it('single routes accept whitespace without trimming and delegate to their public service methods', async () => {+ const calls = [+ vi.spyOn(archive, 'archive').mockResolvedValue({ archivedSessionIds: [' '], meta: {} }),+ vi.spyOn(archive, 'delete').mockResolvedValue({ ok: true }),+ vi.spyOn(archive, 'unarchive').mockResolvedValue({ ok: true }),+ vi.spyOn(session, 'openDir').mockResolvedValue({ ok: true }),+ ]+ const paths = [['POST', '/session/archive'], ['DELETE', '/session/archive'], ['POST', '/session/archive/restore'], ['POST', '/session/open/path']]+ const harness = createHarness()+ const dispose = mount(harness)+ const base = await listen(harness.registered)+ for (const [method, path] of paths) {+ const response = await postJson(base, `${P}${path}`, method!, JSON.stringify({ sessionId: ' ' }))+ expect(response.status).toBe(200)+ }+ for (const call of calls) {+ expect(call).toHaveBeenCalledExactlyOnceWith(' ')+ }+ dispose()+ })++ it.each(['POST', 'DELETE'])('workspace %s preserves String conversion, duplicates, order and optional workspaceId', async (method) => {+ const call = method === 'POST'+ ? vi.spyOn(archive, 'archiveWorkspace').mockResolvedValue({ archivedSessionIds: [], meta: {} })+ : vi.spyOn(archive, 'deleteSelected').mockResolvedValue({ ok: true })+ const harness = createHarness()+ const dispose = mount(harness)+ const base = await listen(harness.registered)+ const response = await postJson(base, `${P}/session/workspace/archive`, method, JSON.stringify({+ workspaceId: 'workspace',+ sessionIds: ['', 'id', 'id', 0, false, null, {}, ' '],+ }))+ expect(response.status).toBe(200)+ expect(call).toHaveBeenCalledExactlyOnceWith(['id', 'id', '0', 'false', 'null', '[object Object]', ' '])+ dispose()+ })+it('按 RESTful 资源树声明 exact 路由,同路径多方法收敛为一行,卸载后清空注册', () => {const harness = createHarness()const dispose = mount(harness)diff --git a/packages/dsh-tauri-archive/src/host/routes/index.utils.ts b/packages/dsh-tauri-archive/src/host/routes/index.utils.tsnew file mode 100644index 00000000..e9ce021c--- /dev/null+++ b/packages/dsh-tauri-archive/src/host/routes/index.utils.ts@@ -0,0 +1,18 @@+import type { H3Event } from 'dsh-tauri'+import type { SessionIdBody, SessionIdsBody } from './index.types'++export function validateSessionId(event: H3Event, body: SessionIdBody | null | undefined) {+ const sessionId = typeof body?.sessionId === 'string' ? body.sessionId : ''+ if (sessionId.length > 0)+ return sessionId+ event.res.status = 400+ return { ok: false as const, error: 'invalid-session-id' }+}++export function validateSessionIds(event: H3Event, body: SessionIdsBody | null | undefined) {+ const sessionIds = Array.isArray(body?.sessionIds) ? body.sessionIds.map(String).filter(Boolean) : []+ if (sessionIds.length > 0)+ return sessionIds+ event.res.status = 400+ return { ok: false as const, error: 'invalid-session-ids' }+}diff --git a/packages/dsh-tauri-archive/src/host/routes/session/archive/delete.ts b/packages/dsh-tauri-archive/src/host/routes/session/archive/delete.tsindex 956ce6f6..0190bc74 100644--- a/packages/dsh-tauri-archive/src/host/routes/session/archive/delete.ts+++ b/packages/dsh-tauri-archive/src/host/routes/session/archive/delete.ts@@ -1,13 +1,10 @@import type { SessionIdBody } from '../../index.types'import { defineEventHandler, readBody } from 'dsh-tauri'import { archive } from '../../../service/archive'+import { validateSessionId } from '../../index.utils'export default defineEventHandler(async (event) => {const body = await readBody<SessionIdBody>(event, { type: 'json' })- const sessionId = typeof body?.sessionId === 'string' ? body.sessionId : ''- if (sessionId.length === 0) {- event.res.status = 400- return { ok: false as const, error: 'invalid-session-id' }- }- return archive.delete(sessionId)+ const sessionId = validateSessionId(event, body)+ return typeof sessionId === 'string' ? archive.delete(sessionId) : sessionId})diff --git a/packages/dsh-tauri-archive/src/host/routes/session/archive/post.ts b/packages/dsh-tauri-archive/src/host/routes/session/archive/post.tsindex 6fe31195..3fbee733 100644--- a/packages/dsh-tauri-archive/src/host/routes/session/archive/post.ts+++ b/packages/dsh-tauri-archive/src/host/routes/session/archive/post.ts@@ -1,13 +1,10 @@import type { SessionIdBody } from '../../index.types'import { defineEventHandler, readBody } from 'dsh-tauri'import { archive } from '../../../service/archive'+import { validateSessionId } from '../../index.utils'export default defineEventHandler(async (event) => {const body = await readBody<SessionIdBody>(event, { type: 'json' })- const sessionId = typeof body?.sessionId === 'string' ? body.sessionId : ''- if (sessionId.length === 0) {- event.res.status = 400- return { ok: false as const, error: 'invalid-session-id' }- }- return archive.archive(sessionId)+ const sessionId = validateSessionId(event, body)+ return typeof sessionId === 'string' ? archive.archive(sessionId) : sessionId})diff --git a/packages/dsh-tauri-archive/src/host/routes/session/archive/restore/post.ts b/packages/dsh-tauri-archive/src/host/routes/session/archive/restore/post.tsindex 2ff0dcd7..6a7026cb 100644--- a/packages/dsh-tauri-archive/src/host/routes/session/archive/restore/post.ts+++ b/packages/dsh-tauri-archive/src/host/routes/session/archive/restore/post.ts@@ -1,13 +1,10 @@import type { SessionIdBody } from '../../../index.types'import { defineEventHandler, readBody } from 'dsh-tauri'import { archive } from '../../../../service/archive'+import { validateSessionId } from '../../../index.utils'export default defineEventHandler(async (event) => {const body = await readBody<SessionIdBody>(event, { type: 'json' })- const sessionId = typeof body?.sessionId === 'string' ? body.sessionId : ''- if (sessionId.length === 0) {- event.res.status = 400- return { ok: false as const, error: 'invalid-session-id' }- }- return archive.unarchive(sessionId)+ const sessionId = validateSessionId(event, body)+ return typeof sessionId === 'string' ? archive.unarchive(sessionId) : sessionId})diff --git a/packages/dsh-tauri-archive/src/host/routes/session/open/path/post.ts b/packages/dsh-tauri-archive/src/host/routes/session/open/path/post.tsindex 19f24d61..f38c5800 100644--- a/packages/dsh-tauri-archive/src/host/routes/session/open/path/post.ts+++ b/packages/dsh-tauri-archive/src/host/routes/session/open/path/post.ts@@ -2,14 +2,13 @@ import type { EventHandlerRequest } from 'dsh-tauri'import type { OpenSessionDirResult, SessionIdBody } from '../../../index.types'import { defineEventHandler, readBody } from 'dsh-tauri'import { session } from '../../../../service/session'+import { validateSessionId } from '../../../index.utils'export default defineEventHandler<EventHandlerRequest, Promise<OpenSessionDirResult>>(async (event) => {const body = await readBody<SessionIdBody>(event, { type: 'json' })- const sessionId = typeof body?.sessionId === 'string' ? body.sessionId : ''- if (sessionId.length === 0) {- event.res.status = 400- return { ok: false as const, error: 'invalid-session-id' }- }+ const sessionId = validateSessionId(event, body)+ if (typeof sessionId !== 'string')+ return sessionIdconst result = await session.openDir(sessionId)if (!result.ok)diff --git a/packages/dsh-tauri-archive/src/host/routes/session/workspace/archive/delete.ts b/packages/dsh-tauri-archive/src/host/routes/session/workspace/archive/delete.tsindex 2190d2e5..ca39f78f 100644--- a/packages/dsh-tauri-archive/src/host/routes/session/workspace/archive/delete.ts+++ b/packages/dsh-tauri-archive/src/host/routes/session/workspace/archive/delete.ts@@ -1,15 +1,10 @@import type { SessionIdsBody } from '../../../index.types'import { defineEventHandler, readBody } from 'dsh-tauri'import { archive } from '../../../../service/archive'+import { validateSessionIds } from '../../../index.utils'export default defineEventHandler(async (event) => {const body = await readBody<SessionIdsBody>(event, { type: 'json' })- const sessionIds = Array.isArray(body?.sessionIds)- ? body.sessionIds.map(String).filter(Boolean)- : []- if (sessionIds.length === 0) {- event.res.status = 400- return { ok: false as const, error: 'invalid-session-ids' }- }- return archive.deleteSelected(sessionIds)+ const sessionIds = validateSessionIds(event, body)+ return Array.isArray(sessionIds) ? archive.deleteSelected(sessionIds) : sessionIds})diff --git a/packages/dsh-tauri-archive/src/host/routes/session/workspace/archive/post.ts b/packages/dsh-tauri-archive/src/host/routes/session/workspace/archive/post.tsindex efa32a5d..2e49503a 100644--- a/packages/dsh-tauri-archive/src/host/routes/session/workspace/archive/post.ts+++ b/packages/dsh-tauri-archive/src/host/routes/session/workspace/archive/post.ts@@ -1,15 +1,10 @@import type { WorkspaceArchiveBody } from '../../../index.types'import { defineEventHandler, readBody } from 'dsh-tauri'import { archive } from '../../../../service/archive'+import { validateSessionIds } from '../../../index.utils'export default defineEventHandler(async (event) => {const body = await readBody<WorkspaceArchiveBody>(event, { type: 'json' })- const sessionIds = Array.isArray(body?.sessionIds)- ? body.sessionIds.map(String).filter(Boolean)- : []- if (sessionIds.length === 0) {- event.res.status = 400- return { ok: false as const, error: 'invalid-session-ids' }- }- return archive.archiveWorkspace(sessionIds)+ const sessionIds = validateSessionIds(event, body)+ return Array.isArray(sessionIds) ? archive.archiveWorkspace(sessionIds) : sessionIds})diff --git a/packages/dsh-tauri-archive/src/host/service/archive.test.ts b/packages/dsh-tauri-archive/src/host/service/archive.test.tsnew file mode 100644index 00000000..06f5678c--- /dev/null+++ b/packages/dsh-tauri-archive/src/host/service/archive.test.ts@@ -0,0 +1,209 @@+import type { ArchiveRegistrySurface, SessionHost, SessionLike, WorkspaceEntryLike } from '../types'+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+import { clearHostRuntime, setCurrentHostInstance } from '../config/runtime'+import { archiveHooks } from '../events'+import { archive } from './archive'+import { ledger } from './ledger'+import { session } from './session'++function harness(ids = ['a', 'b', 'orphan']) {+ const operations: string[] = []+ let state = { archivedSessionIds: [...ids], extra: 'preserved' }+ const sessions = new Map<string, SessionLike>([+ ['a', { id: 'a', header: { cwd: '/project', createdAt: 1 }, title: 'base', displayTitle: 'display' }],+ ['b', { id: 'b', header: { cwd: '/project', createdAt: 2 } }],+ ])+ const workspaces: WorkspaceEntryLike[] = [+ { id: 'first', path: '/project', sessionIds: ['a', 'b', 'keep'] },+ { id: 'last', path: '/project', sessionIds: ['a', 'b', 'keep'] },+ ]+ const table = {+ entries: () => workspaces.map(workspace => [workspace.id, workspace] as [string, WorkspaceEntryLike]),+ update: vi.fn(async (id: string, update: (value: { sessionIds?: readonly string[] }) => { sessionIds: string[] }) => {+ operations.push(`account:${id}`)+ const workspace = workspaces.find(item => item.id === id)!+ Object.assign(workspace, update(workspace))+ }),+ }+ const registry: ArchiveRegistrySurface = {+ get archivedSessionIds() { return state.archivedSessionIds },+ archiveSession: vi.fn(async (id) => {+ operations.push(`archive:${id}`)+ if (!state.archivedSessionIds.includes(id))+ state.archivedSessionIds.push(id)+ }),+ list: () => workspaces,+ enqueueOperation: vi.fn(async (fn) => {+ operations.push('enqueue')+ await fn()+ operations.push('commit')+ }),+ requireState: () => state,+ requireTable: () => table,+ setState: vi.fn(async (next) => {+ operations.push('state')+ state = next as typeof state+ }),+ }+ const host: SessionHost = {+ sessions: {+ get: id => sessions.get(id),+ remove: vi.fn((id) => {+ operations.push(`memory:${id}`)+ return sessions.delete(id)+ }),+ },+ workspaceRegistry: registry,+ logger: { warn: vi.fn(), info: vi.fn() },+ }+ setCurrentHostInstance(host)+ const removeDir = vi.spyOn(session, 'removeDir').mockImplementation((id) => {+ operations.push(`disk:${id}`)+ return id !== 'orphan'+ })+ return { host, registry, table, workspaces, sessions, operations, removeDir, state: () => state }+}++beforeEach(() => {+ archiveHooks.removeAllHooks()+})++afterEach(() => {+ archiveHooks.removeAllHooks()+ clearHostRuntime()+ vi.restoreAllMocks()+})++describe('archive and ledger behavior', () => {+ it('projects resolved sessions, preserves display title and lists orphan ids without mutating snapshots', () => {+ const h = harness()+ const snapshot = ledger.list()+ snapshot.pop()+ expect(ledger.list()).toEqual(['a', 'b', 'orphan'])+ expect(ledger.load()).toEqual({+ archivedSessionIds: ['a', 'b'],+ meta: { a: { cwd: '/project', createdAt: 1, title: 'display' }, b: { cwd: '/project', createdAt: 2 } },+ })+ expect(h.operations).toEqual([])+ })++ it('archives in input order and preserves per-input lifecycle notifications including duplicates', async () => {+ const h = harness([])+ const added = vi.fn()+ archiveHooks.hook('archive:added', added)+ expect(await archive.archiveWorkspace(['b', 'a', 'b'])).toEqual({+ archivedSessionIds: ['b', 'a'],+ meta: { b: { cwd: '/project', createdAt: 2 }, a: { cwd: '/project', createdAt: 1, title: 'display' } },+ })+ await archive.archive('a')+ await Promise.resolve()+ expect(h.operations).toEqual(['archive:b', 'archive:a', 'archive:b', 'archive:a'])+ expect(added.mock.calls).toEqual([['b'], ['a'], ['b'], ['a']])+ })++ it('deduplicates deletes in first-occurrence order, removes all accounting matches and commits before notifying', async () => {+ const h = harness(['a', 'b', 'a', 'orphan'])+ archiveHooks.hook('archive:deleted', ids => h.operations.push(`hook:${ids.join(',')}`))+ expect(await archive.deleteSelected(['', 'b', 'b', 'a'])).toEqual({ ok: true })+ await Promise.resolve()+ expect(h.removeDir.mock.calls).toEqual([['b'], ['a']])+ expect(h.state()).toEqual({ archivedSessionIds: ['orphan'], extra: 'preserved' })+ expect(h.workspaces.map(workspace => workspace.sessionIds)).toEqual([['keep'], ['keep']])+ expect(h.operations).toEqual(['memory:b', 'memory:a', 'disk:b', 'disk:a', 'enqueue', 'account:first', 'account:last', 'state', 'commit', 'hook:b,a'])+ })++ it('delete and deleteAll remain callable public entry points, including unresolved archived ids', async () => {+ const h = harness()+ expect(await archive.delete('a')).toEqual({ ok: true })+ expect(await archive.deleteAll()).toEqual({ ok: true })+ expect(h.removeDir.mock.calls).toEqual([['a'], ['b'], ['orphan']])+ expect(h.state().archivedSessionIds).toEqual([])+ await expect(archive.deleteAll()).rejects.toThrow('缺少 sessionIds')+ })++ it('rejects empty or nonmember ids before any destructive work and reports the first missing id', async () => {+ const h = harness()+ await expect(archive.deleteSelected(['', ''])).rejects.toThrow('缺少 sessionIds')+ await expect(archive.deleteSelected(['b', 'missing', 'other'])).rejects.toThrow('会话 \'missing\' 不在归档集合中,拒绝删除')+ expect(h.operations).toEqual([])+ expect(h.removeDir).not.toHaveBeenCalled()+ })++ it.each(['enqueueOperation', 'requireTable'] as const)('preflights missing %s before memory or disk mutation', async (field) => {+ const h = harness()+ h.registry[field] = undefined+ await expect(archive.delete('a')).rejects.toThrow('宿主 workspaceRegistry 未暴露')+ expect(h.operations).toEqual([])+ expect(h.removeDir).not.toHaveBeenCalled()+ })++ it('checks live SessionStore.remove before disk deletion but does not require it for orphan ids', async () => {+ const h = harness()+ h.host.sessions.remove = undefined+ await expect(archive.delete('a')).rejects.toThrow('宿主未提供 SessionStore.remove,请先更新桌面壳')+ expect(h.operations).toEqual([])+ expect(await archive.delete('orphan')).toEqual({ ok: true })+ expect(h.removeDir).toHaveBeenCalledExactlyOnceWith('orphan')+ })++ it('session.remove checks every input while dropping empty or unresolved ids and preserving live duplicates', () => {+ const h = harness()+ const get = vi.spyOn(h.host.sessions, 'get')+ expect(session.remove(['', 'a', 'missing', 'a'])).toEqual(['a'])+ expect(get.mock.calls).toEqual([[''], ['a'], ['missing'], ['a']])+ expect(h.operations).toEqual(['memory:a', 'memory:a'])+ })++ it('warns on best-effort memory failures while still deleting disk data', async () => {+ const h = harness()+ h.host.sessions.remove = vi.fn(() => false)+ await archive.delete('a')+ expect(h.host.logger?.warn).toHaveBeenCalledExactlyOnceWith('[dsh-tauri-archive] 会话 \'a\' 无法从内存移除,刷新后消失')+ expect(h.removeDir).toHaveBeenCalledExactlyOnceWith('a')+ })++ it('aborts a physical failure before registry mutation or deleted hooks and can retry the unchanged ledger', async () => {+ const h = harness()+ const deleted = vi.fn()+ archiveHooks.hook('archive:deleted', deleted)+ h.removeDir.mockImplementation((id) => {+ if (id === 'b')+ throw new Error('locked')+ return true+ })+ await expect(archive.deleteSelected(['a', 'b'])).rejects.toThrow('删除会话数据失败:b(locked)')+ expect(h.state().archivedSessionIds).toEqual(['a', 'b', 'orphan'])+ expect(h.registry.enqueueOperation).not.toHaveBeenCalled()+ expect(deleted).not.toHaveBeenCalled()+ h.removeDir.mockReturnValue(false)+ await archive.deleteSelected(['a', 'b'])+ await Promise.resolve()+ expect(h.state().archivedSessionIds).toEqual(['orphan'])+ expect(deleted).toHaveBeenCalledExactlyOnceWith(['a', 'b'])+ })++ it('reattaches missing accounting to the last workspace with the same path and avoids duplicate slots', async () => {+ const h = harness()+ h.workspaces[0]!.sessionIds = ['keep']+ h.workspaces[1]!.sessionIds = ['keep']+ const restored = vi.fn()+ archiveHooks.hook('archive:restored', restored)+ expect(await archive.unarchive('a')).toEqual({ ok: true })+ await ledger.remove(['a', 'a'], 'attach')+ await Promise.resolve()+ expect(h.workspaces.map(workspace => workspace.sessionIds)).toEqual([['keep'], ['keep', 'a']])+ expect(h.table.update).toHaveBeenCalledTimes(1)+ expect(h.state().archivedSessionIds).toEqual(['b', 'orphan'])+ expect(restored).toHaveBeenCalledExactlyOnceWith('a')+ expect(h.removeDir).not.toHaveBeenCalled()+ })++ it('restore tolerates missing optional workspace listing and leaves existing accounting intact', async () => {+ const h = harness()+ h.registry.list = undefined+ await ledger.remove(['a'], 'attach')+ expect(h.table.update).not.toHaveBeenCalled()+ expect(h.state().archivedSessionIds).toEqual(['b', 'orphan'])+ expect(h.workspaces[0]!.sessionIds).toEqual(['a', 'b', 'keep'])+ })+})diff --git a/packages/dsh-tauri-archive/src/host/service/archive.ts b/packages/dsh-tauri-archive/src/host/service/archive.tsindex 49f75e7c..41e8a909 100644--- a/packages/dsh-tauri-archive/src/host/service/archive.ts+++ b/packages/dsh-tauri-archive/src/host/service/archive.ts@@ -1,6 +1,5 @@import type { ArchivedListPayload } from './ledger.types'import { defineService } from 'dsh-tauri'-import { compact, difference, isEmpty, uniq } from 'lodash-es'import { getCurrentHostInstance } from '../config/runtime'import { archiveHooks } from '../events'import { ledger } from './ledger'@@ -58,11 +57,12 @@ export const archive = defineService({*/async function permanentlyDelete(rawIds: readonly string[]): Promise<{ ok: true }> {const host = getCurrentHostInstance()- const ids = uniq(compact(rawIds.map(String)))- if (isEmpty(ids))+ const ids = [...new Set(rawIds.map(String).filter(Boolean))]+ if (ids.length === 0)throw new Error('缺少 sessionIds')- const missing = difference(ids, ledger.list())+ const archived = new Set(ledger.list())+ const missing = ids.filter(id => !archived.has(id))if (missing.length > 0)throw new Error(`会话 '${missing[0]}' 不在归档集合中,拒绝删除`)diff --git a/packages/dsh-tauri-archive/src/host/service/ledger.ts b/packages/dsh-tauri-archive/src/host/service/ledger.tsindex a9955c95..fa368610 100644--- a/packages/dsh-tauri-archive/src/host/service/ledger.ts+++ b/packages/dsh-tauri-archive/src/host/service/ledger.ts@@ -1,7 +1,6 @@-import type { ArchiveRegistrySurface, ArchiveTableSurface, SessionLike, WorkspaceEntryLike } from '../types'+import type { ArchiveRegistrySurface, ArchiveTableSurface, SessionLike } from '../types'import type { ArchiveAccounting, ArchivedListPayload } from './ledger.types'import { defineService } from 'dsh-tauri'-import { difference, keyBy, uniq } from 'lodash-es'import { getCurrentHostInstance } from '../config/runtime'import { session } from './session'@@ -51,7 +50,7 @@ export const ledger = defineService({*/async remove(sessionIds: readonly string[], accounting: ArchiveAccounting = 'detach'): Promise<void> {const registry = requireWritableRegistry(getCurrentHostInstance().workspaceRegistry)- const ids = uniq(sessionIds)+ const ids = [...new Set(sessionIds)]await registry.enqueueOperation(async () => {if (accounting === 'attach')await restoreWorkspaceAccounting(registry, ids)@@ -59,7 +58,7 @@ export const ledger = defineService({await detachWorkspaceAccounting(registry, ids)const state = registry.requireState()const archived = state.archivedSessionIds ?? []- const next = difference(archived, ids)+ const next = archived.filter(id => !ids.includes(id))if (next.length !== archived.length)await registry.setState({ ...state, archivedSessionIds: next })})@@ -90,7 +89,7 @@ async function detachWorkspaceAccounting(registry: ArchiveRegistrySurface, sessiconst table = requireTable(registry)for (const [workspaceId, record] of table.entries()) {const current = record.sessionIds ?? []- const next = difference(current, sessionIds)+ const next = current.filter(id => !sessionIds.includes(id))if (next.length !== current.length)await table.update(workspaceId, value => ({ ...value, sessionIds: next }))}@@ -105,7 +104,7 @@ async function restoreWorkspaceAccounting(registry: ArchiveRegistrySurface, sessconst workspaces = registry.list?.()if (!table || !workspaces)return- const byPath = keyBy<WorkspaceEntryLike>(workspaces, 'path')+ const byPath = Object.fromEntries(workspaces.map(workspace => [workspace.path, workspace]))for (const sessionId of sessionIds) {const cwd = cwdOf(session.get(sessionId))const workspace = cwd ? byPath[cwd] : undefineddiff --git a/packages/dsh-tauri-archive/src/host/service/session.ts b/packages/dsh-tauri-archive/src/host/service/session.tsindex 2668d3fe..13cba14c 100644--- a/packages/dsh-tauri-archive/src/host/service/session.ts+++ b/packages/dsh-tauri-archive/src/host/service/session.ts@@ -2,7 +2,6 @@ import type { SessionLike } from '../types'import type { OpenSessionDirectoryResult } from './session.types'import { rmSync } from 'node:fs'import { defineService, openDirectory } from 'dsh-tauri'-import { compact } from 'lodash-es'import { dirname, resolve } from 'pathe'import { getCurrentHostInstance } from '../config/runtime'import { findSessionDataDir, isWithinRoot, readDirectory, sessionsRoot } from './session.utils'@@ -24,7 +23,7 @@ export const session = defineService({*/remove(ids: readonly string[]): string[] {const sessions = getCurrentHostInstance().sessions- const live = compact(ids.map(id => (sessions.get?.(id) ? id : null)))+ const live = ids.filter(id => sessions.get?.(id) && id)if (live.length > 0 && !sessions.remove)throw new Error('宿主未提供 SessionStore.remove,请先更新桌面壳')return live.filter(id => !sessions.remove?.(id))diff --git a/packages/dsh-tauri-pet/src/client/components/pet-settings.test.tsx b/packages/dsh-tauri-pet/src/client/components/pet-settings.test.tsxnew file mode 100644index 00000000..c30732a8--- /dev/null+++ b/packages/dsh-tauri-pet/src/client/components/pet-settings.test.tsx@@ -0,0 +1,244 @@+// @vitest-environment jsdom+import type { ButtonHTMLAttributes, ReactNode } from 'react'+import type { PetActionResult } from '../service/pet.types'+import { act } from 'react'+import { createRoot } from 'react-dom/client'+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+import { PET_DEFAULT_SIZE } from '../constants'+import { locale } from '../locales'+import * as petService from '../service/pet'+import { store } from '../store'+import { PetSettings } from './pet-settings'++vi.mock('dsh-tauri/client', async () => ({+ ...await import('../../../../dsh-tauri/src/client/modules/valtio-define.ts'),+ ...await import('../../../../dsh-tauri/src/client/locale/index.ts'),+ ...await import('@reause/core'),+ ...await import('tailwind-variants'),+}))++vi.mock('dsh-tauri-ui/client', () => ({+ ArrowRightFromSquare: () => null,+ Plus: () => null,+ Icon: () => null,+ Button: ({ variant: _variant, size: _size, icon: _icon, ...props }: ButtonHTMLAttributes<HTMLButtonElement> & { variant?: string, size?: string, icon?: ReactNode }) => <button {...props} />,+ SegmentedControl: ({ value, onChange }: { value: string, onChange: (value: string) => void }) => (+ <div>+ {['pets', 'codex'].map(tab => <button key={tab} aria-pressed={value === tab} onClick={() => onChange(tab)}>{tab}</button>)}+ </div>+ ),+}))++vi.mock('../service/pet', () => ({+ choosePet: vi.fn(),+ clearPetSelection: vi.fn(),+ enablePet: vi.fn(),+ importPetArchive: vi.fn(),+ loadForceXwayland: vi.fn(),+ loadPetCatalog: vi.fn(),+ loadPetOverlaySupported: vi.fn(),+ resizePet: vi.fn(),+ toggleForceXwayland: vi.fn(),+ togglePet: vi.fn(),+}))++let container: HTMLDivElement+let root: ReturnType<typeof createRoot>++function deferred() {+ let resolve!: (value: PetActionResult) => void+ const promise = new Promise<PetActionResult>((done) => {+ resolve = done+ })+ return { promise, resolve }+}++function button(text: string): HTMLButtonElement {+ const result = Array.from(container.querySelectorAll('button')).find(item => item.textContent === text)+ if (!result)+ throw new Error(`Missing button ${text}`)+ return result+}++function card(name: string): HTMLDivElement {+ const result = Array.from(container.querySelectorAll('div')).find(item => item.querySelector(':scope > span > span > span')?.textContent === name)+ if (!(result instanceof HTMLDivElement))+ throw new Error(`Missing card ${name}`)+ return result+}++async function click(node: HTMLElement): Promise<void> {+ await act(async () => {+ node.click()+ })+}++async function mount(onCreate = vi.fn().mockResolvedValue({ ok: true }), close = vi.fn()): Promise<void> {+ await act(async () => {+ root.render(<PetSettings onCreate={onCreate} close={close} />)+ })+}++beforeEach(() => {+ vi.stubGlobal('IS_REACT_ACT_ENVIRONMENT', true)+ vi.resetAllMocks()+ Object.assign(store.pet.$state, {+ status: { active_pet: 'chat', enabled: false, visible: false },+ fetchRevision: 0,+ catalogLoaded: true,+ presetPets: [{ id: 'preset', name: 'Preset', desc: 'Preset description', image: 'preset.gif' }],+ chatPets: [{ id: 'chat', name: 'Chat', source: 'chat', description: 'Chat description', thumbnail: 'chat.png' }],+ codexPets: [{ id: 'codex', name: 'Codex', source: 'codex', thumbnail: 'codex.png' }],+ prefills: {},+ overlaySupported: false,+ forceXwayland: false,+ })+ for (const action of [petService.loadPetCatalog, petService.choosePet, petService.clearPetSelection, petService.enablePet, petService.togglePet, petService.toggleForceXwayland, petService.resizePet, petService.importPetArchive])+ vi.mocked(action).mockResolvedValue({ ok: true })+ container = document.createElement('div')+ document.body.append(container)+ root = createRoot(container)+})++afterEach(async () => {+ await act(async () => {+ root.unmount()+ })+ container.remove()+ vi.restoreAllMocks()+ vi.unstubAllGlobals()+})++describe('pet settings action boundaries', () => {+ it('renders preset images separately from identical Chat/Codex spritesheet cards and keeps active clear actions', async () => {+ await mount()+ expect(card('Preset').querySelector('img')?.parentElement).toBe(card('Preset'))+ expect(card('Preset').textContent).toContain('Preset description')+ expect(card('Preset').querySelector('button')?.textContent).toBe(locale.text('enable'))+ expect(card('Chat').querySelector('img')?.parentElement?.tagName).toBe('SPAN')+ expect(card('Chat').textContent).toContain('Chat description')+ expect(card('Chat').querySelector('button')?.textContent).toBe(locale.text('clear'))+ await click(card('Chat').querySelector('button')!)+ expect(petService.clearPetSelection).toHaveBeenCalledExactlyOnceWith()+ expect(petService.choosePet).not.toHaveBeenCalled()+ await click(button('codex'))+ expect(card('Codex').querySelector('img')?.parentElement?.tagName).toBe('SPAN')+ expect(card('Codex').querySelector('button')?.textContent).toBe(locale.text('select'))+ await click(card('Codex').querySelector('button')!)+ expect(petService.choosePet).toHaveBeenCalledExactlyOnceWith({ id: 'codex' })+ })++ it.each([+ { kind: 'preset', errorKey: 'setPetFailed', mock: 'enablePet' },+ { kind: 'chat', errorKey: 'clearFailed', mock: 'clearPetSelection' },+ { kind: 'codex', errorKey: 'setPetFailed', mock: 'choosePet' },+ { kind: 'toggle', errorKey: 'toggleFailed', mock: 'togglePet' },+ { kind: 'xwayland', errorKey: 'xwaylandFailed', mock: 'toggleForceXwayland' },+ ] as const)('$kind disables actions while pending, releases busy on failure and shows its own error', async ({ kind, errorKey, mock }) => {+ const pending = deferred()+ vi.mocked(petService[mock]).mockReturnValueOnce(pending.promise)+ await mount()+ if (kind === 'codex')+ await click(button('codex'))+ const action = kind === 'preset'+ ? card('Preset').querySelector('button')!+ : kind === 'chat'+ ? card('Chat').querySelector('button')!+ : kind === 'codex'+ ? card('Codex').querySelector('button')!+ : button(locale.text(kind === 'toggle' ? 'enablePet' : 'xwaylandEnable'))+ await click(action)+ expect(action.disabled).toBe(true)+ const calls = vi.mocked(petService[mock]).mock.calls.length+ await click(action)+ expect(vi.mocked(petService[mock])).toHaveBeenCalledTimes(calls)+ expect(container.querySelector('[role="alert"]')).toBeNull()+ expect(container.querySelector('input[type="range"]')?.hasAttribute('disabled')).toBe(false)+ await act(async () => {+ pending.resolve({ ok: false, error: 'native failure' })+ })+ expect(action.disabled).toBe(false)+ expect(container.querySelector('[role="alert"]')?.textContent).toBe(locale.text(errorKey))+ expect(container.textContent).not.toContain(locale.text('xwaylandRestart'))+ await click(action)+ expect(container.querySelector('[role="alert"]')).toBeNull()+ expect(action.disabled).toBe(false)+ })++ it('global toggles preserve boolean arguments and show restart only after XWayland success', async () => {+ await mount()+ await click(button(locale.text('enablePet')))+ expect(petService.togglePet).toHaveBeenCalledExactlyOnceWith({ enabled: true })+ await click(button(locale.text('xwaylandEnable')))+ expect(petService.toggleForceXwayland).toHaveBeenCalledExactlyOnceWith({ enabled: true })+ expect(container.textContent).toContain(locale.text('xwaylandRestart'))+ })++ it('default size remains interactive during other busy actions and sends each changed value', async () => {+ const pending = deferred()+ vi.mocked(petService.togglePet).mockReturnValueOnce(pending.promise)+ vi.mocked(petService.resizePet).mockResolvedValueOnce({ ok: false, error: 'bad size' })+ await mount()+ const slider = container.querySelector<HTMLInputElement>('input[type="range"]')!+ expect(slider.value).toBe(String(PET_DEFAULT_SIZE))+ await click(button(locale.text('enablePet')))+ await act(async () => {+ Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value')!.set!.call(slider, '160')+ slider.dispatchEvent(new Event('change', { bubbles: true }))+ })+ expect(petService.resizePet).toHaveBeenCalledExactlyOnceWith({ size: 160 })+ expect(container.querySelector('[role="alert"]')?.textContent).toBe(locale.text('setSizeFailed'))+ expect(button(locale.text('enablePet')).disabled).toBe(true)+ await act(async () => {+ pending.resolve({ ok: true })+ })+ })++ it('create forwards the close callback and keeps busy on success but releases it on failure', async () => {+ const close = vi.fn()+ const pending = deferred()+ const onCreate = vi.fn().mockReturnValueOnce(pending.promise).mockResolvedValue({ ok: true })+ await mount(onCreate, close)+ await click(button(locale.text('create')))+ expect(onCreate).toHaveBeenCalledExactlyOnceWith(close)+ expect(button(locale.text('create')).disabled).toBe(true)+ await act(async () => {+ pending.resolve({ ok: false, error: 'no session' })+ })+ expect(container.querySelector('[role="alert"]')?.textContent).toBe(locale.text('createFailed'))+ expect(button(locale.text('create')).disabled).toBe(false)+ await click(button(locale.text('create')))+ expect(container.querySelector('[role="alert"]')).toBeNull()+ expect(button(locale.text('create')).disabled).toBe(true)+ })++ it('catalog failure releases initial busy and only lazy-loads unknown environment flags', async () => {+ Object.assign(store.pet.$state, { catalogLoaded: false, overlaySupported: null, forceXwayland: null })+ vi.mocked(petService.loadPetCatalog).mockResolvedValue({ ok: false, error: 'catalog failed' })+ await mount()+ expect(petService.loadPetCatalog).toHaveBeenCalledExactlyOnceWith()+ expect(petService.loadPetOverlaySupported).toHaveBeenCalledExactlyOnceWith()+ expect(petService.loadForceXwayland).toHaveBeenCalledExactlyOnceWith()+ expect(container.querySelector('[role="alert"]')?.textContent).toBe(locale.text('listFailed'))+ expect(button(locale.text('create')).disabled).toBe(false)+ })++ it('import keeps name/base64 arguments and restores busy after a failed native result', async () => {+ vi.mocked(petService.importPetArchive).mockResolvedValue({ ok: false, error: 'bad archive' })+ await mount()+ await click(button('codex'))+ const input = container.querySelector<HTMLInputElement>('input[type="file"]')!+ Object.defineProperty(input, 'files', { value: [new File(['pet'], 'pet.zip', { type: 'application/zip' })] })+ vi.spyOn(FileReader.prototype, 'readAsDataURL').mockImplementation(function (this: FileReader) {+ Object.defineProperty(this, 'result', { value: 'data:application/zip;base64,cGV0' })+ this.dispatchEvent(new ProgressEvent('load'))+ })+ await act(async () => {+ input.dispatchEvent(new Event('change', { bubbles: true }))+ })+ expect(petService.importPetArchive).toHaveBeenCalledExactlyOnceWith({ name: 'pet.zip', data: 'cGV0' })+ expect(container.querySelector('[role="alert"]')?.textContent).toBe(locale.text('importFailed'))+ expect(input.disabled).toBe(false)+ expect(input.value).toBe('')+ })+})diff --git a/packages/dsh-tauri-pet/src/client/components/pet-settings.tsx b/packages/dsh-tauri-pet/src/client/components/pet-settings.tsxindex ee508a01..1f9fa334 100644--- a/packages/dsh-tauri-pet/src/client/components/pet-settings.tsx+++ b/packages/dsh-tauri-pet/src/client/components/pet-settings.tsx@@ -1,5 +1,5 @@import type { ChangeEvent, ReactElement } from 'react'-import type { PetActionResult } from '../service/pet.types'+import type { PetActionResult, PetListItem } from '../service/pet.types'import { ArrowRightFromSquare, Button, Icon, Plus, SegmentedControl } from 'dsh-tauri-ui/client'import { useStore, useWatchImmediate } from 'dsh-tauri/client'import { useEffect, useId, useRef, useState } from 'react'@@ -94,62 +94,44 @@ export function PetSettings(props: PetSettingsProps): ReactElement {}}, [])- async function enablePreset(id: string): Promise<void> {- if (busy || active === id)+ async function run(action: () => Promise<PetActionResult>, errorKey: Parameters<typeof locale.text>[0]): Promise<void> {+ if (busy)returnsetBusy(true)setError(null)- const result = await enablePet({ id })+ const result = await action()if (!result.ok)- setError(locale.text('setPetFailed'))+ setError(locale.text(errorKey))setBusy(false)}+ async function enablePreset(id: string): Promise<void> {+ if (active !== id)+ await run(() => enablePet({ id }), 'setPetFailed')+ }+async function choose(id: string): Promise<void> {- if (busy || active === id)- return- setBusy(true)- setError(null)- const result = await choosePet({ id })- if (!result.ok)- setError(locale.text('setPetFailed'))- setBusy(false)+ if (active !== id)+ await run(() => choosePet({ id }), 'setPetFailed')}async function clearSelection(): Promise<void> {- if (busy || active === '')- return- setBusy(true)- setError(null)- const result = await clearPetSelection()- if (!result.ok)- setError(locale.text('clearFailed'))- setBusy(false)+ if (active !== '')+ await run(clearPetSelection, 'clearFailed')}async function toggleEnabled(): Promise<void> {- if (busy)- return- setBusy(true)- setError(null)- const result = await togglePet({ enabled: !enabled })- if (!result.ok)- setError(locale.text('toggleFailed'))- setBusy(false)+ await run(() => togglePet({ enabled: !enabled }), 'toggleFailed')}/** 切换「强制 XWayland」:应用全局设置,下次启动生效。 */async function toggleXwayland(): Promise<void> {- if (busy)- return- setBusy(true)- setError(null)- const result = await toggleForceXwayland({ enabled: !forceXwayland })- if (result.ok)- setXwaylandRestart(true)- else- setError(locale.text('xwaylandFailed'))- setBusy(false)+ await run(async () => {+ const result = await toggleForceXwayland({ enabled: !forceXwayland })+ if (result.ok)+ setXwaylandRestart(true)+ return result+ }, 'xwaylandFailed')}async function commitSize(value: number): Promise<void> {@@ -194,6 +176,20 @@ export function PetSettings(props: PetSettingsProps): ReactElement {}}+ const cards = (items: readonly PetListItem[]) => items.map(item => (+ <PetCard+ key={item.id}+ thumbnail={item.thumbnail}+ thumbnailType={item.thumbnail ? 'spritesheet' : undefined}+ name={item.name}+ desc={item.description ?? ''}+ active={active === item.id}+ disabled={busy}+ actionLabel={locale.text(active === item.id ? 'clear' : 'select')}+ onAction={() => { void (active === item.id ? clearSelection() : choose(item.id)) }}+ />+ ))+const petsPanel = (<>{busy && presetPets.length === 0 && chatPets.length === 0@@ -212,19 +208,7 @@ export function PetSettings(props: PetSettingsProps): ReactElement {onAction={() => { void (active === item.id ? clearSelection() : enablePreset(item.id)) }}/>))}- {chatPets.map(item => (- <PetCard- key={item.id}- thumbnail={item.thumbnail}- thumbnailType={item.thumbnail ? 'spritesheet' : undefined}- name={item.name}- desc={item.description ?? ''}- active={active === item.id}- disabled={busy}- actionLabel={locale.text(active === item.id ? 'clear' : 'select')}- onAction={() => { void (active === item.id ? clearSelection() : choose(item.id)) }}- />- ))}+ {cards(chatPets)}</div>)}</>@@ -234,19 +218,7 @@ export function PetSettings(props: PetSettingsProps): ReactElement {<div className="flex flex-col gap-[12px]">{codexPets.length === 0? <div className="px-[16px] py-[24px] text-center text-[13px] leading-[20px] rounded-[12px] border border-dashed border-border-weak text-secondary">{locale.text('emptyImported')}</div>- : codexPets.map(item => (- <PetCard- key={item.id}- thumbnail={item.thumbnail}- thumbnailType={item.thumbnail ? 'spritesheet' : undefined}- name={item.name}- desc={item.description ?? ''}- active={active === item.id}- disabled={busy}- actionLabel={locale.text(active === item.id ? 'clear' : 'select')}- onAction={() => { void (active === item.id ? clearSelection() : choose(item.id)) }}- />- ))}+ : cards(codexPets)}</div>)diff --git a/packages/dsh-tauri-pet/src/client/service/pet.invoke.ts b/packages/dsh-tauri-pet/src/client/service/pet.invoke.tsdeleted file mode 100644index 81d4fcc6..00000000--- a/packages/dsh-tauri-pet/src/client/service/pet.invoke.ts+++ /dev/null@@ -1,58 +0,0 @@-/** service/invoke.ts — 桌面端 Tauri 命令出口(经 dsh-tauri invoke 桥)。 */-import type { PetListItem, PetSource, PetStatus, PresetPetItem } from './pet.types'-import { invoke } from 'dsh-tauri/client'-import {- CMD_GET_FORCE_XWAYLAND,- CMD_GET_PET_OVERLAY_SUPPORTED,- CMD_GET_PET_STATUS,- CMD_IMPORT_PET,- CMD_LIST_PETS,- CMD_LIST_PRESET_PETS,- CMD_SET_ACTIVE_PET,- CMD_SET_FORCE_XWAYLAND,- CMD_SET_PET_ENABLED,- CMD_SET_PET_SIZE,-} from '../constants'--export function getPetStatus(): Promise<PetStatus> {- return invoke<PetStatus>(CMD_GET_PET_STATUS)-}--/** 当前环境能否让桌宠窗口置顶并定位(原生 Wayland 下不能,issue #649)。 */-export function getPetOverlaySupported(): Promise<boolean> {- return invoke<boolean>(CMD_GET_PET_OVERLAY_SUPPORTED)-}--/** 「强制 XWayland」开关的当前值(应用全局设置,下次启动生效)。 */-export function getForceXwayland(): Promise<boolean> {- return invoke<boolean>(CMD_GET_FORCE_XWAYLAND)-}--export function postForceXwayland(enabled: boolean): Promise<boolean> {- return invoke<boolean>(CMD_SET_FORCE_XWAYLAND, { enabled })-}--export function postPetEnabled(enabled: boolean): Promise<PetStatus> {- return invoke<PetStatus>(CMD_SET_PET_ENABLED, { enabled })-}--export function postActivePet(id: string): Promise<PetStatus> {- return invoke<PetStatus>(CMD_SET_ACTIVE_PET, { id })-}--export function postPetSize(size: number): Promise<PetStatus> {- return invoke<PetStatus>(CMD_SET_PET_SIZE, { size })-}--export function getPetList(source: PetSource): Promise<PetListItem[]> {- return invoke<PetListItem[]>(CMD_LIST_PETS, { source })-}--export function postPetImport(name: string, data: string): Promise<PetListItem> {- return invoke<PetListItem>(CMD_IMPORT_PET, { name, data })-}--/** 预设宠物清单(清单 `pets.built-in`;条目直连远端素材,无安装态)。 */-export function getPresetPets(): Promise<PresetPetItem[]> {- return invoke<PresetPetItem[]>(CMD_LIST_PRESET_PETS)-}diff --git a/packages/dsh-tauri-pet/src/client/service/pet.test.ts b/packages/dsh-tauri-pet/src/client/service/pet.test.tsnew file mode 100644index 00000000..05219dd8--- /dev/null+++ b/packages/dsh-tauri-pet/src/client/service/pet.test.ts@@ -0,0 +1,282 @@+import type { ClientAdapter } from 'dsh-tauri/client'+import type { PetStatus } from './pet.types'+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+import { PET_HATCH_PROMPT } from '../constants'+import { store } from '../store'+import {+ choosePet,+ clearPetSelection,+ createPetSession,+ enablePet,+ importPetArchive,+ loadForceXwayland,+ loadPetCatalog,+ loadPetOverlaySupported,+ loadPetStatus,+ resizePet,+ toggleForceXwayland,+ togglePet,+} from './pet'++const { invoke } = vi.hoisted(() => ({ invoke: vi.fn() }))++vi.mock('dsh-tauri/client', async () => ({+ ...await import('../../../../dsh-tauri/src/client/modules/valtio-define.ts'),+ invoke,+}))++const status: PetStatus = { active_pet: 'chat-a', enabled: true, visible: true, pet_size: 100 }++function adapter(): ClientAdapter {+ return {+ generation: 'modern',+ migrations: [],+ failures: [],+ ctx: {},+ sessions: { open: vi.fn(), list: { subscribe: vi.fn(), getSnapshot: () => ({ current: 'current' }) } },+ workspaces: {+ connectWorkspace: vi.fn().mockResolvedValue('new-session'),+ list: {+ subscribe: vi.fn(),+ getSnapshot: () => ({ items: [{ id: 'recent' }, { id: 'current-workspace', sessionIds: ['current'] }], recentWorkspaceId: 'recent' }),+ },+ },+ service: () => undefined,+ has: () => false,+ resolveStartSession: () => undefined,+ resolveOpenSession: () => undefined,+ sessionList: () => undefined,+ resolveAddWorkspace: () => undefined,+ startSession: async () => ({ status: 'unavailable', reason: 'unused' }),+ openSession: () => ({ status: 'unavailable', reason: 'unused' }),+ addWorkspace: async () => ({ status: 'unavailable', reason: 'unused' }),+ }+}++function resetStore(): void {+ Object.assign(store.pet.$state, {+ status: null,+ fetchRevision: 0,+ catalogLoaded: false,+ presetPets: [],+ chatPets: [],+ codexPets: [],+ prefills: {},+ overlaySupported: null,+ forceXwayland: null,+ })+}++beforeEach(() => {+ invoke.mockReset()+ resetStore()+})++afterEach(() => {+ resetStore()+ vi.restoreAllMocks()+})++describe('pet service native command contracts', () => {+ it('catalog loads all four native queries and commits their exact lists', async () => {+ const chat = [{ id: 'chat-a', name: 'Chat', source: 'chat' }]+ const codex = [{ id: 'codex-a', name: 'Codex', source: 'codex' }]+ const presets = [{ id: 'builtin', name: 'Built in' }]+ invoke.mockResolvedValueOnce(status).mockResolvedValueOnce(chat).mockResolvedValueOnce(codex).mockResolvedValueOnce(presets)++ expect(await loadPetCatalog()).toEqual({ ok: true })+ expect(invoke.mock.calls).toEqual([+ ['get_pet_status'],+ ['list_pets', { source: 'chat' }],+ ['list_pets', { source: 'codex' }],+ ['list_preset_pets'],+ ])+ expect(store.pet.$state).toMatchObject({ status, catalogLoaded: true, chatPets: chat, codexPets: codex, presetPets: presets })+ })++ it('older status responses cannot replace a newer native action snapshot', async () => {+ let resolve!: (value: PetStatus) => void+ invoke.mockReturnValueOnce(new Promise<PetStatus>((done) => {+ resolve = done+ })).mockResolvedValueOnce(status)+ const pending = loadPetStatus()+ expect(await choosePet({ id: 'chat-a' })).toEqual({ ok: true })+ const stale = { ...status, active_pet: 'stale' }+ resolve(stale)+ expect(await pending).toEqual(stale)+ expect(store.pet.status).toEqual(status)+ expect(invoke.mock.calls).toEqual([['get_pet_status'], ['set_active_pet', { id: 'chat-a' }]])+ })++ it.each([+ { action: () => choosePet({ id: 'chosen' }), call: ['set_active_pet', { id: 'chosen' }] },+ { action: () => togglePet({ enabled: false }), call: ['set_pet_enabled', { enabled: false }] },+ { action: () => resizePet({ size: 160 }), call: ['set_pet_size', { size: 160 }] },+ ])('status action forwards $call and stores the authoritative result', async ({ action, call }) => {+ invoke.mockResolvedValue(status)+ expect(await action()).toEqual({ ok: true })+ expect(invoke.mock.calls).toEqual([call])+ expect(store.pet.status).toEqual(status)+ })++ it.each([true, false])('preset activation only enables the native window when enabled=%s is false', async (enabled) => {+ invoke.mockResolvedValueOnce({ ...status, enabled }).mockResolvedValueOnce(status)+ expect(await enablePet({ id: 'preset' })).toEqual({ ok: true })+ expect(invoke.mock.calls).toEqual(enabled+ ? [['set_active_pet', { id: 'preset' }]]+ : [['set_active_pet', { id: 'preset' }], ['set_pet_enabled', { enabled: true }]])+ expect(store.pet.status).toEqual(status)+ })++ it.each([true, false])('clearing selection disables first only when enabled=%s', async (enabled) => {+ store.pet.setStatus({ ...status, enabled })+ const cleared = { active_pet: '', enabled: false, visible: false }+ invoke.mockImplementation(async command => command === 'set_active_pet' ? cleared : { ...status, enabled: false })+ expect(await clearPetSelection()).toEqual({ ok: true })+ expect(invoke.mock.calls).toEqual(enabled+ ? [['set_pet_enabled', { enabled: false }], ['set_active_pet', { id: '' }]]+ : [['set_active_pet', { id: '' }]])+ expect(store.pet.status).toEqual(cleared)+ })++ it.each(['set_pet_enabled', 'set_active_pet'])('clear failure at %s reloads native status and preserves the original error', async (failingCommand) => {+ const error = new Error('native clear refused')+ const log = vi.spyOn(console, 'error').mockImplementation(() => {})+ store.pet.setStatus(status)+ invoke.mockImplementation(async (command) => {+ if (command === failingCommand)+ throw error+ return status+ })+ expect(await clearPetSelection()).toEqual({ ok: false, error: 'native clear refused' })+ expect(log).toHaveBeenCalledExactlyOnceWith('[dsh-tauri-pet] clear pet selection failed:', error)+ expect(invoke.mock.calls).toEqual(failingCommand === 'set_pet_enabled'+ ? [['set_pet_enabled', { enabled: false }], ['get_pet_status']]+ : [['set_pet_enabled', { enabled: false }], ['set_active_pet', { id: '' }], ['get_pet_status']])+ expect(store.pet.status).toEqual(status)+ })++ it('import forwards archive strings before refreshing only the Codex list', async () => {+ const codex = [{ id: 'imported', name: 'Imported', source: 'codex' }]+ invoke.mockResolvedValueOnce(codex[0]).mockResolvedValueOnce(codex)+ expect(await importPetArchive({ name: 'pet.zip', data: 'base64' })).toEqual({ ok: true })+ expect(invoke.mock.calls).toEqual([['import_pet', { name: 'pet.zip', data: 'base64' }], ['list_pets', { source: 'codex' }]])+ expect(store.pet.codexPets).toEqual(codex)+ expect(store.pet.catalogLoaded).toBe(false)+ })++ it('xWayland query and action retain native boolean results', async () => {+ invoke.mockResolvedValueOnce(true).mockResolvedValueOnce(false)+ expect(await loadForceXwayland()).toBe(true)+ expect(store.pet.forceXwayland).toBe(true)+ expect(await toggleForceXwayland({ enabled: false })).toEqual({ ok: true })+ expect(store.pet.forceXwayland).toBe(false)+ expect(invoke.mock.calls).toEqual([['get_force_xwayland'], ['set_force_xwayland', { enabled: false }]])+ })++ it('overlay query stores false without treating unsupported platforms as failures', async () => {+ invoke.mockResolvedValue(false)+ expect(await loadPetOverlaySupported()).toBe(false)+ expect(store.pet.overlaySupported).toBe(false)+ expect(invoke.mock.calls).toEqual([['get_pet_overlay_supported']])+ })++ it.each([+ { label: 'load pet catalog', action: loadPetCatalog },+ { label: 'choose pet', action: () => choosePet({ id: 'chosen' }) },+ { label: 'enable pet', action: () => enablePet({ id: 'chosen' }) },+ { label: 'toggle pet', action: () => togglePet({ enabled: true }) },+ { label: 'toggle force xwayland', action: () => toggleForceXwayland({ enabled: true }) },+ { label: 'resize pet', action: () => resizePet({ size: 140 }) },+ { label: 'import pet', action: () => importPetArchive({ name: 'bad.zip', data: 'bad' }) },+ ])('$label preserves error messages and logging labels without changing cached values', async ({ label, action }) => {+ const error = new Error('native refused')+ const log = vi.spyOn(console, 'error').mockImplementation(() => {})+ store.pet.setStatus(status)+ invoke.mockRejectedValue(error)+ expect(await action()).toEqual({ ok: false, error: 'native refused' })+ expect(log).toHaveBeenCalledExactlyOnceWith(`[dsh-tauri-pet] ${label} failed:`, error)+ expect(store.pet.status).toEqual(status)+ expect(store.pet.catalogLoaded).toBe(false)+ expect(store.pet.forceXwayland).toBeNull()+ })++ it('guard stringifies non-Error native rejection', async () => {+ const log = vi.spyOn(console, 'error').mockImplementation(() => {})+ invoke.mockRejectedValue('native string')+ expect(await choosePet({ id: 'chosen' })).toEqual({ ok: false, error: 'native string' })+ expect(log).toHaveBeenCalledExactlyOnceWith('[dsh-tauri-pet] choose pet failed:', 'native string')+ })++ it.each([+ { label: 'load pet status', action: loadPetStatus },+ { label: 'load pet overlay support', action: loadPetOverlaySupported },+ { label: 'load force xwayland', action: loadForceXwayland },+ ])('$label failure returns null and retains its previous cache', async ({ label, action }) => {+ const error = new Error('read refused')+ const log = vi.spyOn(console, 'error').mockImplementation(() => {})+ store.pet.setStatus(status)+ store.pet.setOverlaySupported(false)+ store.pet.setForceXwayland(true)+ invoke.mockRejectedValue(error)+ expect(await action()).toBeNull()+ expect(log).toHaveBeenCalledExactlyOnceWith(`[dsh-tauri-pet] ${label} failed:`, error)+ expect(store.pet.$state).toMatchObject({ status, overlaySupported: false, forceXwayland: true })+ })+})++describe('pet session action contracts', () => {+ it('session creation uses the current workspace and prefills before closing and opening', async () => {+ const client = adapter()+ const order: string[] = []+ const close = vi.fn(() => {+ expect(store.pet.prefills).toEqual({ 'new-session': PET_HATCH_PROMPT })+ order.push('close')+ })+ client.sessions.open = vi.fn((id) => {+ expect(id).toBe('new-session')+ order.push('open')+ })+ expect(await createPetSession({ adapter: client, close })).toEqual({ ok: true })+ expect(client.workspaces.connectWorkspace).toHaveBeenCalledExactlyOnceWith('current-workspace')+ expect(order).toEqual(['close', 'open'])+ expect(invoke).not.toHaveBeenCalled()+ })++ it.each([+ { missing: 'workspace', error: 'PET_WORKSPACE_UNAVAILABLE: no workspace can create a pet session' },+ { missing: 'opener', error: 'PET_SESSION_UNAVAILABLE: session opener is unavailable' },+ ])('missing $missing fails before connecting or closing', async ({ missing, error }) => {+ const client = adapter()+ const connect = client.workspaces.connectWorkspace+ const close = vi.fn()+ if (missing === 'workspace')+ client.workspaces.list = undefined+ else+ client.sessions.open = undefined+ expect(await createPetSession({ adapter: client, close })).toEqual({ ok: false, error })+ expect(connect).not.toHaveBeenCalled()+ expect(close).not.toHaveBeenCalled()+ expect(store.pet.prefills).toEqual({})+ })++ it.each(['', undefined, 123])('invalid session id %s fails without prefill or close', async (id) => {+ const client = adapter()+ client.workspaces.connectWorkspace = vi.fn().mockResolvedValue(id)+ const close = vi.fn()+ expect(await createPetSession({ adapter: client, close })).toEqual({ ok: false, error: 'PET_SESSION_UNAVAILABLE: workspace did not return a session id' })+ expect(close).not.toHaveBeenCalled()+ expect(client.sessions.open).not.toHaveBeenCalled()+ expect(store.pet.prefills).toEqual({})+ })++ it('session connection rejection preserves the create logging label and message', async () => {+ const client = adapter()+ const error = new Error('connect refused')+ const log = vi.spyOn(console, 'error').mockImplementation(() => {})+ client.workspaces.connectWorkspace = vi.fn().mockRejectedValue(error)+ expect(await createPetSession({ adapter: client })).toEqual({ ok: false, error: 'connect refused' })+ expect(log).toHaveBeenCalledExactlyOnceWith('[dsh-tauri-pet] create pet session failed:', error)+ expect(client.sessions.open).not.toHaveBeenCalled()+ })+})diff --git a/packages/dsh-tauri-pet/src/client/service/pet.ts b/packages/dsh-tauri-pet/src/client/service/pet.tsindex 946243a7..bdb61e5e 100644--- a/packages/dsh-tauri-pet/src/client/service/pet.ts+++ b/packages/dsh-tauri-pet/src/client/service/pet.ts@@ -1,19 +1,20 @@import type { ClientAdapter } from 'dsh-tauri/client'-import type { PetActionResult, PetStatus } from './pet.types'-import { PET_HATCH_PROMPT } from '../constants'-import { store } from '../store'+import type { PetActionResult, PetListItem, PetStatus, PresetPetItem } from './pet.types'+import { invoke } from 'dsh-tauri/client'import {- getForceXwayland,- getPetList,- getPetOverlaySupported,- getPetStatus,- getPresetPets,- postActivePet,- postForceXwayland,- postPetEnabled,- postPetImport,- postPetSize,-} from './pet.invoke'+ CMD_GET_FORCE_XWAYLAND,+ CMD_GET_PET_OVERLAY_SUPPORTED,+ CMD_GET_PET_STATUS,+ CMD_IMPORT_PET,+ CMD_LIST_PETS,+ CMD_LIST_PRESET_PETS,+ CMD_SET_ACTIVE_PET,+ CMD_SET_FORCE_XWAYLAND,+ CMD_SET_PET_ENABLED,+ CMD_SET_PET_SIZE,+ PET_HATCH_PROMPT,+} from '../constants'+import { store } from '../store'import { chooseWorkspace, messageOf } from './pet.utils'/**@@ -22,12 +23,21 @@ import { chooseWorkspace, messageOf } from './pet.utils'* 两种原型:Query(`load*`,只读数据并更新 store)与 Action(领域动词,响应用户意图* 并更新 store)。无模块级可变状态、无副作用生命周期。*/+async function guard(label: string, action: () => Promise<PetActionResult>): Promise<PetActionResult> {+ try {+ return await action()+ }+ catch (error) {+ console.error(`[dsh-tauri-pet] ${label} failed:`, error)+ return { ok: false, error: messageOf(error) }+ }+}/** Query:拉取桌宠状态快照;按轮次提交,过期响应不覆盖新状态。 */export async function loadPetStatus(): Promise<PetStatus | null> {const revision = store.pet.beginFetch()try {- const status = await getPetStatus()+ const status = await invoke<PetStatus>(CMD_GET_PET_STATUS)store.pet.commitFetch(revision, status)return status}@@ -45,7 +55,7 @@ export async function loadPetStatus(): Promise<PetStatus | null> {*/export async function loadPetOverlaySupported(): Promise<boolean | null> {try {- const supported = await getPetOverlaySupported()+ const supported = await invoke<boolean>(CMD_GET_PET_OVERLAY_SUPPORTED)store.pet.setOverlaySupported(supported)return supported}@@ -63,7 +73,7 @@ export async function loadPetOverlaySupported(): Promise<boolean | null> {*/export async function loadForceXwayland(): Promise<boolean | null> {try {- const enabled = await getForceXwayland()+ const enabled = await invoke<boolean>(CMD_GET_FORCE_XWAYLAND)store.pet.setForceXwayland(enabled)return enabled}@@ -76,48 +86,36 @@ export async function loadForceXwayland(): Promise<boolean | null> {/** Query:装载预设 / Chat / Codex 三份清单,并顺带刷新共享状态快照。 */export async function loadPetCatalog(): Promise<PetActionResult> {const revision = store.pet.beginFetch()- try {+ return guard('load pet catalog', async () => {const [status, chat, codex, presets] = await Promise.all([- getPetStatus(),- getPetList('chat'),- getPetList('codex'),- getPresetPets(),+ invoke<PetStatus>(CMD_GET_PET_STATUS),+ invoke<PetListItem[]>(CMD_LIST_PETS, { source: 'chat' }),+ invoke<PetListItem[]>(CMD_LIST_PETS, { source: 'codex' }),+ invoke<PresetPetItem[]>(CMD_LIST_PRESET_PETS),])store.pet.setCatalog({ presets, chat, codex })store.pet.commitFetch(revision, status)return { ok: true }- }- catch (error) {- console.error('[dsh-tauri-pet] load pet catalog failed:', error)- return { ok: false, error: messageOf(error) }- }+ })}/** Action:选中宠物(状态以桌面端返回的权威快照为准)。 */export async function choosePet(input: { id: string }): Promise<PetActionResult> {- try {- store.pet.setStatus(await postActivePet(input.id))+ return guard('choose pet', async () => {+ store.pet.setStatus(await invoke<PetStatus>(CMD_SET_ACTIVE_PET, { id: input.id }))return { ok: true }- }- catch (error) {- console.error('[dsh-tauri-pet] choose pet failed:', error)- return { ok: false, error: messageOf(error) }- }+ })}/** Action:启用预设宠物——选中它,并确保桌宠被唤醒。 */export async function enablePet(input: { id: string }): Promise<PetActionResult> {- try {- let status = await postActivePet(input.id)+ return guard('enable pet', async () => {+ let status = await invoke<PetStatus>(CMD_SET_ACTIVE_PET, { id: input.id })if (!status.enabled)- status = await postPetEnabled(true)+ status = await invoke<PetStatus>(CMD_SET_PET_ENABLED, { enabled: true })store.pet.setStatus(status)return { ok: true }- }- catch (error) {- console.error('[dsh-tauri-pet] enable pet failed:', error)- return { ok: false, error: messageOf(error) }- }+ })}/**@@ -130,8 +128,8 @@ export async function clearPetSelection(): Promise<PetActionResult> {const status = store.pet.$state.statustry {if (status?.enabled)- store.pet.setStatus(await postPetEnabled(false))- store.pet.setStatus(await postActivePet(''))+ store.pet.setStatus(await invoke<PetStatus>(CMD_SET_PET_ENABLED, { enabled: false }))+ store.pet.setStatus(await invoke<PetStatus>(CMD_SET_ACTIVE_PET, { id: '' }))return { ok: true }}catch (error) {@@ -143,14 +141,10 @@ export async function clearPetSelection(): Promise<PetActionResult> {/** Action:启用/关闭桌宠(纯持久开关,关闭后重启不再自动拉起)。 */export async function togglePet(input: { enabled: boolean }): Promise<PetActionResult> {- try {- store.pet.setStatus(await postPetEnabled(input.enabled))+ return guard('toggle pet', async () => {+ store.pet.setStatus(await invoke<PetStatus>(CMD_SET_PET_ENABLED, { enabled: input.enabled }))return { ok: true }- }- catch (error) {- console.error('[dsh-tauri-pet] toggle pet failed:', error)- return { ok: false, error: messageOf(error) }- }+ })}/**@@ -160,39 +154,27 @@ export async function togglePet(input: { enabled: boolean }): Promise<PetActionR* 生效要等下次启动,调用方据此提示用户重启。*/export async function toggleForceXwayland(input: { enabled: boolean }): Promise<PetActionResult> {- try {- store.pet.setForceXwayland(await postForceXwayland(input.enabled))+ return guard('toggle force xwayland', async () => {+ store.pet.setForceXwayland(await invoke<boolean>(CMD_SET_FORCE_XWAYLAND, { enabled: input.enabled }))return { ok: true }- }- catch (error) {- console.error('[dsh-tauri-pet] toggle force xwayland failed:', error)- return { ok: false, error: messageOf(error) }- }+ })}/** Action:调整桌宠窗口大小。 */export async function resizePet(input: { size: number }): Promise<PetActionResult> {- try {- store.pet.setStatus(await postPetSize(input.size))+ return guard('resize pet', async () => {+ store.pet.setStatus(await invoke<PetStatus>(CMD_SET_PET_SIZE, { size: input.size }))return { ok: true }- }- catch (error) {- console.error('[dsh-tauri-pet] resize pet failed:', error)- return { ok: false, error: messageOf(error) }- }+ })}/** Action:导入宠物压缩包(base64),成功后刷新 Codex 清单。 */export async function importPetArchive(input: { name: string, data: string }): Promise<PetActionResult> {- try {- await postPetImport(input.name, input.data)- store.pet.setCodexPets(await getPetList('codex'))+ return guard('import pet', async () => {+ await invoke<PetListItem>(CMD_IMPORT_PET, { name: input.name, data: input.data })+ store.pet.setCodexPets(await invoke<PetListItem[]>(CMD_LIST_PETS, { source: 'codex' }))return { ok: true }- }- catch (error) {- console.error('[dsh-tauri-pet] import pet failed:', error)- return { ok: false, error: messageOf(error) }- }+ })}/**@@ -213,7 +195,7 @@ export async function createPetSession(input: {if (open === undefined)return { ok: false, error: 'PET_SESSION_UNAVAILABLE: session opener is unavailable' }- try {+ return guard('create pet session', async () => {const sessionId = await connectWorkspace(workspaceId)if (typeof sessionId !== 'string' || sessionId.length === 0)return { ok: false, error: 'PET_SESSION_UNAVAILABLE: workspace did not return a session id' }@@ -221,9 +203,5 @@ export async function createPetSession(input: {close?.()open(sessionId)return { ok: true }- }- catch (error) {- console.error('[dsh-tauri-pet] create pet session failed:', error)- return { ok: false, error: messageOf(error) }- }+ })}diff --git a/packages/dsh-tauri-pet/src/host/service/session-stream.types.ts b/packages/dsh-tauri-pet/src/host/service/session-stream.types.tsindex 9ee8cf73..63002fad 100644--- a/packages/dsh-tauri-pet/src/host/service/session-stream.types.ts+++ b/packages/dsh-tauri-pet/src/host/service/session-stream.types.ts@@ -63,7 +63,6 @@ export interface PetSessionState {task?: string/** 当前工具活动分类(最近一次 working 工具名分类)。 */toolActivity?: PetToolActivity- firstSeqAt: number}/** 宿主 `sessionTitle` 服务的读取面(可选:未挂载时回退 id)。 */diff --git a/packages/dsh-tauri-pet/src/host/service/session-stream.utils.test.ts b/packages/dsh-tauri-pet/src/host/service/session-stream.utils.test.tsindex 9f8aced8..699ae719 100644--- a/packages/dsh-tauri-pet/src/host/service/session-stream.utils.test.ts+++ b/packages/dsh-tauri-pet/src/host/service/session-stream.utils.test.ts@@ -39,6 +39,21 @@ describe('petSessionReducer (host)', () => {expect(pushes[0].payload.status).toBeUndefined()})+ it('preserves the activity alias across running, waiting, error and idle wire payloads', () => {+ const { reducer, pushes } = collect()+ reducer.create(peer())+ expect(pushes.at(-1)!.payload).toHaveProperty('activity', undefined)+ reducer.apply(peer(), ev('turn/start', { turn: 1 }, 1))+ expect(pushes.at(-1)!.payload).toMatchObject({ status: 'running', activity: 'running' })+ reducer.apply(peer(), ev('approval/asked', { id: 'approval' }, 2))+ expect(pushes.at(-1)!.payload).toMatchObject({ status: 'waiting', activity: 'waiting' })+ reducer.apply(peer(), ev('turn/end', { turn: 1, reason: { kind: 'error', error: { message: 'failed' } } }, 3))+ expect(pushes.at(-1)!.payload).toMatchObject({ status: 'error', activity: 'error' })+ reducer.apply(peer(), ev('turn/start', { turn: 2 }, 4))+ reducer.apply(peer(), ev('turn/end', { turn: 2, reason: { kind: 'completed' } }, 5))+ expect(pushes.at(-1)!.payload).toHaveProperty('activity', undefined)+ })+it('turn/start 让 running=true、status=running、workStatus=thinking', () => {const { reducer, pushes } = collect()reducer.create(peer())diff --git a/packages/dsh-tauri-pet/src/host/service/session-stream.utils.ts b/packages/dsh-tauri-pet/src/host/service/session-stream.utils.tsindex c01c6c99..8aac5ec9 100644--- a/packages/dsh-tauri-pet/src/host/service/session-stream.utils.ts+++ b/packages/dsh-tauri-pet/src/host/service/session-stream.utils.ts@@ -163,7 +163,6 @@ function createPetSessionState(id: string, peer: PetSessionPeer): PetSessionStatopenTools: new Map(),reasoningTail: '',assistantText: '',- firstSeqAt: 0,}}diff --git a/packages/dsh-tauri-worktree/package.json b/packages/dsh-tauri-worktree/package.jsonindex b744459f..3fce5865 100644--- a/packages/dsh-tauri-worktree/package.json+++ b/packages/dsh-tauri-worktree/package.json@@ -59,7 +59,6 @@"dsh-tauri": "workspace:*","lodash-es": "catalog:utils","pathe": "catalog:utils",- "simple-git": "catalog:utils","unstorage": "catalog:utils"},"devDependencies": {diff --git a/packages/dsh-tauri-worktree/src/client/service/hydration.ts b/packages/dsh-tauri-worktree/src/client/service/hydration.tsindex c6ed397a..519c9533 100644--- a/packages/dsh-tauri-worktree/src/client/service/hydration.ts+++ b/packages/dsh-tauri-worktree/src/client/service/hydration.ts@@ -266,17 +266,7 @@ export async function calibrateSession(input: {return { kind: 'local' }}-export async function loadJobStatus(input: {- sessionId: string- jobId: string-}): Promise<WorktreeStatus | undefined> {- try {- return await getStatus(input)- }- catch {- return undefined- }-}+export { loadJobStatus } from './worktree'export function planHandoff(input: {state: HydrationStatediff --git a/packages/dsh-tauri-worktree/src/client/service/hydration.types.ts b/packages/dsh-tauri-worktree/src/client/service/hydration.types.tsindex c14011d2..30eb04e1 100644--- a/packages/dsh-tauri-worktree/src/client/service/hydration.types.ts+++ b/packages/dsh-tauri-worktree/src/client/service/hydration.types.ts@@ -1,6 +1,6 @@-export interface SessionListSnapshot {- ids: string[]- current?: string+import type { SessionListSnapshot as SessionSwitchSnapshot } from './session-switch.types'++export interface SessionListSnapshot extends SessionSwitchSnapshot {phase?: 'pending' | 'ready'}diff --git a/packages/dsh-tauri-worktree/src/host/prompts/worktree-context.ts b/packages/dsh-tauri-worktree/src/host/prompts/worktree-context.tsindex 8982e5e8..34252147 100644--- a/packages/dsh-tauri-worktree/src/host/prompts/worktree-context.ts+++ b/packages/dsh-tauri-worktree/src/host/prompts/worktree-context.ts@@ -1,18 +1,4 @@-import { get, isString } from 'lodash-es'-import { WORKTREE_SECTION_ORDER } from '../../shared/constants'-import { ledger } from '../service/ledger'import { worktreeContextText } from '../utils/worktree-facts'+import { promptProvider } from './worktree-section'-export const worktreeContextProvider = {- name: 'plugin:dsh-tauri-worktree:worktree',- order: WORKTREE_SECTION_ORDER,- text(context: any): string {- const sessionId = get(context, 'scope.session.id')- if (!isString(sessionId))- return ''- const binding = ledger.load(sessionId)- if (!binding)- return ''- return worktreeContextText(binding)- },-}+export const worktreeContextProvider = promptProvider('plugin:dsh-tauri-worktree:worktree', worktreeContextText)diff --git a/packages/dsh-tauri-worktree/src/host/prompts/worktree-section.ts b/packages/dsh-tauri-worktree/src/host/prompts/worktree-section.tsindex ba59ccb4..d8adc1b7 100644--- a/packages/dsh-tauri-worktree/src/host/prompts/worktree-section.ts+++ b/packages/dsh-tauri-worktree/src/host/prompts/worktree-section.ts@@ -1,18 +1,23 @@+import type { Binding } from '../types'import { get, isString } from 'lodash-es'import { WORKTREE_SECTION_ORDER } from '../../shared/constants'import { ledger } from '../service/ledger'import { worktreeSectionText } from '../utils/worktree-facts'-export const worktreeSectionProvider = {- name: 'plugin:dsh-tauri-worktree',- order: WORKTREE_SECTION_ORDER,- text(context: any): string {- const sessionId = get(context, 'scope.session.id')- if (!isString(sessionId))- return ''- const binding = ledger.load(sessionId)- if (!binding)- return ''- return worktreeSectionText(binding)- },+export function promptProvider(name: string, build: (binding: Binding) => string): {+ name: string+ order: number+ text: (context: any) => string+} {+ return {+ name,+ order: WORKTREE_SECTION_ORDER,+ text(context: any): string {+ const sessionId = get(context, 'scope.session.id')+ const binding = isString(sessionId) ? ledger.load(sessionId) : null+ return binding ? build(binding) : ''+ },+ }}++export const worktreeSectionProvider = promptProvider('plugin:dsh-tauri-worktree', worktreeSectionText)diff --git a/packages/dsh-tauri-worktree/src/host/routes/bindings/get.ts b/packages/dsh-tauri-worktree/src/host/routes/bindings/get.tsindex 55988931..3fd185fb 100644--- a/packages/dsh-tauri-worktree/src/host/routes/bindings/get.ts+++ b/packages/dsh-tauri-worktree/src/host/routes/bindings/get.ts@@ -4,6 +4,7 @@ import { existsSync } from 'node:fs'import { defineEventHandler } from 'dsh-tauri'import { cleaner } from '../../service/cleaner'import { ledger } from '../../service/ledger'+import { worktreeKey } from '../../utils/paths'export default defineEventHandler<EventHandlerRequest, Promise<WorktreeBindings>>(async () => ({bindings: ledger.list()@@ -13,7 +14,7 @@ export default defineEventHandler<EventHandlerRequest, Promise<WorktreeBindings>sourceSessionId: binding.sourceSessionId ?? '',hash: binding.hash,dirname: binding.dirname,- worktreeKey: `${binding.hash}/${binding.dirname}`,+ worktreeKey: worktreeKey(binding.hash, binding.dirname),worktreePath: binding.worktreePath,projectPath: binding.projectPath,log: Array.isArray(binding.log) ? binding.log : [],diff --git a/packages/dsh-tauri-worktree/src/host/routes/post.ts b/packages/dsh-tauri-worktree/src/host/routes/post.tsindex 04212fcb..d1caf209 100644--- a/packages/dsh-tauri-worktree/src/host/routes/post.ts+++ b/packages/dsh-tauri-worktree/src/host/routes/post.ts@@ -4,6 +4,7 @@ import { defineEventHandler, readBody } from 'dsh-tauri'import { handoff } from '../service/handoff'import { sessionContext } from '../service/session-context'import { worktree } from '../service/worktree'+import { worktreeKey } from '../utils/paths'export default defineEventHandler<EventHandlerRequest, Promise<WorktreeCreate>>(async (event) => {const body = (await readBody<CreateBody>(event)) ?? {}@@ -38,7 +39,7 @@ export default defineEventHandler<EventHandlerRequest, Promise<WorktreeCreate>>(ok: true,hash: binding.hash,dirname: binding.dirname,- worktreeKey: `${binding.hash}/${binding.dirname}`,+ worktreeKey: worktreeKey(binding.hash, binding.dirname),worktreePath: binding.worktreePath,projectPath: binding.projectPath,sourceSessionId: binding.sourceSessionId,diff --git a/packages/dsh-tauri-worktree/src/host/service/cleaner.ts b/packages/dsh-tauri-worktree/src/host/service/cleaner.tsindex 5510d77a..1ca4da0c 100644--- a/packages/dsh-tauri-worktree/src/host/service/cleaner.ts+++ b/packages/dsh-tauri-worktree/src/host/service/cleaner.ts@@ -2,7 +2,7 @@ import type { DiscardJob, OperationResult } from '../types'import { randomUUID } from 'node:crypto'import { clearTimeout, setTimeout } from 'node:timers'import { defineService } from 'dsh-tauri'-import { filter, find, findLast, get, take } from 'lodash-es'+import { find, findLast, get } from 'lodash-es'import { jobs } from './jobs'const DISCARD_JOB_RETENTION = 64@@ -68,7 +68,7 @@ export const cleaner = defineService({unsettled(): DiscardJob[] {restore()- return filter(queueArray(), job => job.state !== 'completed')+ return queueArray().filter(job => job.state !== 'completed')},})@@ -102,8 +102,8 @@ function reuseOf(sessionId: string, worktreeKey: string, force: boolean): Discarfunction prune(): void {if (queue.size < DISCARD_JOB_RETENTION)return- const removable = filter(queueArray(), { state: 'completed' })- take(removable, queue.size - DISCARD_JOB_RETENTION + 1)+ const removable = queueArray().filter(job => job.state === 'completed')+ removable.slice(0, queue.size - DISCARD_JOB_RETENTION + 1).forEach(job => queue.delete(job.jobId))}@@ -123,7 +123,7 @@ function restore(): void {/** 串行落盘,始终写最新快照,避免乱序写回旧状态;写失败留一个补写计时器直到成功。 */function persist(): void {pendingWrite = pendingWrite- .then(() => jobs.save(filter(queueArray(), job => job.state !== 'completed')))+ .then(() => jobs.save(queueArray().filter(job => job.state !== 'completed'))).then(() => clearPersistRetry()).catch(() => schedulePersistRetry())}diff --git a/packages/dsh-tauri-worktree/src/host/service/handoff.test.ts b/packages/dsh-tauri-worktree/src/host/service/handoff.test.tsindex 70f32e45..2d711d90 100644--- a/packages/dsh-tauri-worktree/src/host/service/handoff.test.ts+++ b/packages/dsh-tauri-worktree/src/host/service/handoff.test.ts@@ -159,6 +159,37 @@ describe('handoff.inherit', () => {})describe('handoff.complete', () => {+ it('uses the pending source agent even when it is no longer registered', async () => {+ const followup = vi.fn()+ const create = vi.fn(async (_options: any) => ({ agent: { followup } }))+ const sourceContext = { preset: 'source' }+ const composeFrom = vi.fn()+ const composedPreset = vi.fn(() => 'composed')+ const attachSession = vi.fn(async () => {})+ setCurrentHostInstance({+ agents: { get: () => undefined, create },+ get: () => ({ composedPreset, composeFrom }),+ workspaceRegistry: { resolveByPath: async () => ({ attachSession }) },+ })+ await handoff.complete({+ sourceAgent: { ...(sourceAgent() as object), ctx: sourceContext, options: { model: 'inherited' } },+ targetSessionId: 'session-target',+ binding: { worktreePath: 'C:/worktrees/w1', projectPath: 'C:/project' } as Binding,+ })+ expect(create).toHaveBeenCalledExactlyOnceWith(expect.objectContaining({+ sessionId: 'session-target',+ seed: conversationEvents,+ meta: expect.objectContaining({ cwd: 'C:/worktrees/w1', agentPreset: 'composed' }),+ agentOptions: { model: 'inherited' },+ }))+ expect(composedPreset).toHaveBeenCalledWith(sourceContext)+ const targetContext = { preset: 'target' }+ create.mock.calls[0]![0].setup(targetContext)+ expect(composeFrom).toHaveBeenCalledExactlyOnceWith(targetContext, sourceContext)+ expect(attachSession).toHaveBeenCalledWith('session-target')+ expect(followup).toHaveBeenCalledTimes(1)+ })+it('hands the inherited log to the worktree agent', async () => {const followup = vi.fn()const { created } = setup({ create: async () => ({ agent: { followup } }) })diff --git a/packages/dsh-tauri-worktree/src/host/service/handoff.ts b/packages/dsh-tauri-worktree/src/host/service/handoff.tsindex 38dd8a5e..1a1f5578 100644--- a/packages/dsh-tauri-worktree/src/host/service/handoff.ts+++ b/packages/dsh-tauri-worktree/src/host/service/handoff.ts@@ -75,26 +75,8 @@ export const handoff = defineService({const { sourceAgent, targetSessionId, binding } = pendingconst sourceSession = sourceAgent.sessiontry {- const presets = ctx.get?.('agentPresets')- const parentPreset = presets?.composedPreset(sourceAgent.ctx) ?? sourceSession.header.agentPresetconst seed = sessionEvents(sourceSession)- const handle = await ctx.agents.create({- sessionId: targetSessionId,- seed,- meta: {- cwd: binding.worktreePath,- parentSession: sourceSession.id,- isSeeded: true,- seedLength: seed.length,- ...(parentPreset ? { agentPreset: parentPreset } : {}),- },- inheritedEventCount: seed.length,- agentOptions: sourceAgent.options ?? {},- setup: (agentCtx: any) => {- if (presets && parentPreset)- presets.composeFrom(agentCtx, sourceAgent.ctx)- },- })+ const handle = await createAgent(sourceSession, sourceAgent, targetSessionId, binding.worktreePath, seed)const workspace = await ctx.workspaceRegistry.resolveByPath(binding.projectPath)if (workspace)await workspace.attachSession(targetSessionId)@@ -121,13 +103,7 @@ export const handoff = defineService({// --- internal ----/**- * 继承前缀里是否已有真实的人类消息:区分「换到工作树接着聊」与「换了位置的全新任务」。- *- * 内核只对「无父会话 + 第一条人类消息 + 尚无标题」的全新会话自动生成标题,fork 子会话保留继承标题- * 且永不自动生成。继承前缀里没有人类消息时(工作树模式发送首条消息即此形态),新工作树任务只会拿到- * 首条消息的兜底标题,因此这些会话要在首个请求头落盘时显式补一次模型标题(见 service/title)。- */+/** 内核不给 fork 子会话生成标题,无人类对话的继承前缀需显式登记。 */function hasInheritedConversation(seed: readonly unknown[]): boolean {return seed.some((value) => {const event = value as { type?: unknown, data?: { source?: { kind?: unknown }, content?: unknown } }@@ -162,29 +138,7 @@ async function createInherited(const { cwd, attach = false } = optionsconst targetSessionId = options.targetSessionId ?? `session-${randomUUID()}`try {- const presets = ctx.get?.('agentPresets')- const parentPreset = agent- ? (presets?.composedPreset(agent.ctx) ?? sourceSession.header?.agentPreset)- : sourceSession.header?.agentPreset- const createOptions: any = {- sessionId: targetSessionId,- seed,- meta: {- cwd,- parentSession: options.parentSession ?? sourceSession.id,- isSeeded: true,- seedLength: seed.length,- ...(parentPreset ? { agentPreset: parentPreset } : {}),- },- inheritedEventCount: seed.length,- agentOptions: agent?.options ?? {},- }- if (agent && presets && parentPreset) {- createOptions.setup = (agentCtx: any) => {- presets.composeFrom(agentCtx, agent.ctx)- }- }- await ctx.agents.create(createOptions)+ await createAgent(sourceSession, agent, targetSessionId, cwd, seed, options.parentSession)if (!hasInheritedConversation(seed))pendingWorktreeTitles.add(targetSessionId)if (attach) {@@ -199,7 +153,38 @@ async function createInherited(}}-/** 内核 `Session` 的日志面逐版本漂移:0.1.2-rc.1 起移除 `events` 访问器,以 `snapshotEvents()` 为准,`log` / `events` 仅作兜底。 */+async function createAgent(+ sourceSession: any,+ sourceAgent: any,+ targetSessionId: string,+ cwd: string,+ seed: readonly unknown[],+ parentSession = sourceSession.id,+): Promise<any> {+ const ctx = getCurrentHostInstance()+ const presets = ctx.get?.('agentPresets')+ const parentPreset = sourceAgent+ ? (presets?.composedPreset(sourceAgent.ctx) ?? sourceSession.header?.agentPreset)+ : sourceSession.header?.agentPreset+ return ctx.agents.create({+ sessionId: targetSessionId,+ seed,+ meta: {+ cwd,+ parentSession,+ isSeeded: true,+ seedLength: seed.length,+ ...(parentPreset ? { agentPreset: parentPreset } : {}),+ },+ inheritedEventCount: seed.length,+ agentOptions: sourceAgent?.options ?? {},+ ...(sourceAgent && presets && parentPreset+ ? { setup: (agentCtx: any) => presets.composeFrom(agentCtx, sourceAgent.ctx) }+ : {}),+ })+}++/** 内核 0.1.2-rc.1 移除 events,旧版本以 log/events 兼容。 */function sessionEvents(value: unknown): readonly unknown[] {if (typeof value !== 'object' || value === null)return []diff --git a/packages/dsh-tauri-worktree/src/host/service/jobs.ts b/packages/dsh-tauri-worktree/src/host/service/jobs.tsindex 69d2b18e..a0908a7e 100644--- a/packages/dsh-tauri-worktree/src/host/service/jobs.ts+++ b/packages/dsh-tauri-worktree/src/host/service/jobs.ts@@ -1,7 +1,7 @@import type { DiscardJob } from '../types'import { readFileSync } from 'node:fs'import { defineService, DSH_HOME } from 'dsh-tauri'-import { compact, get, isPlainObject, map } from 'lodash-es'+import { get, isPlainObject } from 'lodash-es'import { join } from 'pathe'import { WORKTREES_DIR } from '../config/constants'import { storage } from '../storage'@@ -35,8 +35,8 @@ export const jobs = defineService({function parseJobs(raw: string): DiscardJob[] {try {const parsed: unknown = JSON.parse(raw)- const list = get(parsed, 'jobs')- return Array.isArray(list) ? compact(map(list, entry => parseJob(entry))) : []+ const list: unknown = get(parsed, 'jobs')+ return Array.isArray(list) ? list.map(parseJob).filter(job => job !== null) : []}catch {return []diff --git a/packages/dsh-tauri-worktree/src/host/service/ledger.ts b/packages/dsh-tauri-worktree/src/host/service/ledger.tsindex 50e6a746..8a8f9bd1 100644--- a/packages/dsh-tauri-worktree/src/host/service/ledger.ts+++ b/packages/dsh-tauri-worktree/src/host/service/ledger.ts@@ -1,7 +1,7 @@import type { Binding } from '../types'import { readdirSync, readFileSync } from 'node:fs'import { defineService, DSH_HOME } from 'dsh-tauri'-import { compact, filter, isPlainObject } from 'lodash-es'+import { isPlainObject } from 'lodash-es'import { join } from 'pathe'import { storage } from '../storage'@@ -22,7 +22,7 @@ export const ledger = defineService({list(): Binding[] {const dir = join(DSH_HOME, LEDGER_DIR)- return compact(readJsonNames(dir).map(name => readBinding(join(dir, name))))+ return readJsonNames(dir).map(name => readBinding(join(dir, name))).filter(binding => binding !== null)},})@@ -34,7 +34,7 @@ function keyOf(sessionId: string): string {function readJsonNames(dir: string): string[] {try {- return filter(readdirSync(dir), name => name.endsWith('.json'))+ return readdirSync(dir).filter(name => name.endsWith('.json'))}catch {return []diff --git a/packages/dsh-tauri-worktree/src/host/service/session-context.ts b/packages/dsh-tauri-worktree/src/host/service/session-context.tsindex 40c0d8de..2f40421d 100644--- a/packages/dsh-tauri-worktree/src/host/service/session-context.ts+++ b/packages/dsh-tauri-worktree/src/host/service/session-context.ts@@ -23,8 +23,6 @@ export const sessionContext = defineService({const cwd = get(session, 'header.cwd') ?? get(session, 'cwd')if (!isString(cwd) || !cwd)return null- if (!cwd)- return nullif (isAbsolute(cwd))return cwdtry {diff --git a/packages/dsh-tauri-worktree/src/host/tools/checkout-worktree.ts b/packages/dsh-tauri-worktree/src/host/tools/checkout-worktree.tsindex fcf0d265..581a6ab4 100644--- a/packages/dsh-tauri-worktree/src/host/tools/checkout-worktree.ts+++ b/packages/dsh-tauri-worktree/src/host/tools/checkout-worktree.ts@@ -1,5 +1,6 @@import { get } from 'lodash-es'import { worktree } from '../service/worktree'+import { textBlock } from './create-worktree'export function checkoutWorktreeTool(): any {return {@@ -64,7 +65,3 @@ export function checkoutWorktreeTool(): any {},}}--function textBlock(text: string): Array<{ type: 'text', text: string }> {- return [{ type: 'text', text }]-}diff --git a/packages/dsh-tauri-worktree/src/host/tools/create-worktree.ts b/packages/dsh-tauri-worktree/src/host/tools/create-worktree.tsindex 633aa80f..950bf41e 100644--- a/packages/dsh-tauri-worktree/src/host/tools/create-worktree.ts+++ b/packages/dsh-tauri-worktree/src/host/tools/create-worktree.ts@@ -86,6 +86,6 @@ export function createWorktreeTool(): any {}}-function textBlock(text: string): Array<{ type: 'text', text: string }> {+export function textBlock(text: string): Array<{ type: 'text', text: string }> {return [{ type: 'text', text }]}diff --git a/packages/dsh-tauri-worktree/src/host/types/index.ts b/packages/dsh-tauri-worktree/src/host/types/index.tsindex 36927a86..d71e57be 100644--- a/packages/dsh-tauri-worktree/src/host/types/index.ts+++ b/packages/dsh-tauri-worktree/src/host/types/index.ts@@ -18,8 +18,6 @@ export interface Binding {linkedDependencies?: string[]}-export type Ledger = Record<string, Binding>-export interface CheckoutContext {projectPath: stringbranch?: string@@ -27,8 +25,6 @@ export interface CheckoutContext {checkedOutAt: string}-export type CheckoutContexts = Record<string, CheckoutContext>-export interface GitOptions {timeout?: numbersignal?: AbortSignaldiff --git a/packages/dsh-tauri-worktree/src/host/utils/git.options.test.ts b/packages/dsh-tauri-worktree/src/host/utils/git.options.test.tsnew file mode 100644index 00000000..9f6265ef--- /dev/null+++ b/packages/dsh-tauri-worktree/src/host/utils/git.options.test.ts@@ -0,0 +1,61 @@+import { EventEmitter } from 'node:events'+import { afterEach, describe, expect, it, vi } from 'vitest'+import { git } from './git'++const { execute } = vi.hoisted(() => ({ execute: vi.fn() }))++vi.mock('node:child_process', async () => {+ const { promisify } = await import('node:util')+ return { execFile: Object.assign(execute, { [promisify.custom]: execute }) }+})++afterEach(() => vi.resetAllMocks())++function completed(stdout: string): void {+ execute.mockImplementation(() => {+ const child = new EventEmitter()+ queueMicrotask(() => child.emit('close'))+ return Object.assign(Promise.resolve({ stdout, stderr: '' }), { child })+ })+}++describe('git execution options', () => {+ it('forwards cwd, abort and timeout without a shell or small output limit', async () => {+ const signal = new AbortController().signal+ completed(' output\n')+ expect(await git(['diff', '--cached', '--binary'], 'repo', { signal, timeout: 123 })).toEqual({ ok: true, out: 'output' })+ expect(execute).toHaveBeenCalledExactlyOnceWith('git', ['diff', '--cached', '--binary'], {+ cwd: 'repo',+ signal,+ timeout: 123,+ windowsHide: true,+ maxBuffer: Infinity,+ encoding: 'utf8',+ })+ })++ it('does not launch a command when its signal is already aborted', async () => {+ const controller = new AbortController()+ controller.abort(new Error('cancelled before dispatch'))+ expect(await git(['checkout', 'main'], 'repo', { signal: controller.signal })).toEqual({ ok: false, error: 'cancelled before dispatch' })+ expect(execute).not.toHaveBeenCalled()+ })++ it.each(['git timed out', 'The operation was aborted'])('waits for child close before reporting %s', async (message) => {+ const child = new EventEmitter()+ const pending = Object.assign(Promise.reject(Object.assign(new Error(message), { killed: true, stderr: '' })), { child })+ execute.mockReturnValue(pending)+ let settled = false+ const result = git(['status'], 'repo', { timeout: 1 }).then((value) => {+ settled = true+ return value+ })+ await pending.catch(() => {})+ await Promise.resolve()+ expect(settled).toBe(false)+ expect(child.listenerCount('close')).toBe(1)+ child.emit('close')+ expect(await result).toEqual({ ok: false, error: message })+ expect(child.listenerCount('close')).toBe(0)+ })+})diff --git a/packages/dsh-tauri-worktree/src/host/utils/git.test.ts b/packages/dsh-tauri-worktree/src/host/utils/git.test.tsnew file mode 100644index 00000000..cccf0aa1--- /dev/null+++ b/packages/dsh-tauri-worktree/src/host/utils/git.test.ts@@ -0,0 +1,58 @@+import { mkdir, mkdtemp, rm } from 'node:fs/promises'+import { tmpdir } from 'node:os'+import { join } from 'pathe'+import { afterEach, describe, expect, it } from 'vitest'+import { git } from './git'++const directories: string[] = []++async function repository(): Promise<string> {+ const cwd = await mkdtemp(join(tmpdir(), 'dsh-worktree-git-'))+ directories.push(cwd)+ expect(await git(['init', '--quiet'], cwd)).toEqual({ ok: true, out: '' })+ return cwd+}++afterEach(async () => {+ await Promise.all(directories.splice(0).map(cwd => rm(cwd, { recursive: true, force: true })))+})++describe('git', () => {+ it('trims stdout without interpreting shell characters in arguments', async () => {+ const cwd = await repository()+ const value = 'literal "quotes" & ; $HOME'+ expect(await git(['config', 'audit.value', value], cwd)).toEqual({ ok: true, out: '' })+ expect(await git(['config', '--get', 'audit.value'], cwd)).toEqual({ ok: true, out: value })+ })++ it('reports a nonzero status even when git writes no stderr', async () => {+ const cwd = await repository()+ const result = await git(['rev-parse', '--verify', '--quiet', 'refs/heads/missing'], cwd)+ expect(result).toEqual({+ ok: false,+ error: 'Command failed: git rev-parse --verify --quiet refs/heads/missing',+ })+ })++ it('returns the git diagnostic for a failed command', async () => {+ const cwd = await repository()+ const result = await git(['rev-parse', '--verify', 'refs/heads/missing'], cwd)+ expect(result).toEqual({ ok: false, error: 'fatal: Needed a single revision' })+ })++ it('returns failure when an abort signal is already aborted', async () => {+ const cwd = await repository()+ const controller = new AbortController()+ controller.abort()+ expect(await git(['status', '--porcelain'], cwd, { signal: controller.signal })).toMatchObject({ ok: false })+ })++ it('rejects a nonexistent cwd as an operation failure', async () => {+ const cwd = await repository()+ const missing = join(cwd, 'missing')+ const result = await git(['status'], missing)+ expect(result.ok).toBe(false)+ await mkdir(missing)+ expect((await git(['rev-parse', '--is-inside-work-tree'], missing)).ok).toBe(true)+ })+})diff --git a/packages/dsh-tauri-worktree/src/host/utils/git.ts b/packages/dsh-tauri-worktree/src/host/utils/git.tsindex a5228e34..24447de7 100644--- a/packages/dsh-tauri-worktree/src/host/utils/git.ts+++ b/packages/dsh-tauri-worktree/src/host/utils/git.ts@@ -1,24 +1,32 @@import type { GitOptions, OperationResult } from '../types'+import { execFile } from 'node:child_process'import { mkdtemp, rm, writeFile } from 'node:fs/promises'import { tmpdir } from 'node:os'+import { promisify } from 'node:util'import { compact, get, partition } from 'lodash-es'import { basename, join, resolve } from 'pathe'-import { simpleGit } from 'simple-git'-/**- * simple-git 只在命令写了 stderr 时抛错:静默失败(如 `--quiet`)会以 `ok: true` + 空输出返回。- * 判断「存在 / 不存在」必须看输出,或者去掉 `--quiet` 让 git 自己报错。- */+const execute = promisify(execFile)+export async function git(args: string[], cwd: string, options: GitOptions = {}): Promise<OperationResult<{ out: string }>> {try {- const client = simpleGit({- baseDir: cwd,- abort: options.signal,- ...(options.timeout === undefined ? {} : { timeout: { block: options.timeout } }),- spawnOptions: { windowsHide: true } as unknown as { uid?: number, gid?: number },- trimmed: true,+ options.signal?.throwIfAborted()+ const pending = execute('git', args, {+ cwd,+ signal: options.signal,+ timeout: options.timeout,+ windowsHide: true,+ maxBuffer: Infinity,+ encoding: 'utf8',})- return { ok: true, out: await client.raw(args) }+ const closed = new Promise<void>(resolve => pending.child.once('close', () => resolve()))+ try {+ const { stdout } = await pending+ return { ok: true, out: stdout.trim() }+ }+ finally {+ await closed+ }}catch (error) {return { ok: false, error: errorMessage(error) }@@ -93,7 +101,7 @@ export async function headSubject(worktreePath: string): Promise<string> {// --- internal ---function errorMessage(error: unknown): string {- return String(get(error, 'stderr') ?? get(error, 'message') ?? error).trim()+ return String(get(error, 'stderr') || get(error, 'message') || error).trim()}async function applyPatchArchive(cwd: string, patch: string, options: GitOptions = {}): Promise<OperationResult<{ out: string }>> {diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 6fe44a2e..3fc60334 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -302,9 +302,6 @@ catalogs:schemastery:specifier: ^3.18.0version: 3.18.0- simple-git:- specifier: ^3.36.0- version: 3.36.0smol-toml:specifier: ^1.3.1version: 1.8.0@@ -634,16 +631,10 @@ importers:hookable:specifier: catalog:utilsversion: 6.1.1- lodash-es:- specifier: catalog:utils- version: 4.18.1pathe:specifier: catalog:utilsversion: 2.0.3devDependencies:- '@types/lodash-es':- specifier: catalog:types- version: 4.17.12dsh-tauri-tsdown:specifier: workspace:*version: link:../dsh-tauri-tsdown@@ -1082,9 +1073,6 @@ importers:pathe:specifier: catalog:utilsversion: 2.0.3- simple-git:- specifier: catalog:utils- version: 3.36.0unstorage:specifier: catalog:utilsversion: 1.17.5([email protected])diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yamlindex 4be5d310..fe28aeb2 100644--- a/pnpm-workspace.yaml+++ b/pnpm-workspace.yaml@@ -213,7 +213,6 @@ catalogs:ofetch: ^1.5.1pathe: ^2.0.3schemastery: ^3.18.0- simple-git: ^3.36.0smol-toml: ^1.3.1ssh2: ^1.17.0unstorage: ^1.17.5