DeepSeek Harness Tauri 桌面版 | Only 8mb installer, zero environment setup, preset plugins, Windows / macOS / Linux.
docs(agents): condense the desktop development guide
hairyf0fda7fc7128e
diff --git a/docs/AGENTS.desktop.md b/docs/AGENTS.desktop.mdindex 135340e4..06aa05f3 100644--- a/docs/AGENTS.desktop.md+++ b/docs/AGENTS.desktop.md@@ -1,380 +1,194 @@-# Development Specification Document+# DeepSeek Harness Desktop 开发规范文档-DeepSeek Harness desktop (Tauri 2 + React 19), embeds the Harness UI served at `http://127.0.0.1:3080`.+> **架构概览**:基于 Tauri 2 + React 19,内嵌服务运行于 `[http://127.0.0.1:3080](http://127.0.0.1:3080)` (Debug 环境默认 `3081`)。-- **端口隔离**:release 默认 `3080`,debug(`pnpm tauri dev` / `cargo build`)默认 `3081`,由 `config::setting::default_port()` 用 `cfg!(debug_assertions)` 区分,避免开发时与已运行的桌面端争用端口。-- **数据隔离(核心共用、数据不共用)**:node/`dependencies/dsh`/`dependencies/pnpm` 为共用核心(AppData);debug 构建的 `$DSH_HOME` 默认为 `~/.dsh.dev`(`config::runtime::get_dsh_data_path` 用 `cfg!(debug_assertions)` 区分)且 store 用独立文件 `.store.dev.dat`(`config::setting::store_dat_file_name`),避免开发版与生产版会话/档案/端口状态互相污染,也防止 dev 版热重启把 release 的服务进程杀掉(`service/workflow::terminate_stale_harness_processes` 在 debug 下为 no-op,改由 `.dsh.dev/.harness.pid` 精确回收)。debug 构建不迁移旧数据(`service/migrate`)、不注册/注销 PATH、不写烘焙 DSH_HOME 的 `dsh` shim(`service/cli`)。-- **Windows 极简模式**:预装插件流程(`service/plugin`)对 Windows 用户列出「修复」项(`dsh-win-terminal-inspector`,黄色 chip 默认勾选),确认后 `dsh plugin add github:clearkurt/dsh-win-terminal-inspector` 从 GitHub 安装(桌面端**不内置**插件源码);随后 `service/workflow/win_inspector.rs`(仅 Windows,幂等)写入 profile `cordis.patch.yml` 挂载行并创作 `$DSH_HOME/.agent-presets/minimal-win/` 用户 preset(Git Bash + danger-full-access,因为 agent preset 组成不受 profile patch 管辖)。-- **内置插件 host 依赖边界**:`packages/*/src/host/` 运行在独立的 `resources/node_modules` 中,禁止直接静态引用任何 `@deepseek-ai/*` 运行时包(包括 `import`、`export ... from` 和 `require`);必须通过宿主上下文的 `loader.import()` 解析 DSH-owned 模块,并按需处理 `loader.unwrapExports()` 的导出形状。`@deepseek-ai/*` 仅可作为 host 的 type-only import,不能产生运行时依赖。-- **桌宠(`src/pet` + `dsh-tauri-pet`)**:渲染整体交给 `dsh-pet-component` 的 `<Pet>`(外部 npm 包,内部用 `@reause/core`),本仓库只保留设置状态(`src/pet/hooks`)、会话气泡聚合、原生窗口拖拽(`src/hooks/use-window-draggable`)与命中穿透(`src/hooks/use-omit-ignore-cursor-events`),提示 UI 为 `src/ui/pet/hint.tsx` 的 `<Hint>`。预设宠物**不下载不安装**——`src-tauri/resources/preset-pets.json` 只登记远端素材地址与渲染参数(`config` / `uri` / `ext` / `kind` / `size`),pet 窗口直连远端播放并落 IndexedDB 缓存;`src/pet/main.tsx` 把全局 `fetch` 换成 `@tauri-apps/plugin-http` 的实现(其余命令与媒体元素不变),绕开 githubusercontent 的 CORS。macOS 用清单里 `uri.mac` / `ext.mac` 的 HEVC-alpha `.mov`(WKWebView 不认 VP9-alpha)。+----- Prioritize using customized components from src/components, hero-ui.-- This will help minimize the need for writing custom classes.-- If you write new content, you need to handle i18n en keys-- i18n keys must be flat (no nesting), use dot-notation flat keys only-- No hardcoded strings; sync i18n locale files (`src/i18n/locales/en-US.json` / `zh-CN.json`)-- If the component you write/modify is too complex, you need to split it into multiple components-- Repeated logic should be encapsulated into methods/components--## Tech Stack--- **Frontend**: React 19 + TS + Tailwind 4 (no plain CSS), Vite (`src/`)-- **Backend**: Rust / Tauri 2 (`src-tauri/src/`)- - `bridge/cmd.rs`: Tauri commands (register in `lib.rs` `generate_handler!`)- - `config/`: constants, paths (`runtime.rs`), settings (`setting.rs`), i18n & theme- - `service/download/`: Node/Dsh/pnpm download & extract (`Installable` trait)- - `service/workflow/`: process lifecycle (Windows no-window: `win_spawn.rs`)- - `service/cli/`: `dsh`/`pnpm` shims + PATH registration (`mod.rs`/`shim.rs`/`path.rs`/`core.rs`)- - `service/scheduler/` + `task/`: health check & polling--## Dev Commands+## 1. 技术栈与常用命令 (Tech Stack & Commands)+* **前端**:React 19, TypeScript, Tailwind CSS v4, Vite (`src/`)+* **后端**:Rust, Tauri v2 (`src-tauri/`)+* **开发命令**:```bash-pnpm install && pnpm dev # frontend dev-pnpm typecheck # frontend TS check (must run after frontend changes)-pnpm tauri dev # full desktop debug-cargo check && cargo test # Rust check & unit tests (run in src-tauri)+pnpm install && pnpm dev # 前端开发+pnpm typecheck # 前端 TS 类型检查 (改动前端后必跑)+pnpm tauri dev # 桌面端完整 Debug 模式+cargo check && cargo test # Rust 检查与单元测试 (src-tauri 目录下)+```-## Basics+----- No `useCallback` / `useMemo` — `react-compiler` 已通过 Vite 接入(`babel-plugin-react-compiler`,target 19)用于自动记忆化;-- Component functions use `function` declaration; inline events/callbacks use arrow functions+## 2. 核心架构设计原则 (Architecture Principles)-## Hooks Specification (reause)+* **端口与数据隔离**:+* **端口**:Release 默认 `3080`;Debug 默认 `3081`(通过 `cfg!(debug_assertions)` 隔离,防止端口争用)。+* **数据**:Debug 环境数据目录为 `~/.dsh.dev`,Store 文件为 `.store.dev.dat`。Debug 下 `terminate_stale_harness_processes` 为 no-op,改用 `.dsh.dev/.harness.pid` 精确回收进程,且不执行旧数据迁移与 PATH 注册。-壳层的副作用一律交给 [`@reause/core`](https://github.com/hairyf/reause)(VueUse 的 React 1:1 移植)。-`react-use` 与 `@hairy/react-lib` 已从依赖中移除,**不要再引入**;新增依赖前先查-`.agents/skills/reause-functions` 的函数表,能在 reause 里找到的不要自己写。+* **内置插件宿主依赖边界**:+* `packages/*/src/host/` 运行于独立的 `resources/node_modules`。+* **禁止**静态引用任何 `@deepseek-ai/*` 运行时包(如 `import`/`require`),仅允许 `type-only import`。+* 必须通过宿主上下文 `loader.import()` 解析模块,并按需使用 `loader.unwrapExports()`。-| 需求 | 用 | 不用 |-| --- | --- | --- |-| 观察值变化后执行 | `useWatch` / `useWhenever`(真值触发一次) | `useEffect(deps)` |-| 仅挂载后执行一次 | `useMount` | `useEffect(…, [])` |-| 卸载时才需要清理 | `useEffect`(返回 cleanup),最后手段 | — |-| Tauri 事件订阅 | `useListen`(`src/hooks/use-listen.ts` = `listen` + 卸载注销 + 竞态防护) | `useEffect` + `listen` |-| DOM 事件 | `useEventListener`(缺省 window,可传 ref/目标) | `addEventListener` |-| 定时轮询 / 延时 | `useIntervalFn` / `useTimeoutFn` | `setInterval` / `setTimeout` |-| 延时 Promise | `promiseTimeout` | `new Promise(r => setTimeout(r, ms))` |-| 系统深浅色 | `usePreferredDark` / `useMediaQuery` | `matchMedia` + 手写监听 |-| 元素溢出判定 | `useElementOverflow` | 手写观测 / `scrollHeight` 比较 |-| 布尔开关 | `useToggle` | `useState(false)` + 手写 toggle |-| 跨组件瞬时事件 | `createEventHook` + `useListener`(键集中在 `src/config/hooks.ts` 的 `hooks`) | 全局 emitter / EventBus key |-| 查询「后端设置变更即失效」 | `useInvalidateOnSettingUpdated(queryKey)` | 各处手写 `useListen('setting_updated', …)` |-| iframe 消息桥(双向) | `useIframePost`(宿主 → iframe:origin 定向 + `source: 'dsh-desktop'`)/ `useIframeMessage`(iframe → 宿主:直接 iframe + origin 校验,按 `type` 分发)/ `useInvokeIframe`(iframe → 宿主 → `invoke`,带命令白名单) | 手写 `postMessage` 与来源校验;逐个桥比对 `data.source` |--- **`useEffect` 是最后手段**:只有「必须注册并注销一个外部资源,且 reause 没有对应 hook」时才写- (例:Tauri 窗口 `onResized` / `onMoved`、需要取消的在途任务);能拆成- `useMount` / `useListen` / `useWatch` 的一律拆开。-- 副作用回调里不要自己维护 `disposed` 竞态标志:`useListen` 已处理注册竞态,- 而 `setState` 在已卸载组件上是 no-op。-- 同一模块的 TypeScript 类型与运行时值一起导入用 `import { type X, y } from '…'`,避免重复 import 语句。--## 目录与组件规划(参考 damn-reports)+* **Windows 极简模式**:+* 修复项 `dsh-win-terminal-inspector` 确认后从 GitHub 动态安装(桌面端不内置源码)。+* 自动挂载 `cordis.patch.yml` 并生成 `$DSH_HOME/.agent-presets/minimal-win/` 预设。-```-src/-├── components/ # 通用件:无业务依赖、可跨面板复用的基础 UI-│ ├── ellipsis.tsx empty.tsx item.tsx info.tsx logs.tsx logs.utils.ts-│ ├── modal.tsx # overlastic 确认弹窗的通用载体-│ ├── panel.tsx # 面板三件套:Panel.Header / Panel.Loadable / Panel.Progress-│ ├── primitives.ts # tv 变体-│ └── toast-provider.tsx-├── config/ # 应用级配置(client / storage / hooks 事件总线 / query-keys 查询键)-├── ui/ # 业务件:按领域分目录,一个文件一个组件-│ ├── config/ # 设置面板:backup / core / debug / plugin / profile(components/ 为面板子件:close-action / launch-on-login)-│ ├── dialog/ # 命令式弹窗:config / about / update / update-core-│ ├── pet/ # 桌宠窗口界面:hint-│ └── plugin/ # 插件界面:recovery-├── hooks/ # 可复用 hook(use-iframe-post / use-iframe-message / use-invoke-iframe / use-listen / use-window-draggable …)-│ # use-zoom-factor:reause Electron 同名 hook 的 Tauri 移植,壳层用它把 store 里的缩放真值应用到 WebView;use-zoom-level 同源但未接线-├── layout/ # 壳层结构(index.tsx 根副作用 + components/:webview 选态、iframe 桥、navbar、setup*)-├── pet/ # 桌宠窗口(独立入口 pet.html;hooks/ 为桌宠专属 hook,utils/ 为纯逻辑如 bubble / bubble-tracker)-├── store/modules/<name>/ # valtio store 模块(harness 内聚 readiness / runtime / utils)-├── styles/ # 全局样式(main.css + components/)-├── types/ # 后端契约类型(Rust 序列化形态):core / plugin / profile / theme,barrel 导出-└── utils/ # 纯函数与跨模块单例(toast / clipboard / zoom / logger …)-```+* **桌宠模块 (`src/pet` + `dsh-tauri-pet`)**:+* 预设宠物**不下载不安装**,由 `preset-pets.json` 登记远端 URL 并直连播放,落 IndexedDB 缓存。+* `src/pet/main.tsx` 使用 `@tauri-apps/plugin-http` 的 `fetch` 实现绕过 CORS。+* macOS 自动使用 `.mov` (HEVC-alpha) 格式。-- **命名**:文件名 kebab-case;组件用 `function` 声明、`PascalCase` 导出;props 类型 `<组件名>Props` 就近导出。-- **放哪里**:只依赖 HeroUI / reause / 纯工具 → `components/`;依赖 store、Tauri 命令或某个业务领域 → `ui/<领域>/`;只被某个 store 模块使用的纯函数 → 该模块目录内(如 `store/modules/harness/readiness.ts`)。-- **弹窗**:命令式弹窗(overlastic `useOverlay`)统一放 `ui/dialog/`;`components/modal.tsx` 只保留通用确认载体。-- **面板子件**:只被某个面板消费的子区块放同领域目录的 `components/`(如 debug 面板里的 `ui/config/components/close-action.tsx` / `launch-on-login.tsx`),面板文件只保留主结构。-- **根副作用**:壳层只在 `layout/index.tsx` 挂「启动 + 轮询 + 事件订阅 + holder」这类一次性副作用,不再为单个副作用另建组件文件。-- **iframe 桥**:出/入站只经 `useIframePost` / `useIframeMessage`;iframe 元素、iframe 自身的桥(通知 / 插件异常 / 剪贴板图片 / boot / 可见性 / 缩放 / invoke 转发)内联在 `layout/components/iframe.tsx` 的 `<Iframe>` 组件里(同一个 `switch (type)`),导航桥(侧边栏折叠与切换)留在 `layout/components/webview.tsx` 用同一对 hook 收发,其 iframe 侧实现收敛在 dsh-tauri 插件的 `client/register/sidebar.ts`(`ctx.layout.toggleSidebar` + 折叠状态回报),缩放快捷键同理在 `register/zoom-shortcut.ts`;Rust 侧只注入无法在插件期实现的桥(通知 API 垫片 / 剪贴板图片回退 / boot 探测 / WebKit 兼容;iframe 全局样式由 dsh-tauri-ui 的 `client/styles/global.cssr.ts` 挂载);宿主侧不比对 `data.source`,也不为每个桥建 hook。-- **缩放真值**:`store.setting.zoom_factor` 是唯一真值(persist 插件写入的 `setting` 键与 Rust 共用同一份 `.store.dat`,Rust 在下一个窗口创建时按同一归一化规则应用);快捷键与缩放桥只改真值,落到 WebView 由 `useZoomFactor` 完成;平台能力判定(macOS 10.15 没有 `WKWebView.pageZoom`)在 hook 内用 `@tauri-apps/plugin-os` 的 `type()` / `version()` 完成。-- **拆分**:列表行 / 卡片行等重复 JSX 抽成独立行组件并复用(`components/item.tsx`);单文件过大时按「卡片 / 行 / 表单」拆成同目录下的兄弟文件。+----## Function Declaration Specification+## 3. 前端编码规范 (Frontend Specifications)-- **Named functions must use `function` declaration, not arrow functions**-- **Arrow functions can only be used when passed as callback parameters**+### 3.1 编码基础与函数声明 (Basics & Function Syntax)+* **组件与函数声明**:命名函数必须使用 `function` 关键字,箭头函数仅用于回调参数。```tsx-// ✅ Correct-function Component() {- function handleClick() {- console.log('click');- }- return <button onClick={handleClick}>Click</button>;+// ✅ 正确+function UserProfile() {+ function handleSave() { /* ... */ }+ return <button onClick={handleSave}>Save</button>;}-// ✅ Correct: Arrow functions can be used for callbacks-useQuery({- queryFn: async () => {- return fetchData();- },-});-```--## Data Processing Specification--### Use directly in pages--**Use case:** When data doesn't need additional processing after fetching+// ✅ 正确:回调中使用箭头函数+useQuery({ queryFn: async () => fetchData() });-```tsx-function MyPage() {- const { data } = useQuery({- queryKey: queryKeys.simpleData, // 查询键统一登记在 src/config/query-keys.ts- queryFn: () => fetchData(),- });-}```-### Create files in services directory--**Use case:** Backend type error handling, parameter processing, composite requests, polling, data caching, etc.--**File naming:** `use-get-{resource}.ts`, `use-post-{resource}.ts`, `use-put-{resource}.ts`, `use-delete-{resource}.ts`--```tsx-// services/use-get-exchange-rates.ts-export function useGetExchangeRates(params) {- return useQuery({- queryKey: [getApiExchangeRatesCurrencyPair.name, params],- queryFn: () => getApiExchangeRatesCurrencyPair(params).then(res => res.data?.data),- });-}-```+* **自动记忆化**:已接入 `react-compiler`(target 19),**禁止使用** `useCallback` / `useMemo`。+* **UI 组件优先**:优先使用 `src/components` 和 HeroUI 组件,减少自定义 CSS 类。+* **i18n 规范**:禁止硬编码字符串。key 必须拍平(扁平点号命名,如 `setting.title`),同步维护 `src/i18n/locales/en-US.json` 与 `zh-CN.json`。-### 面板自己持有查询与变更(`use-dsh-*` 系列的落地方式)+### 3.2 Hooks 使用指南 (`@reause/core`)-- **`use-dsh-*` 系列已全部内联**:只被一个消费者用到的 DSH 查询/变更(含失效、事件同步)- 直接内联在该消费者里——「核心」`ui/config/core.tsx`、「档案」`ui/config/profile.tsx`、- 「插件」`ui/config/plugin.tsx`、外壳主题与插件列表同步 `layout/index.tsx`;不再为单一- 消费者新建包装 hook,后端契约类型统一从 `src/types` 取。-- **查询键集中在 `src/config/query-keys.ts`**:查询键是「谁在读同一份缓存」的契约(面板查询、store 重启- 失效、后端事件写入缓存都按同一份字面量),不要在业务文件里散落 `queryKey: ['plugins']` 这类字面量。-- **跨消费者的缓存由一处维护**:多个组件读同一份数据时,只有「写缓存」的逻辑收敛到一处- (例:`layout/index.tsx` 订阅 `dsh-plugins-updated` 写入 `queryKeys.plugins`,插件面板 / 配置对话框- 异常角标 / 导航栏的 dsh-tauri 检测都只消费同一份缓存)。+壳层副作用**统一使用 `@reause/core**`。已移除 `react-use` 与 `@hairy/react-lib`,禁止引入。-## 类型放置+> ⚠️ **`useEffect` 是最后手段**:仅在“必须注册/注销 reause 未涵盖的外部资源”时使用。-- Rust 侧结构体的序列化形态(camelCase 契约)统一放 `src/types/<领域>.ts`,经 `src/types/index.ts`- 以 `import type { HarnessCore } from '@/types'` 引用;组件 props 等纯前端类型仍就近定义在组件文件里。+| 场景 | 推荐 API | 禁用方式 |+| --- | --- | --- |+| 观察值变化 | `useWatch` / `useWhenever` | `useEffect(deps)` |+| 仅 Mount 时执行 | `useMount` | `useEffect(..., [])` |+| Tauri 事件订阅 | `useListen` (含自动注销/防竞态) | `useEffect` + `listen` |+| DOM 事件 | `useEventListener` | `addEventListener` |+| 定时轮询 / 延时 | `useIntervalFn` / `useTimeoutFn` | `setInterval` / `setTimeout` |+| 异步延时 | `promiseTimeout` | `new Promise(r => setTimeout(r, ms))` |+| 深色模式判定 | `usePreferredDark` / `useMediaQuery` | `matchMedia` 手写监听 |+| 开关状态 | `useToggle` | `useState(false)` 手写逻辑 |+| 跨组件事件 | `createEventHook` + `useListener` | 全局 EventBus |+| 设置变更失效查询 | `useInvalidateOnSettingUpdated(key)` | 手写监听 `setting_updated` |+| iframe 消息通信 | `useIframePost` / `useIframeMessage` | 手写 `postMessage` |-## Conditional Rendering Specification+### 3.3 条件渲染规范 (Conditional Rendering)-Use `If`, `Then`, `Else` components by `react-if-lite` package instead of ternary operators and `&&` operators+禁止使用三元运算符与 `&&`,统一使用 `react-if-lite` 包中的 `<If>`、`<Then>`、`<Else>`。```tsx-// Basic usage<If cond={!isLoading} else={<LoadingSpinner />}><Content /></If>-// Simple condition: use props-<If cond={isBasic} then={<GrayZuanIcon />} else={<ZuanIcon />} />--// Complex condition: use child components<If cond={hasData}>- <Then>- <DataTable data={data} />- </Then>- <Else>- <Empty />- </Else>+ <Then><DataTable data={data} /></Then>+ <Else><Empty /></Else></If>-// Specify render tag-<If cond={condition} as="div">- {content}-</If>```-## State Management Specification+### 3.4 样式与 Variant 设计 (`tv`)-### store 模块组织(参考 damn-reports)+变体多或包含多 Slot 的组件统一使用 `tailwind-variants (tv)`,并使用主题 Token。-`src/store/modules/<name>/` 是一个自洽模块,`index.ts` 是该模块**唯一**的公共出口-(barrel):外部只从这里导入 store、类型与需要外用的工具函数,不深入模块内部文件。+```tsx+export const cardStyle = tv({+ slots: { base: 'relative p-4', icon: 'size-6 rounded-full' },+ variants: {+ intent: {+ success: { icon: 'bg-success-100 text-success' },+ warning: { icon: 'bg-warning-100 text-warning' },+ },+ },+ defaultVariants: { intent: 'success' },+});```-src/store/-├── index.ts # 聚合出口:export const store = { ... }-└── modules/<name>/- ├── index.ts # barrel:export { x } from './store' / export type ... / utils- ├── store.ts # defineStore({ state, getters, actions })- ├── types.ts # 类型 + 对外常量- ├── utils.ts # 与 store 实例无关的纯函数(工厂、格式化、探测)- └── constants.ts # 时序/阈值常量(可选)-```-- 小模块(如 `setting`)可以只有一个 `index.ts`,不必强行拆分;-- 派生状态写 `getters`(复杂 getter 必须显式标注返回类型),不要在组件里重复计算;-- store↔store 协作走兄弟模块的 `index.ts`(如 `harness.launchAndWait()`),不直接引用对方的 `store.ts`;-- 模块级副作用(事件监听、初始 sync)放在 store 文件底部;组件一律 `import { store } from '@/store'`。+---++## 4. 状态与数据流控制 (State & Data Management)++### 4.1 Store 组织规范 (`src/store/modules/<name>/`)++使用 `valtio-define`,按模块封装,`index.ts` 作为**唯一**暴露出口。`defineScope` / `useScope` 已废弃。++```+src/store/modules/user/+├── index.ts # 唯一出口 (barrel):export { user } from './store'; export type ...+├── store.ts # defineStore({ state, getters, actions })+├── types.ts # 模块类型定义+└── utils.ts # 纯逻辑工具函数-```tsx-// store/modules/user/index.ts-export { user } from './store'-export type { User } from './types'--// store/modules/user/store.ts-export const user = defineStore({- state: () => ({ user: null as User | null }),- getters: { hasUser(): boolean { return this.user !== null } },- actions: { async fetchUser() { ... } },-})--// Usage-import { store } from '@/store'-const { user, hasUser } = useStore(store.user)```-## Figma → Code+* 复杂派生状态写在 `getters` 中(需显式声明返回值类型)。+* Store 间的协作只能通过对方的 `index.ts` 调用,禁止越级引用 `store.ts`。-1. **Use theme tokens, not hardcoded colors** — `text-warning` over `text-[#7A5E38]`-2. **Component rules serve the design** — override styles when defaults don't match-3. **Structure is style** — map Figma frames directly to component tree, translate gap/padding directly-4. **Use component APIs** — express states via `value`, `size`, `variant` props instead of hand-writing styles+### 4.2 数据请求与查询 (`TanStack Query`)-## tv Usage+* 查询键 (Query Keys) **必须**集中注册在 `src/config/query-keys.ts` 中。+* 单一消费者查询内联在组件中;跨组件共享数据由 `layout/index.tsx` 或指定管理者统一更新缓存。+* 复杂服务封装文件置于 `services/` 目录,命名遵循 `use-get-{resource}.ts` 规范。-Use `tv` when a component has multiple style variants/slots.+### 4.3 弹窗规范 (`@overlastic/react`)-- `slots` defines all style areas; `variants` only writes changing styles-- Derive variant types via `VariantProps<typeof tvConfig>['variant']`+命令式弹窗统一放在 `src/ui/dialog/`,业务组件结合 `useDisclosure` 实现:```tsx-export const dialog = tv({- slots: {- base: 'relative',- icon: 'size-14 items-center justify-center rounded-full',- iconContent: 'size-[22px]',- },- variants: {- variant: {- success: { icon: 'bg-[#E7EFE3]' },- warning: { icon: 'bg-[#F5EAD3]' },- },- },- defaultVariants: { variant: 'default' },-})-// Use: const { icon } = dialog({ variant })-```+import { useDisclosure, type PropsWithOverlays } from '@overlastic/react';-## Overlastic Dialog Pattern (`@overlastic/react`)+export interface ConfirmDialogProps extends PropsWithOverlays<{ title: string }, boolean> {}-**Use case:** Imperative dialog (confirm, PIN, KYC).+function ConfirmDialog(props: ConfirmDialogProps) {+ const disclosure = useDisclosure({ props, delay: 300 });+ return (+ <Modal isOpen={disclosure.visible} onClose={() => disclosure.cancel()}>+ <Button onPress={() => disclosure.confirm(true)}>Confirm</Button>+ </Modal>+ );+}-```-Hook → useOverlay(Component) returns an async opener function-_layout.tsx → mount OverlaysProvider at root-Component → render actual UI with useDisclosure```-```tsx-// usage — resolves with the confirm value-const { foo } = useOverlay(FooComponent)-const result = await foo(options)-```+----```tsx-// _layout.tsx — mount once at root-<OverlaysProvider>- <App />-</OverlaysProvider>+## 5. 后端与 Rust 规范 (Backend Rules)-// components/foo.tsx — render actual UI-import type { PropsWithOverlays } from '@overlastic/react'-import { useDisclosure } from '@overlastic/react'+1. **注释要求**:仅使用中文注释。模块头用 `//!`,函数说明用 `///`(侧重阐述原因)。+2. **错误处理**:`Result<_, String>` 的错误信息必须包含大写前缀(如 `NODE_NOT_FOUND: ...`)。+3. **Windows 适配**:+* 子进程启动必须使用 `CREATE_NO_WINDOW (0x08000000)`。+* 停止服务时使用 `taskkill /T /F` 杀掉进程树,防止 DLL 锁死。+* 更新 PATH 后需广播 `WM_SETTINGCHANGE`。-export interface FooProps extends PropsWithOverlays, FooOptions { ... }-export function FooComponent(props: FooProps) {- const disclosure = useDisclosure({ props, delay: 300 })- return (- <BottomSheet isOpen={disclosure.visible} onOpenChange={() => disclosure.cancel()}>- {/* ... */}- <Button onPress={() => disclosure.confirm(value)} />- </BottomSheet>- )-}-```+4. **CLI Shim (`service/cli`)**:+* 脚本存放路径:Win `%LOCALAPPDATA%\deepseek-harness\bin`,Unix `~/.local/bin`。+* 优先使用本地 Node (v22.19+ / v24+,不支持 v23),回退到捆绑 Node。+* Shim 文本**必须全英文**,避免编码页乱码。++++---++## 6. 关键踩坑与修复避坑指南 (Pitfalls & Fixes)-- Props are flat options; `PropsWithOverlays<Payload, Result>` types the payload and the promise result-- `disclosure.confirm(value?)` resolves the opener's promise, `disclosure.cancel()` closes without a result-- Component props/result types live in the component file, the hook imports them from there--## Backend Rules (Rust / Tauri)--1. **Comments**: Chinese only; `//!` for module headers, `///` for functions (focus on "why").-2. **Errors/Logs**: `Result<_, String>` errors need an uppercase prefix (e.g. `NODE_NOT_FOUND: ...`); log key paths.-3. **Settings**: new `Setting` fields need `#[serde(default...)]` and export in `config/mod.rs`.-4. **Windows**:- - Spawn children with `CREATE_NO_WINDOW (0x08000000)`.- - Kill the process tree when stopping services (`taskkill /T /F`) to avoid DLL lock on update.- - Broadcast `WM_SETTINGCHANGE` after writing PATH; tell users to reopen terminals.-5. **CLI shim (`service/cli`)**:- - Scripts at Win `%LOCALAPPDATA%\deepseek-harness\bin`, Unix `~/.local/bin`.- - Prefer local Node (v22.19+ / v24+; v23 unsupported), fallback to bundled Node; mind escaping (`%`→`%%`, `'`→`'\''`).- - Shim text must be English-only (cmd/ps1 parse by code page, Chinese breaks).- - pnpm shim: forward user-installed pnpm first, else bundled node `dependencies/pnpm/bin/pnpm.cjs`.- - Install skips when bundled installed **or** user pnpm on PATH (`Pnpm::check_installed`).-6. **Cross-platform/Tests**: Unix-only code gets `#[cfg_attr(windows, allow(dead_code))]`; unit tests in `#[cfg(test)] mod tests`, skip gracefully when restricted.-7. **Deps/Docs**: no heavy deps, prefer existing `windows-sys`; README minimal, en/zh synced.--## Pitfalls--- `dsh` CLI is a Node script (`dependencies/dsh/node_modules/@deepseek-ai/dsh/lib/bin.js`); CLI integration is **shim + PATH**. pnpm is also JS (`dependencies/pnpm/bin/pnpm.cjs`, npm tarball).-- AppData layout(核心共用):`runtime/node.exe`、`dependencies/dsh/`、`dependencies/pnpm/`、`.store.dat` / `.store.dev.dat`(后者为 debug);服务日志 `logs/dsh-web.log`(debug 为 `logs/dsh-web.dev.log`);`$DSH_HOME` 在用户主目录(release `~/.dsh`,debug `~/.dsh.dev`)。-- Service args: `node bin.js --profile web --host 127.0.0.1 --port <setting.port>`; `cli::ensure` runs after install.-- 原生模块 ABI(issue #441):预打包核心的原生模块(`fs-ext` 等 node-gyp 包)在 pkg 构建期编译,ABI 只与构建期 Node 大版本一致,而本地 Node 只按 semver 挑选。`service/core/runtime.rs::prepare_active_runtime` 在 spawn 前用 `NATIVE_PROBE_SCRIPT` 探测(require 核心里的原生包,`NODE_MODULE_VERSION` 不匹配即 ABI 失败):先补 sharp/koffi 平台包,再改用与核心对齐的捆绑运行时(`config::set_prefer_bundled_node_runtime`,`get_node_binary_path`/`get_active_node_version`/`Nodejs::check_installed` 均受其影响,`launch.rs` 会在 prepare 后重新解析 node 路径),再 `npm rebuild`(用所选运行时自带的 npm),最后返回 `CORE_NATIVE_ABI_MISMATCH:` 诊断。CLI shim 的 node 选择仍是 semver-only。-- pnpm store 绑定(`ERR_PNPM_UNEXPECTED_STORE`):pnpm 只在「自己解析出的 store」与档案 `node_modules/.modules.yaml` 里的 `storeDir` 一致时才继续安装,否则直接退出 —— 用户的 pnpm 用户级/全局配置(`store-dir`)或 `npm_config_store_dir` 环境变量把 store 指到别处(典型:用户在其他分区的工程里跑过 pnpm,pnpm 把那份 store 写进全局配置)时,档案安装会**在自身完全健康的情况下**失败,报错却是「插件安装失败」。`service/plugin/install/env.rs::build_plugin_envs` 因此把档案记录的 `storeDir` 显式注入子进程的 `npm_config_store_dir`(环境变量优先级高于 `.npmrc` 与全局配置,`Command::envs` 又会覆盖继承值),`ensure_pnpm` 的 store **主版本**匹配(`profile_store_major`)只解决 pnpm 10/11 布局不兼容,解决不了「同主版本、不同路径」。`storeDir` 解析见 `install/pnpm.rs::parse_store_dir_from_modules_yaml`。--- 补丁层 YAML 语法错误(issue #525):`$DSH_HOME/cordis.patch.yml`(全局层)会叠加到**每个**档案(含 `safe`),所以手写 YAML 里一个未加引号的 `: `(典型:`FOO: !!js process.env.X ? process.env.X : ''`)会让所有档案都起不来,报 `INTERNAL_PLUGIN_INSTALL_FAILED: INTERNAL_PLUGIN_PATCH_PARSE_FAILED: <路径>: <解析错误>`(dsh 上游契约要求**显式失败**,不会静默跳过损坏层,`loadOptionalPatches` 的 JSDoc 明确「present patch file that fails is a misconfiguration and must fail loud at boot」)。桌面端因此只做「显式隔离」而不自动跳过:`service/plugin/patch_guard.rs` 的 `quarantine_patch_layers_in(profile_dir, dsh_home)` 把**无法解析**的层重命名为 `<原名>.broken-<UTC yyyymmddhhmmss>`(同名追加 `-2`/`-3`,**不删除**),由错误页「隔离损坏的补丁文件」按钮(`quarantine_broken_patch_layers`)与「安全模式」(`enter_safe_mode`)触发;`repair_loader_state` 的解析错误现在按 `patch_layer_paths()`(当前档案层 + 全局层)逐个上报,前端用 `INTERNAL_PLUGIN_PATCH_PARSE_FAILED` 前缀识别并给出 `errors.patch_layer_parse_failed` + `buttons.quarantine_patch` 入口。**改名失败即中止**:`PatchQuarantineReport::has_failures()` 为真时两个命令都返回 `PATCH_LAYER_QUARANTINE_FAILED: …` 而不切档案/不重启(损坏文件仍在原地,重启只会再失败一次),前端换成 `errors.patch_quarantine_failed` 提示用户先释放文件或手动改名。--- pnpm 工作区多文档(issue #526):`$DSH_HOME/profiles/<档案>/pnpm-workspace.yaml` 被手工/工具拼接成多个 YAML 文档(`---` 分隔)时,pnpm(js-yaml `load`)与 serde_yaml **都只接受单文档流**(`expected a single document in the stream, but found more` / `deserializing from YAML containing more than one document is not supported`)。`service/profile/mod.rs::ensure_profile_pnpm_policy`(issue #222 的 zod release-age 例外)在插件安装前置步骤里解析该文件,于是整个启动卡在「Plugin installation」阶段,且原报错不含任何文件路径。修法:新增 `service/profile/mod.rs::parse_workspace_document(content)`,单文档正常返回;解析失败时逐文档尝试(`serde_yaml::Deserializer::from_str` 的 Iterator),**全部是映射**才按「后者覆盖前者」合并成一个映射并返回 `normalized = true`,否则保留原始解析错误(issue #49 的重复映射键不会被误当成多文档)。`ensure_profile_pnpm_policy` 与 `service/plugin/install/allowlist.rs::apply_allow_build_keys` 共用它,`normalized` 本身即视为需要落盘的改动,把文件自愈成 pnpm 也能读的单文档(日志 `PROFILE_WORKSPACE_MULTI_DOCUMENT`)。解析错误统一带路径便于定位:`PROFILE_WORKSPACE_INVALID_YAML: <路径>: <解析错误>`。--- 旧版 WebKit 缺全局 `Iterator`(issue #539):dsh 内置插件 `@deepseek-ai/dsh-client-ui-sidebar-documentpreview`- 内联的 pdf.js 在模块顶层执行 `typeof Iterator.prototype.join !== 'function'`(pdf.js 自己补 `join` 是为了兼容旧引擎),- 而 `Iterator` 是 ES2025 iterator helpers 才引入的全局对象(Safari 18.4 / WebKit 2163 起)。- macOS 14 / 15.3 随附的系统 WebKit 没有它,该表达式直接抛 `Can't find variable: Iterator`,- 插件 import 失败,桌面端启动即报「Failed to load plugins: failed to import loader entry …」- (`service/plugin` 的错误页只给出「插件加载失败」,不含缺失的标识符,需对照上面这句才能定位)。- 修法:`src-tauri/src/desktop/compat.rs` 的 `ITERATOR_HELPERS_SHIM_JS`(脚本本体为同目录- `compat_iterator.js.inc`)随其它垫片一起经 `initialization_script_for_all_frames` 注入非 Windows 平台- 的**三个窗口**(`builder.rs` 主窗口与附加窗口、`pet.rs` 桌宠窗口),在真实的 %IteratorPrototype%- (由 `Object.getPrototypeOf(Object.getPrototypeOf([][Symbol.iterator]()))` 取得)上补齐- join / toArray / forEach / some / every / find / reduce / map / filter / take / drop / flatMap 与- `Iterator.from`。两个要点:helper 必须挂在**共享的原型**上(pdf.js 的补丁正是假设 `Iterator.prototype`- 就是它,挂在自建对象上生成器仍解析不到);**只做加法**——`Iterator` 已存在(原生,或宿主页面自带- polyfill)时整体让位,每个 helper 也先按 `typeof` 判断,`typeof Iterator !== 'undefined'` 因此对第三方- 插件仍是可信的能力探测。Windows(WebView2,Chromium ≥ 122)原生支持,不注入(同 `AbortSignal.any` 的取舍)。- 回归测试 `test/compat-iterator.test.ts` 在 VM 里 `delete globalThis.Iterator` 并删掉原型上的原生 helper- 复现旧 WebKit,再把垫片行为与 Node/V8 原生 iterator helpers 做逐值差分(本机无法跑 macOS 14 的 WebKit)。-- macOS 麦克风/摄像头权限(issue #214):内嵌 WKWebView 里的 `getUserMedia` 要同时满足两处,缺任何一处都拿不到流——`src-tauri/Info.plist` 的 `NSMicrophoneUsageDescription` / `NSCameraUsageDescription`(**缺用途说明时 TCC 直接终止进程**,连授权框都不弹,日志里只有 `attempted to access privacy-sensitive data without a usage description`)与 `src-tauri/Entitlements.plist` 的 `com.apple.security.device.audio-input` / `com.apple.security.device.camera`(`bundle.macOS.hardenedRuntime` 默认 true,Hardened Runtime 会把资源访问全部关上,没有对应 entitlement 即使有用途说明也无效)。两处都在 `bundle.macOS` 里显式声明(`infoPlist` / `entitlements`),**相对路径按 bundle 时的 CWD 解析**——`crates/tauri-cli/src/bundle.rs` 会先 `set_current_dir(dirs.tauri)`,所以写 `Info.plist` 而不是 `src-tauri/Info.plist`;CLI 另外还会自动合并 `tauri.conf.json` 同目录下的 `Info.plist`。WKWebView 的 `requestMediaCapturePermissionForOrigin` 不用自己接:wry 0.55.1 的 `WryWebViewUIDelegate` 无条件回 `WKPermissionDecision::Grant`(`src/wkwebview/class/wry_web_view_ui_delegate.rs`)。回归测试见 `src-tauri/src/desktop/builder.rs` 的 `macos_bundle_tests`(macOS 上额外用 `plutil -lint` 校验 plist 语法;`tauri dev` 不产 `.app`,走终端的 TCC 授权,不在覆盖范围内)。--- Linux 托盘点击(issue #386 / #438):`tauri::tray` 固定依赖的 tray-icon 0.24 在 Linux 上只有 libappindicator/GTK 后端,该后端**不上报任何 `TrayIconEvent`**(上游 tauri-apps/tray-icon#104),单击/双击都无法唤起主窗,只能走托盘菜单。上游 0.25.0 的 KSNI 后端把 SNI 的 `Activate` 映射成 `TrayIconEvent::Click { button: Left }`,但 tauri 2.x 的菜单类型来自 muda 0.19,而 tray-icon 0.25 换成了 muda 0.20(`TrayIconBuilder::menu` 的 `ContextMenu` 不是同一个 trait,编译期即不兼容),tauri 2.11.5 的 `tray-icon = "^0.24"` 既不能 `cargo update` 也不能 `[patch.crates-io]` 顶到 0.25,tauri 3 目前只有 alpha。因此 `src-tauri/Cargo.toml` 仅在 `cfg(target_os = "linux")` 直接依赖 `tray-icon = { version = "0.25", default-features = false, features = ["ksni"] }`(`ksni` 会启用 muda 的 `snapshot`,菜单经 D-Bus 导出;同时不再需要 GTK/libappindicator),Linux 托盘改由 `src-tauri/src/desktop/linux_tray.rs` 自建,`desktop::builder::tray` 在 Linux 分支只调它。要点:`TrayIcon` 必须 `Box::leak` 保活(析构即注销 SNI 项);`TrayIconEvent::receiver()` / `MenuEvent::receiver()` 是全局通道且由 KSNI 自己的线程投递(tauri 只给**它自己依赖的** 0.19 / 0.24 装全局处理器,与本模块用的 0.20 / 0.25 是各自独立的静态通道),各起一个线程消费再 `run_on_main_thread` 回主线程执行 `show_main_window` / `app.exit`;没有 SNI watcher(未装 AppIndicator 扩展的 GNOME)或会话总线不可用时只记 `LINUX_TRAY_FAILED`,不让启动失败。macOS / Windows 继续走 `tauri::tray`(避免两套 muda ObjC 菜单实现并存)。tauri 2.x 跟进 bump tray-icon 之后,删掉这份依赖与 `linux_tray.rs` 即可。--## Summary--- **API Import**: 直接 `import { invoke } from '@tauri-apps/api/core'`(本仓库没有 `@/apis` 层);类型就近定义在 hooks/组件文件中-- **Hooks**: 副作用一律用 reause(`useWatch`/`useMount`/`useListen`/`useEventListener`/`useIntervalFn`/`promiseTimeout` 等),`useEffect` 只在需要卸载清理且无对应 hook 时使用;`react-use` / `@hairy/react-lib` 已移除-- **Function Declaration**: Use `function`, not arrow functions-- **Conditional Rendering**: Use `If`, `Then`, `Else` components instead of ternary operators and `&&` operators-- **Data Processing**: Simple scenarios use `useQuery`/`useMutation` directly, complex scenarios create service files-- **State Management**: Multi-module shared state uses `defineStore + useStore`(valtio-define);store 按 `src/store/modules/<name>/` 分模块,`index.ts` 是唯一出口;`defineScope`/`useScope` 已弃用(无引用),新代码勿用+* **原生模块 ABI 校验**:`prepare_active_runtime` 在启动前会运行 `NATIVE_PROBE_SCRIPT` 探测 ABI。若匹配失败,将自动补齐依赖或切至捆绑 Node 运行时。+* **pnpm Store 绑定冲突**:为防止全局 `store-dir` 冲突导致插件安装失败,`build_plugin_envs` 会将档案记录的 `storeDir` 显式注入为 `npm_config_store_dir` 环境变量。+* **YAML 补丁层错误 (Issue #525)**:损坏的 `cordis.patch.yml` 会被隔离为 `<Name>.broken-<Timestamp>`。若隔离/重命名失败,程序将直接中止并返回 `PATCH_LAYER_QUARANTINE_FAILED`,要求用户手动处理。+* **pnpm Workspace 多文档修复 (Issue #526)**:若 `pnpm-workspace.yaml` 被意外包含 `---` 多文档,解析器会自动尝试解析并合并为单文档落盘自愈(日志标记 `PROFILE_WORKSPACE_MULTI_DOCUMENT`)。+* **旧版 WebKit 缺失 Iterator 补丁 (Issue #539)**:在非 Windows 平台的 WebView 初始化时注入 `compat_iterator.js.inc` 垫片,补齐 ES2025 Iterator Helpers(在 `Object.getPrototypeOf(...)` 上挂载),防止旧 macOS WebKit 崩溃。+* **macOS 媒体权限配置 (Issue #214)**:必须同时在 `Info.plist` (声明 Usage Description) 与 `Entitlements.plist` (声明 `com.apple.security.device.*`) 中配置,相对路径基于 tauri bundle 运行时的 CWD 目录。+* **Linux 托盘点击适配 (Issue #386/#438)**:Linux 环境下通过 `linux_tray.rs` 基于 `tray-icon 0.25 (ksni)` 单独构建托盘,避免 muda 依赖版本冲突,通过 `Box::leak` 保活并在独立线程中处理事件。\ No newline at end of file