Skip to content

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

feat(pet): 桌宠渲染改用 dsh-pet-component,预设宠物改为远端直连

hairyf11829b045f7f
diff --git a/README.en.md b/README.en.md
index ba17b91b..9d1372c0 100644
--- a/README.en.md
+++ b/README.en.md
@@ -55,7 +55,7 @@
- ⌨️ **CLI integration** — Install automatically registers the `dsh` command, ready in a new terminal; does not overwrite your existing shell config.
- 🧭 **Launch wizard** — On first launch, choose recommended plugins, or re-select them later in config.
- 🚀 **Self-update** — In-app updates; no need to re-download.
-- 🐾 **Desktop pets** — Manage Pets and Codex sources, download preset pets, import Codex `.zip` packs, and show activity states from conversations.
+- 🐾 **Desktop pets** — Manage Pets and Codex sources with presets that work out of the box (streamed from their upstream asset hosts, no download step), import Codex `.zip` packs, and show activity states from conversations.
## Presets
diff --git a/README.md b/README.md
index 2cb140aa..2a5e16ee 100644
--- a/README.md
+++ b/README.md
@@ -50,7 +50,7 @@
- ⌨️ **命令行集成** — 安装自动注册 `dsh` 命令,新开终端即用;不覆盖你已有 shell 配置。
- 🧭 **启动引导** — 首次启动可选推荐插件,也可在配置中重新选择。
- 🚀 **自更新** — 应用内更新,不需要重新下载;
-- 🐾 **桌宠** — 提供 Pets / Codex 双来源桌宠管理,可下载预设宠物、导入 Codex `.zip` 资源包,并根据会话活动显示状态气泡。
+- 🐾 **桌宠** — 提供 Pets / Codex 双来源桌宠管理,预设宠物开箱即用(直连远端素材,无需下载)、可导入 Codex `.zip` 资源包,并根据会话活动显示状态气泡。
## 预设插件
diff --git a/docs/AGENTS.desktop.md b/docs/AGENTS.desktop.md
index ba6fa958..dc6afc6d 100644
--- a/docs/AGENTS.desktop.md
+++ b/docs/AGENTS.desktop.md
@@ -6,6 +6,7 @@ DeepSeek Harness desktop (Tauri 2 + React 19), embeds the Harness UI served at `
- **数据隔离(核心共用、数据不共用)**: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-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.
diff --git a/package.json b/package.json
index 71435f61..52c24445 100644
--- a/package.json
+++ b/package.json
@@ -29,8 +29,11 @@
"@heroui/react": "catalog:runtime",
"@heroui/styles": "catalog:runtime",
"@overlastic/react": "catalog:runtime",
+ "@reause/core": "catalog:runtime",
"@tanstack/react-query": "catalog:runtime",
"@tauri-apps/api": "catalog:tauri",
+ "@tauri-apps/plugin-http": "catalog:tauri",
+ "dsh-pet-component": "catalog:runtime",
"i18next": "catalog:runtime",
"react": "catalog:runtime",
"react-dom": "catalog:runtime",
diff --git a/packages/dsh-tauri-pet/README.md b/packages/dsh-tauri-pet/README.md
index 5d25b150..50c879e9 100644
--- a/packages/dsh-tauri-pet/README.md
+++ b/packages/dsh-tauri-pet/README.md
@@ -5,29 +5,29 @@ DeepSeek Harness 的桌宠插件。它在设置页提供 `Pets` 与 `Codex` 两
## UI
-- **Pets**:显示预设宠物(`resources/preset-pets.json` 清单,下载到
- `~/.dsh/pets/<id>` 后启用)以及 Chat 来源的宠物卡片;工具栏提供
+- **Pets**:显示预设宠物(`resources/preset-pets.json` 清单,卡片点击即启用,
+ 无需下载)以及 Chat 来源的宠物卡片;工具栏提供
**Create** 和 **Wake pet / Collapse pet**。`Create` 创建标准会话并只预填
`/hatch-dsh-pet 根据你对我的了解,养一只宠物`,不会自动提交。
- **Codex**:显示 Codex 来源(`~/.codex/pets`)的宠物卡片;工具栏只有
**Import**,用于导入 `.zip` 资源包。
-- 预设宠物媒体(WebM / MOV / GIF / config.jsonc)不再随本包内置:用户在设置页
- 「下载」后安装到 `~/.dsh/pets/<id>`,桌宠窗口按 `config.jsonc` 的动画池
- (动画名 = 动画文件名主名)直接播放下载产物,无运行时回退。
- macOS 的 WKWebView 不认 VP9-alpha WebM(alpha 被丢弃、透明区域渲染成黑色,
- issue #434),因此 macOS 按清单 `platforms.macos` 改从
+- 预设宠物**不下载、不安装**:清单条目登记远端素材地址与渲染参数,桌宠窗口直接
+ 把它们交给 [`dsh-pet-component`](https://github.com/hairyf/dsh-pet-component) 的
+ `<Pet>`(`config` / `uri` / `ext` / `kind` / `size`),首次播放按需拉取并落
+ IndexedDB 缓存。macOS 的 WKWebView 不认 VP9-alpha WebM(alpha 被丢弃、透明区域
+ 渲染成黑色,issue #434),因此清单里 macOS 用 `uri.mac` / `ext.mac` 指向
[`dsh-tauri-desk/dsh-pet-mov`](https://github.com/dsh-tauri-desk/dsh-pet-mov)
- 只下载 `config.jsonc` + `mov/`(HEVC-with-Alpha),其余平台继续用上游 WebM。
-- 宠物大小滑条保持 50–200%,默认 100%。侧栏绿色圆点表示窗口当前 **visible** 状态,
- 而不是只表示持久化的 `enabled` 状态。首次点击会永久启用;之后只显示或隐藏窗口,
- 不会因隐藏而写入 `enabled=false`。
+ 的 HEVC-with-Alpha `.mov`,其余平台继续用上游 WebM。
+- 宠物大小滑条保持 50–200%,默认 100%。侧栏入口常驻(预设随时可启用),绿色圆点
+ 表示窗口当前 **visible** 状态,而不是只表示持久化的 `enabled` 状态。首次点击会
+ 永久启用;之后只显示或隐藏窗口,不会因隐藏而写入 `enabled=false`。
## 文件来源与技能
Chat 宠物安装在 `${DSH_HOME:-$HOME/.dsh}/pets`,Codex 宠物安装在
`$HOME/.codex/pets`,两个来源通过 `list_pets({ source: 'chat' | 'codex' })`
-严格分开。预设宠物清单(`src-tauri/resources/preset-pets.json`)登记远端仓库
-与资源子目录,下载解压后只保留 `assets` 前缀下的条目。`skills/hatch-dsh-pet/SKILL.md`
+严格分开。预设宠物清单(`src-tauri/resources/preset-pets.json`)只登记远端素材
+地址与渲染参数,本地不落任何预设产物。`skills/hatch-dsh-pet/SKILL.md`
由 `cordis.patch.yml` 组合进 `@deepseek-ai/dsh-skill-filesystem`,并使用
`providerName: dsh-tauri-pet` 与 `includeDefaultRoots: false`,避免覆盖其他
skill provider 或默认根目录。
@@ -57,11 +57,7 @@ skill provider 或默认根目录。
| `set_pet_size` | 持久化 50–200% 的大小 |
| `list_pets` | 按 `source` 列出 Chat 或 Codex 宠物 |
| `get_pet_asset` | 获取指定宠物的完整 8×11 spritesheet data URL |
-| `list_preset_pets` | 列出预设宠物清单(含安装状态) |
-| `download_preset_pet` | 后台下载并安装预设宠物 |
-| `get_preset_download_progress` | 轮询预设宠物下载/解压进度 |
-| `get_preset_pet_config` | 读取已安装预设的 `config.jsonc`(dsh-pet 协议,校验后返回) |
-| `get_preset_pet_assets` | 列出已安装预设的动画 URL manifest(WebM 或 macOS 的 HEVC MOV,dsh-pet 协议按需流式提供) |
+| `list_preset_pets` | 列出预设宠物清单(远端素材 + 渲染参数,无安装态) |
| `import_pet` | 导入 Codex `.zip` 资源包 |
| `set_pet_activity` | 更新 `idle`、`turn`、`moving-left`、`moving-right`、`waving`、`waiting`、`running`、`review` 或 `failed` |
@@ -69,6 +65,10 @@ skill provider 或默认根目录。
`dsh-tauri/client` 的 `invokeBridgedTauri`。设置卡片直接使用预设清单的浏览图
URL 作为缩略图。
+> 桌宠窗口渲染全部交给 `dsh-pet-component`(`src/pet`):远端素材经
+> `@tauri-apps/plugin-http` 的 `fetch` 拉取(绕开 githubusercontent 的 CORS),
+> 动画池解析、双视频缓冲、雪碧图帧循环、IndexedDB 缓存与双击回应都在组件内。
+
## Build and checks
```sh
diff --git a/packages/dsh-tauri-pet/THIRD_PARTY_NOTICES.md b/packages/dsh-tauri-pet/THIRD_PARTY_NOTICES.md
index 33fc61f0..8126f25b 100644
--- a/packages/dsh-tauri-pet/THIRD_PARTY_NOTICES.md
+++ b/packages/dsh-tauri-pet/THIRD_PARTY_NOTICES.md
@@ -3,10 +3,13 @@
## dsh-pet
The pet media assets (WebM animations, preview GIFs and `config.jsonc`) are **no
-longer bundled** in this package. They are downloaded at runtime from
-[`PC2005-cloud/dsh-pet`](https://github.com/PC2005-cloud/dsh-pet) via the preset
-pet catalog (`src-tauri/resources/preset-pets.json`) and installed under
-`~/.dsh/pets/<id>`. The catalog pins a specific commit for reproducible downloads.
+longer bundled or downloaded** by this package. The preset pet catalog
+(`src-tauri/resources/preset-pets.json`) only registers the remote URLs, and the
+pet window streams them directly from
+[`PC2005-cloud/dsh-pet`](https://github.com/PC2005-cloud/dsh-pet) at play time
+(macOS reads the HEVC-alpha `.mov` mirror from
+[`dsh-tauri-desk/dsh-pet-mov`](https://github.com/dsh-tauri-desk/dsh-pet-mov)).
+The catalog pins specific commits for reproducibility.
MIT License
diff --git a/packages/dsh-tauri-pet/docs/sync-log.md b/packages/dsh-tauri-pet/docs/sync-log.md
index 70438615..0f4f8650 100644
--- a/packages/dsh-tauri-pet/docs/sync-log.md
+++ b/packages/dsh-tauri-pet/docs/sync-log.md
@@ -13,13 +13,38 @@
| `source/dsh-pet` | `e1ff8c1` | v0.2.6 | 预设资产与工作状态语义来源 |
| `source/dsh-dafeiyu` | `f4f4482` | v0.1.9 | 气泡文案/优先级逻辑参考(不下载资产) |
-- 预设下载清单 `src-tauri/resources/preset-pets.json` 的 `ref` 当前为
+- 预设清单 `src-tauri/resources/preset-pets.json` 的素材地址内嵌 ref
`e1ff8c1e4001878cbb80441262d530e16541f138`(须与 dsh-pet 已采纳 HEAD 保持一致,
- 新 WebM 资产在 `903dfde` 才入库,低于此的 ref 会下载不到 6 个工作状态动画)。
+ 新 WebM 资产在 `903dfde` 才入库,低于此的 ref 会取不到 6 个工作状态动画);
+ macOS 侧为 `dsh-pet-mov` 的 `be0f3bb494cb71a4c73f916c0b92d25a3ab4d002`。
- 旧研究参考固定 `docs/plugins/expired/pet.todo.md:96` 指向 `899150e`,仅历史参考。
## 同步记录
+### 2026 —— 预设宠物改为 dsh-pet-component 直连远端(移除下载/解压链路)
+
+不是上游同步,而是渲染层换实现导致预设获取方式的整体变化,记录在此以便后续核对素材来源与命令面。
+
+- **渲染层**:`src/pet` 整体换成 [`hairyf/dsh-pet-component`](https://github.com/hairyf/dsh-pet-component)
+ 的 `<Pet>`(npm `dsh-pet-component@^0.1.1`,内部用 `@reause/core`);`src/pet/components/pet.tsx`
+ (681 行)、`src/pet/config/index.ts`(294 行)、`hooks/use-pet.ts` 删除,动画池解析、
+ 双视频缓冲、雪碧图帧循环、IndexedDB 缓存、双击回应全部由组件接管。`src/pet` 只剩设置状态、
+ 会话气泡聚合、原生窗口拖拽(reause `useEventListener` + `useTimeoutFn`)与命中穿透。
+- **预设不再下载/安装**:`src-tauri/resources/preset-pets.json` 改成组件 props 形状
+ (`id` / `name` / `desc` / `image` / `kind` / `size` / `config` / `uri{default,mac}` /
+ `ext{default,mac}`),Rust `bridge/preset_pet.rs` 从 2148 行缩到只剩读清单 + 校验;
+ `download_preset_pet` / `update_preset_pet` / `get_preset_download_progress` /
+ `get_preset_pet_config` / `get_preset_pet_assets` 与 `dsh-pet://` 自定义协议全部删除。
+ `uri.mac` / `ext.mac` 继续指向 `dsh-tauri-desk/dsh-pet-mov` 的 HEVC-alpha `.mov`(issue #434 结论不变)。
+- **CORS**:`src/pet/main.tsx` 把全局 `fetch` 换成 `@tauri-apps/plugin-http` 的实现
+ (请求走 Rust),否则 `raw.githubusercontent.com` 不返回 `Access-Control-Allow-Origin`,
+ 组件拉配置与抓 blob 会整条失败;能力文件只放开 `https://*.githubusercontent.com/*` scope,
+ 媒体/图片的 CSP 增加 `blob:` 与 `https://*.githubusercontent.com`。
+- **插件前端**:`utils/preset-card.ts`、`utils/availability.ts`(含各自测试)删除——
+ 预设恒可用、卡片只有「启用 / 已选」两态;store 去掉 `petsAvailable`,侧栏入口常驻。
+- 校验:`pnpm typecheck`、`pnpm build`、`pnpm exec eslint src/pet packages/dsh-tauri-pet/src src/hooks/use-iframe-invoke.ts --max-warnings=0`、
+ `pnpm exec vitest run`(295+)、`cargo test --lib`(530 passed)。
+
### 2026 —— 修复 macOS 预设宠物黑底(issue #434,分支 `fix/434-macos-hevc-alpha-mov-pet`)
不是上游同步,而是**素材编码格式**在 macOS 上不可用导致的黑底,记录在此以便后续核对素材来源。
diff --git a/packages/dsh-tauri-pet/src/client/components/pet-settings.tsx b/packages/dsh-tauri-pet/src/client/components/pet-settings.tsx
index 3dec80d8..5cc4365c 100644
--- a/packages/dsh-tauri-pet/src/client/components/pet-settings.tsx
+++ b/packages/dsh-tauri-pet/src/client/components/pet-settings.tsx
@@ -1,14 +1,12 @@
import type { ChangeEvent, ReactElement } from 'react'
-import type { PetListItem, PetSettingsProps, PresetDownloadProgress, PresetPetItem } from '../types'
+import type { PetListItem, PetSettingsProps, PresetPetItem } from '../types'
import { ArrowDownToLine, Icon, Plus, useMountStyle } from 'dsh-tauri-ui/client'
import { useCallback, useEffect, useRef, useState, useSyncExternalStore } from 'react'
import { PET_DEFAULT_SIZE, PET_SIZE_MAX, PET_SIZE_MIN, PET_SIZE_STEP } from '../constants'
import { text, usePetLocale } from '../locales'
import {
- downloadPresetPet,
fetchPetList,
fetchPetStatus,
- fetchPresetDownloadProgress,
fetchPresetPets,
hidePet,
importPet,
@@ -16,16 +14,10 @@ import {
setPetEnabled,
setPetSize,
showPet,
- updatePresetPet,
} from '../service/pet'
-import { beginPetStatusFetch, commitPetStatusFetch, getPetUiSnapshot, setPetsAvailable, setPetStatus, subscribePetUi } from '../store'
-import { hasAvailablePets } from '../utils/availability'
-import { progressPercent, resolvePresetCardAction, resolvePresetCardUpdate } from '../utils/preset-card'
+import { beginPetStatusFetch, commitPetStatusFetch, getPetUiSnapshot, setPetStatus, subscribePetUi } from '../store'
import petSettingsStyle from './pet-settings.cssr'
-/** 预设宠物下载轮询间隔(ms)。 */
-const PRESET_DOWNLOAD_POLL_MS = 400
-
/** 模块级清单缓存:跨组件挂载复用,避免反复打开设置页闪烁(初次仍显示加载占位)。 */
let cachedPresetPets: PresetPetItem[] | null = null
let cachedChatPets: PetListItem[] | null = null
@@ -38,27 +30,17 @@ interface PetCardProps {
disabled: boolean
name: string
onAction: () => void
- /** 下载进度(仅下载/解压中显示进度条)。 */
- progress?: PresetDownloadProgress | null
- /** 下载尺寸标签(`[number]mb`)。 */
- sizeLabel?: string
thumbnail?: string
thumbnailType?: 'gif' | 'spritesheet'
- /** 显示「更新」按钮(已安装且清单提示可更新;位于主动作左侧)。 */
- updateDisabled?: boolean
- updateLabel?: string
- onUpdate?: () => void
}
function PetCard(props: PetCardProps): ReactElement {
const actionClassName = props.active
? 'dshp-pet__card-action dshp-pet__card-actionActive'
: 'dshp-pet__card-action'
- const updateClassName = 'dshp-pet__card-action dshp-pet__card-actionUpdate'
const thumbnailClassName = props.thumbnailType === 'spritesheet'
? 'dshp-pet__card-thumb dshp-pet__card-thumbSprite'
: 'dshp-pet__card-thumb'
- const percent = props.progress ? progressPercent(props.progress) : null
return (
<div className="dshp-pet__card-item">
@@ -74,42 +56,10 @@ function PetCard(props: PetCardProps): ReactElement {
<span className="dshp-pet__card-body">
<span className="dshp-pet__card-nameRow">
<span className="dshp-pet__card-name">{props.name}</span>
- {props.sizeLabel ? <span className="dshp-pet__cardsize">{props.sizeLabel}</span> : null}
</span>
{props.desc ? <span className="dshp-pet__card-desc">{props.desc}</span> : null}
- {props.progress
- ? (
- <span
- className="dshp-pet__card-progress"
- role="progressbar"
- aria-valuemin={0}
- aria-valuemax={100}
- aria-valuenow={percent ?? undefined}
- >
- <span
- className={percent === null ? 'dshp-pet__card-progressFill dshp-pet__card-progressIndeterminate' : 'dshp-pet__card-progressFill'}
- style={percent === null ? undefined : { width: `${percent}%` }}
- />
- </span>
- )
- : null}
</span>
<span className="dshp-pet__card-actions">
- {/* 更新按钮只受更新自身条件约束(busy/下载中),不继承主动作
- disabled(含已选):默认宠物已启用时仍必须能更新
- (update_preset_pet 会先停用、替换安装后再重新启用)。 */}
- {props.onUpdate && props.updateLabel !== undefined
- ? (
- <button
- type="button"
- className={updateClassName}
- disabled={props.updateDisabled === true}
- onClick={props.onUpdate}
- >
- {props.updateLabel}
- </button>
- )
- : null}
<button
type="button"
className={actionClassName}
@@ -136,23 +86,6 @@ function readAsBase64(file: File): Promise<string> {
})
}
-/** 预设宠物卡片右侧动作(已选/下载中/启用/下载),纯状态机见 utils/preset-card。 */
-export function presetCardAction(
- item: Pick<PresetPetItem, 'id' | 'installed' | 'phase'>,
- active: string,
- progress: PresetDownloadProgress | null | undefined,
-): 'download' | 'downloading' | 'enable' | 'selected' {
- return resolvePresetCardAction(item, active, progress)
-}
-
-/** 预设宠物卡片「更新」按钮显隐(已安装且可更新,且非下载中),见 utils/preset-card。 */
-export function presetCardUpdate(
- item: Pick<PresetPetItem, 'installed' | 'update_available' | 'phase'>,
- progress: PresetDownloadProgress | null | undefined,
-): boolean {
- return resolvePresetCardUpdate(item, progress)
-}
-
export function PetSettings(props: PetSettingsProps): ReactElement {
useMountStyle(petSettingsStyle, 'dsh-tauri-pet-settings-styles')
usePetLocale()
@@ -164,9 +97,6 @@ export function PetSettings(props: PetSettingsProps): ReactElement {
const [chatPets, setChatPets] = useState<PetListItem[]>(() => cachedChatPets ?? [])
const [codexPets, setCodexPets] = useState<PetListItem[]>(() => cachedCodexPets ?? [])
const [presetPets, setPresetPets] = useState<PresetPetItem[]>(() => cachedPresetPets ?? [])
- /** 各预设宠物下载进度(key = preset id;phase=done/failed 后由轮询清理)。 */
- const [downloads, setDownloads] = useState<Record<string, PresetDownloadProgress>>({})
- const downloadTimersRef = useRef<Record<string, ReturnType<typeof setInterval>>>({})
const [size, setSize] = useState(status?.pet_size ?? PET_DEFAULT_SIZE)
const committedSizeRef = useRef<number | null>(null)
const enabled = Boolean(status?.enabled)
@@ -179,53 +109,10 @@ export function PetSettings(props: PetSettingsProps): ReactElement {
setSize(statusSize)
}, [statusSize])
- const refreshPresets = useCallback(async (): Promise<void> => {
- try {
- const [nextPresetPets, nextStatus] = await Promise.all([fetchPresetPets(), fetchPetStatus()])
- cachedPresetPets = nextPresetPets
- setPresetPets(nextPresetPets)
- // 下载完成会改变可用性(未安装→已安装),同步侧栏入口显隐(chat/codex 用缓存清单)。
- setPetsAvailable(hasAvailablePets(nextPresetPets, cachedChatPets ?? [], cachedCodexPets ?? []))
- const revision = beginPetStatusFetch()
- commitPetStatusFetch(revision, nextStatus)
- setPetStatus(nextStatus)
- }
- catch (refreshError) {
- console.error('[dsh-tauri-pet] refresh preset pets failed:', refreshError)
- setError(text('listFailed'))
- }
- }, [])
-
- /** 轮询下载进度;终态后清理定时器并刷新清单。 */
- const pollPresetDownload = useCallback((id: string): void => {
- if (downloadTimersRef.current[id])
- return
- const timer = setInterval(() => {
- void fetchPresetDownloadProgress(id).then((progress) => {
- setDownloads(previous => ({ ...previous, [id]: progress }))
- if (progress.phase === 'done' || progress.phase === 'failed') {
- if (downloadTimersRef.current[id]) {
- clearInterval(downloadTimersRef.current[id])
- delete downloadTimersRef.current[id]
- }
- if (progress.phase === 'failed')
- setError(progress.error ?? text('downloadFailed'))
- else
- void refreshPresets()
- }
- }).catch(() => {
- if (downloadTimersRef.current[id]) {
- clearInterval(downloadTimersRef.current[id])
- delete downloadTimersRef.current[id]
- }
- })
- }, PRESET_DOWNLOAD_POLL_MS)
- downloadTimersRef.current[id] = timer
- }, [refreshPresets])
-
useEffect(() => {
let cancelled = false
const revision = beginPetStatusFetch()
+ // 预设直连远端素材:清单拉回来即可直接启用,没有安装/下载状态需要跟踪。
void Promise.all([fetchPetStatus(), fetchPetList('chat'), fetchPetList('codex'), fetchPresetPets()])
.then(([nextStatus, nextChatPets, nextCodexPets, nextPresetPets]) => {
if (cancelled)
@@ -237,20 +124,6 @@ export function PetSettings(props: PetSettingsProps): ReactElement {
setChatPets(nextChatPets)
setCodexPets(nextCodexPets)
setPresetPets(nextPresetPets)
- // 同步侧栏入口显隐:无任何可用宠物(全新安装)时隐藏入口图标。
- setPetsAvailable(hasAvailablePets(nextPresetPets, nextChatPets, nextCodexPets))
- // 跨挂载恢复进行中的下载:清单 phase 标记 downloading/extracting 的项重新轮询,
- // 避免「返回应用再进设置」丢失进度视图、重复点击触发 PET_PRESET_BUSY。
- // 占位进度先写入 downloads,让不确定进度条在第一次轮询返回前立即出现。
- const resumed: Record<string, PresetDownloadProgress> = {}
- for (const item of nextPresetPets) {
- if (item.phase === 'downloading' || item.phase === 'extracting') {
- resumed[item.id] = { phase: item.phase, received: 0, total: 0 }
- pollPresetDownload(item.id)
- }
- }
- if (Object.keys(resumed).length > 0)
- setDownloads(previous => ({ ...previous, ...resumed }))
})
.catch((loadError) => {
if (cancelled)
@@ -264,60 +137,11 @@ export function PetSettings(props: PetSettingsProps): ReactElement {
})
return () => {
cancelled = true
- for (const timer of Object.values(downloadTimersRef.current))
- clearInterval(timer)
- downloadTimersRef.current = {}
- }
- }, [pollPresetDownload])
-
- async function startDownload(id: string): Promise<void> {
- if (busy)
- return
- setBusy(true)
- setError(null)
- try {
- await downloadPresetPet(id)
- pollPresetDownload(id)
}
- catch (downloadError) {
- // PET_PRESET_BUSY:下载已在后台进行(例如清单 phase 尚未刷新、跨挂载竞态)。
- // 恢复轮询接管既有下载,而不是报错或再次触发。
- if (String(downloadError).includes('PET_PRESET_BUSY'))
- pollPresetDownload(id)
- else
- setError(text('downloadFailed'))
- }
- finally {
- setBusy(false)
- }
- }
-
- /**
- * 更新已安装的预设宠物:走与首次下载完全相同的下载/解压流程(同一进度轮询)。
- * 宿主侧在宠物正在使用时先强制停用,更新结束后自动重新启用(前端无需处理)。
- */
- async function startUpdate(id: string): Promise<void> {
- if (busy)
- return
- setBusy(true)
- setError(null)
- try {
- await updatePresetPet(id)
- pollPresetDownload(id)
- }
- catch (updateError) {
- if (String(updateError).includes('PET_PRESET_BUSY'))
- pollPresetDownload(id)
- else
- setError(text('updateFailed'))
- }
- finally {
- setBusy(false)
- }
- }
+ }, [])
/** 启用预设宠物:选择它,并确保桌宠被唤醒(自动触发唤醒)。 */
- async function enablePreset(id: string): Promise<void> {
+ const enablePreset = useCallback(async (id: string): Promise<void> => {
if (busy || active === id)
return
setBusy(true)
@@ -335,7 +159,7 @@ export function PetSettings(props: PetSettingsProps): ReactElement {
finally {
setBusy(false)
}
- }
+ }, [active, busy])
async function choose(id: string): Promise<void> {
if (busy || active === id)
@@ -416,8 +240,6 @@ export function PetSettings(props: PetSettingsProps): ReactElement {
const nextCodexPets = await fetchPetList('codex')
cachedCodexPets = nextCodexPets
setCodexPets(nextCodexPets)
- // 导入成功后本地宠物集合变化,同步侧栏入口显隐。
- setPetsAvailable(hasAvailablePets(cachedPresetPets ?? [], cachedChatPets ?? [], nextCodexPets))
}
catch (importError) {
console.error('[dsh-tauri-pet] import failed:', importError)
@@ -434,34 +256,19 @@ export function PetSettings(props: PetSettingsProps): ReactElement {
? <div className="dshp-pet__loading">{text('loading')}</div>
: (
<div className="dshp-pet__cards">
- {presetPets.map((item) => {
- const progress = downloads[item.id] ?? null
- const action = presetCardAction(item, active, progress)
- const downloading = action === 'downloading'
- const canUpdate = resolvePresetCardUpdate(item, progress)
- return (
- <PetCard
- key={item.id}
- thumbnail={item.image ?? undefined}
- name={item.name}
- desc={item.desc ?? ''}
- sizeLabel={item.size_mb != null ? `${Math.round(item.size_mb)}mb` : undefined}
- progress={downloading ? progress : null}
- active={action === 'selected'}
- disabled={busy || downloading || action === 'selected'}
- actionLabel={action === 'selected' ? text('selected') : action === 'enable' ? text('enable') : downloading ? text('downloading') : text('download')}
- onAction={() => {
- if (action === 'enable')
- void enablePreset(item.id)
- else if (action === 'download')
- void startDownload(item.id)
- }}
- updateLabel={canUpdate ? text('update') : undefined}
- updateDisabled={busy || downloading}
- onUpdate={canUpdate ? () => { void startUpdate(item.id) } : undefined}
- />
- )
- })}
+ {/* 预设宠物直连远端素材:没有下载/更新步骤,卡片动作只有「启用 / 已选」。 */}
+ {presetPets.map(item => (
+ <PetCard
+ key={item.id}
+ thumbnail={item.image ?? undefined}
+ name={item.name}
+ desc={item.desc ?? ''}
+ active={active === item.id}
+ disabled={busy || active === item.id}
+ actionLabel={active === item.id ? text('selected') : text('enable')}
+ onAction={() => { void enablePreset(item.id) }}
+ />
+ ))}
{chatPets.map(item => (
<PetCard
key={item.id}
diff --git a/packages/dsh-tauri-pet/src/client/constants/index.ts b/packages/dsh-tauri-pet/src/client/constants/index.ts
index 41c30283..a58a4bff 100644
--- a/packages/dsh-tauri-pet/src/client/constants/index.ts
+++ b/packages/dsh-tauri-pet/src/client/constants/index.ts
@@ -21,14 +21,8 @@ export const CMD_HIDE_PET = 'hide_pet'
export const CMD_LIST_PETS = 'list_pets'
export const CMD_IMPORT_PET = 'import_pet'
export const CMD_GET_PET_ASSET = 'get_pet_asset'
+/** 预设清单(`resources/preset-pets.json`)——预设直连远端素材,只有读取没有安装。 */
export const CMD_LIST_PRESET_PETS = 'list_preset_pets'
-export const CMD_DOWNLOAD_PRESET_PET = 'download_preset_pet'
-export const CMD_UPDATE_PRESET_PET = 'update_preset_pet'
-export const CMD_GET_PRESET_DOWNLOAD_PROGRESS = 'get_preset_download_progress'
-export const BUILTIN_PET_ID = 'maid-deepseek-whale'
-export const BUILTIN_PET_NAME = 'Maid DeepSeek Whale'
-export const BUILTIN_PET_DESC_ZH = '一只小小的七比蓝头发的鲸鱼女仆Codex宠物,穿着海军蓝裙子,白色褶边,蓝眼睛,侧鳍和鲸鱼尾巴。'
-export const BUILTIN_PET_DESC_EN = 'A tiny blue-haired whale maid Codex pet in a navy dress with white ruffles, blue eyes, side fins, and a whale tail.'
export const SIDEBAR_SELECTOR = '[data-slot="sidebar"]'
export const SETTINGS_TRIGGER_SELECTOR = '.dshp-settings-trigger'
export const PET_ICON_ATTRIBUTE = 'data-dsh-tauri-pet-icon'
diff --git a/packages/dsh-tauri-pet/src/client/dom/sidebar-icon.ts b/packages/dsh-tauri-pet/src/client/dom/sidebar-icon.ts
index ea1a8687..e20e89ce 100644
--- a/packages/dsh-tauri-pet/src/client/dom/sidebar-icon.ts
+++ b/packages/dsh-tauri-pet/src/client/dom/sidebar-icon.ts
@@ -11,15 +11,13 @@
* document.body,侧栏就绪后插入并持续看护(React 重渲染容器后自动补插);
* guard 属性 + 位置校验防止重复插入与死循环。
*
- * 可用性:无任何可用宠物(已安装预设或本地 chat/codex 均无)时入口隐藏,避免
- * 展示一个点了没意义的按钮;快照由本模块挂载时拉取一次,设置页在清单变化
- * (下载完成/导入)后写回。
+ * 入口常驻:预设宠物直连远端素材,任何安装状态下都可直接启用,因此不再需要
+ * 「有没有可用宠物」的可用性判定。
*/
import { PET_ICON_ATTRIBUTE, PET_ICON_RETRY_MAX, PET_ICON_RETRY_MS, PET_SETTINGS_ROW_CLASS, SETTINGS_TRIGGER_SELECTOR, SIDEBAR_SELECTOR } from '../constants'
import { text } from '../locales'
-import { fetchPetList, fetchPetStatus, fetchPresetPets, hidePet, setPetEnabled, showPet } from '../service/pet'
-import { beginPetStatusFetch, commitPetStatusFetch, getPetUiSnapshot, setPetsAvailable, setPetStatus, subscribePetUi } from '../store'
-import { hasAvailablePets } from '../utils/availability'
+import { fetchPetStatus, hidePet, setPetEnabled, showPet } from '../service/pet'
+import { beginPetStatusFetch, commitPetStatusFetch, getPetUiSnapshot, setPetStatus, subscribePetUi } from '../store'
/** 入口图标(爪印,currentColor 跟随官方 iconButton 悬停变色)。 */
const PET_ICON_SVG = '<svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor" aria-hidden="true"><path d="M12 13.5c-2.7 0-5.5 2-5.5 4.3 0 1.4 1 2.2 2.3 2.2 1 0 1.9-.6 3.2-.6s2.2.6 3.2.6c1.3 0 2.3-.8 2.3-2.2 0-2.3-2.8-4.3-5.5-4.3z"/><path d="M7.3 8.1c-1 .1-1.8 1.2-1.7 2.5.1 1.2 1 2.1 2 2 .9-.1 1.7-1.2 1.6-2.4-.1-1.2-1-2.2-1.9-2.1z"/><path d="M12 4.5c-1.1 0-2 1.1-2 2.5s.9 2.5 2 2.5 2-1.1 2-2.5-.9-2.5-2-2.5z"/><path d="M16.7 8.1c-.9-.1-1.8.9-1.9 2.1-.1 1.2.7 2.3 1.6 2.4 1 .1 1.9-.8 2-2 .1-1.3-.7-2.4-1.7-2.5z"/><path d="M4.8 12.3c-.8.3-1.2 1.4-.9 2.4.3 1 1.2 1.6 2 1.3.8-.3 1.1-1.4.8-2.4-.3-1-1.1-1.6-1.9-1.3z"/><path d="M19.2 12.3c-.8-.3-1.6.3-1.9 1.3-.3 1 0 2.1.8 2.4.8.3 1.7-.3 2-1.3.3-1-.1-2.1-.9-2.4z"/></svg>'
@@ -57,37 +55,14 @@ function createPetIconButton(): HTMLButtonElement {
return button
}
-/** 按共享状态缓存同步按钮显隐与两态(绿点显隐 + aria-pressed)。 */
+/** 按共享状态缓存同步按钮两态(绿点显隐 + aria-pressed)。 */
function syncIconState(button: HTMLButtonElement): void {
- const shared = getPetUiSnapshot()
- const status = shared.status
- // 没有宠物时隐藏入口;只有存在可用宠物时才显示按钮。
- button.style.display = shared.petsAvailable ? '' : 'none'
+ const status = getPetUiSnapshot().status
const active = Boolean(status?.enabled && status?.visible)
button.classList.toggle('dshp-pet__icon--on', active)
button.setAttribute('aria-pressed', String(active))
}
-/**
- * 拉取全部宠物清单并写入「是否有可用宠物」快照(侧栏入口显隐用)。失败时按
- * 有宠物处理(fail-open),避免桥接瞬时错误把入口藏掉;此后清单变化(下载
- * 完成/导入)由设置页写回同一快照。
- */
-async function refreshPetsAvailability(): Promise<void> {
- try {
- const [presets, chatPets, codexPets] = await Promise.all([
- fetchPresetPets(),
- fetchPetList('chat'),
- fetchPetList('codex'),
- ])
- setPetsAvailable(hasAvailablePets(presets, chatPets, codexPets))
- }
- catch (error) {
- console.error('[dsh-tauri-pet] refresh pets availability failed:', error)
- setPetsAvailable(true)
- }
-}
-
/**
* 安装侧栏入口补丁。返回卸载函数(移除按钮、断开观察器与订阅)。
* 桌宠状态缓存在这里初始化拉取一次;此后由设置页与按钮自身的切换写入。
@@ -112,9 +87,6 @@ export function registerSidebarPetIcon(): () => void {
commitPetStatusFetch(revision, status)
})
.catch(error => console.error('[dsh-tauri-pet] fetchPetStatus failed:', error))
- // 初始可用性:无任何可用宠物时隐藏入口(按钮按默认快照先隐藏,拉取成功后才
- // 决定是否显示;fail-open 策略见 refreshPetsAvailability)。
- void refreshPetsAvailability()
syncIconState(button)
/**
diff --git a/packages/dsh-tauri-pet/src/client/locales/index.ts b/packages/dsh-tauri-pet/src/client/locales/index.ts
index 6aefdce0..9abac232 100644
--- a/packages/dsh-tauri-pet/src/client/locales/index.ts
+++ b/packages/dsh-tauri-pet/src/client/locales/index.ts
@@ -3,23 +3,14 @@ import type { ClientContext } from 'dsh-tauri/client'
import type { LocaleKey } from '../types'
import { createExternalStore } from 'dsh-tauri/client'
import { useSyncExternalStore } from 'react'
-import {
- BUILTIN_PET_DESC_EN,
- BUILTIN_PET_DESC_ZH,
- BUILTIN_PET_NAME,
- PET_CLIENT_NS as NS,
-} from '../constants'
+import { PET_CLIENT_NS as NS } from '../constants'
export { PET_CLIENT_NS as NS } from '../constants'
const DICT_ZH: Record<LocaleKey, string> = {
- codex: 'Codex',
collapsePet: '收起宠物',
create: '创建',
createFailed: '创建宠物会话失败',
- download: '下载',
- downloadFailed: '下载预设宠物失败',
- downloading: '下载中',
emptyImported: '尚未导入宠物,点击右上角「导入」添加 .zip 资源包',
enable: '启用',
import: '导入',
@@ -27,9 +18,6 @@ const DICT_ZH: Record<LocaleKey, string> = {
listFailed: '读取宠物列表失败',
loading: '加载中…',
name: '宠物',
- noPetSelected: '未选择宠物,请在设置页选择你的宠物',
- petDescWhale: BUILTIN_PET_DESC_ZH,
- petNameWhale: BUILTIN_PET_NAME,
select: '选择',
selected: '已选',
setPetFailed: '选择宠物失败',
@@ -39,19 +27,13 @@ const DICT_ZH: Record<LocaleKey, string> = {
tabCodexDesc: '从 Codex 或压缩包中导入 Codex 宠物(支持 .zip 文件)',
tabInstalledDesc: '宠物会管理对话串,并突出显示需要关注的事项',
toggleFailed: '切换桌宠窗口失败',
- update: '更新',
- updateFailed: '更新预设宠物失败',
wakePet: '唤醒宠物',
}
const DICT_EN: Record<LocaleKey, string> = {
- codex: 'Codex',
collapsePet: 'Collapse pet',
create: 'Create',
createFailed: 'Failed to create a pet session',
- download: 'Download',
- downloadFailed: 'Failed to download preset pet',
- downloading: 'Downloading',
emptyImported: 'No pets imported yet. Click “Import” to add a .zip package',
enable: 'Enable',
import: 'Import',
@@ -59,9 +41,6 @@ const DICT_EN: Record<LocaleKey, string> = {
listFailed: 'Failed to load pet list',
loading: 'Loading…',
name: 'Pets',
- noPetSelected: 'No pet selected. Please choose your pet in the settings page',
- petDescWhale: BUILTIN_PET_DESC_EN,
- petNameWhale: BUILTIN_PET_NAME,
select: 'Choose',
selected: 'Selected',
setPetFailed: 'Failed to select pet',
@@ -71,8 +50,6 @@ const DICT_EN: Record<LocaleKey, string> = {
tabCodexDesc: 'Import Codex pets from Codex or archives (.zip files supported)',
tabInstalledDesc: 'Pets manage your conversation threads and highlight items that need attention',
toggleFailed: 'Failed to toggle the pet window',
- update: 'Update',
- updateFailed: 'Failed to update preset pet',
wakePet: 'Wake pet',
}
diff --git a/packages/dsh-tauri-pet/src/client/service/pet.ts b/packages/dsh-tauri-pet/src/client/service/pet.ts
index 5eedce16..bb9e0697 100644
--- a/packages/dsh-tauri-pet/src/client/service/pet.ts
+++ b/packages/dsh-tauri-pet/src/client/service/pet.ts
@@ -1,10 +1,8 @@
-import type { PetAsset, PetListItem, PetSource, PetStatus, PresetDownloadProgress, PresetPetItem } from '../types'
+import type { PetAsset, PetListItem, PetSource, PetStatus, PresetPetItem } from '../types'
import { invokeBridgedTauri } from 'dsh-tauri/client'
import {
- CMD_DOWNLOAD_PRESET_PET,
CMD_GET_PET_ASSET,
CMD_GET_PET_STATUS,
- CMD_GET_PRESET_DOWNLOAD_PROGRESS,
CMD_HIDE_PET,
CMD_IMPORT_PET,
CMD_LIST_PETS,
@@ -13,7 +11,6 @@ import {
CMD_SET_PET_ENABLED,
CMD_SET_PET_SIZE,
CMD_SHOW_PET,
- CMD_UPDATE_PRESET_PET,
} from '../constants'
export function fetchPetStatus(): Promise<PetStatus> {
@@ -52,25 +49,7 @@ export function importPet(name: string, data: string): Promise<PetListItem> {
return invokeBridgedTauri<PetListItem>(CMD_IMPORT_PET, { name, data })
}
-/** 预设宠物清单(resources/preset-pets.json + 本机安装状态)。 */
+/** 预设宠物清单(`resources/preset-pets.json`;条目直连远端素材,无安装态)。 */
export function fetchPresetPets(): Promise<PresetPetItem[]> {
return invokeBridgedTauri<PresetPetItem[]>(CMD_LIST_PRESET_PETS)
}
-
-/** 开始下载并安装预设宠物(后台执行;进度用 fetchPresetDownloadProgress 轮询)。 */
-export function downloadPresetPet(id: string): Promise<void> {
- return invokeBridgedTauri<void>(CMD_DOWNLOAD_PRESET_PET, { id })
-}
-
-/**
- * 更新已安装的预设宠物(后台执行;进度用 fetchPresetDownloadProgress 轮询)。
- * 若宠物正在使用,宿主会先强制停用,更新结束后自动重新启用。
- */
-export function updatePresetPet(id: string): Promise<void> {
- return invokeBridgedTauri<void>(CMD_UPDATE_PRESET_PET, { id })
-}
-
-/** 查询预设宠物下载进度。 */
-export function fetchPresetDownloadProgress(id: string): Promise<PresetDownloadProgress> {
- return invokeBridgedTauri<PresetDownloadProgress>(CMD_GET_PRESET_DOWNLOAD_PROGRESS, { id })
-}
diff --git a/packages/dsh-tauri-pet/src/client/store/index.ts b/packages/dsh-tauri-pet/src/client/store/index.ts
index f84c9bab..246569c0 100644
--- a/packages/dsh-tauri-pet/src/client/store/index.ts
+++ b/packages/dsh-tauri-pet/src/client/store/index.ts
@@ -13,12 +13,10 @@ import { createExternalStore } from 'dsh-tauri/client'
export interface PetShared {
/** 最近一次从桌面端读回的桌宠状态缓存(图标绿点与设置页共用)。 */
status: PetStatus | null
- /** 是否存在可用宠物(已安装预设或本地 chat/codex);无可用宠物时侧栏入口图标隐藏。 */
- petsAvailable: boolean
}
/** dsh-tauri 外部 store(getSnapshot 稳定,uSES 安全)。 */
-export const petUiStore = createExternalStore<PetShared>({ status: null, petsAvailable: false })
+export const petUiStore = createExternalStore<PetShared>({ status: null })
let fetchRevision = 0
/** Start a status fetch; only its latest revision may write the initial snapshot. */
export function beginPetStatusFetch(): number {
@@ -47,8 +45,3 @@ export function setPetStatus(status: PetStatus | null): void {
fetchRevision += 1
petUiStore.set(state => (state.status === status ? state : { ...state, status }))
}
-
-/** 写入「是否有可用宠物」快照(侧栏入口图标显隐用)。 */
-export function setPetsAvailable(available: boolean): void {
- petUiStore.set(state => (state.petsAvailable === available ? state : { ...state, petsAvailable: available }))
-}
diff --git a/packages/dsh-tauri-pet/src/client/types/index.ts b/packages/dsh-tauri-pet/src/client/types/index.ts
index 60e01369..3259bde8 100644
--- a/packages/dsh-tauri-pet/src/client/types/index.ts
+++ b/packages/dsh-tauri-pet/src/client/types/index.ts
@@ -24,26 +24,20 @@ export interface PetAsset {
spritesheet: string
}
-/** 预设宠物清单条目(`resources/preset-pets.json` 的展示层投影)。 */
+/**
+ * 预设宠物清单条目(`resources/preset-pets.json` 的展示层投影)。
+ *
+ * 预设不再下载/安装:清单里的条目本身就是桌宠组件的渲染参数(`config` / `uri` /
+ * `ext` 等由 pet 窗口直接消费),设置页只需要展示字段,因此这里只声明投影形状,
+ * Rust 返回的其余字段前端原样忽略。
+ */
export interface PresetPetItem {
desc?: string | null
id: string
image?: string | null
- installed: boolean
+ kind?: 'dsh' | 'codex' | null
name: string
- size_mb?: number | null
- /** 已安装且清单 ref 与安装记录不同(或无记录)→ 可更新。 */
- update_available?: boolean
- /** 当前下载阶段(idle|downloading|extracting|done|failed),跨挂载恢复下载中视图用。 */
- phase?: PresetDownloadProgress['phase'] | null
-}
-
-/** 预设宠物下载进度快照(设置页轮询 `get_preset_download_progress`)。 */
-export interface PresetDownloadProgress {
- phase: 'idle' | 'downloading' | 'extracting' | 'done' | 'failed'
- received: number
- total: number
- error?: string | null
+ size?: number | null
}
export interface WorkspaceItem {
@@ -86,13 +80,9 @@ export interface ConversationInputLeftProps {
}
export type LocaleKey
- = | 'codex'
- | 'collapsePet'
+ = | 'collapsePet'
| 'create'
| 'createFailed'
- | 'download'
- | 'downloadFailed'
- | 'downloading'
| 'emptyImported'
| 'enable'
| 'import'
@@ -100,10 +90,6 @@ export type LocaleKey
| 'listFailed'
| 'loading'
| 'name'
-
- | 'noPetSelected'
- | 'petDescWhale'
- | 'petNameWhale'
| 'select'
| 'selected'
| 'setPetFailed'
@@ -113,6 +99,4 @@ export type LocaleKey
| 'tabCodexDesc'
| 'tabInstalledDesc'
| 'toggleFailed'
- | 'update'
- | 'updateFailed'
| 'wakePet'
diff --git a/packages/dsh-tauri-pet/src/client/utils/availability.test.ts b/packages/dsh-tauri-pet/src/client/utils/availability.test.ts
deleted file mode 100644
index b50be793..00000000
--- a/packages/dsh-tauri-pet/src/client/utils/availability.test.ts
+++ /dev/null
@@ -1,32 +0,0 @@
-import type { PetListItem, PresetPetItem } from '../types'
-import { describe, expect, it } from 'vitest'
-import { hasAvailablePets } from './availability'
-
-function preset(installed: boolean): PresetPetItem {
- return { id: 'maid-deepseek-whale', installed, name: 'Maid DeepSeek Whale' }
-}
-
-function listItem(id: string, source: PetListItem['source']): PetListItem {
- return { id, name: id, source }
-}
-
-describe('hasAvailablePets', () => {
- it('空清单 → false', () => {
- expect(hasAvailablePets([], [], [])).toBe(false)
- })
-
- it('仅有未安装的预设宠物(可下载但不可用)→ false', () => {
- expect(hasAvailablePets([preset(false)], [], [])).toBe(false)
- })
-
- it('已安装的预设宠物 → true', () => {
- expect(hasAvailablePets([preset(true)], [], [])).toBe(true)
- expect(hasAvailablePets([preset(false), preset(true)], [], [])).toBe(true)
- })
-
- it('任意本地 chat/codex 宠物 → true', () => {
- expect(hasAvailablePets([], [listItem('chat-pet', 'chat')], [])).toBe(true)
- expect(hasAvailablePets([], [], [listItem('codex-pet', 'codex')])).toBe(true)
- expect(hasAvailablePets([preset(false)], [listItem('a', 'chat')], [])).toBe(true)
- })
-})
diff --git a/packages/dsh-tauri-pet/src/client/utils/availability.ts b/packages/dsh-tauri-pet/src/client/utils/availability.ts
deleted file mode 100644
index fe585af5..00000000
--- a/packages/dsh-tauri-pet/src/client/utils/availability.ts
+++ /dev/null
@@ -1,14 +0,0 @@
-import type { PetListItem, PresetPetItem } from '../types'
-
-/**
- * 是否存在可直接使用的宠物:已安装的预设宠物(installed)或任意本地 chat/codex
- * 宠物。未安装的预设(仅可下载)不算可用——启用后没有可播放资产,侧栏切换
- * 入口对用户没有意义;无任何可用宠物时侧栏入口图标隐藏。
- */
-export function hasAvailablePets(
- presets: readonly PresetPetItem[],
- chatPets: readonly PetListItem[],
- codexPets: readonly PetListItem[],
-): boolean {
- return presets.some(item => item.installed) || chatPets.length > 0 || codexPets.length > 0
-}
diff --git a/packages/dsh-tauri-pet/src/client/utils/preset-card.test.ts b/packages/dsh-tauri-pet/src/client/utils/preset-card.test.ts
deleted file mode 100644
index c3e9246c..00000000
--- a/packages/dsh-tauri-pet/src/client/utils/preset-card.test.ts
+++ /dev/null
@@ -1,83 +0,0 @@
-import { describe, expect, it } from 'vitest'
-import { progressPercent, resolvePresetCardAction, resolvePresetCardUpdate } from './preset-card'
-
-function progress(phase: PresetDownloadPhase, received = 0, total = 0): { phase: PresetDownloadPhase, received: number, total: number, error?: string | null } {
- return { phase, received, total }
-}
-
-type PresetDownloadPhase = 'idle' | 'downloading' | 'extracting' | 'done' | 'failed'
-
-describe('resolvePresetCardAction', () => {
- const maid = { id: 'maid-deepseek-whale', installed: false, phase: 'idle' as const }
-
- it('已选仅限已安装的当前宠物;未安装的当前宠物(默认预设)给出下载入口', () => {
- // 内置归一 id 与预设卡 id 相同:新装环境默认宠物未下载,卡片不能显示已选(issue #401)。
- expect(resolvePresetCardAction(maid, 'maid-deepseek-whale', progress('downloading'))).toBe('downloading')
- expect(resolvePresetCardAction(maid, 'maid-deepseek-whale', null)).toBe('download')
- expect(resolvePresetCardAction({ ...maid, installed: true }, 'maid-deepseek-whale', null)).toBe('selected')
- expect(resolvePresetCardAction({ ...maid, installed: true }, 'maid-deepseek-whale', progress('downloading'))).toBe('selected')
- })
-
- it('激活 id 为空串(全新安装无默认选择):未安装给出下载、已安装给出启用', () => {
- // 不再默认选中内置宠物;active_pet 为空 → 任何预设卡都不显示「已选」。
- expect(resolvePresetCardAction(maid, '', null)).toBe('download')
- expect(resolvePresetCardAction({ ...maid, installed: true }, '', null)).toBe('enable')
- })
-
- it('下载/解压中显示 downloading,不因已安装而跳到 enable', () => {
- expect(resolvePresetCardAction(maid, 'other', progress('downloading'))).toBe('downloading')
- expect(resolvePresetCardAction(maid, 'other', progress('extracting'))).toBe('downloading')
- expect(resolvePresetCardAction({ ...maid, installed: true }, 'other', progress('downloading'))).toBe('downloading')
- })
-
- it('无轮询进度时用清单 phase 恢复下载中视图(跨挂载场景)', () => {
- expect(resolvePresetCardAction({ ...maid, phase: 'downloading' }, 'other', null)).toBe('downloading')
- expect(resolvePresetCardAction({ ...maid, phase: 'extracting' }, 'other', null)).toBe('downloading')
- expect(resolvePresetCardAction({ ...maid, phase: 'done' }, 'other', null)).toBe('download')
- expect(resolvePresetCardAction({ ...maid, phase: 'failed' }, 'other', null)).toBe('download')
- })
-
- it('已安装且非当前 → enable;未安装 → download', () => {
- expect(resolvePresetCardAction({ ...maid, installed: true }, 'other', null)).toBe('enable')
- expect(resolvePresetCardAction(maid, 'other', null)).toBe('download')
- expect(resolvePresetCardAction(maid, 'other', progress('done'))).toBe('download')
- expect(resolvePresetCardAction(maid, 'other', progress('failed'))).toBe('download')
- })
-})
-
-describe('resolvePresetCardUpdate', () => {
- const maid = { id: 'maid-deepseek-whale', installed: true, update_available: true, phase: 'idle' as const }
-
- it('已安装且可更新 → 显示更新按钮', () => {
- expect(resolvePresetCardUpdate(maid, null)).toBe(true)
- expect(resolvePresetCardUpdate(maid, progress('done'))).toBe(true)
- })
-
- it('未安装 / 清单未提示更新 → 不显示', () => {
- expect(resolvePresetCardUpdate({ ...maid, installed: false }, null)).toBe(false)
- expect(resolvePresetCardUpdate({ ...maid, update_available: false }, null)).toBe(false)
- expect(resolvePresetCardUpdate({ ...maid, update_available: undefined }, null)).toBe(false)
- })
-
- it('下载/解压中 → 隐藏更新按钮(避免与替换安装冲突)', () => {
- expect(resolvePresetCardUpdate(maid, progress('downloading'))).toBe(false)
- expect(resolvePresetCardUpdate(maid, progress('extracting'))).toBe(false)
- // 清单 phase 兜底(跨挂载恢复下载中视图)。
- expect(resolvePresetCardUpdate({ ...maid, phase: 'downloading' }, null)).toBe(false)
- expect(resolvePresetCardUpdate({ ...maid, phase: 'extracting' }, null)).toBe(false)
- })
-})
-
-describe('progressPercent', () => {
- it('已知总量返回截断百分比', () => {
- expect(progressPercent(progress('downloading', 50, 200))).toBe(25)
- expect(progressPercent(progress('downloading', 200, 200))).toBe(100)
- expect(progressPercent(progress('downloading', 300, 200))).toBe(100)
- })
-
- it('未知总量:下载早期与解压中均返回 null(不确定进度)', () => {
- expect(progressPercent(progress('downloading'))).toBeNull()
- expect(progressPercent(progress('extracting'))).toBeNull()
- expect(progressPercent(progress('idle'))).toBe(0)
- })
-})
diff --git a/packages/dsh-tauri-pet/src/client/utils/preset-card.ts b/packages/dsh-tauri-pet/src/client/utils/preset-card.ts
deleted file mode 100644
index 9cf6040c..00000000
--- a/packages/dsh-tauri-pet/src/client/utils/preset-card.ts
+++ /dev/null
@@ -1,51 +0,0 @@
-import type { PresetDownloadProgress, PresetPetItem } from '../types'
-
-/**
- * 预设宠物卡片右侧动作的纯状态机。
- *
- * 优先级:已选(selected)> 下载/解压中(downloading)> 已安装(enable)>
- * 未安装(download)。与设置页 `presetCardAction` 一一对应。
- *
- * 已选必须同时满足「已安装且为当前激活宠物」:预设卡 id(maid-deepseek-whale)与
- * 激活 id 相同但产物尚未下载,或全新安装 active_pet 为空串(未选择任何宠物)时,
- * 卡片必须给出下载入口,而不是显示已选禁用(issue #401)。
- *
- * 下载中状态有两个来源:`progress.phase`(进行中的轮询快照)与 `item.phase`
- * (`list_preset_pets` 返回的进程内注册表阶段,跨挂载恢复下载中视图用——组件
- * 卸载后重进设置页时,轮询未启动、`progress` 为 null,但清单已带 phase)。
- */
-export function resolvePresetCardAction(
- item: Pick<PresetPetItem, 'id' | 'installed' | 'phase'>,
- active: string,
- progress: PresetDownloadProgress | null | undefined,
-): 'download' | 'downloading' | 'enable' | 'selected' {
- if (item.installed && item.id === active)
- return 'selected'
- const phase = progress?.phase ?? item.phase
- if (phase === 'downloading' || phase === 'extracting')
- return 'downloading'
- if (item.installed)
- return 'enable'
- return 'download'
-}
-
-/**
- * 是否显示「更新」按钮:已安装、清单提示可更新、且不在下载/解压中。
- * 更新按钮位于主动作(已选/启用)左侧;下载中时隐藏,避免与替换安装冲突。
- */
-export function resolvePresetCardUpdate(
- item: Pick<PresetPetItem, 'installed' | 'update_available' | 'phase'>,
- progress: PresetDownloadProgress | null | undefined,
-): boolean {
- if (!item.installed || item.update_available !== true)
- return false
- const phase = progress?.phase ?? item.phase
- return phase !== 'downloading' && phase !== 'extracting'
-}
-
-/** 把下载进度渲染成百分比;未知总量(下载早期/解压中)返回 null 表示不确定进度。 */
-export function progressPercent(progress: PresetDownloadProgress): number | null {
- if (progress.total > 0)
- return Math.min(100, Math.round((progress.received / progress.total) * 100))
- return progress.phase === 'extracting' || progress.phase === 'downloading' ? null : 0
-}
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 841c80b6..2b73cbdb 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -149,9 +149,15 @@ catalogs:
'@overlastic/react':
specifier: ^0.9.0
version: 0.9.0
+ '@reause/core':
+ specifier: ^0.1.4
+ version: 0.1.4
'@tanstack/react-query':
specifier: ^5.101.4
version: 5.101.4
+ dsh-pet-component:
+ specifier: ^0.1.1
+ version: 0.1.1
i18next:
specifier: ^26.3.6
version: 26.3.6
@@ -186,6 +192,9 @@ catalogs:
'@tauri-apps/cli':
specifier: ^2.11.4
version: 2.11.4
+ '@tauri-apps/plugin-http':
+ specifier: ^2.6.0
+ version: 2.6.0
testing:
vitest:
specifier: ^4.1.11
@@ -287,12 +296,21 @@ importers:
'@overlastic/react':
specifier: catalog:runtime
+ '@reause/core':
+ specifier: catalog:runtime
+ version: 0.1.4([email protected])
'@tanstack/react-query':
specifier: catalog:runtime
version: 5.101.4([email protected])
'@tauri-apps/api':
specifier: catalog:tauri
version: 2.11.1
+ '@tauri-apps/plugin-http':
+ specifier: catalog:tauri
+ version: 2.6.0
+ dsh-pet-component:
+ specifier: catalog:runtime
i18next:
specifier: catalog:runtime
version: 26.3.6([email protected])
@@ -485,7 +503,7 @@ importers:
version: 1.5.1
unstorage:
specifier: catalog:utils
- version: 1.17.5
+ version: 1.17.5([email protected])
devDependencies:
'@deepseek-ai/dsh-api-session-controller':
specifier: catalog:dsh
@@ -2744,6 +2762,58 @@ packages:
peerDependencies:
react: ^16.8.0 || ^17.0.0-rc.1 || ^18.0.0 || ^19.0.0-rc.1
+ '@reause/[email protected]':
+ resolution: {integrity: sha512-NkEzEvYyFpWND8H2yQ3e3iikifUqhMObdLXe1xNiGbfcZLDsExljt5SF/cCEgx9V4S/HLeNpcPnQU/yL7Y8Czw==}
+ peerDependencies:
+ react: '>=18'
+
+ '@reause/[email protected]':
+ resolution: {integrity: sha512-1UzzEb6lLbH5SYKnNDLyUONd1+dT8RtJH6W71fWXwmU/6jiZSFNbOU8GNyVnxDOWkBokPe4/5kIoo7YHEePdfQ==}
+ peerDependencies:
+ async-validator: ^4
+ axios: ^1
+ change-case: ^5
+ drauu: ^1
+ focus-trap: ^7 || ^8
+ fuse.js: ^7
+ idb-keyval: ^6
+ jwt-decode: ^4
+ nprogress: ^0.2
+ qrcode: ^1.5
+ react: '>=18'
+ sortablejs: ^1
+ universal-cookie: ^7 || ^8
+ peerDependenciesMeta:
+ async-validator:
+ optional: true
+ axios:
+ optional: true
+ change-case:
+ optional: true
+ drauu:
+ optional: true
+ focus-trap:
+ optional: true
+ fuse.js:
+ optional: true
+ idb-keyval:
+ optional: true
+ jwt-decode:
+ optional: true
+ nprogress:
+ optional: true
+ qrcode:
+ optional: true
+ sortablejs:
+ optional: true
+ universal-cookie:
+ optional: true
+
+ '@reause/[email protected]':
+ resolution: {integrity: sha512-RyCfBgBq4K7dVlyI1c+MPgFk5f+OkWIccWhkPwZqfH4zjzss3Vz3egsLS0rvS6IYgxw6vA3IKN+MoyD6+1a22g==}
+ peerDependencies:
+ react: '>=18'
+
'@rolldown/[email protected]':
resolution: {integrity: sha512-Ok9V8o7o6YfSdTTYA/uHH30r3YtOxLD6G3wih/U9DO0ucBBFq8WPt/DslU53OgfteLRHITZny9N/qCUxMf9kjQ==}
engines: {node: ^20.19.0 || >=22.12.0}
@@ -3318,6 +3388,9 @@ packages:
engines: {node: '>= 10'}
hasBin: true
+ '@tauri-apps/[email protected]':
+ resolution: {integrity: sha512-QYXwbGb4hQ9/8Riv/ejU/kPFFnbBIrBcWwV1LIXv2xBKfoj8lkWfGkd9pkCSsBI/pljPtz+IPqfrE3t3bVl3mg==}
+
resolution: {integrity: sha512-F3fo1MYrRJYL3zER0OUOmkutjr1Vp23m7OsSgp7nq4SP6OqX6C/56XFIPAl5bt3zaBRjmW7SGz3u/6LwFpYcOg==}
@@ -3871,6 +3944,11 @@ packages:
resolution: {integrity: sha512-nI4U3TottKAcAD9LLud4Cb7b2QztQMUEfHbvhTH09bqXTxnSie8WnjPALV/WMCrJZ6UV/qHJ6L03OqO3LcdYZw==}
engines: {node: '>=12'}
+ resolution: {integrity: sha512-M2bDCPP3Nva2acdFgu1c8BD5UZ9v0rUfTVrUm7yhSDWUSsn+x1dLtgbU//65JiDHUwh9+r5HdRal0rIJZGyIWg==}
+ peerDependencies:
+ react: ^19.0.0
+
resolution: {integrity: sha512-bihc7jPC90VrosXNzK0LTE2cuLP6jr0Ro8jk+kMugHReJVLIpHz/xadeq3MhuwyO4TD4OA3L1Q8pBBFRc08Tsw==}
engines: {node: '>=20.19.0'}
@@ -4348,6 +4426,9 @@ packages:
typescript:
optional: true
+ resolution: {integrity: sha512-um+2dgAWmYsu615EXpWVwSmapJhON0G43t3Ka/EVaohzPQXSMqKEqeDK/oIW3Ow+BXaF2PvSc+oBTFp793A5Ow==}
+
resolution: {integrity: sha512-SLX4H/vtcYlYnL7XqnuJKHU7Z8517TgsW9nmQiGOgMCjQ8V/deLYu6bEmbGoXe7WMMhc9+EUGyFFneHja8KabA==}
engines: {node: '>=18'}
@@ -8469,6 +8550,23 @@ snapshots:
dependencies:
react: 19.2.8
+ dependencies:
+ '@reause/shared': 0.1.4([email protected])
+ react: 19.2.8
+
+ dependencies:
+ '@reause/shared': 0.1.4([email protected])
+ react: 19.2.8
+ optionalDependencies:
+ change-case: 5.4.4
+ idb-keyval: 6.3.0
+
+ dependencies:
+ react: 19.2.8
+
'@rolldown/[email protected]':
optional: true
@@ -8859,6 +8957,10 @@ snapshots:
'@tauri-apps/cli-win32-ia32-msvc': 2.11.4
'@tauri-apps/cli-win32-x64-msvc': 2.11.4
+ '@tauri-apps/[email protected]':
+ dependencies:
+ '@tauri-apps/api': 2.11.1
+
dependencies:
tslib: 2.8.1
@@ -9459,6 +9561,26 @@ snapshots:
+ dependencies:
+ '@reause/core': 0.1.4([email protected])
+ '@reause/integrations': 0.1.4([email protected])([email protected])([email protected])
+ css-render: 0.15.14
+ idb-keyval: 6.3.0
+ react: 19.2.8
+ transitivePeerDependencies:
+ - async-validator
+ - axios
+ - change-case
+ - drauu
+ - focus-trap
+ - fuse.js
+ - jwt-decode
+ - nprogress
+ - qrcode
+ - sortablejs
+ - universal-cookie
+
optionalDependencies:
oxc-resolver: 11.24.2
@@ -10064,6 +10186,8 @@ snapshots:
optionalDependencies:
typescript: 5.8.3
+
dependencies:
reserved-identifiers: 1.2.0
@@ -11458,7 +11582,7 @@ snapshots:
optionalDependencies:
synckit: 0.11.13
dependencies:
anymatch: 3.1.3
chokidar: 5.0.0
@@ -11468,6 +11592,8 @@ snapshots:
node-fetch-native: 1.6.7
ofetch: 1.5.1
ufo: 1.6.4
+ optionalDependencies:
+ idb-keyval: 6.3.0
dependencies:
diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yaml
index 0a4cc83b..23f7feba 100644
--- a/pnpm-workspace.yaml
+++ b/pnpm-workspace.yaml
@@ -80,7 +80,11 @@ catalogs:
'@heroui/react': ^3.2.4
'@heroui/styles': ^3.2.4
'@overlastic/react': ^0.9.0
+ '@reause/core': ^0.1.4
'@tanstack/react-query': ^5.101.4
+ # 统一桌宠组件(dsh-pet / Codex 两套协议一个 <Pet>):预设宠物直连远程素材,
+ # 不再下载到本地,动画池/双视频缓冲/雪碧图/IndexedDB 缓存全部由它接管。
+ dsh-pet-component: ^0.1.1
i18next: ^26.3.6
react: ^19.2.8
react-dom: ^19.2.8
@@ -94,6 +98,9 @@ catalogs:
tauri:
'@tauri-apps/api': ^2.11.1
'@tauri-apps/cli': ^2.11.4
+ # 桌宠窗口用插件版 fetch 拉取远程宠物素材:请求走 Rust,绕开 githubusercontent
+ # 的 CORS 限制(远端不返回 Access-Control-Allow-Origin)。
+ '@tauri-apps/plugin-http': ^2.6.0
# 测试
testing:
vitest: ^4.1.11
diff --git a/src-tauri/Cargo.lock b/src-tauri/Cargo.lock
index 2f430d7f..0d8b6f80 100644
--- a/src-tauri/Cargo.lock
+++ b/src-tauri/Cargo.lock
@@ -16,7 +16,7 @@ checksum = "b169f7a6d4742236a0a00c541b845991d0ac43e546831af1249753ab4c3aa3a0"
dependencies = [
"cfg-if",
"cipher",
- "cpufeatures",
+ "cpufeatures 0.2.17",
]
[[package]]
@@ -90,7 +90,7 @@ dependencies = [
"enumflags2",
"futures-channel",
"futures-util",
- "rand",
+ "rand 0.9.5",
"raw-window-handle",
"serde",
"serde_repr",
@@ -580,6 +580,23 @@ version = "1.0.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801"
+[[package]]
+name = "cfg_aliases"
+version = "0.2.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f079e83a288787bcd14a6aea84cee5c87a67c5a3e660c30f557a3d24761b3527"
+
+[[package]]
+name = "chacha20"
+version = "0.10.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "65c35e4b699c7e15ccbe7ee35c005e4fc0a278d22238a2857e6ce2dadeda1b06"
+dependencies = [
+ "cfg-if",
+ "cpufeatures 0.3.1",
+ "rand_core 0.10.1",
+]
+
[[package]]
name = "chrono"
version = "0.4.45"
@@ -657,10 +674,29 @@ version = "0.18.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1a373e3602691c3cdea496d2f0ee5935151e6168fe87739483c463db1b2f2f87"
dependencies = [
+ "percent-encoding",
"time",
"version_check",
]
+[[package]]
+name = "cookie_store"
+version = "0.22.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "15b2c103cf610ec6cae3da84a766285b42fd16aad564758459e6ecf128c75206"
+dependencies = [
+ "cookie",
+ "document-features",
+ "idna",
+ "log",
+ "publicsuffix",
+ "serde",
+ "serde_derive",
+ "serde_json",
+ "time",
+ "url",
+]
+
[[package]]
name = "core-foundation"
version = "0.7.0"
@@ -760,6 +796,15 @@ dependencies = [
"libc",
]
+[[package]]
+name = "cpufeatures"
+version = "0.3.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5ca28b0ae3115b884660db4118d803791fd6756b6e88f39c0f3f7859060d7566"
+dependencies = [
+ "libc",
+]
+
[[package]]
name = "crc32fast"
version = "1.5.0"
@@ -892,6 +937,12 @@ dependencies = [
"syn 2.0.119",
]
+[[package]]
+name = "data-url"
+version = "0.3.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "be1e0bca6c3637f992fc1cc7cbc52a78c1ef6db076dbf1059c4323d6a2048376"
+
[[package]]
name = "dbus"
version = "0.9.12"
@@ -935,6 +986,7 @@ dependencies = [
"tauri-build",
"tauri-plugin-autostart",
"tauri-plugin-fs",
+ "tauri-plugin-http",
"tauri-plugin-notification",
"tauri-plugin-opener",
"tauri-plugin-single-instance",
@@ -1121,6 +1173,15 @@ dependencies = [
"syn 2.0.119",
]
+[[package]]
+name = "document-features"
+version = "0.2.12"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d4b8a88685455ed29a21542a33abd9cb6510b6b129abadabdcef0f4c55bc8f61"
+dependencies = [
+ "litrs",
+]
+
[[package]]
name = "dom_query"
version = "0.27.0"
@@ -1650,8 +1711,10 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0"
dependencies = [
"cfg-if",
+ "js-sys",
"libc",
"wasi",
+ "wasm-bindgen",
]
[[package]]
@@ -1673,8 +1736,11 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099"
dependencies = [
"cfg-if",
+ "js-sys",
"libc",
"r-efi 6.0.0",
+ "rand_core 0.10.1",
+ "wasm-bindgen",
]
[[package]]
@@ -1992,6 +2058,7 @@ dependencies = [
"tokio",
"tokio-rustls",
"tower-service",
+ "webpki-roots",
]
[[package]]
@@ -2515,6 +2582,12 @@ version = "0.8.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "47d9d19d1d6efa0109d2f65ff4c85cddd50bd572e5a00127ab10987290bcefae"
+[[package]]
+name = "litrs"
+version = "1.0.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "11d3d7f243d5c5a8b9bb5d6dd2b1602c0cb0b9db1621bafc7ed66e35ff9fe092"
+
[[package]]
name = "lock_api"
version = "0.4.14"
@@ -2530,6 +2603,12 @@ version = "0.4.33"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0ceec5bc11778974d1bcb055b18002eba7f4b3518b6a0081b3af5f21666da9ad"
+[[package]]
+name = "lru-slab"
+version = "0.1.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "112b39cec0b298b6c1999fee3e31427f74f676e4cb9879ed1a121b43661a4154"
+
[[package]]
name = "mac-notification-sys"
version = "0.6.15"
@@ -3390,6 +3469,22 @@ dependencies = [
"unicode-ident",
]
+[[package]]
+name = "psl-types"
+version = "2.0.11"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "33cb294fe86a74cbcf50d4445b37da762029549ebeea341421c7c70370f86cac"
+
+[[package]]
+name = "publicsuffix"
+version = "2.3.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6f42ea446cab60335f76979ec15e12619a2165b5ae2c12166bef27d283a9fadf"
+dependencies = [
+ "idna",
+ "psl-types",
+]
+
[[package]]
name = "pxfm"
version = "0.1.30"
@@ -3411,6 +3506,62 @@ dependencies = [
"memchr",
]
+[[package]]
+name = "quinn"
+version = "0.11.11"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0c1a41e437b6bbd489372cd4971de128e85c855f56c57f283d20ff016cf7c0a8"
+dependencies = [
+ "bytes",
+ "cfg_aliases",
+ "pin-project-lite",
+ "quinn-proto",
+ "quinn-udp",
+ "rustc-hash",
+ "rustls",
+ "socket2",
+ "thiserror 2.0.20",
+ "tokio",
+ "tracing",
+ "web-time",
+]
+
+[[package]]
+name = "quinn-proto"
+version = "0.11.17"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "04759210543be93709136e28212294a659ef5001836ff4eab4d663e4529bba83"
+dependencies = [
+ "bytes",
+ "getrandom 0.4.3",
+ "lru-slab",
+ "rand 0.10.2",
+ "rand_pcg",
+ "ring",
+ "rustc-hash",
+ "rustls",
+ "rustls-pki-types",
+ "slab",
+ "thiserror 2.0.20",
+ "tinyvec",
+ "tracing",
+ "web-time",
+]
+
+[[package]]
+name = "quinn-udp"
+version = "0.5.15"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "35a133f956daabe89a61a685c2649f13d82d5aa4bd5d12d1277e1072a21c0694"
+dependencies = [
+ "cfg_aliases",
+ "libc",
+ "once_cell",
+ "socket2",
+ "tracing",
+ "windows-sys 0.61.2",
+]
+
[[package]]
name = "quote"
version = "1.0.47"
@@ -3442,6 +3593,17 @@ dependencies = [
"rand_core 0.9.5",
]
+[[package]]
+name = "rand"
+version = "0.10.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c7f5fa3a058cd35567ef9bfa5e75732bee0f9e4c55fa90477bef2dfcdbc4be80"
+dependencies = [
+ "chacha20",
+ "getrandom 0.4.3",
+ "rand_core 0.10.1",
+]
+
[[package]]
name = "rand_chacha"
version = "0.9.0"
@@ -3467,6 +3629,21 @@ dependencies = [
"getrandom 0.3.4",
]
+[[package]]
+name = "rand_core"
+version = "0.10.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "63b8176103e19a2643978565ca18b50549f6101881c443590420e4dc998a3c69"
+
+[[package]]
+name = "rand_pcg"
+version = "0.10.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "caa0f4137e1c0a72f4c651489402276c8e8e1cf081f3b0ba156d2cbeef09e86a"
+dependencies = [
+ "rand_core 0.10.1",
+]
+
[[package]]
name = "raw-window-handle"
version = "0.6.2"
@@ -3597,6 +3774,8 @@ checksum = "eddd3ca559203180a307f12d114c268abf583f59b03cb906fd0b3ff8646c1147"
dependencies = [
"base64 0.22.1",
"bytes",
+ "cookie",
+ "cookie_store",
"encoding_rs",
"futures-core",
"futures-util",
@@ -3614,6 +3793,8 @@ dependencies = [
"native-tls",
"percent-encoding",
"pin-project-lite",
+ "quinn",
+ "rustls",
"rustls-pki-types",
"serde",
"serde_json",
@@ -3621,6 +3802,7 @@ dependencies = [
"sync_wrapper",
"tokio",
"tokio-native-tls",
+ "tokio-rustls",
"tokio-util",
"tower",
"tower-http",
@@ -3630,6 +3812,7 @@ dependencies = [
"wasm-bindgen-futures",
"wasm-streams 0.4.2",
"web-sys",
+ "webpki-roots",
]
[[package]]
@@ -3739,6 +3922,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0283386ce02abc0151e1761d08802dfe86c173b0b494af5cbc086574e453da06"
dependencies = [
"once_cell",
+ "ring",
"rustls-pki-types",
"rustls-webpki",
"subtle",
@@ -3751,6 +3935,7 @@ version = "1.15.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2f4925028c7eb5d1fcdaf196971378ed9d2c1c4efc7dc5d011256f76c99c0a96"
dependencies = [
+ "web-time",
"zeroize",
]
@@ -4101,7 +4286,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a978451301f4db1d02937a4ab3ccce137717b81826e79b7d49ffe3244a13c3b8"
dependencies = [
"cfg-if",
- "cpufeatures",
+ "cpufeatures 0.2.17",
"digest",
]
@@ -4112,7 +4297,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283"
dependencies = [
"cfg-if",
- "cpufeatures",
+ "cpufeatures 0.2.17",
"digest",
]
@@ -4604,6 +4789,30 @@ dependencies = [
"url",
]
+[[package]]
+name = "tauri-plugin-http"
+version = "2.5.9"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b5bd512048e1985b7ec78f96d99083e2ddaf7e0d906b2b63c44ce5bb8b894067"
+dependencies = [
+ "bytes",
+ "cookie_store",
+ "data-url",
+ "http",
+ "regex",
+ "reqwest 0.12.28",
+ "schemars 0.8.22",
+ "serde",
+ "serde_json",
+ "tauri",
+ "tauri-plugin",
+ "tauri-plugin-fs",
+ "thiserror 2.0.20",
+ "tokio",
+ "url",
+ "urlpattern",
+]
+
[[package]]
name = "tauri-plugin-notification"
version = "2.3.3"
@@ -4612,7 +4821,7 @@ checksum = "01fc2c5ff41105bd1f7242d8201fdf3efd70749b82fa013a17f2126357d194cc"
dependencies = [
"log",
"notify-rust",
- "rand",
+ "rand 0.9.5",
"serde",
"serde_json",
"serde_repr",
@@ -5648,6 +5857,16 @@ dependencies = [
"wasm-bindgen",
]
+[[package]]
+name = "web-time"
+version = "1.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5a6580f308b1fad9207618087a65c04e7a10bc77e02c8e84e9b00dd4b12fa0bb"
+dependencies = [
+ "js-sys",
+ "wasm-bindgen",
+]
+
[[package]]
name = "web_atoms"
version = "0.2.6"
@@ -5704,6 +5923,15 @@ dependencies = [
"system-deps",
]
+[[package]]
+name = "webpki-roots"
+version = "1.0.9"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7dcd9d09a39985f5344844e66b0c530a33843579125f23e21e9f0f220850f22a"
+dependencies = [
+ "rustls-pki-types",
+]
+
[[package]]
name = "webview2-com"
version = "0.38.2"
diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.toml
index 71e3a604..dc3501e6 100644
--- a/src-tauri/Cargo.toml
+++ b/src-tauri/Cargo.toml
@@ -32,6 +32,8 @@ tauri-plugin-fs = "2"
tauri-plugin-store = "2"
tauri-plugin-notification = "2"
tauri-plugin-autostart = "2"
+# 桌宠素材直连远端:插件版 HTTP 从 Rust 发起请求,绕开 githubusercontent 的 CORS。
+tauri-plugin-http = "2"
image = { version = "0.25", default-features = false, features = [ "png" ] }
arboard = { version = "3", features = [ "wayland-data-control" ] }
base64 = "0.22"
diff --git a/src-tauri/capabilities/default.json b/src-tauri/capabilities/default.json
index bd8a1f20..49bb98fd 100644
--- a/src-tauri/capabilities/default.json
+++ b/src-tauri/capabilities/default.json
@@ -32,6 +32,14 @@
"opener:allow-open-url",
"opener:allow-default-urls",
"opener:allow-reveal-item-in-dir",
- "store:default"
+ "store:default",
+ {
+ "identifier": "http:default",
+ "allow": [
+ {
+ "url": "https://*.githubusercontent.com/*"
+ }
+ ]
+ }
]
}
diff --git a/src-tauri/resources/preset-pets.json b/src-tauri/resources/preset-pets.json
index e2d723e5..f0616db1 100644
--- a/src-tauri/resources/preset-pets.json
+++ b/src-tauri/resources/preset-pets.json
@@ -4,17 +4,16 @@
"name": "Maid DeepSeek Whale",
"desc": "一只小小的七比蓝头发的鲸鱼女仆Codex宠物,穿着海军蓝裙子,白色褶边,蓝眼睛,侧鳍和鲸鱼尾巴。",
"image": "https://raw.githubusercontent.com/PC2005-cloud/dsh-pet/e1ff8c1e4001878cbb80441262d530e16541f138/dsh-pet/assets/preview/daiji-huxi-xiuxian.gif",
- "repo": "https://github.com/PC2005-cloud/dsh-pet",
- "ref": "e1ff8c1e4001878cbb80441262d530e16541f138",
- "assets": "dsh-pet/assets",
- "sizeMb": 113,
- "platforms": {
- "macos": {
- "repo": "https://github.com/dsh-tauri-desk/dsh-pet-mov",
- "ref": "be0f3bb494cb71a4c73f916c0b92d25a3ab4d002",
- "assets": "",
- "sizeMb": 79
- }
+ "kind": "dsh",
+ "size": 220,
+ "config": "https://raw.githubusercontent.com/PC2005-cloud/dsh-pet/e1ff8c1e4001878cbb80441262d530e16541f138/dsh-pet/assets/config.jsonc",
+ "uri": {
+ "default": "https://raw.githubusercontent.com/PC2005-cloud/dsh-pet/e1ff8c1e4001878cbb80441262d530e16541f138/dsh-pet/assets/webm",
+ "mac": "https://raw.githubusercontent.com/dsh-tauri-desk/dsh-pet-mov/be0f3bb494cb71a4c73f916c0b92d25a3ab4d002/mov"
+ },
+ "ext": {
+ "default": "webm",
+ "mac": "mov"
}
}
]
diff --git a/src-tauri/src/bridge/pet.rs b/src-tauri/src/bridge/pet.rs
index e24c9df4..b8994669 100644
--- a/src-tauri/src/bridge/pet.rs
+++ b/src-tauri/src/bridge/pet.rs
@@ -140,8 +140,9 @@ pub struct PetAsset {
}
/// 将缺省、旧版未限定 id 或非法选择归一化为空字符串(未选择任何宠物)。
-/// 合法值:预设宠物 id(~/.dsh/pets 目录,安全字符集)或来源限定 id。
-/// 注意:不再默认给内置宠物 —— 全新安装下 active_pet 为空,需用户先下载再启用。
+/// 合法值:预设宠物 id(`resources/preset-pets.json` 的安全字符集)或来源限定 id。
+/// 注意:不再默认给内置宠物 —— 全新安装下 active_pet 为空,由用户在设置页主动启用
+/// (预设条目直连远端素材,启用即用,无需任何安装步骤)。
fn normalize_active_pet(active_pet: Option<&str>) -> String {
let Some(id) = active_pet.map(str::trim).filter(|id| !id.is_empty()) else {
return String::new();
diff --git a/src-tauri/src/bridge/preset_pet.rs b/src-tauri/src/bridge/preset_pet.rs
index 64f8f30a..80493cfc 100644
--- a/src-tauri/src/bridge/preset_pet.rs
+++ b/src-tauri/src/bridge/preset_pet.rs
@@ -1,205 +1,89 @@
-//! bridge/preset_pet.rs — 预设宠物清单、下载与安装。
+//! bridge/preset_pet.rs — 预设宠物清单(`resources/preset-pets.json`)。
//!
-//! 预设宠物(preset pet)不再随 `dsh-tauri-pet` 包内置媒体资源,而是由
-//! `resources/preset-pets.json` 登记远端仓库与资源子目录,用户从设置页「下载」
-//! 后安装到 DSH 数据目录的 pets 目录(`~/.dsh/pets`,debug 为 `~/.dsh.dev/pets`)。
+//! 预设宠物不再下载到本地:清单里的条目本身就是 `dsh-pet-component` 的
+//! `<Pet>` 渲染参数(`config` / `uri` / `ext` / `kind` / `size`),pet 窗口按
+//! 当前激活 id 取到条目后直连远端素材播放(macOS 用 `uri.mac` / `ext.mac`
+//! 指向 HEVC-with-Alpha 的 `.mov` 素材:WKWebView 不认 VP9-alpha WebM)。
//!
-//! 下载流程(全部在后台任务执行,设置页通过进度轮询感知):
-//! 1. 按清单条目构造 `https://codeload.github.com/{owner}/{repo}/tar.gz/{ref}`
-//! 下载整个仓库 tarball(带 ghfast.top 镜像兜底),进度写入进程内注册表;
-//! 2. 只解压清单 `assets` 子目录下的条目(如 `dsh-pet/assets/`),跳过其余仓库
-//! 文件(源码、脚本等一律不落盘);
-//! 3. 校验解压产物含可解析的 `config.jsonc`(JSONC 协议),随后 staging 原子
-//! rename 到 `pets/<id>`;
-//! 4. 失败只清理本次 staging 与临时 tarball,不触碰其它宠物。
-//!
-//! 安全约束与 `import_pet` 同一纪律:拒绝 traversal/绝对路径/反斜杠/冒号、
-//! symlink/特殊条目、条目数/单文件/总量上限、全局互斥串行、staging 原子安装。
-//!
-//! 平台差异(issue #434):macOS 的 WKWebView 解码 VP9-alpha WebM 时会丢弃 alpha
-//! 平面,透明区域渲染成不透明黑色且不触发 error 事件。因此 macOS 通过清单 `platforms`
-//! 覆盖块改从 `dsh-tauri-desk/dsh-pet-mov`(只保留 `config.jsonc` + `mov/`)下载
-//! HEVC-with-Alpha `.mov`,其余平台继续用上游 WebM;协议层同时接受 `mov/` 子目录与
-//! `.mov` 扩展名,`get_preset_pet_assets` 按目录存在性自动选源。
+//! 于是本模块只剩两件事,全部与「下载/解压/安装」无关:
+//! 1. 定位并读取随安装包分发的清单;
+//! 2. 校验形状(id 安全 + 唯一、地址非空、kind 合法)后原样交给前端。
-use crate::config;
-use crate::desktop::pet as pet_window;
-use futures_util::StreamExt;
use serde::{Deserialize, Serialize};
-use serde_json::Value;
-use std::collections::{BTreeMap, HashMap, HashSet};
+use std::collections::HashSet;
use std::fs;
-use std::io::{Read, Seek, SeekFrom, Write};
-use std::path::{Component, Path, PathBuf};
-use std::sync::{Mutex, OnceLock};
-use std::time::{SystemTime, UNIX_EPOCH};
-use tauri::{
- http::{header::CONTENT_LENGTH, Method, Request, Response, StatusCode},
- AppHandle, Manager,
-};
-use tokio::io::AsyncWriteExt;
+use std::path::PathBuf;
+use tauri::{AppHandle, Manager};
/// 预设宠物清单文件名(随安装包分发,见 `tauri.conf.json` 的 bundle.resources)。
const PRESET_PETS_FILE: &str = "preset-pets.json";
-/// 单个预设宠物包解压后的总字节上限(dsh-pet 资产 ~113 MiB,留足余量)。
-const PET_PRESET_MAX_UNCOMPRESSED_BYTES: u64 = 256 * 1024 * 1024;
-/// tarball 条目数上限。
-const PET_PRESET_MAX_ENTRIES: usize = 2048;
-/// 单文件解压上限。
-const PET_PRESET_MAX_FILE_BYTES: u64 = 32 * 1024 * 1024;
-/// 配置读取上限(与内置配置同一档位)。
-const PET_PRESET_CONFIG_MAX_BYTES: u64 = 256 * 1024;
-/// 下载客户端 User-Agent(与 `service::download` 一致,避免被 GitHub 拒绝)。
-const PET_PRESET_USER_AGENT: &str =
- "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (deepseek-harness-desktop)";
/// 清单条目(`resources/preset-pets.json` 的一个元素)。
-#[derive(Debug, Clone, Deserialize)]
-#[serde(rename_all = "camelCase", deny_unknown_fields)]
-struct PresetPetSpec {
- id: String,
- name: String,
- #[serde(default)]
- desc: Option<String>,
- /// 浏览图 URL(设置页卡片缩略图)。
- #[serde(default)]
- image: Option<String>,
- /// 仓库地址(`https://github.com/{owner}/{repo}`)。
- repo: String,
- /// 仓库内资源子目录(如 `dsh-pet/assets`)。
- assets: String,
- /// 固定提交(ref);缺省回退 `main`。固定后下载可复现。
- #[serde(default)]
- r#ref: Option<String>,
- /// 下载尺寸(MiB,用于卡片上的 `[number]mb` 标签)。
- #[serde(default)]
- size_mb: Option<f64>,
- /// 按平台覆盖素材来源,键为 `std::env::consts::OS`(如 `macos`)。
- /// 当前平台命中时在 `read_preset_catalog` 里并回基础条目(见 issue #434:
- /// macOS 的 WKWebView 不认 VP9-alpha WebM,改从 HEVC-with-Alpha 仓库下载)。
- #[serde(default)]
- platforms: HashMap<String, PresetPetPlatformOverride>,
-}
-
-/// 平台覆盖块(`PresetPetSpec::platforms` 的一项):只写需要改的字段,其余继承基础条目。
///
-/// 两个结构都 `deny_unknown_fields`:清单随安装包分发,字段名写错(如 `sizeMB`)必须
-/// 立刻报 `PET_PRESET_CATALOG_INVALID`,而不是被 serde 静默忽略后沿用基础取值。
-#[derive(Debug, Clone, Default, Deserialize)]
+/// 字段名与 `dsh-pet-component` 的 props 一一对应,前端拿到后直接展开给 `<Pet>`;
+/// `deny_unknown_fields` 保证清单写错字段(如 `sizeMB`)立即报错,而不是被静默忽略。
+#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
-struct PresetPetPlatformOverride {
- #[serde(default)]
- desc: Option<String>,
- /// 浏览图 URL;macOS 移植仓库只保留 `config.jsonc` + `mov/`,覆盖时可指向原仓库预览图。
- #[serde(default)]
- image: Option<String>,
- #[serde(default)]
- repo: Option<String>,
- #[serde(default)]
- assets: Option<String>,
- #[serde(default)]
- r#ref: Option<String>,
- #[serde(default)]
- size_mb: Option<f64>,
-}
-
-/// 并回当前平台的覆盖块(`platform` 为 `std::env::consts::OS` 的值)。
-/// 没有该平台的键时原样返回;覆盖块里没写的字段保持基础条目取值。
-fn apply_platform_override(spec: &mut PresetPetSpec, platform: &str) {
- let Some(overrides) = spec.platforms.remove(platform) else {
- return;
- };
- if let Some(value) = overrides.desc {
- spec.desc = Some(value);
- }
- if let Some(value) = overrides.image {
- spec.image = Some(value);
- }
- if let Some(value) = overrides.repo {
- spec.repo = value;
- }
- if let Some(value) = overrides.assets {
- spec.assets = value;
- }
- if let Some(value) = overrides.r#ref {
- spec.r#ref = Some(value);
- }
- if let Some(value) = overrides.size_mb {
- spec.size_mb = Some(value);
- }
-}
-
-/// 已安装预设宠物的版本记录文件名(安装目录根下,记录安装时的 ref)。
-/// 设置页据此判断「是否有更新」:清单 ref 与安装记录不一致(或旧安装无记录)
-/// 时给出更新入口。
-const PRESET_REF_FILE: &str = ".preset-ref";
-
-/// 设置页可展示的清单条目(含本机安装状态、版本更新提示与进行中的下载阶段)。
-#[derive(Debug, Clone, Serialize)]
-pub struct PresetPetListItem {
+pub struct PresetPetSpec {
+ /// 唯一标识(`active_pet` 持久化的就是它)。
pub id: String,
+ /// 设置页展示名。
pub name: String,
+ /// 设置页展示描述。
+ #[serde(default, skip_serializing_if = "Option::is_none")]
pub desc: Option<String>,
+ /// 设置页卡片预览图(远端 URL,主窗口 CSP 需允许该图源)。
+ #[serde(default, skip_serializing_if = "Option::is_none")]
pub image: Option<String>,
- pub size_mb: Option<f64>,
- pub installed: bool,
- /// 已安装且清单 ref 与安装记录不同(或无记录)→ 可更新。
- /// 清单未固定 ref(跟随 main)时恒为 false,无法检测差异。
- pub update_available: bool,
- /// 当前下载阶段(idle | downloading | extracting | done | failed)。
- /// 设置页跨挂载恢复「下载中」视图用:返回应用再进设置时,进程内注册表仍保留
- /// 进行中的下载阶段,前端据此显示进度条并自动恢复轮询。
- pub phase: String,
-}
-
-/// 下载进度快照(设置页轮询 `get_preset_download_progress`)。
-#[derive(Debug, Clone, Serialize)]
-pub struct PresetDownloadProgress {
- /// idle | downloading | extracting | done | failed
- pub phase: String,
- pub received: u64,
- pub total: u64,
- pub error: Option<String>,
-}
-
-impl Default for PresetDownloadProgress {
- fn default() -> Self {
- Self {
- phase: "idle".to_string(),
- received: 0,
- total: 0,
- error: None,
- }
- }
-}
-
-/// 进程内下载进度注册表(按宠物 id)。
-fn preset_downloads() -> &'static Mutex<HashMap<String, PresetDownloadProgress>> {
- static STATE: OnceLock<Mutex<HashMap<String, PresetDownloadProgress>>> = OnceLock::new();
- STATE.get_or_init(|| Mutex::new(HashMap::new()))
+ /// 渲染器协议:`dsh`(逐动作透明视频)/ `codex`(单张雪碧图集);缺省由组件自动判定。
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub kind: Option<String>,
+ /// 渲染宽度 px(高度由协议画布比例推算);缺省取组件默认值。
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub size: Option<f64>,
+ /// 配置文件地址(dsh-pet `config.jsonc` 或 Codex `pet.json`)。
+ pub config: String,
+ /// 素材地址(dsh-pet 用 `{ default, mac }`:macOS 换 HEVC-alpha 素材)。
+ pub uri: PresetPetUri,
+ /// 素材后缀;缺省 `{ default: "webm", mac: "mov" }`(Codex 渲染器忽略)。
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub ext: Option<PresetPetExt>,
+}
+
+/// 素材基地址:`default` 必填,`mac` 覆盖 Apple 平台(WKWebView 不认 VP9-alpha)。
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase", deny_unknown_fields)]
+pub struct PresetPetUri {
+ pub default: String,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub mac: Option<String>,
}
-fn set_preset_progress(id: &str, progress: PresetDownloadProgress) {
- preset_downloads()
- .lock()
- .unwrap_or_else(|error| error.into_inner())
- .insert(id.to_string(), progress);
+/// 素材后缀:`default` 必填,`mac` 覆盖 Apple 平台。
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase", deny_unknown_fields)]
+pub struct PresetPetExt {
+ pub default: String,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub mac: Option<String>,
}
-fn get_preset_progress(id: &str) -> PresetDownloadProgress {
- preset_downloads()
- .lock()
- .unwrap_or_else(|error| error.into_inner())
- .get(id)
- .cloned()
- .unwrap_or_default()
+/// 预设 id 是否安全(直接进入设置持久化与命令参数,只允许 ASCII 字母数字与 `-`/`_`)。
+pub(crate) fn safe_preset_id(id: &str) -> bool {
+ !id.is_empty()
+ && id.len() <= 64
+ && id
+ .chars()
+ .all(|value| value.is_ascii_alphanumeric() || value == '-' || value == '_')
}
/// 定位清单文件:优先随安装包分发的资源目录,回落源码 `resources/`。
fn preset_pets_path(app: &AppHandle) -> Option<PathBuf> {
if let Ok(dir) = app.path().resource_dir() {
- for candidate in [dir.join(PRESET_PETS_FILE), dir.join("resources").join(PRESET_PETS_FILE)]
- {
+ for candidate in [
+ dir.join(PRESET_PETS_FILE),
+ dir.join("resources").join(PRESET_PETS_FILE),
+ ] {
if candidate.exists() {
return Some(candidate);
}
@@ -211,7 +95,8 @@ fn preset_pets_path(app: &AppHandle) -> Option<PathBuf> {
source.exists().then_some(source)
}
-fn read_preset_catalog(app: &AppHandle) -> Result<Vec<PresetPetSpec>, String> {
+/// 读取并校验清单。任何形状问题都返回带 `PET_PRESET_CATALOG_*` 前缀的错误,不做静默兜底。
+pub fn read_preset_catalog(app: &AppHandle) -> Result<Vec<PresetPetSpec>, String> {
let path = preset_pets_path(app)
.ok_or_else(|| "PET_PRESET_CATALOG_MISSING: preset-pets.json was not found".to_string())?;
let bytes = fs::read(&path).map_err(|error| {
@@ -220,1929 +105,186 @@ fn read_preset_catalog(app: &AppHandle) -> Result<Vec<PresetPetSpec>, String> {
path.display()
)
})?;
- serde_json::from_slice(&bytes).map_err(|error| {
+ let catalog: Vec<PresetPetSpec> = serde_json::from_slice(&bytes).map_err(|error| {
format!("PET_PRESET_CATALOG_INVALID: invalid preset-pets.json: {error}")
- })
-}
-
-/// 读取清单并套用当前平台的覆盖块(macOS 换 HEVC-with-Alpha 素材仓库,见 #434)。
-fn read_platform_catalog(app: &AppHandle, platform: &str) -> Result<Vec<PresetPetSpec>, String> {
- let mut catalog = read_preset_catalog(app)?;
- for spec in &mut catalog {
- apply_platform_override(spec, platform);
- }
- Ok(catalog)
-}
-
-/// 预设宠物安装根目录:与 Chat 宠物共用 DSH 数据目录(`~/.dsh/pets` / `~/.dsh.dev/pets`)。
-fn preset_pets_root(app: &AppHandle) -> PathBuf {
- config::get_dsh_data_path(app).join("pets")
-}
-
-fn installed_dir(root: &Path, id: &str) -> PathBuf {
- root.join(id)
-}
-
-/// 清单条目实际下载/安装所用的引用:固定 ref,缺省回退 `main`。
-fn preset_reference(spec: &PresetPetSpec) -> String {
- spec.r#ref
- .clone()
- .filter(|value| !value.is_empty())
- .unwrap_or_else(|| "main".to_string())
-}
-
-/// 读取已安装宠物目录的版本记录(`.preset-ref`);缺失或内容为空白返回 None。
-/// 旧安装(记录功能上线前下载的)无此文件,视为「未知版本」而非「最新」。
-fn read_installed_ref(dir: &Path) -> Option<String> {
- let value = fs::read_to_string(dir.join(PRESET_REF_FILE)).ok()?;
- let trimmed = value.trim();
- (!trimmed.is_empty()).then(|| trimmed.to_string())
-}
-
-/// 在安装目录写入 ref 版本记录(安装/更新成功后调用,供后续更新检测)。
-fn write_installed_ref(dir: &Path, reference: &str) -> Result<(), String> {
- fs::write(dir.join(PRESET_REF_FILE), reference).map_err(|error| {
- format!(
- "PET_PRESET_REF_WRITE_FAILED: failed to write {}: {error}",
- dir.join(PRESET_REF_FILE).display()
- )
- })
-}
-
-/// 是否可更新:已安装,且清单 ref 与安装记录不一致(或无记录)。
-/// 清单未固定 ref(跟随 main 分支)时无法判断差异,恒为 false。
-fn preset_update_available(installed: bool, catalog_ref: Option<&str>, installed_ref: Option<&str>) -> bool {
- if !installed {
- return false;
- }
- match catalog_ref.filter(|value| !value.is_empty()) {
- None => false,
- Some(catalog) => installed_ref.as_deref() != Some(catalog),
- }
-}
-
-pub(crate) fn safe_preset_id(id: &str) -> bool {
- !id.is_empty()
- && id.len() <= 64
- && id
- .chars()
- .all(|value| value.is_ascii_alphanumeric() || value == '-' || value == '_')
-}
-
-/// 从仓库 URL 提取 owner/repo;只接受 github.com 形态,拒绝其它主机。
-fn parse_repo_owner(url: &str) -> Result<(String, String), String> {
- let url = url.trim();
- let rest = url
- .strip_prefix("https://github.com/")
- .or_else(|| url.strip_prefix("http://github.com/"))
- .or_else(|| url.strip_prefix("github.com/"))
- .ok_or_else(|| {
- "PET_PRESET_REPO_INVALID: repo must be a github.com URL".to_string()
- })?;
- let mut parts = rest.trim_end_matches('/').split('/');
- let owner = parts.next().filter(|part| !part.is_empty());
- let repo = parts.next().map(|part| part.trim_end_matches(".git"));
- match (owner, repo) {
- (Some(owner), Some(repo)) if !repo.is_empty() && parts.next().is_none() => Ok((
- owner.to_string(),
- repo.to_string(),
- )),
- _ => Err("PET_PRESET_REPO_INVALID: repo must be https://github.com/{owner}/{repo}".to_string()),
- }
-}
-
-/// 构造仓库 tarball 下载地址(codeload 直连 + ghfast.top 镜像兜底)。
-fn tarball_urls(spec: &PresetPetSpec) -> Result<Vec<String>, String> {
- let (owner, repo) = parse_repo_owner(&spec.repo)?;
- let reference = preset_reference(spec);
- if reference.contains('/') || reference.contains('\\') || reference.contains("..") {
- return Err("PET_PRESET_REF_INVALID: ref must be a plain commit or branch name".to_string());
- }
- let primary = format!("https://codeload.github.com/{owner}/{repo}/tar.gz/{reference}");
- Ok(vec![primary.clone(), config::mirror_download_url(&primary)])
-}
-
-/// 解压产物必须含可解析的 `config.jsonc`(JSONC 协议,剥注释后为合法 JSON)。
-fn validate_preset_config(root: &Path) -> Result<(), String> {
- let path = root.join("config.jsonc");
- if !path.is_file() {
- return Err("PET_PRESET_CONFIG_MISSING: preset package must include config.jsonc".to_string());
- }
- let bytes = read_bounded_file(&path, PET_PRESET_CONFIG_MAX_BYTES, "PET_PRESET_CONFIG_READ_FAILED")?;
- let text = std::str::from_utf8(&bytes)
- .map_err(|error| format!("PET_PRESET_CONFIG_INVALID: config.jsonc is not UTF-8: {error}"))?;
- let json = strip_jsonc(text);
- let value: serde_json::Value = serde_json::from_str(&json)
- .map_err(|error| format!("PET_PRESET_CONFIG_INVALID: config.jsonc is not valid JSON: {error}"))?;
- if !value.get("animations").map(serde_json::Value::is_object).unwrap_or(false) {
- return Err(
- "PET_PRESET_CONFIG_INVALID: config.jsonc must contain an animations object".to_string(),
- );
- }
- Ok(())
-}
-
-/// 限量读取文件(与 `bridge::pet` 同一实现,避免跨模块可见性耦合)。
-fn read_bounded_file(path: &Path, limit: u64, prefix: &str) -> Result<Vec<u8>, String> {
- let file = fs::File::open(path)
- .map_err(|error| format!("{prefix}: failed to read {}: {error}", path.display()))?;
- let metadata = file
- .metadata()
- .map_err(|error| format!("{prefix}: failed to read {}: {error}", path.display()))?;
- if !metadata.is_file() {
- return Err(format!("{prefix}: {} is not a file", path.display()));
- }
- if metadata.len() > limit {
- return Err(format!(
- "{prefix}: {} exceeds the {limit} byte limit",
- path.display()
- ));
- }
- let mut bytes = Vec::with_capacity(usize::try_from(metadata.len()).unwrap_or(0));
- file.take(limit.saturating_add(1))
- .read_to_end(&mut bytes)
- .map_err(|error| format!("{prefix}: failed to read {}: {error}", path.display()))?;
- if bytes.len() as u64 > limit {
- return Err(format!(
- "{prefix}: {} exceeds the {limit} byte limit",
- path.display()
- ));
- }
- Ok(bytes)
-}
-
-/// 剥除 JSONC 注释(行注释 // 与块注释 /* */),字符串字面量内原样保留。
-/// 与 `bridge::pet::strip_jsonc` 语义一致。
-fn strip_jsonc(src: &str) -> String {
- let bytes: Vec<char> = src.chars().collect();
- let mut out = String::with_capacity(src.len());
- let mut index = 0;
- let mut in_string = false;
- let mut escaped = false;
- while index < bytes.len() {
- let c = bytes[index];
- if in_string {
- out.push(c);
- if escaped {
- escaped = false;
- }
- else if c == '\\' {
- escaped = true;
- }
- else if c == '"' {
- in_string = false;
- }
- index += 1;
- continue;
- }
- match c {
- '"' => {
- in_string = true;
- out.push(c);
- index += 1;
- }
- '/' if index + 1 < bytes.len() && bytes[index + 1] == '/' => {
- index += 2;
- while index < bytes.len() && bytes[index] != '\n' {
- index += 1;
- }
- }
- '/' if index + 1 < bytes.len() && bytes[index + 1] == '*' => {
- index += 2;
- let mut closed = false;
- while index + 1 < bytes.len() {
- if bytes[index] == '*' && bytes[index + 1] == '/' {
- index += 2;
- closed = true;
- break;
- }
- index += 1;
- }
- if !closed {
- break;
- }
- }
- _ => {
- out.push(c);
- index += 1;
- }
- }
- }
- out
-}
-
-/// 路径只允许普通相对组件;显式拒绝反斜杠和冒号(覆盖 Windows 语义)。
-fn safe_relative_path(value: &str) -> Result<PathBuf, String> {
- if value.is_empty() || value.contains('\0') || value.contains('\\') || value.contains(':') {
- return Err("PET_PRESET_PATH_INVALID: path must be a portable relative path".to_string());
- }
- let mut result = PathBuf::new();
- for component in Path::new(value).components() {
- match component {
- Component::Normal(part) if !part.is_empty() => result.push(part),
- _ => {
- return Err(
- "PET_PRESET_PATH_INVALID: path must not be absolute or contain traversal"
- .to_string(),
- )
- }
- }
- }
- if result.as_os_str().is_empty() {
- return Err("PET_PRESET_PATH_INVALID: path must not be empty".to_string());
- }
- Ok(result)
-}
-
-/// 流式复制并计数,超限立即截断(不能只信任 tarball 声明的文件大小)。
-fn copy_bounded<R: Read, W: Write>(
- reader: &mut R,
- writer: &mut W,
- total: &mut u64,
- file_budget: &mut u64,
-) -> Result<(), String> {
- let mut buffer = [0_u8; 64 * 1024];
- loop {
- if *file_budget == 0 {
+ })?;
+ let mut ids = HashSet::new();
+ for spec in &catalog {
+ if !safe_preset_id(&spec.id) {
return Err(format!(
- "PET_PRESET_FILE_TOO_LARGE: single file exceeds {PET_PRESET_MAX_FILE_BYTES} bytes"
+ "PET_PRESET_CATALOG_INVALID: preset id {:?} is not a safe id",
+ spec.id
));
}
- let chunk_limit = usize::try_from(*file_budget)
- .unwrap_or(usize::MAX)
- .min(buffer.len());
- let count = reader.read(&mut buffer[..chunk_limit]).map_err(|error| {
- format!("PET_PRESET_EXTRACT_FAILED: failed to read archive entry: {error}")
- })?;
- if count == 0 {
- return Ok(());
- }
- writer.write_all(&buffer[..count]).map_err(|error| {
- format!("PET_PRESET_EXTRACT_FAILED: failed to write archive entry: {error}")
- })?;
- *total = total
- .checked_add(count as u64)
- .ok_or_else(|| "PET_PRESET_TOO_LARGE: uncompressed size overflow".to_string())?;
- *file_budget -= count as u64;
- if *total > PET_PRESET_MAX_UNCOMPRESSED_BYTES {
+ if !ids.insert(spec.id.as_str()) {
return Err(format!(
- "PET_PRESET_TOO_LARGE: uncompressed files must not exceed {PET_PRESET_MAX_UNCOMPRESSED_BYTES} bytes"
+ "PET_PRESET_CATALOG_INVALID: duplicate preset id {:?}",
+ spec.id
));
}
- }
-}
-
-/// 只解压 tarball 中 `assets/` 前缀下的条目到 staging(剥离仓库根目录与前缀)。
-///
-/// codeload tarball 的布局是 `<repo>-<ref>/<assets>/...`:第一段是仓库根目录,
-/// 随后必须是清单声明的 assets 前缀,其余仓库文件(源码/脚本等)一律跳过。
-/// 生产路径走 `extract_preset_assets_with_progress`(带解压进度回调);此无回调
-/// 版本仅供测试直接调用。
-#[cfg(test)]
-fn extract_preset_assets(tarball: &Path, staging: &Path, assets_prefix: &str) -> Result<(), String> {
- extract_preset_assets_with_progress(tarball, staging, assets_prefix, None)
-}
-
-/// `extract_preset_assets` 的带进度回调版本:`on_progress` 在每解压完一个文件后
-/// 收到已解压字节数(供设置页 extracting 阶段显示百分比,避免进度条长时间不确定)。
-fn extract_preset_assets_with_progress(
- tarball: &Path,
- staging: &Path,
- assets_prefix: &str,
- mut on_progress: Option<&mut dyn FnMut(u64)>,
-) -> Result<(), String> {
- let file = fs::File::open(tarball)
- .map_err(|error| format!("PET_PRESET_READ_FAILED: failed to open tarball: {error}"))?;
- let decoder = flate2::read::GzDecoder::new(file);
- let mut archive = tar::Archive::new(decoder);
- let prefix = assets_prefix.trim_matches('/').to_string();
- let prefix_path = Path::new(&prefix);
-
- fs::create_dir_all(staging).map_err(|error| {
- format!("PET_PRESET_STAGING_FAILED: failed to create staging: {error}")
- })?;
- let mut entries_count = 0_usize;
- let mut total = 0_u64;
- let mut outputs = HashSet::new();
-
- for entry in archive.entries().map_err(|error| {
- format!("PET_PRESET_EXTRACT_FAILED: failed to read tarball entries: {error}")
- })? {
- let mut entry = entry.map_err(|error| {
- format!("PET_PRESET_EXTRACT_FAILED: failed to read archive entry: {error}")
- })?;
- entries_count += 1;
- if entries_count > PET_PRESET_MAX_ENTRIES {
+ if spec.name.trim().is_empty() {
return Err(format!(
- "PET_PRESET_ENTRY_LIMIT: archive must contain at most {PET_PRESET_MAX_ENTRIES} entries"
+ "PET_PRESET_CATALOG_INVALID: preset {:?} must have a non-empty name",
+ spec.id
));
}
- // 拒绝 symlink/hardlink 与其它特殊 Unix 文件类型:先看条目类型(tar 的
- // symlink 头 mode 可能为 0,unix_mode 检查不足以兜底),再核对 unix mode。
- let entry_type = entry.header().entry_type();
- if entry_type.is_symlink() || entry_type.is_hard_link() {
- return Err("PET_PRESET_LINK_FORBIDDEN: archive links are not allowed".to_string());
- }
- let mode = entry.header().mode().unwrap_or(0);
- let file_type = mode & 0o170000;
- if file_type != 0 && file_type != 0o040000 && file_type != 0o100000 {
- return Err("PET_PRESET_LINK_FORBIDDEN: archive links are not allowed".to_string());
- }
- let path = entry.path().map_err(|error| {
- format!("PET_PRESET_EXTRACT_FAILED: invalid entry path: {error}")
- })?;
- let mut components = path.components();
- let _root = components.next(); // `<repo>-<ref>/` 根目录
- let relative = components.as_path();
- // 只接受 assets 前缀下的条目;根目录条目与仓库其它文件跳过。
- // 空前缀(`assets: ""`)表示整个仓库就是素材(如 dsh-pet-mov 只保留
- // `config.jsonc` + `mov/`),此时不做前缀过滤。
- let relative = if prefix.is_empty() {
- relative
- } else {
- let Ok(relative) = relative.strip_prefix(prefix_path) else {
- continue;
- };
- relative
- };
- if relative.as_os_str().is_empty() {
- continue; // assets 目录本身的条目
- }
- let relative = safe_relative_path(&relative.to_string_lossy())?;
- if !outputs.insert(relative.clone()) {
- return Err("PET_PRESET_DUPLICATE_ENTRY: duplicate output path".to_string());
- }
- let output_path = staging.join(&relative);
- if entry.header().entry_type().is_dir() {
- fs::create_dir_all(&output_path).map_err(|error| {
- format!("PET_PRESET_EXTRACT_FAILED: failed to create directory: {error}")
- })?;
- continue;
- }
- if let Some(parent) = output_path.parent() {
- fs::create_dir_all(parent).map_err(|error| {
- format!("PET_PRESET_EXTRACT_FAILED: failed to create directory: {error}")
- })?;
- }
- let mut output = fs::OpenOptions::new()
- .write(true)
- .create_new(true)
- .open(&output_path)
- .map_err(|error| {
- format!("PET_PRESET_EXTRACT_FAILED: failed to create file: {error}")
- })?;
- let mut file_budget = PET_PRESET_MAX_FILE_BYTES;
- copy_bounded(&mut entry, &mut output, &mut total, &mut file_budget)?;
- if let Some(on_progress) = on_progress.as_deref_mut() {
- on_progress(total);
- }
- }
- Ok(())
-}
-
-/// 下载 tarball 到临时文件(直连失败切镜像源),进度写入注册表。
-///
-/// codeload 对 tar.gz 响应是 chunked(无 Content-Length),`content_length()` 拿不到
-/// 真实总量;此时用清单 `size_mb` 估算 total,让设置页进度条显示实际百分比,
-/// 而不是一直停在不确定进度。真实总量已知时(镜像源返回 Content-Length)优先用它。
-async fn download_tarball(
- id: &str,
- urls: &[String],
- dest: &Path,
- estimated_total: u64,
-) -> Result<(), String> {
- let client = reqwest::Client::builder()
- .user_agent(PET_PRESET_USER_AGENT)
- .connect_timeout(std::time::Duration::from_secs(20))
- .build()
- .map_err(|error| format!("PET_PRESET_DOWNLOAD_FAILED: failed to build client: {error}"))?;
-
- let mut last_error = String::new();
- for url in urls {
- log::info!(
- "[preset-pet] download {id}: trying {url} (estimated {estimated_total} bytes)"
- );
- let response = client.get(url).send().await;
- match response {
- Ok(response) if response.status().is_success() => {
- let total = response.content_length().unwrap_or(estimated_total);
- let mut received = 0_u64;
- // 日志节流:每 10% 打一条进度,避免逐 chunk 刷屏。
- let mut last_logged_pct = 0_u8;
- let mut file = tokio::fs::File::create(dest).await.map_err(|error| {
- format!("PET_PRESET_DOWNLOAD_FAILED: failed to create temp file: {error}")
- })?;
- let mut stream = response.bytes_stream();
- while let Some(chunk) = stream.next().await {
- let chunk = chunk.map_err(|error| {
- format!("PET_PRESET_DOWNLOAD_FAILED: download stream error: {error}")
- })?;
- received = received
- .checked_add(chunk.len() as u64)
- .ok_or_else(|| "PET_PRESET_TOO_LARGE: download size overflow".to_string())?;
- if received > PET_PRESET_MAX_UNCOMPRESSED_BYTES {
- return Err(format!(
- "PET_PRESET_TOO_LARGE: tarball exceeds {PET_PRESET_MAX_UNCOMPRESSED_BYTES} bytes"
- ));
- }
- file.write_all(&chunk).await.map_err(|error| {
- format!("PET_PRESET_DOWNLOAD_FAILED: failed to write temp file: {error}")
- })?;
- set_preset_progress(
- id,
- PresetDownloadProgress {
- phase: "downloading".to_string(),
- received,
- total,
- error: None,
- },
- );
- if total > 0 {
- let pct = ((received.saturating_mul(100)) / total).min(100) as u8;
- if pct / 10 > last_logged_pct / 10 && pct < 100 {
- last_logged_pct = pct;
- log::info!(
- "[preset-pet] download {id}: {received} / {total} bytes ({pct}%)"
- );
- }
- }
- }
- file.flush().await.map_err(|error| {
- format!("PET_PRESET_DOWNLOAD_FAILED: failed to flush temp file: {error}")
- })?;
- log::info!(
- "[preset-pet] download {id}: completed, {received} bytes from {url}"
- );
- return Ok(());
- }
- Ok(response) => {
- last_error = format!(
- "PET_PRESET_DOWNLOAD_FAILED: HTTP {} from {url}",
- response.status()
- );
- log::warn!("{last_error}");
- }
- Err(error) => {
- last_error = format!("PET_PRESET_DOWNLOAD_FAILED: {error} for {url}");
- log::warn!("{last_error}");
- }
- }
- }
- Err(last_error)
-}
-
-/// 把 staging 安装到 target:
-/// - 首次安装(target 不存在)直接 rename;
-/// - 更新安装(target 存在且 `replace`):两步 rename(旧目录→备份、staging→target)
-/// 原子换新,任一步失败回滚备份,成功后清理备份目录。
-fn install_staging(
- root: &Path,
- id: &str,
- nonce: u128,
- staging: &Path,
- target: &Path,
- replace: bool,
-) -> Result<(), String> {
- if !target.exists() {
- return fs::rename(staging, target).map_err(|error| {
- format!("PET_PRESET_INSTALL_FAILED: failed to install preset pet: {error}")
- });
- }
- if !replace {
- return Err(format!(
- "PET_PRESET_ALREADY_INSTALLED: preset pet {} is already installed",
- id
- ));
- }
- let backup = root.join(format!(".preset-backup-{id}-{nonce}"));
- fs::rename(target, &backup).map_err(|error| {
- format!(
- "PET_PRESET_INSTALL_FAILED: failed to back up existing preset pet: {error}"
- )
- })?;
- if let Err(error) = fs::rename(staging, target) {
- // 新目录就位失败:回滚备份,保留旧版本完整可用(宁可更新失败也不丢宠物)。
- let _ = fs::rename(&backup, target);
- return Err(format!(
- "PET_PRESET_INSTALL_FAILED: failed to install updated preset pet: {error}"
- ));
- }
- let _ = fs::remove_dir_all(&backup);
- Ok(())
-}
-
-/// 后台安装流程:下载 → 解压 assets → 校验 → staging 原子安装(首次或替换)。
-async fn run_preset_download(app: &AppHandle, spec: PresetPetSpec, replace: bool) -> Result<(), String> {
- let root = preset_pets_root(app);
- fs::create_dir_all(&root).map_err(|error| {
- format!("PET_PRESET_DIR_FAILED: failed to create pets directory: {error}")
- })?;
- let urls = tarball_urls(&spec)?;
- let nonce = SystemTime::now()
- .duration_since(UNIX_EPOCH)
- .unwrap_or_default()
- .as_nanos();
- let tarball = root.join(format!(".preset-{}-{nonce}.tar.gz", spec.id));
- let staging = root.join(format!(".preset-staging-{}-{nonce}", spec.id));
-
- let result = (|| async {
- // 清单 size_mb 是解压后 assets 大小(MiB);codeload 响应无 Content-Length,
- // 用它估算下载总量供进度条显示百分比(真实总量已知时优先)。
- let estimated_total = spec
- .size_mb
- .map(|mb| (mb * 1024.0 * 1024.0).round() as u64)
- .unwrap_or(0);
- log::info!(
- "[preset-pet] install {}: start (assets={:?}, estimated {estimated_total} bytes, replace={replace})",
- spec.id,
- spec.assets
- );
- download_tarball(&spec.id, &urls, &tarball, estimated_total).await?;
- set_preset_progress(
- &spec.id,
- PresetDownloadProgress {
- phase: "extracting".to_string(),
- received: 0,
- total: 0,
- error: None,
- },
- );
- log::info!("[preset-pet] install {}: extracting tarball", spec.id);
- // 解压进度:以清单估算总量为 total,每解压完一个文件上报已解压字节,
- // 设置页 extracting 阶段显示百分比(而不是不确定进度条)。
- let extract_total = estimated_total;
- extract_preset_assets_with_progress(&tarball, &staging, &spec.assets, Some(&mut |uncompressed| {
- set_preset_progress(
- &spec.id,
- PresetDownloadProgress {
- phase: "extracting".to_string(),
- received: uncompressed,
- total: extract_total,
- error: None,
- },
- );
- }))?;
- log::info!("[preset-pet] install {}: tarball extracted", spec.id);
- validate_preset_config(&staging)?;
- let target = installed_dir(&root, &spec.id);
- install_staging(&root, &spec.id, nonce, &staging, &target, replace)?;
- // 版本记录:供设置页检测更新(清单 ref 与记录不一致时提示可更新)。
- write_installed_ref(&target, &preset_reference(&spec))?;
- log::info!(
- "[preset-pet] install {}: installed at {}",
- spec.id,
- target.display()
- );
- Ok(())
- })()
- .await;
-
- let _ = fs::remove_file(&tarball);
- if result.is_err() {
- let _ = fs::remove_dir_all(&staging);
- }
- result
-}
-
-/// 列出预设宠物清单(含安装状态与版本更新提示)。
-#[tauri::command]
-pub fn list_preset_pets(app: AppHandle) -> Result<Vec<PresetPetListItem>, String> {
- let catalog = read_platform_catalog(&app, std::env::consts::OS)?;
- let root = preset_pets_root(&app);
- let mut items = Vec::with_capacity(catalog.len());
- let mut ids = HashSet::new();
- for spec in catalog {
- if !safe_preset_id(&spec.id) {
+ if spec.config.trim().is_empty() {
return Err(format!(
- "PET_PRESET_CATALOG_INVALID: preset id {:?} is not a safe id",
+ "PET_PRESET_CATALOG_INVALID: preset {:?} must have a non-empty config",
spec.id
));
}
- if !ids.insert(spec.id.clone()) {
+ if spec.uri.default.trim().is_empty() {
return Err(format!(
- "PET_PRESET_CATALOG_INVALID: duplicate preset id {:?}",
+ "PET_PRESET_CATALOG_INVALID: preset {:?} must have a non-empty uri.default",
spec.id
));
}
- let phase = get_preset_progress(&spec.id).phase;
- let installed = installed_dir(&root, &spec.id).is_dir();
- let installed_ref = installed.then(|| read_installed_ref(&installed_dir(&root, &spec.id))).flatten();
- items.push(PresetPetListItem {
- installed,
- update_available: preset_update_available(installed, spec.r#ref.as_deref(), installed_ref.as_deref()),
- id: spec.id,
- name: spec.name,
- desc: spec.desc,
- image: spec.image,
- size_mb: spec.size_mb,
- phase,
- });
- }
- Ok(items)
-}
-
-/// 开始下载并安装预设宠物(后台执行,立即返回;进度用轮询查询)。
-#[tauri::command]
-pub fn download_preset_pet(app: AppHandle, id: String) -> Result<(), String> {
- let id = id.trim().to_string();
- let catalog = read_platform_catalog(&app, std::env::consts::OS)?;
- let spec = catalog
- .into_iter()
- .find(|entry| entry.id == id)
- .ok_or_else(|| format!("PET_PRESET_NOT_FOUND: preset pet {id} is not in the catalog"))?;
- let root = preset_pets_root(&app);
- if installed_dir(&root, &id).is_dir() {
- return Err(format!("PET_PRESET_ALREADY_INSTALLED: preset pet {id} is already installed"));
- }
- if get_preset_progress(&id).phase == "downloading" || get_preset_progress(&id).phase == "extracting" {
- return Err(format!("PET_PRESET_BUSY: preset pet {id} is already downloading"));
- }
- set_preset_progress(
- &id,
- PresetDownloadProgress {
- phase: "downloading".to_string(),
- received: 0,
- total: 0,
- error: None,
- },
- );
- let app = app.clone();
- tauri::async_runtime::spawn(async move {
- let progress = match run_preset_download(&app, spec, false).await {
- Ok(()) => PresetDownloadProgress {
- phase: "done".to_string(),
- received: 0,
- total: 0,
- error: None,
- },
- Err(error) => PresetDownloadProgress {
- phase: "failed".to_string(),
- received: 0,
- total: 0,
- error: Some(error),
- },
- };
- set_preset_progress(&id, progress);
- });
- Ok(())
-}
-
-/// 更新已安装的预设宠物(后台执行,立即返回;进度用轮询查询)。
-///
-/// 需求语义:
-/// 1. 仅对「已安装」开放(未安装走 `download_preset_pet`);
-/// 2. 若该宠物正在使用(激活且启用)则先强制停用(隐藏桌宠窗口),避免更新
-/// 替换媒体文件时窗口仍在按旧 URL 流式读取;
-/// 3. 走与首次下载完全相同的下载/解压/校验流程(替换模式:旧目录备份 → 新目录
-/// 原子换入,失败回滚保旧版本可用),完成后写 `.preset-ref` 版本记录;
-/// 4. 更新结束(无论成败)后若该宠物此前正在使用,重新启用桌宠。若失败则
-/// 旧版本仍可用,重新启用后食用旧版本(下一次更新再试)。
-#[tauri::command]
-pub fn update_preset_pet(app: AppHandle, id: String) -> Result<(), String> {
- let id = id.trim().to_string();
- let catalog = read_platform_catalog(&app, std::env::consts::OS)?;
- let spec = catalog
- .into_iter()
- .find(|entry| entry.id == id)
- .ok_or_else(|| format!("PET_PRESET_NOT_FOUND: preset pet {id} is not in the catalog"))?;
- let root = preset_pets_root(&app);
- if !installed_dir(&root, &id).is_dir() {
- return Err(format!("PET_PRESET_NOT_INSTALLED: preset pet {id} is not installed"));
- }
- if get_preset_progress(&id).phase == "downloading" || get_preset_progress(&id).phase == "extracting" {
- return Err(format!("PET_PRESET_BUSY: preset pet {id} is already downloading"));
- }
-
- // 快照「是否正在使用该宠物」:激活 id 相同且桌宠启用。使用中则先强制停用,
- // 更新结束后恢复启用(无论成败:失败时旧版本仍在,继续可用)。
- let status = crate::bridge::pet::get_pet_status(app.clone());
- let was_active = status.active_pet == id;
- let was_enabled = status.enabled && was_active;
- if was_enabled {
- log::info!("[preset-pet] update {id}: pet in use, disabling pet window during update");
- crate::bridge::pet::set_pet_enabled(app.clone(), false)?;
- }
-
- set_preset_progress(
- &id,
- PresetDownloadProgress {
- phase: "downloading".to_string(),
- received: 0,
- total: 0,
- error: None,
- },
- );
- let app = app.clone();
- tauri::async_runtime::spawn(async move {
- let progress = match run_preset_download(&app, spec, true).await {
- Ok(()) => PresetDownloadProgress {
- phase: "done".to_string(),
- received: 0,
- total: 0,
- error: None,
- },
- Err(error) => PresetDownloadProgress {
- phase: "failed".to_string(),
- received: 0,
- total: 0,
- error: Some(error),
- },
- };
- let next_phase = progress.phase.clone();
- set_preset_progress(&id, progress);
- if next_phase == "done" {
- // 资源换新后重载桌宠窗口:URL 不变但文件已替换,WebView 缓存可能命中
- // 旧 webm。哪怕当前未启用(窗口隐藏)也重载——页面重新加载后按
- // get_pet_status 维持隐藏状态,下次启用时直接呈现新资源。
- crate::desktop::pet::reload_pet_window(&app);
- }
- // 更新前在用 → 重新启用桌宠窗口(新文件已就位,或旧版本被回滚后继续可用)。
- if was_enabled {
- log::info!("[preset-pet] update {id}: re-enabling pet window after update");
- if let Err(error) = crate::bridge::pet::set_pet_enabled(app.clone(), true) {
- log::warn!("[preset-pet] update {id}: failed to re-enable pet window: {error}");
- }
- }
- });
- Ok(())
-}
-
-/// 查询指定预设宠物的下载进度(设置页轮询)。
-#[tauri::command]
-pub fn get_preset_download_progress(id: String) -> PresetDownloadProgress {
- get_preset_progress(id.trim())
-}
-
-/// 预设宠物媒体协议的 URL 前缀(与旧内置资产同一协议,见 builder 注册的 dsh-pet scheme)。
-#[cfg(target_os = "windows")]
-const PRESET_ASSET_ORIGIN: &str = "http://dsh-pet.localhost";
-#[cfg(not(target_os = "windows"))]
-const PRESET_ASSET_ORIGIN: &str = "dsh-pet://localhost";
-
-/// 预设宠物媒体 URL manifest(name → URL;name 为 webm 文件主名,URL 经 dsh-pet 协议按需流式提供)。
-#[derive(Debug, Clone, Serialize)]
-pub struct PresetPetAssets {
- pub assets: BTreeMap<String, String>,
-}
-
-/// 只对非保留字符做百分号编码(UTF-8 逐字节),其余原样保留:视频文件名含中文时
-/// 协议 URL 必须是合法 ASCII,WebView2 会按编码后的路径发起请求。
-fn percent_encode_segment(value: &str) -> String {
- let mut out = String::with_capacity(value.len() * 2);
- for byte in value.as_bytes() {
- if byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'_' | b'.' | b'~') {
- out.push(*byte as char);
- } else {
- out.push_str(&format!("%{byte:02X}"));
- }
- }
- out
-}
-
-/// 百分号解码为 UTF-8 字符串;没有 % 的路径原样返回(兼容 WebView 已解码的请求)。
-fn percent_decode_segment(value: &str) -> Result<String, String> {
- let bytes = value.as_bytes();
- let mut out = Vec::with_capacity(bytes.len());
- let mut index = 0;
- while index < bytes.len() {
- if bytes[index] == b'%' {
- if index + 2 >= bytes.len() {
- return Err("PET_PRESET_ASSET_PATH_INVALID: truncated percent-encoding".to_string());
- }
- let hex = &value[index + 1..index + 3];
- let byte = u8::from_str_radix(hex, 16)
- .map_err(|_| "PET_PRESET_ASSET_PATH_INVALID: bad percent-encoding".to_string())?;
- out.push(byte);
- index += 3;
- } else {
- out.push(bytes[index]);
- index += 1;
- }
- }
- String::from_utf8(out)
- .map_err(|_| "PET_PRESET_ASSET_PATH_INVALID: asset name is not valid UTF-8".to_string())
-}
-
-/// 已安装预设宠物目录下的受控相对路径(webm/、mov/ 或 preview/ 单层子目录内)。
-///
-/// `mov/` 只出现在 macOS:WKWebView 不认 VP9-alpha WebM(alpha 平面被 parser 丢弃,
-/// 透明区域渲染成黑色且无 error 事件),改播 HEVC-with-Alpha `.mov`(issue #434)。
-fn resolve_preset_asset(app: &AppHandle, id: &str, subdir: &str, name: &str) -> Result<PathBuf, String> {
- if !matches!(subdir, "webm" | "mov" | "preview") {
- return Err("PET_PRESET_ASSET_PATH_INVALID: subdir must be webm, mov or preview".to_string());
- }
- let root = preset_pets_root(app);
- let dir = installed_dir(&root, id);
- let sub = dir.join(subdir);
- let candidate = sub.join(name);
- let link_metadata = fs::symlink_metadata(&candidate).map_err(|error| {
- format!("PET_PRESET_ASSET_READ_FAILED: failed to inspect {}: {error}", candidate.display())
- })?;
- if link_metadata.file_type().is_symlink() || !link_metadata.is_file() {
- return Err(format!(
- "PET_PRESET_ASSET_INVALID: {} is not a regular file",
- candidate.display()
- ));
- }
- let resolved = candidate.canonicalize().map_err(|error| {
- format!("PET_PRESET_ASSET_READ_FAILED: failed to resolve {}: {error}", candidate.display())
- })?;
- let sub = sub.canonicalize().map_err(|error| {
- format!("PET_PRESET_ASSET_READ_FAILED: failed to resolve {}: {error}", sub.display())
- })?;
- if !resolved.starts_with(&sub) {
- return Err("PET_PRESET_ASSET_INVALID: asset escapes the preset pet directory".to_string());
- }
- let metadata = fs::metadata(&resolved).map_err(|error| {
- format!("PET_PRESET_ASSET_READ_FAILED: failed to inspect {}: {error}", resolved.display())
- })?;
- if !metadata.is_file() {
- return Err(format!(
- "PET_PRESET_ASSET_INVALID: {} is not a regular file",
- resolved.display()
- ));
- }
- if metadata.len() > PET_PRESET_MAX_FILE_BYTES {
- return Err(format!(
- "PET_PRESET_ASSET_TOO_LARGE: {} exceeds {PET_PRESET_MAX_FILE_BYTES} bytes",
- resolved.display()
- ));
- }
- Ok(resolved)
-}
-
-/// 协议请求路径 → (pet id, 子目录, 文件名)。兼容 Windows WebView 把 authority
-/// 归一化进 path 的 `localhost/` 前缀;只接受单层子目录 + 单文件名,杜绝遍历。
-fn preset_asset_path(path: &str) -> Option<(&str, &str, &str)> {
- let path = path.trim_matches('/');
- let path = path.strip_prefix("localhost/").unwrap_or(path);
- let mut parts = path.split('/');
- let id = parts.next().filter(|part| !part.is_empty())?;
- let subdir = parts.next().filter(|part| !part.is_empty())?;
- let name = parts.next().filter(|part| !part.is_empty())?;
- if parts.next().is_some() {
- return None;
- }
- if id.contains('\\') || id.contains(':') || id.contains("..") {
- return None;
- }
- Some((id, subdir, name))
-}
-
-/// 预设媒体扩展名 → Content-Type;同时充当扩展名白名单(None = 拒绝该资源)。
-/// `.mov` 必须是 `video/quicktime`:WKWebView 交给 AVFoundation 解码 HEVC-with-Alpha
-/// (`hvc1`)时才认得 alpha 通道。
-fn preset_asset_mime(name: &str) -> Option<&'static str> {
- match name.rsplit_once('.').map(|(_, extension)| extension) {
- Some("webm") => Some("video/webm"),
- Some("mov") => Some("video/quicktime"),
- Some("gif") => Some("image/gif"),
- _ => None,
- }
-}
-
-/// 为 dsh-pet 自定义协议读取已安装预设宠物的媒体文件;调用方已在 builder 限制为 pet WebView。
-/// 与旧内置协议同一安全纪律:webview 白名单 + GET/HEAD + 路径三层解析 + canonicalize
-/// 包含性校验 + 符号链接拒绝 + 单文件大小上限 + Range 单字节区间。
-pub fn preset_pet_asset_response(
- app: &AppHandle,
- webview_label: &str,
- request: Request<Vec<u8>>,
-) -> Response<Vec<u8>> {
- if webview_label != pet_window::PET_WINDOW_LABEL {
- return protocol_error(StatusCode::FORBIDDEN, "PET_PRESET_ASSET_FORBIDDEN: request is not from pet window");
- }
- if request.method() != Method::GET && request.method() != Method::HEAD {
- return protocol_error(StatusCode::METHOD_NOT_ALLOWED, "PET_PRESET_ASSET_METHOD_INVALID: only GET and HEAD are allowed");
- }
- let Some((id, subdir, encoded_name)) = preset_asset_path(request.uri().path()) else {
- return protocol_error(StatusCode::FORBIDDEN, "PET_PRESET_ASSET_PATH_INVALID: path is not a safe asset path");
- };
- if !safe_preset_id(id) {
- return protocol_error(StatusCode::FORBIDDEN, "PET_PRESET_ASSET_PATH_INVALID: pet id is not a safe preset id");
- }
- let Ok(name) = percent_decode_segment(encoded_name) else {
- return protocol_error(StatusCode::FORBIDDEN, "PET_PRESET_ASSET_PATH_INVALID: asset name is not valid");
- };
- let Ok(relative) = safe_relative_path(&name) else {
- return protocol_error(StatusCode::FORBIDDEN, "PET_PRESET_ASSET_PATH_INVALID: asset name is not a safe relative path");
- };
- if relative.components().count() != 1 {
- return protocol_error(StatusCode::FORBIDDEN, "PET_PRESET_ASSET_PATH_INVALID: asset must be a single file");
- }
- let Some(mime) = preset_asset_mime(&name) else {
- return protocol_error(StatusCode::FORBIDDEN, "PET_PRESET_ASSET_PATH_INVALID: asset must be a single webm/mov/gif file");
- };
- let path = match resolve_preset_asset(app, id, subdir, &name) {
- Ok(path) => path,
- Err(error) => return protocol_error(StatusCode::NOT_FOUND, &error),
- };
- let Ok(file) = fs::File::open(&path) else {
- return protocol_error(StatusCode::NOT_FOUND, "PET_PRESET_ASSET_READ_FAILED: asset could not be opened");
- };
- let Ok(length) = file.metadata().map(|metadata| metadata.len()) else {
- return protocol_error(StatusCode::NOT_FOUND, "PET_PRESET_ASSET_READ_FAILED: asset metadata unavailable");
- };
- let base = Response::builder()
- .header("Content-Type", mime)
- .header("Accept-Ranges", "bytes");
- if request.method() == Method::HEAD {
- return base.header(CONTENT_LENGTH, length).status(StatusCode::OK).body(Vec::new()).unwrap();
- }
- let Some(range) = request.headers().get("range").and_then(|value| value.to_str().ok()) else {
- let mut bytes = Vec::new();
- let mut limited = file.take(PET_PRESET_MAX_FILE_BYTES.saturating_add(1));
- if limited.read_to_end(&mut bytes).is_err() || bytes.len() as u64 > PET_PRESET_MAX_FILE_BYTES {
- return Response::builder().status(StatusCode::PAYLOAD_TOO_LARGE).body(Vec::new()).unwrap();
- }
- return base.header(CONTENT_LENGTH, bytes.len()).status(StatusCode::OK).body(bytes).unwrap();
- };
- let Some((start, end)) = parse_single_byte_range(range, length) else {
- return base.header("Content-Range", format!("bytes */{length}")).status(StatusCode::RANGE_NOT_SATISFIABLE).body(Vec::new()).unwrap();
- };
- let size = end - start + 1;
- let Ok(capacity) = usize::try_from(size) else {
- return Response::builder().status(StatusCode::RANGE_NOT_SATISFIABLE).body(Vec::new()).unwrap();
- };
- let mut bytes = vec![0; capacity];
- let mut file = file;
- if file.seek(SeekFrom::Start(start)).is_err() || file.read_exact(&mut bytes).is_err() {
- return Response::builder().status(StatusCode::INTERNAL_SERVER_ERROR).body(Vec::new()).unwrap();
- }
- base.header(CONTENT_LENGTH, size)
- .header("Content-Range", format!("bytes {start}-{end}/{length}"))
- .status(StatusCode::PARTIAL_CONTENT)
- .body(bytes)
- .unwrap()
-}
-
-fn protocol_error(status: StatusCode, error: &str) -> Response<Vec<u8>> {
- log::warn!("{error}");
- Response::builder()
- .status(status)
- .header("Content-Type", "text/plain; charset=utf-8")
- .body(error.as_bytes().to_vec())
- .unwrap()
-}
-
-fn parse_single_byte_range(value: &str, length: u64) -> Option<(u64, u64)> {
- let value = value.strip_prefix("bytes=")?.split(',').next()?.trim();
- let (start, end) = value.split_once('-')?;
- if start.is_empty() {
- let suffix = end.parse::<u64>().ok()?;
- if suffix == 0 || length == 0 { return None; }
- return Some((length.saturating_sub(suffix), length - 1));
- }
- let start = start.parse::<u64>().ok()?;
- if start >= length { return None; }
- let end = if end.is_empty() { length - 1 } else { end.parse::<u64>().ok()?.min(length - 1) };
- (end >= start).then_some((start, end))
-}
-
-/// 动画子目录候选:(目录名, 扩展名),按优先级排列。
-///
-/// macOS 安装的是仓库 [dsh-tauri-desk/dsh-pet-mov] 的 HEVC-with-Alpha `mov/`,
-/// 其余平台是上游 VP9-alpha 的 `webm/`。两者文件名主名都等于 config.jsonc 的池
-/// 条目,播放层按主名取 URL,因此这里只按目录存在性选源,前端无需感知格式。
-const PRESET_ANIMATION_DIRS: [(&str, &str); 2] = [("mov", ".mov"), ("webm", ".webm")];
-
-/// 按优先级挑选动画目录,返回 主名 → 协议 URL 的映射(目录全缺/为空返回空表)。
-///
-/// 同一份 config.jsonc 的池条目对两种格式通用:命中第一个有内容的动画目录即停,
-/// 不会因为残留了另一种格式的目录而给出两套重叠 URL。
-fn collect_animation_assets(dir: &Path, id: &str) -> Result<BTreeMap<String, String>, String> {
- let mut assets = BTreeMap::new();
- for (subdir, extension) in PRESET_ANIMATION_DIRS {
- let animation_dir = dir.join(subdir);
- if !animation_dir.is_dir() {
- continue;
- }
- let mut entries = fs::read_dir(&animation_dir)
- .map_err(|error| format!("PET_PRESET_ASSETS_READ_FAILED: failed to list {}: {error}", animation_dir.display()))?;
- let mut files = Vec::new();
- while let Some(entry) = entries.next() {
- let entry = entry.map_err(|error| format!("PET_PRESET_ASSETS_READ_FAILED: {error}"))?;
- let file_name = entry.file_name();
- let Some(name) = file_name.to_str() else { continue };
- if name.ends_with(extension) {
- files.push(name.to_string());
- }
- }
- if files.is_empty() {
- continue;
- }
- files.sort();
- for file in files {
- let stem = file.strip_suffix(extension).unwrap_or(&file).to_string();
- let url = format!(
- "{PRESET_ASSET_ORIGIN}/{id}/{subdir}/{}",
- percent_encode_segment(&file)
- );
- assets.insert(stem, url);
- }
- break;
- }
- Ok(assets)
-}
-
-/// 列出已安装预设宠物的全部媒体(动画 + preview 首张 gif 兜底图)。
-/// 池条目(config.jsonc 里的动画名)即动画文件名主名,与 dsh-pet 协议一致。
-#[tauri::command]
-pub fn get_preset_pet_assets(app: AppHandle, id: String) -> Result<PresetPetAssets, String> {
- let id = id.trim();
- if !safe_preset_id(id) {
- return Err(format!("PET_PRESET_ID_INVALID: preset pet id {id:?} is not a safe id"));
- }
- let dir = installed_dir(&preset_pets_root(&app), id);
- if !dir.is_dir() {
- return Err(format!("PET_PRESET_NOT_INSTALLED: preset pet {id} is not installed"));
- }
- let mut assets = collect_animation_assets(&dir, id)?;
- // 兜底图:preview 目录第一张 gif(按文件名排序,与 dsh-pet preview 语义一致)。
- let preview_dir = dir.join("preview");
- if preview_dir.is_dir() {
- let mut entries = fs::read_dir(&preview_dir)
- .map_err(|error| format!("PET_PRESET_ASSETS_READ_FAILED: failed to list {}: {error}", preview_dir.display()))?;
- let mut gifs = Vec::new();
- while let Some(entry) = entries.next() {
- let entry = entry.map_err(|error| format!("PET_PRESET_ASSETS_READ_FAILED: {error}"))?;
- let file_name = entry.file_name();
- let Some(name) = file_name.to_str() else { continue };
- if name.ends_with(".gif") {
- gifs.push(name.to_string());
+ if let Some(kind) = spec.kind.as_deref() {
+ if kind != "dsh" && kind != "codex" {
+ return Err(format!(
+ "PET_PRESET_CATALOG_INVALID: preset {:?} kind must be dsh or codex",
+ spec.id
+ ));
}
}
- gifs.sort();
- if let Some(first) = gifs.into_iter().next() {
- let url = format!(
- "{PRESET_ASSET_ORIGIN}/{id}/preview/{}",
- percent_encode_segment(&first)
- );
- assets.insert("fallback".to_string(), url);
- }
- }
- Ok(PresetPetAssets { assets })
-}
-
-/// 统一预设配置校验错误前缀。
-fn preset_config_invalid(detail: impl Into<String>) -> String {
- format!("PET_PRESET_CONFIG_INVALID: {}", detail.into())
-}
-
-/// 校验已安装预设宠物的 config.jsonc 协议形状(dsh-pet assets/config.jsonc 协议子集):
-/// - 顶层必须含 pets(非空数组,每项有非空 id)与 animations / animationWeights;
-/// - animations 必须含 idle/turn/drag/clicks 字符串池、moves(default 对象 +
-/// actions 数组)、categories(id/weight/actions)、可选 events;
-/// - 池条目是动画名(webm 文件名主名),不做内置键白名单——合法性由
-/// get_preset_pet_assets 的文件清单兜底,未知名字在播放层自然不可解析;
-/// - animationWeights 的 idle/turn/move 必须是非负数字。
-/// 任一不符返回带 PET_PRESET_CONFIG_INVALID 前缀的错误,不做静默兜底。
-fn validate_preset_pet_config(value: &Value) -> Result<(), String> {
- let invalid = preset_config_invalid;
- let root = value
- .as_object()
- .ok_or_else(|| invalid("config root must be an object".to_string()))?;
-
- let pets = root
- .get("pets")
- .and_then(Value::as_array)
- .ok_or_else(|| invalid("pets must be a non-empty array".to_string()))?;
- if pets.is_empty() {
- return Err(invalid("pets must contain at least one pet".to_string()));
- }
- for pet in pets {
- let id = pet
- .get("id")
- .and_then(Value::as_str)
- .map(str::trim)
- .filter(|id| !id.is_empty())
- .ok_or_else(|| invalid("each pet must have a non-empty string id".to_string()))?;
- let _ = id;
- }
-
- let animations = root
- .get("animations")
- .and_then(Value::as_object)
- .ok_or_else(|| invalid("animations must be an object".to_string()))?;
- for pool in ["idle", "turn", "drag", "clicks"] {
- let entries = animations
- .get(pool)
- .and_then(Value::as_array)
- .ok_or_else(|| invalid(format!("animations.{pool} must be an array")))?;
- validate_preset_pool_entries(entries, pool)?;
- }
-
- let moves = animations
- .get("moves")
- .and_then(Value::as_object)
- .ok_or_else(|| invalid("animations.moves must be an object".to_string()))?;
- if !moves.contains_key("default") || moves.get("default").and_then(Value::as_object).is_none() {
- return Err(invalid("animations.moves.default must be an object".to_string()));
- }
- let move_actions = moves
- .get("actions")
- .and_then(Value::as_array)
- .ok_or_else(|| invalid("animations.moves.actions must be an array".to_string()))?;
- for action in move_actions {
- let name = action
- .get("name")
- .and_then(Value::as_str)
- .map(str::trim)
- .filter(|name| !name.is_empty())
- .ok_or_else(|| invalid("each moves action must have a non-empty name".to_string()))?;
- let _ = name;
}
-
- let categories = animations
- .get("categories")
- .and_then(Value::as_array)
- .ok_or_else(|| invalid("animations.categories must be an array".to_string()))?;
- for category in categories {
- let id = category
- .get("id")
- .and_then(Value::as_str)
- .map(str::trim)
- .filter(|id| !id.is_empty())
- .ok_or_else(|| invalid("each category must have a non-empty id".to_string()))?;
- let _ = id;
- let weight = category
- .get("weight")
- .and_then(Value::as_f64)
- .ok_or_else(|| invalid("each category must have a numeric weight".to_string()))?;
- if !weight.is_finite() || weight < 0.0 {
- return Err(invalid("category weight must be a non-negative number".to_string()));
- }
- let actions = category
- .get("actions")
- .and_then(Value::as_array)
- .ok_or_else(|| invalid("each category must have an actions array".to_string()))?;
- validate_preset_pool_entries(actions, "categories.actions")?;
- }
-
- if let Some(events) = animations.get("events") {
- let events = events
- .as_object()
- .ok_or_else(|| invalid("animations.events must be an object".to_string()))?;
- for (event, pool) in events {
- let pool = pool
- .as_array()
- .ok_or_else(|| invalid(format!("animations.events.{event} must be an array")))?;
- validate_preset_pool_entries(pool, &format!("events.{event}"))?;
- }
- }
-
- let weights = root
- .get("animationWeights")
- .and_then(Value::as_object)
- .ok_or_else(|| invalid("animationWeights must be an object".to_string()))?;
- for key in ["idle", "turn", "move"] {
- let weight = weights
- .get(key)
- .and_then(Value::as_f64)
- .ok_or_else(|| invalid(format!("animationWeights.{key} must be a number")))?;
- if !weight.is_finite() || weight < 0.0 {
- return Err(invalid(format!(
- "animationWeights.{key} must be a non-negative number"
- )));
- }
- }
- Ok(())
-}
-
-/// 池条目必须是非空字符串;空池(无动画可用)也允许,由运行时回落默认动画,
-/// 但写了空字符串必须显式报错。
-fn validate_preset_pool_entries(entries: &[Value], pool: &str) -> Result<(), String> {
- let invalid = preset_config_invalid;
- for entry in entries {
- let name = entry
- .as_str()
- .map(str::trim)
- .filter(|name| !name.is_empty())
- .ok_or_else(|| invalid(format!("{pool} entries must be non-empty strings")))?;
- let _ = name;
- }
- Ok(())
+ Ok(catalog)
}
-/// 读取并解析已安装预设宠物的 config.jsonc(JSONC 协议),返回校验后的 JSON。
-/// 与媒体同一资源边界:固定文件名 + 已安装目录 + 限量读取 + 显式错误前缀。
+/// 列出预设宠物清单(前端按当前激活 id 自行取用;条目即 `<Pet>` 的渲染参数)。
#[tauri::command]
-pub fn get_preset_pet_config(app: AppHandle, id: String) -> Result<Value, String> {
- let id = id.trim();
- if !safe_preset_id(id) {
- return Err(format!("PET_PRESET_ID_INVALID: preset pet id {id:?} is not a safe id"));
- }
- let dir = installed_dir(&preset_pets_root(&app), id);
- if !dir.is_dir() {
- return Err(format!("PET_PRESET_NOT_INSTALLED: preset pet {id} is not installed"));
- }
- let path = dir.join("config.jsonc");
- let bytes = read_bounded_file(&path, PET_PRESET_CONFIG_MAX_BYTES, "PET_PRESET_CONFIG_READ_FAILED")?;
- let text = std::str::from_utf8(&bytes)
- .map_err(|error| format!("PET_PRESET_CONFIG_INVALID: config.jsonc is not UTF-8: {error}"))?;
- let json = strip_jsonc(text);
- let value: Value = serde_json::from_str(&json)
- .map_err(|error| format!("PET_PRESET_CONFIG_INVALID: invalid JSON: {error}"))?;
- validate_preset_pet_config(&value)?;
- Ok(value)
+pub fn list_preset_pets(app: AppHandle) -> Result<Vec<PresetPetSpec>, String> {
+ read_preset_catalog(&app)
}
#[cfg(test)]
mod tests {
use super::*;
- use std::io::Cursor;
-
- struct TestDirectory(PathBuf);
- impl TestDirectory {
- fn new(name: &str) -> Self {
- let nonce = SystemTime::now()
- .duration_since(UNIX_EPOCH)
- .unwrap_or_default()
- .as_nanos();
- Self(
- std::env::temp_dir().join(format!("dsh-preset-{name}-{}-{nonce}", std::process::id())),
- )
- }
- }
-
- impl Drop for TestDirectory {
- fn drop(&mut self) {
- let _ = fs::remove_dir_all(&self.0);
- }
+ fn shipped_catalog() -> Vec<PresetPetSpec> {
+ let bytes = fs::read(concat!(
+ env!("CARGO_MANIFEST_DIR"),
+ "/resources/preset-pets.json"
+ ))
+ .unwrap();
+ let catalog: Vec<PresetPetSpec> = serde_json::from_slice(&bytes).unwrap();
+ assert!(!catalog.is_empty(), "预设清单不应为空");
+ catalog
}
- fn build_tar_gz(entries: &[(&str, &[u8])]) -> Vec<u8> {
- let mut encoder = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::default());
- {
- let mut archive = tar::Builder::new(&mut encoder);
- for (name, bytes) in entries {
- let mut header = tar::Header::new_gnu();
- header.set_size(bytes.len() as u64);
- header.set_mode(0o100644);
- header.set_cksum();
- archive.append_data(&mut header, name, Cursor::new(bytes)).unwrap();
+ #[test]
+ fn shipped_catalog_is_valid_and_remote_only() {
+ // 随包分发的清单是唯一事实来源:字段名/形状写错必须在这里炸,
+ // 而不是等用户点「启用」才在运行时静默失败。
+ for spec in shipped_catalog() {
+ assert!(safe_preset_id(&spec.id), "非法 id: {}", spec.id);
+ assert!(!spec.name.trim().is_empty());
+ assert!(!spec.config.trim().is_empty());
+ assert!(!spec.uri.default.trim().is_empty());
+ // 不再有本地安装:素材与配置都必须是远端地址。
+ assert!(
+ spec.config.starts_with("https://"),
+ "config 必须是 https 地址"
+ );
+ assert!(
+ spec.uri.default.starts_with("https://"),
+ "uri.default 必须是 https 地址"
+ );
+ if let Some(kind) = spec.kind.as_deref() {
+ assert!(kind == "dsh" || kind == "codex");
}
}
- encoder.finish().unwrap()
}
- /// 手工构造含非法路径条目的 tar.gz(tar::Builder 会拒绝 `..`,这里绕开其校验,
- /// 先把非法条目按 POSIX ustar 头格式写入字节流,再追加正常条目并收尾)。
- fn build_tar_gz_with_raw_entry(good: &[(&str, &[u8])], raw_name: &str, raw_bytes: &[u8]) -> Vec<u8> {
- let mut tar_bytes = Vec::new();
- // 先写非法路径条目(必须在 end-of-archive 零块之前,否则 tar 读不到)。
- let mut header = [0_u8; 512];
- let name = raw_name.as_bytes();
- header[..name.len().min(100)].copy_from_slice(&name[..name.len().min(100)]);
- header[100..108].copy_from_slice(b"0000644\0"); // mode
- header[108..116].copy_from_slice(b"0000000\0"); // uid
- header[116..124].copy_from_slice(b"0000000\0"); // gid
- header[124..136].copy_from_slice(&format!("{:011o}\0", raw_bytes.len()).as_bytes()); // size
- header[136..148].copy_from_slice(b"00000000000\0"); // mtime
- header[156] = b'0'; // typeflag = regular file
- let checksum: u32 = header.iter().map(|byte| u32::from(*byte)).sum();
- header[148..156].copy_from_slice(&format!("{checksum:06o}\0 ").as_bytes());
- tar_bytes.extend_from_slice(&header);
- let mut data = raw_bytes.to_vec();
- while data.len() % 512 != 0 {
- data.push(0);
- }
- tar_bytes.extend_from_slice(&data);
- // 正常条目 + 收尾零块。
- {
- let mut archive = tar::Builder::new(&mut tar_bytes);
- for (name, bytes) in good {
- let mut header = tar::Header::new_gnu();
- header.set_size(bytes.len() as u64);
- header.set_mode(0o100644);
- header.set_cksum();
- archive.append_data(&mut header, name, Cursor::new(bytes)).unwrap();
- }
- archive.finish().unwrap();
- }
- let mut encoder = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::default());
- encoder.write_all(&tar_bytes).unwrap();
- encoder.finish().unwrap()
+ #[test]
+ fn shipped_catalog_provides_macos_mov_override() {
+ // macOS 的 WKWebView 不认 VP9-alpha:至少一个预设必须给出 .mov 覆盖块。
+ let spec = shipped_catalog()
+ .into_iter()
+ .find(|spec| spec.uri.mac.is_some())
+ .expect("至少一个预设应提供 macOS 素材覆盖");
+ let mac = spec.uri.mac.unwrap();
+ assert!(mac.starts_with("https://"));
+ assert!(mac.ends_with("/mov"), "macOS 素材目录应为 mov/: {mac}");
+ assert_eq!(
+ spec.ext.as_ref().and_then(|ext| ext.mac.as_deref()),
+ Some("mov")
+ );
}
#[test]
- fn catalog_deserializes_with_defaults_and_rejects_unknown_shape() {
+ fn catalog_entry_deserializes_with_defaults_and_rejects_unknown_fields() {
let spec: PresetPetSpec = serde_json::from_str(
r#"{
"id": "maid-deepseek-whale",
"name": "Maid DeepSeek Whale",
- "repo": "https://github.com/PC2005-cloud/dsh-pet",
- "assets": "dsh-pet/assets",
- "sizeMb": 113
+ "config": "https://example.com/config.jsonc",
+ "uri": { "default": "https://example.com/webm" }
}"#,
)
.unwrap();
assert_eq!(spec.id, "maid-deepseek-whale");
- assert_eq!(spec.r#ref, None);
- assert_eq!(spec.size_mb, Some(113.0));
- assert_eq!(spec.image, None);
- assert!(spec.platforms.is_empty());
- }
-
- #[test]
- fn platform_override_switches_only_macos_to_the_mov_repository() {
- // 与 resources/preset-pets.json 同形状:macOS 换仓库/空前缀/尺寸,其余继承。
- let base: PresetPetSpec = serde_json::from_str(
+ assert_eq!(spec.desc, None);
+ assert_eq!(spec.kind, None);
+ assert_eq!(spec.size, None);
+ assert_eq!(spec.ext, None);
+ assert_eq!(spec.uri.mac, None);
+
+ // 字段名写错(如旧的 sizeMb)必须立刻报错,而不是被静默忽略。
+ let error = serde_json::from_str::<PresetPetSpec>(
r#"{
- "id": "maid-deepseek-whale",
- "name": "Maid DeepSeek Whale",
- "desc": "base",
- "image": "https://example.com/preview.gif",
- "repo": "https://github.com/PC2005-cloud/dsh-pet",
- "ref": "e1ff8c1",
- "assets": "dsh-pet/assets",
- "sizeMb": 113,
- "platforms": {
- "macos": {
- "repo": "https://github.com/dsh-tauri-desk/dsh-pet-mov",
- "ref": "be0f3bb",
- "assets": "",
- "sizeMb": 79
- }
- }
+ "id": "x",
+ "name": "X",
+ "config": "https://example.com/config.jsonc",
+ "uri": { "default": "https://example.com/webm" },
+ "sizeMb": 113
}"#,
)
- .unwrap();
-
- // 非 macOS:覆盖块不生效,仍用上游 webm 仓库。
- let mut untouched = base.clone();
- apply_platform_override(&mut untouched, "windows");
- assert_eq!(untouched.repo, "https://github.com/PC2005-cloud/dsh-pet");
- assert_eq!(untouched.assets, "dsh-pet/assets");
- assert_eq!(untouched.r#ref.as_deref(), Some("e1ff8c1"));
- assert_eq!(untouched.size_mb, Some(113.0));
- assert_eq!(
- tarball_urls(&untouched).unwrap()[0],
- "https://codeload.github.com/PC2005-cloud/dsh-pet/tar.gz/e1ff8c1"
- );
-
- // macOS:换到只含 config.jsonc + mov/ 的仓库,assets 为空前缀(仓库根即素材)。
- let mut macos = base;
- apply_platform_override(&mut macos, "macos");
- assert_eq!(macos.repo, "https://github.com/dsh-tauri-desk/dsh-pet-mov");
- assert_eq!(macos.assets, "");
- assert_eq!(macos.r#ref.as_deref(), Some("be0f3bb"));
- assert_eq!(macos.size_mb, Some(79.0));
- // 覆盖块未写的字段继续继承基础条目。
- assert_eq!(macos.desc.as_deref(), Some("base"));
- assert_eq!(macos.image.as_deref(), Some("https://example.com/preview.gif"));
- assert_eq!(
- tarball_urls(&macos).unwrap()[0],
- "https://codeload.github.com/dsh-tauri-desk/dsh-pet-mov/tar.gz/be0f3bb"
- );
- // 覆盖块被消费后不再残留,避免同一 spec 二次套用。
- assert!(macos.platforms.is_empty());
- }
-
- #[test]
- fn shipped_catalog_parses_and_macos_override_is_downloadable() {
- // 随包分发的清单是唯一事实来源:字段名/形状写错必须在这里炸,
- // 而不是等用户点「下载」才在运行时静默沿用基础取值。
- let bytes = fs::read(concat!(env!("CARGO_MANIFEST_DIR"), "/resources/preset-pets.json")).unwrap();
- let mut catalog: Vec<PresetPetSpec> = serde_json::from_slice(&bytes).unwrap();
- assert!(!catalog.is_empty(), "预设清单不应为空");
-
- let mov = catalog
- .iter()
- .find(|spec| spec.platforms.contains_key("macos"))
- .expect("至少一个预设应提供 macOS 覆盖块");
- let (owner, repo) = parse_repo_owner(
- &mov.platforms["macos"].repo.clone().expect("macOS 覆盖块必须给出 repo"),
- )
- .unwrap();
- assert_eq!((owner.as_str(), repo.as_str()), ("dsh-tauri-desk", "dsh-pet-mov"));
- // dsh-pet-mov 只保留 config.jsonc 与 mov/:素材目录就是仓库根。
- assert_eq!(mov.platforms["macos"].assets.as_deref(), Some(""));
-
- for spec in &mut catalog {
- // 基础条目与 macOS 覆盖都必须能构造出下载地址。
- tarball_urls(spec).unwrap();
- apply_platform_override(spec, "macos");
- tarball_urls(spec).unwrap();
- }
- }
-
- #[test]
- fn repo_owner_parsing_accepts_github_forms_and_rejects_others() {
- assert_eq!(
- parse_repo_owner("https://github.com/PC2005-cloud/dsh-pet").unwrap(),
- ("PC2005-cloud".to_string(), "dsh-pet".to_string())
- );
- assert_eq!(
- parse_repo_owner("http://github.com/owner/repo.git").unwrap(),
- ("owner".to_string(), "repo".to_string())
+ .unwrap_err();
+ assert!(
+ error.to_string().contains("sizeMb"),
+ "unexpected error: {error}"
);
- for invalid in ["https://gitlab.com/o/r", "ftp://github.com/o/r", "https://github.com/o", "not a url"] {
- assert!(
- parse_repo_owner(invalid).is_err(),
- "应拒绝 {invalid}"
- );
- }
}
#[test]
- fn tarball_urls_use_pinned_ref_and_append_mirror() {
+ fn serialization_omits_absent_optional_fields() {
+ // 前端 props 里 optional 字段缺省即 undefined:null 会让 `mac?: string` 变成 null。
let spec = PresetPetSpec {
id: "p".to_string(),
name: "P".to_string(),
desc: None,
image: None,
- repo: "https://github.com/PC2005-cloud/dsh-pet".to_string(),
- assets: "dsh-pet/assets".to_string(),
- r#ref: Some("f0f772e".to_string()),
- size_mb: None,
- platforms: HashMap::new(),
- };
- let urls = tarball_urls(&spec).unwrap();
- assert_eq!(
- urls[0],
- "https://codeload.github.com/PC2005-cloud/dsh-pet/tar.gz/f0f772e"
- );
- assert!(urls[1].starts_with("https://ghfast.top/"));
- assert_eq!(urls[1], format!("https://ghfast.top/{}", urls[0]));
- }
-
- #[test]
- fn extraction_keeps_only_assets_prefix_and_strips_root_and_prefix() {
- let tarball = build_tar_gz(&[
- ("dsh-pet-f0f772e/dsh-pet/assets/config.jsonc", br#"{"animations":{}}"#),
- ("dsh-pet-f0f772e/dsh-pet/assets/webm/待机呼吸休闲.webm", b"webm-bytes"),
- ("dsh-pet-f0f772e/README.md", b"skip-me"),
- ("dsh-pet-f0f772e/dsh-pet/src/client.ts", b"skip-source"),
- ]);
- let directory = TestDirectory::new("prefix");
- fs::create_dir_all(&directory.0).unwrap();
- let tarball_path = directory.0.join("pkg.tar.gz");
- fs::write(&tarball_path, &tarball).unwrap();
- let staging = directory.0.join("staging");
- extract_preset_assets(&tarball_path, &staging, "dsh-pet/assets").unwrap();
- assert!(staging.join("config.jsonc").is_file());
- assert!(staging.join("webm/待机呼吸休闲.webm").is_file());
- assert_eq!(
- fs::read(staging.join("webm/待机呼吸休闲.webm")).unwrap(),
- b"webm-bytes"
- );
- assert!(!staging.join("README.md").exists());
- assert!(!staging.join("src/client.ts").exists());
- }
-
- #[test]
- fn empty_assets_prefix_extracts_the_whole_repository_root() {
- // dsh-pet-mov 只保留 config.jsonc + mov/,清单用空前缀把仓库根当素材目录。
- let tarball = build_tar_gz(&[
- ("dsh-pet-mov-be0f3bb/config.jsonc", br#"{"animations":{}}"#),
- ("dsh-pet-mov-be0f3bb/mov/待机呼吸休闲.mov", b"mov-bytes"),
- ("dsh-pet-mov-be0f3bb/README.md", b"readme"),
- ]);
- let directory = TestDirectory::new("root-prefix");
- fs::create_dir_all(&directory.0).unwrap();
- let tarball_path = directory.0.join("pkg.tar.gz");
- fs::write(&tarball_path, &tarball).unwrap();
- let staging = directory.0.join("staging");
- extract_preset_assets(&tarball_path, &staging, "").unwrap();
- assert!(staging.join("config.jsonc").is_file());
- assert!(staging.join("mov/待机呼吸休闲.mov").is_file());
- assert_eq!(fs::read(staging.join("mov/待机呼吸休闲.mov")).unwrap(), b"mov-bytes");
- // 仓库根仍以 `<repo>-<ref>/` 第一段被剥掉,不落盘。
- assert!(!staging.join("dsh-pet-mov-be0f3bb").exists());
-
- // GitHub codeload 的 tar.gz 首条是 pax 全局头(typeflag 'g',名为
- // `pax_global_header`):空前缀下它不能落盘成文件,也不能覆盖真实条目。
- let mut encoder = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::default());
- {
- let mut archive = tar::Builder::new(&mut encoder);
- archive.append_pax_extensions([("comment", &b"codeload test"[..])]).unwrap();
- for (name, bytes) in [
- ("dsh-pet-mov-be0f3bb/config.jsonc", &br#"{"animations":{}}"#[..]),
- ("dsh-pet-mov-be0f3bb/mov/待机呼吸休闲.mov", b"mov-bytes"),
- ] {
- let mut header = tar::Header::new_gnu();
- header.set_size(bytes.len() as u64);
- header.set_mode(0o100644);
- header.set_cksum();
- archive.append_data(&mut header, name, Cursor::new(bytes)).unwrap();
- }
- }
- let with_pax = encoder.finish().unwrap();
- let pax_tarball = directory.0.join("pax.tar.gz");
- fs::write(&pax_tarball, &with_pax).unwrap();
- let pax_staging = directory.0.join("pax-staging");
- extract_preset_assets(&pax_tarball, &pax_staging, "").unwrap();
- assert!(pax_staging.join("config.jsonc").is_file());
- assert!(pax_staging.join("mov/待机呼吸休闲.mov").is_file());
- assert!(!pax_staging.join("pax_global_header").exists(), "pax 全局头不得落盘");
- }
-
- #[test]
- fn asset_mime_whitelists_webm_mov_and_gif_only() {
- assert_eq!(preset_asset_mime("待机呼吸休闲.webm"), Some("video/webm"));
- // HEVC-with-Alpha 必须是 video/quicktime,WKWebView 才交给 AVFoundation 解码 alpha。
- assert_eq!(preset_asset_mime("待机呼吸休闲.mov"), Some("video/quicktime"));
- assert_eq!(preset_asset_mime("daiji.gif"), Some("image/gif"));
- for rejected in ["evil.sh", "clip.mp4", "noext", "clip.mov.exe"] {
- assert_eq!(preset_asset_mime(rejected), None, "应拒绝 {rejected}");
- }
- }
-
- #[test]
- fn animation_assets_prefer_mov_over_webm() {
- let directory = TestDirectory::new("anim-source");
- let macos_pet = directory.0.join("macos-pet");
- fs::create_dir_all(macos_pet.join("mov")).unwrap();
- fs::write(macos_pet.join("mov/待机呼吸休闲.mov"), b"mov").unwrap();
- fs::write(macos_pet.join("mov/东张西望.mov"), b"mov").unwrap();
- // 目录里的非动画文件不应进入 manifest(池条目只会按主名取 URL)。
- fs::write(macos_pet.join("mov/notes.txt"), b"skip").unwrap();
- let assets = collect_animation_assets(&macos_pet, "macos-pet").unwrap();
- assert_eq!(assets.len(), 2);
- assert_eq!(
- assets.get("待机呼吸休闲"),
- Some(&format!(
- "{PRESET_ASSET_ORIGIN}/macos-pet/mov/{}",
- percent_encode_segment("待机呼吸休闲.mov")
- ))
- );
-
- // 只有 webm/(非 macOS 安装)时回落 webm。
- let other_pet = directory.0.join("other-pet");
- fs::create_dir_all(other_pet.join("webm")).unwrap();
- fs::write(other_pet.join("webm/待机呼吸休闲.webm"), b"webm").unwrap();
- let assets = collect_animation_assets(&other_pet, "other-pet").unwrap();
- assert_eq!(
- assets.get("待机呼吸休闲"),
- Some(&format!(
- "{PRESET_ASSET_ORIGIN}/other-pet/webm/{}",
- percent_encode_segment("待机呼吸休闲.webm")
- ))
- );
-
- // 两种目录同时存在时以 mov/ 为准,不会产出两套重叠 URL。
- fs::create_dir_all(other_pet.join("mov")).unwrap();
- fs::write(other_pet.join("mov/待机呼吸休闲.mov"), b"mov").unwrap();
- let assets = collect_animation_assets(&other_pet, "other-pet").unwrap();
- assert_eq!(assets.len(), 1);
- assert_eq!(
- assets.get("待机呼吸休闲"),
- Some(&format!(
- "{PRESET_ASSET_ORIGIN}/other-pet/mov/{}",
- percent_encode_segment("待机呼吸休闲.mov")
- ))
- );
-
- // 目录缺失 / 目录为空都返回空表而不报错。
- assert!(collect_animation_assets(&directory.0.join("missing"), "missing").unwrap().is_empty());
- let empty_pet = directory.0.join("empty-pet");
- fs::create_dir_all(empty_pet.join("mov")).unwrap();
- assert!(collect_animation_assets(&empty_pet, "empty-pet").unwrap().is_empty());
- }
-
- #[test]
- fn extraction_reports_uncompressed_bytes_via_progress_callback() {
- let tarball = build_tar_gz(&[
- ("dsh-pet-f0f772e/dsh-pet/assets/webm/一.webm", b"0123456789"),
- ("dsh-pet-f0f772e/dsh-pet/assets/webm/二.webm", b"abcdefghijklmno"),
- ]);
- let directory = TestDirectory::new("progress");
- fs::create_dir_all(&directory.0).unwrap();
- let tarball_path = directory.0.join("pkg.tar.gz");
- fs::write(&tarball_path, &tarball).unwrap();
- let staging = directory.0.join("staging");
- let mut reported = Vec::new();
- extract_preset_assets_with_progress(
- &tarball_path,
- &staging,
- "dsh-pet/assets",
- Some(&mut |bytes| reported.push(bytes)),
- )
- .unwrap();
- // 每个文件解压后回调一次,字节数单调不减,末值 = 全部已解压字节。
- assert_eq!(reported, vec![10, 10 + 15]);
- }
-
- #[test]
- fn extraction_rejects_traversal_and_links_before_writing() {
- let directory = TestDirectory::new("traversal");
- fs::create_dir_all(&directory.0).unwrap();
-
- // traversal:tar 0.4 的 Archive 自身会拒绝 `..` 条目(读取即报错/跳过),
- // 解压层还有 safe_relative_path 兜底;这里断言无论哪一层拒绝,都不能把
- // 文件写到 staging 之外。
- let traversal = build_tar_gz_with_raw_entry(
- &[("root/dsh-pet/assets/config.jsonc", br#"{"animations":{}}"#)],
- "root/dsh-pet/assets/../escape.txt",
- b"bad",
- );
- let tarball_path = directory.0.join("bad.tar.gz");
- fs::write(&tarball_path, &traversal).unwrap();
- let staging = directory.0.join("staging");
- let result = extract_preset_assets(&tarball_path, &staging, "dsh-pet/assets");
- if let Err(error) = result {
- assert!(
- error.starts_with("PET_PRESET_PATH_INVALID:")
- || error.starts_with("PET_PRESET_EXTRACT_FAILED:")
- );
- }
- assert!(!directory.0.join("escape.txt").exists(), "不得逃逸到 staging 之外");
-
- // safe_relative_path 直接兜底:任何 traversal/绝对/反斜杠/冒号路径必须被拒。
- for bad in ["../escape", "/absolute", "a/../../escape", "C:/escape", "..\\escape", "a:b"] {
- assert!(
- safe_relative_path(bad).is_err(),
- "应拒绝 {bad}"
- );
- }
- assert!(safe_relative_path("webm/待机呼吸休闲.webm").is_ok());
-
- // symlink 条目应被拒绝(entry_type = Symlink)
- let mut encoder = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::default());
- {
- let mut archive = tar::Builder::new(&mut encoder);
- let mut manifest = tar::Header::new_gnu();
- manifest.set_size(br#"{"animations":{}}"#.len() as u64);
- manifest.set_mode(0o100644);
- manifest.set_cksum();
- archive
- .append_data(
- &mut manifest,
- "root/dsh-pet/assets/config.jsonc",
- Cursor::new(br#"{"animations":{}}"#),
- )
- .unwrap();
- let mut link = tar::Header::new_gnu();
- link.set_entry_type(tar::EntryType::Symlink);
- link.set_mode(0o120777);
- link.set_size(0);
- link.set_cksum();
- archive.append_link(&mut link, "root/dsh-pet/assets/link", "config.jsonc").unwrap();
- }
- let with_link = encoder.finish().unwrap();
- let tarball_path = directory.0.join("link.tar.gz");
- fs::write(&tarball_path, &with_link).unwrap();
- let staging = directory.0.join("staging2");
- let link_result = extract_preset_assets(&tarball_path, &staging, "dsh-pet/assets");
- assert!(
- link_result.as_ref().err().map(String::as_str).unwrap_or("").starts_with("PET_PRESET_LINK_FORBIDDEN:"),
- "unexpected link result: {link_result:?}"
- );
- assert!(!staging.join("link").exists(), "不得落盘链接条目");
- let _ = fs::remove_dir_all(&staging);
- }
-
- #[test]
- fn config_validation_requires_animations_object() {
- let directory = TestDirectory::new("config");
- fs::create_dir_all(directory.0.join("staging")).unwrap();
- fs::write(
- directory.0.join("staging/config.jsonc"),
- "// 注释\n{\n \"animations\": { \"idle\": [\"idle\"] }\n}\n",
- )
- .unwrap();
- assert!(validate_preset_config(&directory.0.join("staging")).is_ok());
-
- let missing = directory.0.join("staging-missing");
- fs::create_dir_all(&missing).unwrap();
- fs::write(missing.join("config.jsonc"), "{\"pets\": []}").unwrap();
- assert!(validate_preset_config(&missing)
- .unwrap_err()
- .starts_with("PET_PRESET_CONFIG_INVALID:"));
- }
-
- #[test]
- fn progress_registry_round_trips_and_defaults_to_idle() {
- assert_eq!(get_preset_progress("nope").phase, "idle");
- set_preset_progress(
- "p1",
- PresetDownloadProgress {
- phase: "downloading".to_string(),
- received: 10,
- total: 100,
- error: None,
+ kind: Some("dsh".to_string()),
+ size: Some(220.0),
+ config: "https://example.com/config.jsonc".to_string(),
+ uri: PresetPetUri {
+ default: "https://example.com/webm".to_string(),
+ mac: None,
},
- );
- let progress = get_preset_progress("p1");
- assert_eq!(progress.phase, "downloading");
- assert_eq!(progress.received, 10);
- assert_eq!(progress.total, 100);
- }
-
- #[test]
- fn preset_config_accepts_protocol_shaped_document() {
- let value: Value = serde_json::from_str(
- r#"{
- "pets": [{ "id": "main", "name": "蓝毛小女仆", "size": 462 }],
- "animations": {
- "idle": ["待机呼吸休闲"],
- "turn": ["东张西望"],
- "drag": ["被鼠标拖拽悬空反馈"],
- "clicks": ["点击回应-开心跃动", "点击回应-元气挥手"],
- "moves": {
- "default": { "minDist": 60, "maxDist": 240, "margin": 20, "leadSec": 2, "tailSec": 2 },
- "actions": [{ "name": "螃蟹走路" }, { "name": "原地漂浮踏步", "params": { "minDist": 40 } }]
- },
- "categories": [
- { "id": "小动作", "weight": 20, "actions": ["悠闲哼歌", "写代码"] },
- { "id": "文字", "weight": 10, "noMirror": true, "actions": ["是啊,吃什么"] }
- ],
- "events": { "balance": ["余额-钱袋满溢"], "whisper": ["碎碎念-擦桌碎碎念"] }
- },
- "eventsRefreshSec": { "balance": 1800, "whisper": 300 },
- "animationWeights": { "idle": 10, "turn": 5, "move": 5 },
- "physics": { "gravity": 1400 }
-}"#,
- )
- .unwrap();
- assert!(validate_preset_pet_config(&value).is_ok());
- }
-
- #[test]
- fn preset_config_rejects_bad_shape_and_empty_entries() {
- let missing_pets: Value = serde_json::from_str(
- r#"{
- "animations": {
- "idle": ["待机呼吸休闲"], "turn": ["东张西望"],
- "drag": ["被鼠标拖拽悬空反馈"], "clicks": ["点击回应-开心跃动"],
- "moves": { "default": {}, "actions": [] }, "categories": []
- },
- "animationWeights": { "idle": 1, "turn": 1, "move": 1 }
-}"#,
- )
- .unwrap();
- assert!(validate_preset_pet_config(&missing_pets)
- .unwrap_err()
- .starts_with("PET_PRESET_CONFIG_INVALID:"));
-
- let empty_entry: Value = serde_json::from_str(
- r#"{
- "pets": [{ "id": "main" }],
- "animations": {
- "idle": [""], "turn": ["东张西望"],
- "drag": ["被鼠标拖拽悬空反馈"], "clicks": ["点击回应-开心跃动"],
- "moves": { "default": {}, "actions": [] }, "categories": []
- },
- "animationWeights": { "idle": 1, "turn": 1, "move": 1 }
-}"#,
- )
- .unwrap();
- assert!(validate_preset_pet_config(&empty_entry)
- .unwrap_err()
- .starts_with("PET_PRESET_CONFIG_INVALID:"));
-
- let bad_weights: Value = serde_json::from_str(
- r#"{
- "pets": [{ "id": "main" }],
- "animations": {
- "idle": ["待机呼吸休闲"], "turn": ["东张西望"],
- "drag": ["被鼠标拖拽悬空反馈"], "clicks": ["点击回应-开心跃动"],
- "moves": { "default": {}, "actions": [] }, "categories": []
- },
- "animationWeights": { "idle": -1, "turn": 1, "move": 1 }
-}"#,
- )
- .unwrap();
- assert!(validate_preset_pet_config(&bad_weights)
- .unwrap_err()
- .starts_with("PET_PRESET_CONFIG_INVALID:"));
- }
-
- #[test]
- fn percent_round_trips_and_rejects_bad_input() {
- assert_eq!(percent_encode_segment("待机呼吸休闲.webm"), "%E5%BE%85%E6%9C%BA%E5%91%BC%E5%90%B8%E4%BC%91%E9%97%B2.webm");
- assert_eq!(percent_encode_segment("maid-idle.webm"), "maid-idle.webm");
- assert_eq!(
- percent_decode_segment("%E5%BE%85%E6%9C%BA%E5%91%BC%E5%90%B8%E4%BC%91%E9%97%B2.webm").unwrap(),
- "待机呼吸休闲.webm"
- );
- assert_eq!(percent_decode_segment("maid-idle.webm").unwrap(), "maid-idle.webm");
- assert!(percent_decode_segment("%E5%ZZ").is_err());
- assert!(percent_decode_segment("%E5%BE").is_err());
- // 半截编码应报错而非静默截断
- assert!(percent_decode_segment("abc%").is_err());
- }
-
- #[test]
- fn preset_asset_path_parses_segments_and_rejects_traversal() {
- assert_eq!(
- preset_asset_path("/maid-deepseek-whale/webm/%E5%BE%85.webm"),
- Some(("maid-deepseek-whale", "webm", "%E5%BE%85.webm"))
- );
- assert_eq!(
- preset_asset_path("/localhost/maid-deepseek-whale/preview/daiji.gif"),
- Some(("maid-deepseek-whale", "preview", "daiji.gif"))
- );
- // macOS 的 HEVC-with-Alpha 素材(dsh-pet-mov 的 mov/)。
- assert_eq!(
- preset_asset_path("/maid-deepseek-whale/mov/%E5%BE%85.mov"),
- Some(("maid-deepseek-whale", "mov", "%E5%BE%85.mov"))
- );
- assert_eq!(preset_asset_path("/a/b/c/d"), None);
- assert_eq!(preset_asset_path("/../escape/webm/x.webm"), None);
- assert_eq!(preset_asset_path("/a\\b/webm/x.webm"), None);
- assert_eq!(preset_asset_path("/a/webm/"), None);
- assert_eq!(preset_asset_path("/a/webm/../x.webm"), None);
- }
-
- #[test]
- fn strip_jsonc_removes_comments_outside_strings() {
- let src = r#"{
- // 行注释
- "url": "https://example.com/a//b", /* 块注释 */ "s": "/* kept */"
-}"#;
- let stripped = strip_jsonc(src);
- assert!(!stripped.contains("行注释"));
- assert!(!stripped.contains("块注释"));
- assert!(stripped.contains("\"https://example.com/a//b\""));
- assert!(stripped.contains("\"/* kept */\""));
- let parsed: Value = serde_json::from_str(&stripped).expect("valid JSON");
- assert_eq!(parsed["url"], "https://example.com/a//b");
- }
-
- #[test]
- fn installed_ref_round_trips_and_handles_missing() {
- let directory = TestDirectory::new("ref");
- fs::create_dir_all(&directory.0).unwrap();
- // 无记录 → None(旧安装视为未知版本,不误判为最新)。
- assert_eq!(read_installed_ref(&directory.0), None);
- // 写入后可读回;空白内容视为无记录。
- write_installed_ref(&directory.0, "e1ff8c1e4001878cbb80441262d530e16541f138").unwrap();
- assert_eq!(
- read_installed_ref(&directory.0).as_deref(),
- Some("e1ff8c1e4001878cbb80441262d530e16541f138")
- );
- fs::write(directory.0.join(PRESET_REF_FILE), " ").unwrap();
- assert_eq!(read_installed_ref(&directory.0), None);
- }
-
- #[test]
- fn update_available_requires_installed_and_differs_from_catalog_ref() {
- // 未安装 → 不可更新(走下载入口)。
- assert!(!preset_update_available(false, Some("abc"), Some("abc")));
- assert!(!preset_update_available(false, Some("abc"), None));
- // 已安装且清单未固定 ref(跟随 main)→ 无法检测差异,不可更新。
- assert!(!preset_update_available(true, None, Some("abc")));
- assert!(!preset_update_available(true, None, None));
- // 已安装且 ref 与安装记录一致 → 最新,不可更新。
- assert!(!preset_update_available(true, Some("abc"), Some("abc")));
- // 已安装且 ref 不一致 → 可更新。
- assert!(preset_update_available(true, Some("abc"), Some("def")));
- // 已安装但无安装记录(升级前下载的旧安装)→ 无法确认版本,视为可更新。
- assert!(preset_update_available(true, Some("abc"), None));
- }
-
- #[test]
- fn install_staging_replaces_existing_with_backup_and_rolls_back_on_failure() {
- let directory = TestDirectory::new("replace");
- let root = directory.0.join("root");
- fs::create_dir_all(&root).unwrap();
- let target = root.join("pets");
- let staging = root.join("staging");
- fs::create_dir_all(&target).unwrap();
- fs::write(target.join("old-config.jsonc"), b"old").unwrap();
- fs::create_dir_all(&staging).unwrap();
- fs::write(staging.join("new-config.jsonc"), b"new").unwrap();
-
- // 替换:旧目录被换出,新目录就位,备份被清理。
- let nonce = 100_u128;
- install_staging(&root, "pets", nonce, &staging, &target, true).unwrap();
- assert!(target.join("new-config.jsonc").is_file());
- assert!(!target.join("old-config.jsonc").exists());
- assert!(!root.join(".preset-backup-pets-100").exists());
-
- // 替换失败(staging 缺失)→ 回滚备份,旧版本完整保留。
- let bad_staging = root.join("bad-staging");
- let err = install_staging(&root, "pets", nonce + 1, &bad_staging, &target, true).unwrap_err();
- assert!(err.starts_with("PET_PRESET_INSTALL_FAILED:"));
- assert!(target.join("new-config.jsonc").is_file(), "回滚后保留新版本");
- assert!(!root.join(".preset-backup-pets-101").exists(), "备份回滚后不残留");
+ ext: None,
+ };
+ let value = serde_json::to_value(&spec).unwrap();
+ assert!(value.get("desc").is_none());
+ assert!(value.get("ext").is_none());
+ assert!(value["uri"].get("mac").is_none());
+ assert_eq!(value["kind"], "dsh");
+ assert_eq!(value["size"], 220.0);
}
#[test]
- fn install_staging_first_install_and_non_replace_reject() {
- let directory = TestDirectory::new("fresh");
- let root = directory.0.join("root");
- fs::create_dir_all(&root).unwrap();
- let target = root.join("fresh-pet");
- let staging = root.join("staging");
- fs::create_dir_all(&staging).unwrap();
- fs::write(staging.join("config.jsonc"), b"{}").unwrap();
-
- // 首次安装:target 不存在 → 直接 rename。
- install_staging(&root, "fresh-pet", 1, &staging, &target, false).unwrap();
- assert!(target.join("config.jsonc").is_file());
-
- // 非替换模式下 target 已存在 → 拒绝;staging 保留,由调用方(run_preset_download
- // 失败路径 remove_dir_all)清理,install_staging 自身不动它。
- let staging2 = root.join("staging2");
- fs::create_dir_all(&staging2).unwrap();
- fs::write(staging2.join("config.jsonc"), b"{}").unwrap();
- let err = install_staging(&root, "fresh-pet", 2, &staging2, &target, false).unwrap_err();
- assert!(err.starts_with("PET_PRESET_ALREADY_INSTALLED:"));
- assert!(target.join("config.jsonc").is_file());
- assert!(staging2.join("config.jsonc").is_file(), "staging 保留等待调用方清理");
+ fn catalog_validation_rejects_unsafe_ids_and_bad_kind() {
+ let bad_id = r#"[{ "id": "../escape", "name": "X", "config": "https://e.com/c.jsonc", "uri": { "default": "https://e.com/w" } }]"#;
+ let catalog: Vec<PresetPetSpec> = serde_json::from_str(bad_id).unwrap();
+ assert!(!safe_preset_id(&catalog[0].id));
+
+ let bad_kind = r#"[{ "id": "x", "name": "X", "kind": "sprite", "config": "https://e.com/c.jsonc", "uri": { "default": "https://e.com/w" } }]"#;
+ let catalog: Vec<PresetPetSpec> = serde_json::from_str(bad_kind).unwrap();
+ assert_eq!(catalog[0].kind.as_deref(), Some("sprite"));
+ assert!(catalog[0]
+ .kind
+ .as_deref()
+ .is_some_and(|kind| kind != "dsh" && kind != "codex"));
}
}
diff --git a/src-tauri/src/desktop/builder.rs b/src-tauri/src/desktop/builder.rs
index 4961e3c6..36a168a2 100644
--- a/src-tauri/src/desktop/builder.rs
+++ b/src-tauri/src/desktop/builder.rs
@@ -498,13 +498,53 @@ mod tests {
#[cfg(test)]
mod security_tests {
+ use serde_json::Value;
+
+ fn capability() -> Value {
+ serde_json::from_str(include_str!("../../capabilities/default.json")).unwrap()
+ }
+
#[test]
fn remote_capability_allows_only_loopback_harness() {
- let capability = include_str!("../../capabilities/default.json");
- assert!(capability.contains("\"remote\""));
- let wildcard_loopback = ["http://127.0.0.1:", "*"].concat();
- assert!(capability.contains(wildcard_loopback.as_str()));
- assert!(!capability.contains("https://"));
+ let capability = capability();
+ // 允许被远程页承载的 origin 只有本机回环:远程页面不得驱动任意 Tauri command。
+ let urls = capability["remote"]["urls"]
+ .as_array()
+ .expect("remote.urls must be an array");
+ assert!(!urls.is_empty(), "remote.urls must not be empty");
+ for url in urls {
+ let url = url.as_str().expect("remote urls must be strings");
+ assert!(
+ url.starts_with("http://127.0.0.1:"),
+ "unexpected remote origin: {url}"
+ );
+ }
+ }
+
+ #[test]
+ fn pet_http_scope_is_limited_to_remote_asset_hosts() {
+ // 桌宠窗口经插件版 fetch 直连远端素材(绕开 githubusercontent 的 CORS),
+ // 但 scope 必须收口到素材主机:出现任意 https 通配等于把插件 fetch 面
+ // 整个开放给桌宠窗口。
+ let capability = capability();
+ let permissions = capability["permissions"]
+ .as_array()
+ .expect("permissions must be an array");
+ let mut scoped: Vec<String> = Vec::new();
+ for permission in permissions {
+ let Some(allow) = permission.get("allow").and_then(Value::as_array) else {
+ continue;
+ };
+ for entry in allow {
+ if let Some(url) = entry.get("url").and_then(Value::as_str) {
+ scoped.push(url.to_string());
+ }
+ }
+ }
+ assert_eq!(
+ scoped,
+ vec!["https://*.githubusercontent.com/*".to_string()]
+ );
}
#[test]
@@ -603,12 +643,7 @@ pub fn handler() -> impl Fn(Invoke<Wry>) -> bool + Send + Sync + 'static {
crate::bridge::list_pets,
crate::bridge::import_pet,
crate::bridge::get_pet_asset,
- crate::bridge::preset_pet::get_preset_pet_config,
- crate::bridge::preset_pet::get_preset_pet_assets,
crate::bridge::list_preset_pets,
- crate::bridge::download_preset_pet,
- crate::bridge::update_preset_pet,
- crate::bridge::get_preset_download_progress,
crate::desktop::pet_mouse::start_pet_mouse_stream,
]
}
@@ -617,13 +652,6 @@ pub fn handler() -> impl Fn(Invoke<Wry>) -> bool + Send + Sync + 'static {
pub fn builder() -> tauri::Builder<tauri::Wry> {
let builder = tauri::Builder::default()
.manage(crate::desktop::pet_mouse::PetMouseStreamState::default())
- .register_asynchronous_uri_scheme_protocol("dsh-pet", |context, request, responder| {
- let app = context.app_handle().clone();
- let label = context.webview_label().to_owned();
- std::thread::spawn(move || {
- responder.respond(crate::bridge::preset_pet::preset_pet_asset_response(&app, &label, request));
- });
- })
.setup(|app| {
let app_handle = app.handle().clone();
// 首装检测必须最先执行:窗口几何恢复/退出保存等任何 store 写入都会
@@ -769,6 +797,9 @@ pub fn builder() -> tauri::Builder<tauri::Wry> {
.plugin(tauri_plugin_notification::init())
// FS plugin
.plugin(tauri_plugin_fs::init())
+ // HTTP plugin:桌宠窗口拉取远端宠物素材时把 fetch 交给 Rust 发起,
+ // 绕开 raw.githubusercontent.com 不返回 CORS 头导致的浏览器拦截。
+ .plugin(tauri_plugin_http::init())
// Simple Store plugin
.plugin(tauri_plugin_store::Builder::new().build())
}
diff --git a/src-tauri/src/desktop/pet.rs b/src-tauri/src/desktop/pet.rs
index 5c9997df..dd07850e 100644
--- a/src-tauri/src/desktop/pet.rs
+++ b/src-tauri/src/desktop/pet.rs
@@ -38,11 +38,11 @@ const PET_WINDOW_BOTTOM_PAD: f64 = 10.0;
/// 顶栏 Toast 区的最小窗口宽度(逻辑像素):桌宠较小时仍保证气泡可读,
/// 与 pet WebView 的 PET_BUBBLE_MIN_WIDTH 保持一致。
const PET_WINDOW_MIN_WIDTH: f64 = 420.0;
-/// 预设动画画布 16:9(高/宽 = 9/16),与 dsh-pet 协议画布比例保持一致
+/// 预设宠物默认画布 16:9(高/宽 = 9/16):与 dsh-pet 协议画布一致
/// (WebM 与 macOS 的 HEVC-with-Alpha MOV 共用同一画布)。
const PET_BUILTIN_ASPECT: f64 = 9.0 / 16.0;
-/// 自定义 Codex v2 精灵图默认 8x11 的 192x208 比例;实际比例以前端加载后为准,
-/// 这里仅作为窗口初始/DPI 尺寸的近似,避免与前端内置画布比例互相打架。
+/// Codex 图集(自定义精灵图,或清单条目声明 `kind: "codex"`)的 8x11 / 192x208 比例;
+/// 实际比例以前端加载后为准,这里仅作为窗口初始/DPI 尺寸的近似,避免与前端互相打架。
const PET_CUSTOM_ASPECT: f64 = 208.0 / 192.0;
/// 宠物大小百分比合法区间(设置页滑条 50%–200%;bridge/pet.rs 引用同一常量)。
pub const PET_SIZE_MIN_PERCENT: f64 = 50.0;
@@ -123,10 +123,10 @@ pub fn get_pet_size_percent<R: Runtime>(app: &AppHandle<R>) -> f64 {
.clamp(PET_SIZE_MIN_PERCENT, PET_SIZE_MAX_PERCENT)
}
-/// 当前激活宠物使用的画布比例(高度/宽度):预设 WebM(未限定 id)固定 9/16,
-/// 自定义精灵图(chat:/codex: 来源限定 id)用 208/192 作为窗口初始/DPI 尺寸的近似。
-/// 真正的自定义比例由前端加载后修正,因此这里不再把 208/192 硬编码给所有宠物,
-/// 避免窗口大小的两个来源互相冲突。
+/// 当前激活宠物使用的画布比例(高度/宽度):预设宠物(未限定 id)默认 dsh-pet 的
+/// 16:9 透明视频画布,自定义精灵图(chat:/codex: 来源限定 id)用 208/192。
+/// 真正的比例由 pet WebView 拿到清单条目/图集后实时修正,这里只是窗口创建与
+/// DPI 变化时的初始近似。
pub fn pet_window_aspect<R: Runtime>(app: &AppHandle<R>) -> f64 {
let setting = crate::config::get_store_dat_setting(app);
let active = setting
@@ -449,12 +449,9 @@ pub fn init_pet_window<R: Runtime>(app: &AppHandle<R>) {
}
}
-/// 重载桌宠窗口页面(预设宠物更新/替换后调用)。
+/// 重载桌宠窗口页面。
///
-/// 桌宠窗口按 `activePet` 只拉取一次协议资源(config + webm manifest),
-/// 更新换入新文件后 URL 不变,WebView 可能继续命中缓存里的旧 webm;
-/// 显式 reload 让新资源立即生效。窗口已被收起(销毁)时无需 reload——下次显示
-/// 会重新创建 webview,天然加载新资源。
+/// 窗口已被收起(销毁)时无需 reload——下次显示会重新创建 webview,天然加载新资源。
pub fn reload_pet_window<R: Runtime>(app: &AppHandle<R>) {
if let Some(window) = app.get_webview_window(PET_WINDOW_LABEL) {
let _ = window.eval("location.reload()");
diff --git a/src-tauri/tauri.conf.json b/src-tauri/tauri.conf.json
index 06255e75..85fed54f 100644
--- a/src-tauri/tauri.conf.json
+++ b/src-tauri/tauri.conf.json
@@ -12,8 +12,8 @@
"app": {
"macOSPrivateApi": true,
"security": {
- "csp": "default-src 'self'; connect-src 'self' ipc: http://ipc.localhost dsh-pet://localhost http://dsh-pet.localhost; img-src 'self' asset: http://asset.localhost data: dsh-pet://localhost http://dsh-pet.localhost; media-src 'self' data: dsh-pet://localhost http://dsh-pet.localhost; style-src 'self' 'unsafe-inline'; font-src 'self' data:; script-src 'self'; frame-src http://127.0.0.1:*",
- "devCsp": "default-src 'self'; connect-src 'self' ipc: http://ipc.localhost http://localhost:1420 ws://localhost:1421 dsh-pet://localhost http://dsh-pet.localhost; img-src 'self' asset: http://asset.localhost data: dsh-pet://localhost http://dsh-pet.localhost; media-src 'self' data: dsh-pet://localhost http://dsh-pet.localhost; style-src 'self' 'unsafe-inline'; font-src 'self' data:; script-src 'self'; frame-src http://127.0.0.1:*"
+ "csp": "default-src 'self'; connect-src 'self' ipc: http://ipc.localhost; img-src 'self' asset: http://asset.localhost data: blob: https://*.githubusercontent.com; media-src 'self' data: blob: https://*.githubusercontent.com; style-src 'self' 'unsafe-inline'; font-src 'self' data:; script-src 'self'; frame-src http://127.0.0.1:*",
+ "devCsp": "default-src 'self'; connect-src 'self' ipc: http://ipc.localhost http://localhost:1420 ws://localhost:1421; img-src 'self' asset: http://asset.localhost data: blob: https://*.githubusercontent.com; media-src 'self' data: blob: https://*.githubusercontent.com; style-src 'self' 'unsafe-inline'; font-src 'self' data:; script-src 'self'; frame-src http://127.0.0.1:*"
}
},
"bundle": {
diff --git a/src/hooks/use-iframe-invoke.ts b/src/hooks/use-iframe-invoke.ts
index 098fdffa..4c76b4a8 100644
--- a/src/hooks/use-iframe-invoke.ts
+++ b/src/hooks/use-iframe-invoke.ts
@@ -46,9 +46,6 @@ const ALLOWED_INVOKE_CMDS = new Set([
'import_pet',
'get_pet_asset',
'list_preset_pets',
- 'download_preset_pet',
- 'update_preset_pet',
- 'get_preset_download_progress',
])
export function useIframeInvoke(iframeRef: RefObject<HTMLIFrameElement | null>): void {
diff --git a/src/pet/app.tsx b/src/pet/app.tsx
index f01fc973..ea50d1a1 100644
--- a/src/pet/app.tsx
+++ b/src/pet/app.tsx
@@ -1,66 +1,76 @@
-import type { DragDirection } from './hooks/use-drag'
-import type { PetHandle, PetStatus } from './hooks/use-pet'
-import { useWatch } from '@hairy/react-lib'
+import type { PetRef, PetRenderMotion } from 'dsh-pet-component'
+import { useEventListener } from '@reause/core'
+import { Pet } from 'dsh-pet-component'
import { useRef } from 'react'
+import { If } from 'react-if-lite'
import { ToastProvider } from '@/components/toast-provider'
-import { Pet } from './components/pet'
-import { isLoopingAnimation } from './config'
+import { PetHint } from './components/pet-hint'
+import { PET_BASE_WIDTH, PET_DSH_ASPECT } from './constants'
import { useBubble } from './hooks/use-bubble'
import { useDrag } from './hooks/use-drag'
import { useOmitIgnoreCursorEvents } from './hooks/use-omit-ignore-cursor-events'
-import { usePet } from './hooks/use-pet'
+import { usePetSource } from './hooks/use-pet-source'
+import { normalizeSizePercent, usePetStatus } from './hooks/use-pet-status'
+import { usePetWindowSize } from './hooks/use-pet-window'
-/** 拖拽方向 → 动画状态:桌面宠物在原生拖拽期间播放对应的移动动画。 */
-const DRAW_STATUS: Record<DragDirection, PetStatus> = {
- left: 'moving-left',
- right: 'moving-right',
-}
-
-/** 桌宠窗口的唯一组合入口:只把会话状态映射到公开的 Pet 命令面。 */
+/**
+ * 桌宠窗口的唯一组合入口。
+ *
+ * 三条输入各管一段,互不越界:
+ * - 设置状态(`usePetStatus`)→ 选哪个宠物、多大、是否可见;
+ * - 会话气泡(`useBubble`)→ 聚合出的动作档位;
+ * - 手势(`useDrag`)→ 拖动期间的方向动作。
+ *
+ * 动作全部经 `pet.motion(...)` / `pet.clear()` 下发到 `<Pet>` 的命令面(优先级高于
+ * 声明式 `motion` prop),渲染细节(动画池解析、双视频缓冲、雪碧图、缓存、双击回应)
+ * 由 `dsh-pet-component` 接管。
+ */
export function App() {
- const petRef = useRef<PetHandle>(null)
- const pet = usePet(petRef)
+ const petRef = useRef<PetRef>(null)
+ const status = usePetStatus()
+ const activePet = status?.active_pet ?? ''
+ const { source, error } = usePetSource(activePet)
+ const hitboxRef = useRef<HTMLDivElement>(null)
const bubble = useBubble()
- const dragRef = useRef<HTMLDivElement>(null)
- const { clickCount, direction, dragging } = useDrag(dragRef)
- useOmitIgnoreCursorEvents(dragRef)
- const drawStatus = direction === undefined ? undefined : DRAW_STATUS[direction]
- // 会话状态未变化时跳过下发:同一档位的重复命令不应重启动画。视频层还有第二层
- // 按「动画目标(资源 + 循环语义 + 重播序号)」的去重(pet.tsx → shouldReloadAnimation),
- // 即使不同档位解析到同一个动画也不会重新播放。
- const lastStatusRef = useRef<PetStatus | undefined>(undefined)
+ const { dragging, direction } = useDrag()
- useWatch(
- [bubble.status, pet],
- () => {
- if (bubble.status === lastStatusRef.current)
- return
- lastStatusRef.current = bubble.status
- if (bubble.status === undefined)
- return pet.clear()
- // 细分档位(thinking/working/result/waiting)与 running 均为循环档;
- // 终态档(success/error)与 review/failed 播一次后回落(handleEnded)。
- pet.change({
- loop: isLoopingAnimation(bubble.status),
- status: bubble.status,
- })
- },
- )
+ const visible = status === null || (status.enabled !== false && status.visible !== false)
+ const width = (source?.width ?? PET_BASE_WIDTH) * normalizeSizePercent(status?.pet_size) / 100
+ usePetWindowSize(width, source?.aspect ?? PET_DSH_ASPECT, visible)
+ useOmitIgnoreCursorEvents(hitboxRef)
+ // 桌宠窗口是装饰性的透明置顶小窗:右键不应弹出 WebView 默认 context menu。
+ useEventListener('contextmenu', (event: Event) => event.preventDefault())
+
+ // 手势优先于会话档位:拖动期间按方向播走路动画(dsh-pet 渲染器内部强制走 drag 池,
+ // 会忽略这里的方向,由组件保证);拖动结束或方向停摆后自动回落到会话档位。
+ const motion: PetRenderMotion | undefined = dragging
+ ? (direction === undefined ? undefined : `moving-${direction}`)
+ : bubble.motion
return (
<ToastProvider custom>
- {/* 外层只负责铺满透明窗口,保持 pointer-events-none;dragRef 绑定到 Pet 内部
- 与 dsh-pet .dsh-pet-hit 一致的唯一可交互命中区。useDrag 负责拖拽/双击,
- useOmitIgnoreCursorEvents 负责穿透恢复,调用方无需管理鼠标流和窗口几何。 */}
- <div className="pointer-events-none h-full w-full touch-none select-none">
- <Pet
- status={drawStatus}
- dragging={dragging}
- clickCount={clickCount}
- hitboxRef={dragRef}
- ref={petRef}
- />
- </div>
+ {/* 外层只负责铺满透明窗口并让宠物锚定底部居中;窗口内可交互面只有命中箱,
+ 其余区域由 useOmitIgnoreCursorEvents 按命中箱矩形整体穿透。 */}
+ <main className={`pointer-events-none fixed inset-0 flex items-end justify-center ${visible ? '' : 'invisible'}`}>
+ {source && (
+ <Pet
+ ref={petRef}
+ kind={source.kind}
+ config={source.config}
+ uri={source.uri}
+ ext={source.ext}
+ motion={motion}
+ size={width}
+ dragging={dragging}
+ cache={true}
+ hidden={!visible}
+ hitboxRef={hitboxRef}
+ />
+ )}
+ {/* 选中了宠物但资源解析不出来(导入的宠物被删除、清单里没有该 id):必须给出
+ 可见提示 —— 透明窗口里「空」与「在加载」观感相同,静默留空等于让用户以为坏了。 */}
+ <If cond={error !== null} then={<PetHint petId={activePet} />} />
+ </main>
</ToastProvider>
)
}
diff --git a/src/pet/components/pet-hint.tsx b/src/pet/components/pet-hint.tsx
new file mode 100644
index 00000000..75970373
--- /dev/null
+++ b/src/pet/components/pet-hint.tsx
@@ -0,0 +1,28 @@
+/**
+ * pet-hint.tsx — 桌宠窗口里唯一会出现的文字提示。
+ *
+ * 桌宠窗口是透明置顶小窗,**没有任何其它 UI 或 i18n 基础设施**(气泡文案同样就地取
+ * 单语),所以这里按窗口语言就近给出单句提示。静默留空是不行的:用户看到的是
+ * 「宠物加载不出来」,既不知道原因也不知道去哪修。
+ */
+const IS_ZH = (typeof document !== 'undefined' ? document.documentElement.lang || navigator.language : 'zh-CN')
+ .toLowerCase()
+ .startsWith('zh')
+
+export interface PetHintProps {
+ /** 已选中的宠物 id(用于提示里点名,便于用户回设置页找到它)。 */
+ petId: string
+}
+
+/** 选中的宠物解析不出资源时的可见提示(导入的宠物被删除、清单里没有这个 id 等)。 */
+export function PetHint(props: PetHintProps) {
+ return (
+ <div className="pointer-events-none absolute inset-x-0 bottom-6 flex justify-center select-none">
+ <div className="max-w-[95%] rounded-lg bg-black/70 px-3 py-1.5 text-center text-xs leading-relaxed text-white">
+ {IS_ZH
+ ? `宠物「${props.petId}」的资源不可用,请在 设置 → 宠物 中重新选择`
+ : `Pet “${props.petId}” is unavailable — pick another one in Settings → Pets`}
+ </div>
+ </div>
+ )
+}
diff --git a/src/pet/components/pet.tsx b/src/pet/components/pet.tsx
deleted file mode 100644
index 142fd5fb..00000000
--- a/src/pet/components/pet.tsx
+++ /dev/null
@@ -1,681 +0,0 @@
-import type { CSSProperties, Ref, RefObject, SyntheticEvent } from 'react'
-import type { PetAnimationTarget, PetConfig } from '../config'
-import type { PetHandle, PetStatus } from '../hooks/use-pet'
-import { invoke } from '@tauri-apps/api/core'
-import { listen } from '@tauri-apps/api/event'
-import { getCurrentWindow, LogicalSize } from '@tauri-apps/api/window'
-import { useEffect, useImperativeHandle, useMemo, useRef, useState } from 'react'
-import { If } from 'react-if-lite'
-import {
- fallbackPresetName,
- isLoopingAnimation,
- pick,
- pickCategoryAction,
- poolEntryToStatus,
- resolvePresetName,
- rollKind,
- shouldReloadAnimation,
- spriteStatusFallback,
-} from '../config'
-import { PET_STATUSES } from '../hooks/use-pet'
-
-const PET_BASE_WIDTH = 220
-/** 已安装预设被清理/未安装时的提示文案:桌宠窗口无 i18n 基础设施(气泡文案同样硬编码),按窗口语言就近显示。 */
-const PRESET_MISSING_HINT = (document.documentElement.lang || navigator.language || 'zh-CN').toLowerCase().startsWith('zh')
- ? '预设宠物未安装,请在设置中下载'
- : 'Preset pet not installed. Download it in Settings.'
-const PET_DEFAULT_SIZE_PERCENT = 100
-const PET_SIZE_MIN_PERCENT = 50
-const PET_SIZE_MAX_PERCENT = 200
-/** 透明窗口右侧留白(逻辑像素),与 Rust pet_window_logical_size 的 PAD 常量一致。 */
-const PET_WINDOW_PAD_X = 32
-/** 顶部 Toast 区 + 底部留白(逻辑像素),与 Rust 的 TOP_PAD + BOTTOM_PAD 一致。 */
-const PET_WINDOW_PAD_Y = 82
-/** 顶栏 Toast 区的最小窗口宽度(逻辑像素),与 Rust pet_window_logical_size 的 MIN_WIDTH 一致。 */
-const PET_BUBBLE_MIN_WIDTH = 420
-const IDLE_DURATIONS = [280, 110, 110, 140, 140, 320] as const
-/**
- * 待机转向插播间隔下限/上限(ms):平时以循环待机动画为主,参考 dsh-pet
- * animationWeights idle:10 / turn:5 的权重语义——turn 是播完掷骰链里的低频事件,
- * 只有长时间持续待机才偶尔插播一次转身,避免高频切换的观感。
- * 当内置 config.jsonc 可用时,实际掷骰改由协议权重(rollKind)驱动,这两个
- * 常量仅作为「每次掷骰的间隔」使用。
- */
-const IDLE_TURN_DELAY_MIN = 25000
-const IDLE_TURN_DELAY_MAX = 50000
-/**
- * 拖拽/点击命中区(视频筐内百分比),与 dsh-pet 的 HIT_BOX 一致
- * (source/dsh-pet/dsh-pet/src/shared/constants.ts:8,640×360 画布坐标
- * x0:200 y0:50 x1:440 y1:335):命中区 = 宠物身体,视频/空白区不响应事件。
- */
-const PET_HIT_BOX = { left: '31.25%', top: '13.8888888889%', width: '37.5%', height: '79.1666666667%' } as const
-const ACTIONS = {
- 'moving-right': { row: 1, frames: 8, duration: 120, lastDuration: 220 },
- 'moving-left': { row: 2, frames: 8, duration: 120, lastDuration: 220 },
- 'waving': { row: 3, frames: 4, duration: 140, lastDuration: 280 },
- 'failed': { row: 5, frames: 8, duration: 140, lastDuration: 240 },
- 'waiting': { row: 6, frames: 6, duration: 150, lastDuration: 260 },
- 'running': { row: 7, frames: 6, duration: 120, lastDuration: 220 },
- 'review': { row: 8, frames: 6, duration: 150, lastDuration: 280 },
-} as const
-
-type Animation = PetStatus | 'bubble' | 'dragging'
-
-interface Asset {
- columns: number
- id: string
- rows: number
- sprite_version_number: number
- spritesheet: string
-}
-
-interface RustPetStatus {
- active_pet?: string | null
- enabled?: boolean
- pet_size?: number | null
- visible?: boolean | null
-}
-
-export interface PetProps {
- ref?: Ref<PetHandle | null>
- hitboxRef?: RefObject<HTMLDivElement | null>
- status?: PetStatus
- /** 原生拖拽会话进行中;内置宠物据此播放拖拽浮动动画(忽略方向)。 */
- dragging?: boolean
- /**
- * 点击计次(useDrag 判定「按下-松开且窗口未达拖拽阈值 = 点击」后递增);
- * 变化时播放一次点击回应动画(waving)。不依赖 DOM click/dblclick 合成。
- */
- clickCount?: number
-}
-
-interface Frame {
- column: number
- duration: number
- row: number
-}
-
-/** 桌宠唯一视觉组件:资源加载、WebM/Codex v2 播放和 Tauri 窗口细节全部封装。 */
-export function Pet(props: PetProps) {
- const [rustStatus, setRustStatus] = useState<RustPetStatus>({ enabled: true, visible: true })
- const [customAsset, setCustomAsset] = useState<Asset | null>(null)
- const [customAssetPet, setCustomAssetPet] = useState<string | null>(null)
- const [spriteAspect, setSpriteAspect] = useState<{ id: string, value: number } | null>(null)
- const [failed, setFailed] = useState(false)
- const [override, setOverride] = useState<{ loop: boolean, revision: number, status: PetStatus } | null>(null)
- const revisionRef = useRef(0)
- const [adHoc, setAdHoc] = useState<{ seq: number, status: string } | null>(null)
- const adHocRef = useRef(adHoc)
- adHocRef.current = adHoc
- const adHocSeqRef = useRef(0)
- // 预设宠物资源(config.jsonc + 动画 manifest):按宠物 id 一起拉取并整体更新,
- // 避免切换宠物时残留上一个宠物的动画池/URL(旧数据在 fetch 完成前不生效)。
- const [petResources, setPetResources] = useState<{
- pet: string
- config: PetConfig | null
- assets: Record<string, string>
- /** 预设资源拉取失败的错误信息(如 PET_PRESET_NOT_INSTALLED);null = 成功。 */
- error: string | null
- } | null>(null)
- const [reducedMotion, setReducedMotion] = useState(() => globalThis.matchMedia?.('(prefers-reduced-motion: reduce)').matches ?? false)
- const videoARef = useRef<HTMLVideoElement | null>(null)
- const videoBRef = useRef<HTMLVideoElement | null>(null)
- const frontIdxRef = useRef(0)
- const [frontIdx, setFrontIdx] = useState(0)
- /** 正在后台加载的切换代次(gen);loadeddata 回调据此判断自己是否已被更新的切换取代。 */
- const pendingRef = useRef<number | null>(null)
- /** 已下发播放的动画目标(资源 URL + 循环语义 + 重播序号);目标不变即不重载,见 shouldReloadAnimation。 */
- const appliedRef = useRef<PetAnimationTarget | null>(null)
- const genRef = useRef(0)
- const spriteRef = useRef<HTMLDivElement | null>(null)
- const overrideRef = useRef(override)
- overrideRef.current = override
- const prevClickRef = useRef(0)
- const handleEndedRef = useRef<(event?: Event) => void>(() => {})
-
- const activePet = normalizeActivePet(rustStatus.active_pet)
- // 预设宠物(未限定 id,来自 ~/.dsh/pets 下载产物)走 <video> 协议渲染:
- // Windows/Linux 是 VP9-alpha WebM,macOS 是 HEVC-with-Alpha MOV(issue #434,
- // WKWebView 不认 WebM alpha)。此处只认 manifest 给的 URL,不感知格式;
- // 来源限定 id(chat:/codex:)走 Codex v2 精灵图渲染。
- const isPreset = !activePet.includes(':')
- // 预设宠物资源按当前激活宠物生效:切换宠物时旧资源保持到新 fetch 完成,避免闪烁。
- // 统一 memo 成稳定的 config/assets 引用,避免每次渲染产生新对象导致视频 effect 重跑。
- const { config, assets, error } = useMemo(() => {
- const preset = petResources !== null && petResources.pet === activePet ? petResources : null
- return {
- config: preset?.config ?? null,
- assets: preset?.assets ?? {},
- error: preset?.error ?? null,
- }
- }, [activePet, petResources])
- // 已选预设宠物未安装(如资源被外部清理):资源拉取失败时视频层静默空白,
- // 这里给出可见提示引导去设置页下载(issue #401)。全新安装 active_pet 为空串
- // (无默认选择),不会走此分支。
- const presetMissing = isPreset && error?.includes('PET_PRESET_NOT_INSTALLED') === true
- // 预设宠物配置驱动动画池:池条目是动画名(动画文件名主名,如 待机呼吸休闲),
- // 点击/拖拽/待机链按名字从 assets map 取 URL。配置缺失或命令失败时回落与旧
- // 实现一致的默认池(idle/turn/wave),这些名字在 assets 中不存在时自然不播放。
- const pools = useMemo(() => {
- const animations = config?.animations
- return {
- idlePool: animations?.idle.length ? animations.idle : ['idle'],
- turnPool: animations?.turn.length ? animations.turn : ['turn'],
- dragPool: animations?.drag.length ? animations.drag : ['drag'],
- clicksPool: animations?.clicks.length ? animations.clicks : ['wave'],
- categories: animations?.categories ?? [],
- weights: config?.animationWeights ?? { idle: 10, turn: 5, move: 5 },
- }
- }, [config])
- const { idlePool, turnPool, clicksPool, categories, weights } = pools
-
- // 预设宠物拖拽中:播放拖拽悬空浮动动画(不区分方向);自定义宠物仍用方向转向。
- const dragHold = props.dragging === true && isPreset
- // 优先级:拖拽浮动动画 > 手势方向 > 一次性回应(点击/待机链,预设宠物池条目即动画名) > ref 命令(会话状态)> 默认 idle。
- // 一次性动画在 override 之上但低于手势方向:点击回应可打断会话状态,拖拽方向仍优先。
- const activity: Animation | string = dragHold ? 'dragging' : props.status ?? adHoc?.status ?? override?.status ?? 'idle'
- const size = normalizePetSize(rustStatus.pet_size)
- const visible = rustStatus.enabled !== false && rustStatus.visible !== false
- const hasCustomAsset = customAsset !== null && customAssetPet === activePet
- // 预设 WebM 画布 16:9(高/宽 = 9/16,与 dsh-pet 协议一致);自定义精灵图用
- // 加载后探测到的真实画布比例(帧高/帧宽),未探测到前回落到图集默认比例。
- const petAspect = isPreset ? 9 / 16 : (spriteAspect?.id === activePet ? spriteAspect.value : 208 / 192)
-
- useImperativeHandle(props.ref, () => ({
- change(options) {
- if (!isPetStatus(options.status))
- return
- const current = overrideRef.current
- // 同一档位重复下发(会话状态未变化,或多会话聚合档位来回切到同一档)不刷新 override:
- // revision 递增会让视频层重新加载同一个动画并从头播放——用户报告「明明是同一条信息
- // 『整理结果中』,下一条还是它,动画却一直重新播放」。override 已被 handleEnded 清空
- // (终态一次性动画播完回落)时不做该去重,仍按新命令重新下发。
- if (current !== null && current.status === options.status && current.loop === (options.loop === true))
- return
- setOverride({ loop: options.loop === true, revision: ++revisionRef.current, status: options.status })
- },
- clear() {
- setOverride(null)
- },
- get status() {
- return props.status ?? overrideRef.current?.status ?? 'idle'
- },
- }), [props.status])
-
- useEffect(() => {
- let disposed = false
- let unlisten: (() => void) | undefined
- void listen<RustPetStatus>('pet://status', (event) => {
- if (!disposed)
- setRustStatus(event.payload)
- }).then((dispose) => {
- if (disposed)
- dispose()
- else
- unlisten = dispose
- }).catch(() => {})
- void invoke<RustPetStatus>('get_pet_status').then((value) => {
- if (!disposed)
- setRustStatus(value)
- }).catch(() => {})
- return () => {
- disposed = true
- unlisten?.()
- }
- }, [])
-
- // 预设宠物按 activePet 拉取协议配置与媒体 manifest;切换宠物时重载。
- // 已安装预设的 config.jsonc 池条目(待机呼吸休闲 等)即 动画文件名主名,
- // assets map 的 key 与池条目一一对应,动画链/点击/拖拽直接按名字取 URL。
- useEffect(() => {
- // 无激活宠物(active_pet 为空串,全新安装未选择)时不拉取任何资源,避免
- // 对空 id 发无意义请求或误显示「预设未安装」提示;窗口在未启用时本就不展示。
- if (isPreset === false || activePet === '')
- return undefined
- let disposed = false
- let loadError: string | null = null
- void Promise.all([
- invoke<PetConfig>('get_preset_pet_config', { id: activePet }).catch((error) => {
- console.warn('[pet] PET_PRESET_CONFIG_LOAD_FAILED:', error)
- loadError ??= String(error)
- return null
- }),
- invoke<{ assets?: Record<string, string> }>('get_preset_pet_assets', { id: activePet }).catch((error) => {
- console.warn('[pet] PET_PRESET_ASSETS_LOAD_FAILED:', error)
- loadError ??= String(error)
- return { assets: {} }
- }),
- ]).then(([config, value]) => {
- if (disposed)
- return
- // 一起提交,避免 config 与 assets 不同步导致短暂按旧池解析。
- setPetResources({ pet: activePet, config, assets: value.assets ?? {}, error: loadError })
- })
- return () => {
- disposed = true
- }
- }, [activePet, isPreset])
-
- useEffect(() => {
- const query = globalThis.matchMedia?.('(prefers-reduced-motion: reduce)')
- if (query === undefined)
- return undefined
- function updateMotion() {
- setReducedMotion(query.matches)
- }
- query.addEventListener('change', updateMotion)
- return () => query.removeEventListener('change', updateMotion)
- }, [])
-
- useEffect(() => {
- // 窗口由隐藏恢复显示(主 webview 重新开启宠物)时,WebView2 在隐藏窗口
- // 上可能暂停媒体播放;这里在 visible 恢复为 true 时重放前台视频,避免
- // 宠物「显示出来但静止不动」。元素始终常驻 DOM(CSS invisible),无需重载 src。
- if (!visible)
- return undefined
- const front = frontIdxRef.current === 0 ? videoARef.current : videoBRef.current
- if (front !== null && front.paused && front.src !== '' && !front.error) {
- void front.play().catch(() => setFailed(true))
- }
- return undefined
- }, [visible])
-
- useEffect(() => {
- if (isPreset)
- return undefined
- let disposed = false
- void invoke<Asset>('get_pet_asset', { id: activePet }).then((value) => {
- if (!disposed && isSupportedAsset(value)) {
- setCustomAsset(value)
- setCustomAssetPet(activePet)
- }
- }).catch(() => {})
- return () => {
- disposed = true
- }
- }, [activePet, isPreset])
-
- // 原生窗口尺寸跟随当前资源真实画布比例缩放(设置页 drag 滑块实时生效),
- // 避免与 Rust 只按图集默认比例重设窗口导致两处 set_size 打架(issue #308)。
- useEffect(() => {
- if (!visible)
- return undefined
- const appWindow = getCurrentWindow()
- // 气泡常驻窗口右侧留白之上,窗口宽度兜底到气泡可读宽度;宠物锚定右侧,
- // 加宽窗口只向左扩展透明区,宠物在屏幕上的位置保持不变。
- const width = Math.max((PET_BASE_WIDTH * size) / 100 + PET_WINDOW_PAD_X, PET_BUBBLE_MIN_WIDTH)
- const height = (PET_BASE_WIDTH * size) / 100 * petAspect + PET_WINDOW_PAD_Y
- void appWindow.setSize(new LogicalSize(width, height)).then(() => {
- // 放大后把窗口夹回可见显示器,避免右侧/底部被推出屏幕。
- void invoke<void>('move_pet_window', { deltaX: 0, deltaY: 0 }).catch(() => {})
- }).catch((error) => {
- console.warn('[pet] PET_WINDOW_RESIZE_FAILED:', error)
- })
- }, [petAspect, size, visible])
-
- useEffect(() => {
- // 双 video 缓冲切换(移植 dsh-pet switchTo):新动画先在后台视频加载,
- // loadeddata 后才交换前台并淡入,旧视频淡出 + pause + 清 onended(拆雷,
- // 防止后台残留事件掐断前台动画);全程无空窗/黑帧,动画切换不闪跳。
- // 只用于预设宠物(WebM);自定义宠物走精灵图渲染,不走视频。
- if (isPreset === false || videoARef.current === null || videoBRef.current === null)
- return undefined
- // 预设配置池条目 = 动画名 = 动画文件名主名;adHoc 已携带动画名时直接命中,
- // 会话状态(waiting/running/review/failed/bubble)经 PRESET_SESSION_ANIMATIONS
- // 叠加映射到具体动画名(写代码/轻快记录/玩游戏气急败坏…)。
- const name = resolvePresetName(activity, pools, assets)
- // 会话状态(override/props 驱动)解析不到资产时不得静默保持当前动画——旧语义
- // 会让宠物永久卡在上一个循环上:细分工作档资产缺失的旧预设(e1ff8c1 资产差集
- // 前的安装)中,会话运行显示待机、拖拽结束后永远循环拖拽动画。改为降级链
- // (细分工作档 → 粗态写代码 → 待机池,见 fallbackPresetName);adHoc(点击
- // 回应/待机插播)缺失仍保持当前动画,避免把一次性风味动画错播成工作/待机动画。
- ?? (adHoc === null ? fallbackPresetName(activity, pools, assets) : null)
- if (name === null)
- return undefined
- const source = assets[name]
- if (source === undefined)
- return undefined
- // adHoc(点击回应/待机插播)是一次性动画:是否循环只由动画自身决定,不能继承
- // override 的 loop 标志——否则会话运行(override.loop=true)期间双击的点击回应
- // 视频会被加载成循环播放,ended 永不触发、adHoc 永不清除,宠物卡在双击动画
- // 里回不到会话动画(待机时 override 为 null 走 isLoopingAnimation,故不复现)。
- const once = adHoc === null
- ? !(override?.loop ?? isLoopingAnimation(activity))
- : !isLoopingAnimation(activity)
- // adHoc seq:点击同一动画时 seq 递增强制重播(对应 dsh-pet 的 seq 重放)。
- const seq = adHoc?.seq ?? 0
- // 防重:同一播放目标(资源 URL + 循环语义 + 重播序号)不重复加载。
- // override.revision 不是重播依据 —— 会话档位反复下发(同一档位重复到达,或多会话
- // 交错让聚合档位在解析结果相同的动画之间来回切)时,按 revision 重载会让同一个
- // 视频从头播放:用户看到「气泡信息没变,动画却一直重新播放」。只有点击回应等
- // 显式重播(seq 递增)或目标真的变化时才重载。
- const nextTarget: PetAnimationTarget = { once, seq, src: source }
- if (!shouldReloadAnimation(appliedRef.current, nextTarget))
- return undefined
- const gen = ++genRef.current
- pendingRef.current = gen
- const target = frontIdxRef.current === 0 ? videoBRef.current : videoARef.current
- target.src = source
- target.loop = !once
- target.onended = once ? event => handleEndedRef.current(event) : null
- target.load()
- const onReady = () => {
- target.removeEventListener('loadeddata', onReady)
- if (pendingRef.current !== gen)
- return // 已被更新的切换取代
- const old = frontIdxRef.current === 0 ? videoARef.current : videoBRef.current
- if (old !== null && old !== target) {
- old.onended = null // 拆雷:后台残留 onended 会掐断前台动画
- old.pause()
- }
- frontIdxRef.current = frontIdxRef.current === 0 ? 1 : 0
- // 交换前台发生在 loadeddata 事件回调(或视频已就绪的立即分支):属于响应加载完成,
- // 而非渲染副作用;规则无法区分事件回调与 effect 同步阶段,忽略。
- // eslint-disable-next-line react/set-state-in-effect
- setFrontIdx(frontIdxRef.current)
- appliedRef.current = nextTarget
- pendingRef.current = null
- void target.play().catch(() => setFailed(true))
- }
- target.addEventListener('loadeddata', onReady)
- if (target.readyState >= 2)
- onReady()
- return () => {
- target.removeEventListener('loadeddata', onReady)
- // 若本次加载尚未完成(StrictMode 双挂载 / 依赖变化提前清理),清掉 pending,
- // 让下一次 effect 重新发起加载,避免「监听器已移除但 pending 仍在」的死锁。
- if (pendingRef.current === gen)
- pendingRef.current = null
- }
- }, [activity, adHoc, assets, isPreset, override?.loop, override?.revision, pools])
-
- // 点击回应:clickCount 变化(useDrag 判定「500ms 内两次按下且未拖拽 = 双击」后递增)
- // → 播放一次点击回应动画。adHoc 优先级在会话 override 之上:双击回应可打断会话状态,
- // 播完回落原动画(handleEnded)。动画名来自预设 config.jsonc 的 clicks 池(协议,
- // 池条目 = 动画名 = 动画文件名主名);配置缺失/池条目不可播放时回落 waving。
- useEffect(() => {
- if (props.clickCount === undefined || props.clickCount === prevClickRef.current)
- return undefined
- prevClickRef.current = props.clickCount
- const entry = pick(clicksPool)
- const status = isPreset ? (entry ?? 'waving') : (toAdHocStatus(entry) ?? 'waving')
- // 点击回应:以 props 变化驱动一次性动画状态,属于事件联动而非渲染副作用。
- // eslint-disable-next-line react/set-state-in-effect
- setAdHoc({ seq: ++adHocSeqRef.current, status })
- }, [clicksPool, isPreset, props.clickCount])
-
- // 待机链(dsh-pet 权重掷骰链):预设宠物长时间持续待机时,以低频
- // (IDLE_TURN_DELAY_MIN~MAX 随机间隔)按 config.jsonc 的 animationWeights 掷骰,
- // 命中 turn/action 才插播一次一次性动画,平时保持循环待机。move 命中时因 DSH
- // 不自动漫游而保持待机(协议字段保留,行为对齐「移除自动移动」规格)。
- // 池条目即动画名:turn/action 命中的条目直接作为 adHoc.status 交给视频切换层。
- useEffect(() => {
- if (isPreset === false || reducedMotion || activity !== 'idle')
- return undefined
- let timer: number | undefined
- function scheduleNextRoll() {
- const delay = IDLE_TURN_DELAY_MIN + Math.random() * (IDLE_TURN_DELAY_MAX - IDLE_TURN_DELAY_MIN)
- timer = window.setTimeout(() => {
- const kind = rollKind(Math.random(), weights)
- if (kind === 'turn' && turnPool.length > 0) {
- const status = pick(turnPool)
- if (status !== undefined && status !== 'idle') {
- setAdHoc({ seq: ++adHocSeqRef.current, status })
- return
- }
- }
- if (kind === 'action' && categories.length > 0) {
- const current = adHocRef.current?.status ?? 'idle'
- const action = pickCategoryAction(categories, idlePool, 'left', current)
- if (action.name !== undefined && action.name !== 'idle' && action.name !== current) {
- setAdHoc({ seq: ++adHocSeqRef.current, status: action.name })
- return
- }
- }
- // idle / move(不自动漫游)/ 不可播放条目:继续待机并等待下一次掷骰。
- scheduleNextRoll()
- }, delay)
- }
- scheduleNextRoll()
- return () => window.clearTimeout(timer)
- }, [activity, categories, idlePool, isPreset, reducedMotion, turnPool, weights])
-
- useEffect(() => {
- const sprite = spriteRef.current
- const asset = customAsset
- if (isPreset || asset === null || customAssetPet !== activePet || sprite === null)
- return undefined
- const element = sprite
- const loadedAsset = asset
- // 与视频路径同理:adHoc 播放期间 loop 只由动画自身决定,不继承 override 的
- // loop 标志,避免会话运行期间点击回应精灵动作循环到 adHoc 计时器到期才回落。
- const loop = adHoc === null
- ? (override?.loop ?? isLoopingAnimation(activity))
- : isLoopingAnimation(activity)
- const sequence = spriteSequence(activity, reducedMotion, loop)
- let index = 0
- let timer: number | undefined
- function paint() {
- const frame = sequence.frames[index]
- element.style.backgroundPosition = framePosition(frame, loadedAsset.columns, loadedAsset.rows)
- if (sequence.frames.length > 1) {
- timer = window.setTimeout(() => {
- index = index + 1 >= sequence.frames.length ? (sequence.loopStart ?? index) : index + 1
- paint()
- }, frame.duration)
- }
- }
- paint()
- return () => {
- if (timer !== undefined)
- window.clearTimeout(timer)
- }
- }, [activity, activePet, adHoc, customAsset, customAssetPet, isPreset, override?.loop, reducedMotion])
-
- useEffect(() => {
- if (override?.loop !== false || override === null || isPreset || !hasCustomAsset)
- return undefined
- const frames = spriteAction(override.status)
- const duration = (reducedMotion ? [frames[0]] : frames).reduce((total, frame) => total + frame.duration, 0)
- const timer = window.setTimeout(setOverride, duration, null)
- return () => window.clearTimeout(timer)
- }, [hasCustomAsset, isPreset, override, reducedMotion])
-
- // 自定义精灵无 ended 事件:adHoc(点击回应/待机转向)播完按帧时长估算后清掉,
- // 让 activity 回落 idle(预设宠物由视频 ended 事件驱动,走 handleEnded)。
- useEffect(() => {
- if (adHoc === null || isPreset || !hasCustomAsset)
- return undefined
- const frames = spriteAction(adHoc.status)
- const duration = (reducedMotion ? [frames[0]] : frames).reduce((total, frame) => total + frame.duration, 0)
- const timer = window.setTimeout(setAdHoc, duration, null)
- return () => window.clearTimeout(timer)
- }, [adHoc, hasCustomAsset, isPreset, reducedMotion])
-
- function handleEnded(event?: Event) {
- // 只响应前台视频的 ended:被降级的后台视频在切换时已 pause + 清 onended(拆雷),
- // 不会触发;双保险再校验一次事件来源是否为当前前台视频。
- const source = event?.currentTarget as HTMLVideoElement | undefined
- const front = frontIdxRef.current === 0 ? videoARef.current : videoBRef.current
- if (source !== undefined && source !== front)
- return
- // 一次性动画已播完:前台视频停在末帧,appliedRef 记录的「已下发目标」不再代表
- // 正在播放的动画,必须作废——否则同一个一次性目标(终态档重复到达、回落又切回)
- // 若在兜底动画加载完成前再次下发,会被 shouldReloadAnimation 判为「目标未变」而
- // 跳过加载,前台就永远停在末帧。作废后同一目标也一定会重新加载播放。
- appliedRef.current = null
- // 一次性动画播完:优先清 adHoc(点击回应 waving / 待机转向 turn),
- // 否则清非 loop 的 override 命令(bubble 会话动画播完回 idle)。
- if (adHocRef.current !== null) {
- setAdHoc(null)
- return
- }
- if (overrideRef.current?.loop !== true)
- setOverride(null)
- }
- handleEndedRef.current = handleEnded
-
- function handleSpriteLoaded(event: SyntheticEvent<HTMLImageElement>) {
- const image = event.currentTarget
- if (customAsset !== null) {
- const frameWidth = image.naturalWidth / customAsset.columns
- const frameHeight = image.naturalHeight / customAsset.rows
- if (frameWidth > 0 && frameHeight > 0)
- setSpriteAspect({ id: customAsset.id, value: frameHeight / frameWidth })
- }
- setFailed(false)
- }
-
- const style = {
- '--pet-width': `${PET_BASE_WIDTH * size / 100}px`,
- '--pet-aspect': String(petAspect),
- } as CSSProperties
-
- return (
- // 保持 <main> 与全部子元素(双 video、命中区)常驻 DOM,visible=false 时仅用
- // visibility:hidden 隐藏:隐藏/重开(主 webview 关闭宠物再开启)不会重挂载出
- // 新元素,useDrag 的监听器与视频加载 effect 都只绑定/加载一次,无需 F5 恢复;
- // 不用 display:none —— useOmitIgnoreCursorEvents 依赖 hitbox 的 getBoundingClientRect
- // 做鼠标穿透判定,display:none 会得到全 0 rect。窗口本身的显隐由 Rust 的
- // show/hide 控制,这里只负责 WebView 内部一致性。
- <main
- className={`pointer-events-none fixed inset-0 flex items-end justify-center overflow-visible ${visible ? '' : 'invisible'}`}
- style={style}
- >
- {/* 视频筐本身不响应事件:可交互面收缩到下方 PET_HIT_BOX 命中区(与 dsh-pet
- .dsh-pet-hit 一致),事件从命中区冒泡到 app.tsx 的 dragRef 壳触发拖拽。 */}
- <div className="pointer-events-none relative h-[calc(var(--pet-width)*var(--pet-aspect))] w-[var(--pet-width)] select-none">
- <If cond={isPreset}>
- {/* 双 video 缓冲:前台 opacity-100 淡入、后台 opacity-0 淡出,
- 切换经 loadeddata 就绪后交换(见开关 effect),无空窗/黑帧闪跳。
- 视频均 pointer-events-none,避免截获命中区外的点击。 */}
- <video
- ref={videoARef}
- className={`pointer-events-none absolute inset-0 h-full w-full object-contain transition-opacity duration-200 ${frontIdx === 0 ? 'opacity-100' : 'opacity-0'}`}
- muted
- playsInline
- preload="auto"
- onError={() => setFailed(true)}
- />
- <video
- ref={videoBRef}
- className={`pointer-events-none absolute inset-0 h-full w-full object-contain transition-opacity duration-200 ${frontIdx === 1 ? 'opacity-100' : 'opacity-0'}`}
- muted
- playsInline
- preload="auto"
- onError={() => setFailed(true)}
- />
- </If>
- <If cond={!isPreset && hasCustomAsset}>
- <div
- ref={spriteRef}
- className="pointer-events-none absolute inset-0 bg-contain bg-no-repeat"
- style={{
- backgroundImage: customAsset ? `url(${customAsset.spritesheet})` : undefined,
- backgroundSize: customAsset ? `${customAsset.columns * 100}% ${customAsset.rows * 100}%` : undefined,
- }}
- />
- {/* 探测精灵图真实像素尺寸,换算成帧比例供窗口缩放使用;0×0 不可见。 */}
- <img
- className="pointer-events-none absolute h-0 w-0 opacity-0"
- src={customAsset?.spritesheet}
- alt=""
- draggable={false}
- onError={() => setFailed(true)}
- onLoad={handleSpriteLoaded}
- />
- </If>
- <If cond={failed && assets.fallback !== undefined}>
- <img className="pointer-events-none absolute inset-0 h-full w-full object-contain" src={assets.fallback} alt="" draggable={false} />
- </If>
- {/* 命中区:唯一可交互面(拖拽/双击),尺寸与 dsh-pet .dsh-pet-hit 一致。 */}
- <div
- ref={props.hitboxRef}
- className="pointer-events-auto absolute cursor-grab touch-none select-none"
- style={PET_HIT_BOX}
- />
- <If cond={presetMissing}>
- {/* 预设宠物未安装:视频层无可播放资产会静默空白,用可见提示引导去设置页下载(issue #401)。 */}
- <div className="pointer-events-none absolute inset-x-0 bottom-full mb-2 flex justify-center select-none">
- <div className="max-w-[95%] rounded-lg bg-black/60 px-3 py-1.5 text-center text-xs leading-relaxed text-white">
- {PRESET_MISSING_HINT}
- </div>
- </div>
- </If>
- </div>
- </main>
- )
-}
-
-function isPetStatus(value: string): value is PetStatus {
- return (PET_STATUSES as readonly string[]).includes(value)
-}
-
-/**
- * 把预设配置池条目(动画名,动画文件名主名)映射为可播放状态:预设宠物条目
- * 直接就是动画名(如 待机呼吸休闲 / 点击回应-开心跃动);兼容旧内置键 'wave'
- * → 'waving' 的归一化。拖拽/方向专用状态不参与回应池;其余必须命中会话状态
- * 或 bubble,否则返回 null(调用方回落默认动画)。
- */
-function toAdHocStatus(entry: string | undefined): string | null {
- if (entry === undefined)
- return null
- const status = poolEntryToStatus(entry)
- if (status === 'bubble')
- return status
- if (status === 'dragging' || status === 'moving-left' || status === 'moving-right')
- return null
- // 池条目为动画名时直接作为播放状态使用;其余必须是会话状态或 bubble。
- return isPetStatus(status) ? status : (status.length > 0 ? status : null)
-}
-
-function normalizeActivePet(value: string | null | undefined): string {
- // 全新安装 active_pet 为空串(未选择任何宠物),不再回落内置宠物;窗口据此
- // 感知「无宠物」态,避免误渲染一个未安装的默认预设。
- return value?.trim() || ''
-}
-
-function normalizePetSize(value: number | null | undefined): number {
- if (typeof value !== 'number' || !Number.isFinite(value))
- return PET_DEFAULT_SIZE_PERCENT
- return Math.min(PET_SIZE_MAX_PERCENT, Math.max(PET_SIZE_MIN_PERCENT, value))
-}
-
-function isSupportedAsset(value: Asset): boolean {
- return value.sprite_version_number === 2
- && value.columns === 8
- && value.rows === 11
- && typeof value.spritesheet === 'string'
- && value.spritesheet.length > 0
-}
-
-function spriteSequence(activity: Animation | string, reducedMotion: boolean, loop: boolean): { frames: Frame[], loopStart: number | null } {
- const idleFrames = IDLE_DURATIONS.map((duration, column) => ({ column, duration: duration * 6, row: 0 }))
- const action = spriteAction(activity)
- if (activity === 'idle')
- return reducedMotion ? { frames: [idleFrames[0]], loopStart: 0 } : { frames: idleFrames, loopStart: 0 }
- if (reducedMotion)
- return { frames: [action[0]], loopStart: loop ? 0 : null }
- if (loop)
- return { frames: action, loopStart: 0 }
- return { frames: [...action, ...idleFrames], loopStart: action.length }
-}
-
-function spriteAction(activity: Animation | string): Frame[] {
- if (activity === 'idle')
- return IDLE_DURATIONS.map((duration, column) => ({ column, duration, row: 0 }))
- // 自定义图集无细分档行:先近似映射到既有行(thinking→waiting 等),
- // 此类档位对预设宠物(WebM)不影响——它们走 resolvePresetName 直接命中资产。
- const base = spriteStatusFallback(activity)
- const mapped = base === 'turn' ? 'moving-right' : base === 'bubble' ? 'waving' : base === 'dragging' ? 'moving-right' : base
- const config = ACTIONS[mapped as keyof typeof ACTIONS] ?? ACTIONS.waving
- return Array.from({ length: config.frames }, (_, column) => ({
- column,
- duration: column === config.frames - 1 ? config.lastDuration : config.duration,
- row: config.row,
- }))
-}
-
-function framePosition(frame: Frame, columns: number, rows: number): string {
- return `${frame.column * 100 / Math.max(1, columns - 1)}% ${frame.row * 100 / Math.max(1, rows - 1)}%`
-}
diff --git a/src/pet/config/index.test.ts b/src/pet/config/index.test.ts
deleted file mode 100644
index a131dbef..00000000
--- a/src/pet/config/index.test.ts
+++ /dev/null
@@ -1,275 +0,0 @@
-import type { PetAnimationTarget, PetCategory, PetWeights } from './'
-import { describe, expect, it, vi } from 'vitest'
-import {
- fallbackPresetName,
- isLoopingAnimation,
- pick,
- pickCategoryAction,
- pickWeightedCategory,
- poolEntryToStatus,
- resolvePresetName,
- rollKind,
- shouldReloadAnimation,
- spriteStatusFallback,
-} from './'
-
-const WEIGHTS: PetWeights = { idle: 10, turn: 5, move: 5 }
-
-describe('rollKind', () => {
- it('maps roll ranges to idle/turn/move/action by weights', () => {
- expect(rollKind(0.0, WEIGHTS)).toBe('idle')
- expect(rollKind(0.0999, WEIGHTS)).toBe('idle')
- expect(rollKind(0.10, WEIGHTS)).toBe('turn')
- expect(rollKind(0.1499, WEIGHTS)).toBe('turn')
- expect(rollKind(0.15, WEIGHTS)).toBe('move')
- expect(rollKind(0.1999, WEIGHTS)).toBe('move')
- // topEnd = (10+5+5)/100 = 0.20,剩余 0.20~1.00 全归 action
- expect(rollKind(0.20, WEIGHTS)).toBe('action')
- expect(rollKind(0.9999, WEIGHTS)).toBe('action')
- })
-
- it('treats zero-sum weights as always-action', () => {
- expect(rollKind(0.0, { idle: 0, turn: 0, move: 0 })).toBe('action')
- expect(rollKind(0.9, { idle: 0, turn: 0, move: 0 })).toBe('action')
- })
-})
-
-describe('pickWeightedCategory', () => {
- const categories: PetCategory[] = [
- { id: '小动作', weight: 20, actions: ['wave', 'bubble'] },
- { id: '玩耍', weight: 20, actions: ['turn'] },
- { id: '文字', weight: 10, noMirror: true, actions: ['waiting'] },
- ]
-
- it('excludes noMirror categories while facing right', () => {
- vi.spyOn(Math, 'random').mockReturnValue(0.95)
- const left = pickWeightedCategory(categories, 'left')
- const right = pickWeightedCategory(categories, 'right')
- // facing=right 时 noMirror 分类被排除,抽取结果只剩前两个分类
- expect(['小动作', '玩耍', '文字']).toContain(left?.id)
- expect(['小动作', '玩耍']).toContain(right?.id)
- expect(right?.id).not.toBe('文字')
- vi.restoreAllMocks()
- })
-
- it('skips categories without actions and returns null for empty pools', () => {
- expect(pickWeightedCategory([], 'left')).toBeNull()
- expect(pickWeightedCategory([{ id: '空', weight: 1, actions: [] }], 'left')).toBeNull()
- })
-})
-
-describe('pickCategoryAction', () => {
- it('picks an action from a weighted category', () => {
- vi.spyOn(Math, 'random').mockReturnValue(0.0)
- const result = pickCategoryAction(
- [{ id: '小动作', weight: 1, actions: ['wave', 'bubble'] }],
- ['idle'],
- 'left',
- 'idle',
- )
- expect(result.id).toBe('小动作')
- expect(result.name).toBe('wave')
- vi.restoreAllMocks()
- })
-
- it('falls back to the idle pool when no category is available', () => {
- vi.spyOn(Math, 'random').mockReturnValue(0.5)
- const result = pickCategoryAction([], ['idle', 'turn'], 'left', 'idle')
- expect(result.id).toBe('FALLBACK')
- expect(['idle', 'turn']).toContain(result.name)
- vi.restoreAllMocks()
- })
-})
-
-describe('pick', () => {
- it('picks from a pool and avoids the excluded entry when possible', () => {
- vi.spyOn(Math, 'random').mockReturnValue(0.0)
- expect(pick(['a', 'b'], 'a')).toBe('b')
- vi.restoreAllMocks()
- })
-
- it('falls back to the original pool when exclusion empties it', () => {
- vi.spyOn(Math, 'random').mockReturnValue(0.0)
- expect(pick(['a'], 'a')).toBe('a')
- vi.restoreAllMocks()
- })
-})
-
-describe('poolEntryToStatus', () => {
- it('normalizes the wave asset key to the waving status', () => {
- expect(poolEntryToStatus('wave')).toBe('waving')
- expect(poolEntryToStatus('idle')).toBe('idle')
- expect(poolEntryToStatus('bubble')).toBe('bubble')
- expect(poolEntryToStatus('turn')).toBe('turn')
- })
-})
-
-describe('resolvePresetName', () => {
- const pools = {
- idlePool: ['待机呼吸休闲'],
- turnPool: ['东张西望'],
- dragPool: ['被鼠标拖拽悬空反馈'],
- clicksPool: ['点击回应-开心跃动', '点击回应-元气挥手'],
- } as const
- const assets: Record<string, string> = {
- '待机呼吸休闲': 'dsh-pet://localhost/maid-deepseek-whale/webm/%E5%BE%85.webm',
- '东张西望': 'dsh-pet://localhost/maid-deepseek-whale/webm/%E4%B8%9C.webm',
- '被鼠标拖拽悬空反馈': 'dsh-pet://localhost/maid-deepseek-whale/webm/%E8%A2%AB.webm',
- '点击回应-开心跃动': 'dsh-pet://localhost/maid-deepseek-whale/webm/%E5%BC%80.webm',
- // DSH 细分工作状态档位叠加映射名(e1ff8c1 起的 6 个新 webm)
- '工作状态-思考冒泡': 'dsh-pet://localhost/maid-deepseek-whale/webm/%E6%80%9D.webm',
- '工作状态-忙碌点按': 'dsh-pet://localhost/maid-deepseek-whale/webm/%E5%BF%99.webm',
- '工作状态-清点归档': 'dsh-pet://localhost/maid-deepseek-whale/webm/%E6%B8%85.webm',
- '工作状态-原地踱步张望': 'dsh-pet://localhost/maid-deepseek-whale/webm/%E8%B8%B1.webm',
- '工作状态-雀跃庆祝': 'dsh-pet://localhost/maid-deepseek-whale/webm/%E9%9B%80.webm',
- '工作状态-垂头叹气冒汗': 'dsh-pet://localhost/maid-deepseek-whale/webm/%E5%9E%82.webm',
- // 旧粗态兼容映射名
- '写代码': 'dsh-pet://localhost/maid-deepseek-whale/webm/%E5%86%99.webm',
- '轻快记录': 'dsh-pet://localhost/maid-deepseek-whale/webm/%E8%BD%BB.webm',
- '玩游戏气急败坏': 'dsh-pet://localhost/maid-deepseek-whale/webm/%E6%B0%94.webm',
- }
-
- it('returns the asset name directly when activity is already a playable name', () => {
- expect(resolvePresetName('待机呼吸休闲', pools, assets)).toBe('待机呼吸休闲')
- expect(resolvePresetName('点击回应-开心跃动', pools, assets)).toBe('点击回应-开心跃动')
- })
-
- it('maps statuses to their protocol pools', () => {
- vi.spyOn(Math, 'random').mockReturnValue(0.0)
- expect(resolvePresetName('idle', pools, assets)).toBe('待机呼吸休闲')
- expect(resolvePresetName('turn', pools, assets)).toBe('东张西望')
- expect(resolvePresetName('dragging', pools, assets)).toBe('被鼠标拖拽悬空反馈')
- expect(resolvePresetName('waving', pools, assets)).toBe('点击回应-开心跃动')
- vi.restoreAllMocks()
- })
-
- it('maps session statuses to the DSH overlay animation names', () => {
- // 细分工作状态档位(e1ff8c1 起的 6 个新 webm)
- expect(resolvePresetName('thinking', pools, assets)).toBe('工作状态-思考冒泡')
- expect(resolvePresetName('working', pools, assets)).toBe('工作状态-忙碌点按')
- expect(resolvePresetName('result', pools, assets)).toBe('工作状态-清点归档')
- expect(resolvePresetName('waiting', pools, assets)).toBe('工作状态-原地踱步张望')
- expect(resolvePresetName('success', pools, assets)).toBe('工作状态-雀跃庆祝')
- expect(resolvePresetName('error', pools, assets)).toBe('工作状态-垂头叹气冒汗')
- // 旧粗态兼容映射
- expect(resolvePresetName('running', pools, assets)).toBe('写代码')
- expect(resolvePresetName('review', pools, assets)).toBe('轻快记录')
- expect(resolvePresetName('failed', pools, assets)).toBe('玩游戏气急败坏')
- })
-
- it('isLoopingAnimation:细分非终态档与 idle/running 循环,终态档与 review/failed 播一次', () => {
- expect(isLoopingAnimation('idle')).toBe(true)
- expect(isLoopingAnimation('thinking')).toBe(true)
- expect(isLoopingAnimation('working')).toBe(true)
- expect(isLoopingAnimation('result')).toBe(true)
- expect(isLoopingAnimation('waiting')).toBe(true)
- expect(isLoopingAnimation('running')).toBe(true)
- expect(isLoopingAnimation('success')).toBe(false)
- expect(isLoopingAnimation('error')).toBe(false)
- expect(isLoopingAnimation('review')).toBe(false)
- expect(isLoopingAnimation('failed')).toBe(false)
- expect(isLoopingAnimation('waving')).toBe(false)
- })
-
- it('spriteStatusFallback:自定义图集无细分档行,近似映射到既有行', () => {
- expect(spriteStatusFallback('thinking')).toBe('waiting')
- expect(spriteStatusFallback('working')).toBe('running')
- expect(spriteStatusFallback('result')).toBe('review')
- expect(spriteStatusFallback('success')).toBe('waving')
- expect(spriteStatusFallback('error')).toBe('failed')
- expect(spriteStatusFallback('idle')).toBe('idle')
- expect(spriteStatusFallback('running')).toBe('running')
- })
-
- it('returns null for session statuses whose overlay asset is missing', () => {
- const partial: Record<string, string> = { 待机呼吸休闲: 'x.webm' }
- expect(resolvePresetName('running', pools, partial)).toBeNull()
- expect(resolvePresetName('bubble', pools, partial)).toBeNull()
- })
-
- it('returns null when the pool entry is not backed by an asset', () => {
- expect(resolvePresetName('idle', { ...pools, idlePool: ['不存在.webm'] }, assets)).toBeNull()
- expect(resolvePresetName('idle', { ...pools, idlePool: [] }, assets)).toBeNull()
- })
-})
-
-describe('shouldReloadAnimation', () => {
- const thinking: PetAnimationTarget = {
- once: false,
- seq: 0,
- src: 'dsh-pet://localhost/maid-deepseek-whale/webm/%E6%80%9D.webm',
- }
-
- it('首次下发(无已播放目标)必须加载', () => {
- expect(shouldReloadAnimation(null, thinking)).toBe(true)
- })
-
- it('同一状态重复下发解析到同一目标时不重载(动画不重新播放)', () => {
- // 会话档位「整理结果中」连续两次(或聚合档位来回切到同一解析结果):
- // 资源/循环语义/重播序号都不变 → 继续播放,不从头重播。
- expect(shouldReloadAnimation(thinking, { ...thinking })).toBe(false)
- })
-
- it('目标动画变化时重载', () => {
- const result: PetAnimationTarget = {
- once: false,
- seq: 0,
- src: 'dsh-pet://localhost/maid-deepseek-whale/webm/%E6%B8%85.webm',
- }
- expect(shouldReloadAnimation(thinking, result)).toBe(true)
- })
-
- it('同名动画但资源 URL 不同(切换宠物)必须重载', () => {
- const other: PetAnimationTarget = {
- ...thinking,
- src: 'dsh-pet://localhost/other-pet/webm/%E6%80%9D.webm',
- }
- expect(shouldReloadAnimation(thinking, other)).toBe(true)
- })
-
- it('循环语义变化必须重载', () => {
- expect(shouldReloadAnimation(thinking, { ...thinking, once: true })).toBe(true)
- })
-
- it('显式重播序号变化必须重载(点击同一动画再看一次)', () => {
- expect(shouldReloadAnimation(thinking, { ...thinking, seq: 1 })).toBe(true)
- })
-})
-
-describe('fallbackPresetName', () => {
- // 旧预设(e1ff8c1 资产差集前的安装):无 工作状态-*,但有待机与写代码。
- const stale: Record<string, string> = {
- 待机呼吸休闲: 'dsh-pet://localhost/maid-deepseek-whale/webm/idle.webm',
- 写代码: 'dsh-pet://localhost/maid-deepseek-whale/webm/code.webm',
- }
- const pools = { idlePool: ['待机呼吸休闲'] } as const
-
- it('降级细分工作档到粗态写代码(资产缺失时不再卡旧循环)', () => {
- vi.spyOn(Math, 'random').mockReturnValue(0.0)
- expect(fallbackPresetName('thinking', pools, stale)).toBe('写代码')
- expect(fallbackPresetName('working', pools, stale)).toBe('写代码')
- expect(fallbackPresetName('result', pools, stale)).toBe('写代码')
- expect(fallbackPresetName('waiting', pools, stale)).toBe('写代码')
- expect(fallbackPresetName('running', pools, stale)).toBe('写代码')
- vi.restoreAllMocks()
- })
-
- it('细分档资产存在时无需降级(fallback 只作 resolve 失败的后备)', () => {
- expect(fallbackPresetName('thinking', pools, { '待机呼吸休闲': 'idle.webm', '工作状态-思考冒泡': 'think.webm', '写代码': 'code.webm' })).toBe('写代码')
- })
-
- it('终态档/其他状态降到待机池', () => {
- vi.spyOn(Math, 'random').mockReturnValue(0.0)
- expect(fallbackPresetName('success', pools, stale)).toBe('待机呼吸休闲')
- expect(fallbackPresetName('error', pools, stale)).toBe('待机呼吸休闲')
- expect(fallbackPresetName('review', pools, stale)).toBe('待机呼吸休闲')
- expect(fallbackPresetName('failed', pools, stale)).toBe('待机呼吸休闲')
- expect(fallbackPresetName('bubble', pools, stale)).toBe('待机呼吸休闲')
- vi.restoreAllMocks()
- })
-
- it('待机池也无资产时返回 null(调用方保持当前动画)', () => {
- expect(fallbackPresetName('working', pools, {})).toBeNull()
- expect(fallbackPresetName('working', { idlePool: [] }, {})).toBeNull()
- })
-})
diff --git a/src/pet/config/index.ts b/src/pet/config/index.ts
deleted file mode 100644
index 03761b90..00000000
--- a/src/pet/config/index.ts
+++ /dev/null
@@ -1,294 +0,0 @@
-/**
- * pet-config.ts — 预设桌宠配置(dsh-pet assets/config.jsonc 协议)的纯逻辑层。
- *
- * 配置由 Rust 从 ~/.dsh/pets/<id>/config.jsonc 读取、剥注释并校验后经
- * `get_preset_pet_config` 命令返回(字段形状 = 子仓库 dsh-pet assets/config.jsonc
- * 协议的受支持子集,动画池条目 = 动画名 = 动画文件名主名)。本模块只做两件事:
- * 1. 类型收敛:把命令返回值声明成可直接消费的结构;
- * 2. 权重掷骰:移植 dsh-pet src/shared/pickers.ts 的 rollKind / pickWeightedCategory /
- * pickCategoryAction(DSH 无自动漫游,move 档由调用方决定保持待机,不在本模块移动窗口),
- * 以及按播放状态解析实际动画名(resolvePresetName)。
- * 无 React / DOM / Tauri 依赖,可独立单测。
- */
-
-/** 动画链掷骰结果类别。 */
-export type PetRollKind = 'idle' | 'turn' | 'move' | 'action'
-
-/** 动画链顶层权重(idle/turn/move,协议字段 animationWeights)。 */
-export interface PetWeights {
- idle: number
- turn: number
- move: number
-}
-
-/** 随机动作分类(带文字、镜像会颠倒的池带 noMirror)。 */
-export interface PetCategory {
- id: string
- weight: number
- noMirror?: boolean
- actions: string[]
-}
-
-/** 移动池(DSH 不自动移动窗口,仅保留协议字段供未来对齐)。 */
-export interface PetMovesConfig {
- default: Record<string, number>
- actions: { name: string, params?: Record<string, number> }[]
-}
-
-/** config.jsonc 的 animations 段(协议子集)。 */
-export interface PetAnimationsConfig {
- idle: string[]
- turn: string[]
- drag: string[]
- clicks: string[]
- moves: PetMovesConfig
- categories: PetCategory[]
- events?: Record<string, string[]>
-}
-
-/** config.jsonc 全集(受支持子集;pets/physics/eventsRefreshSec 由 Rust 校验)。 */
-export interface PetConfig {
- pets: { id: string, name?: string, size?: number }[]
- animations: PetAnimationsConfig
- animationWeights: PetWeights
- physics?: Record<string, unknown>
- eventsRefreshSec?: Record<string, number>
-}
-
-/**
- * 播放状态是否循环。
- * - idle/running/moving-*\/dragging:常驻循环(手势期间持续直到结束);
- * - 细分工作状态档位 thinking/working/result/waiting:非终态档,常驻循环播动画
- * (对齐 dsh-pet workStatusTick 语义:等用户/干活期间动画不自动结束);
- * - 终态档 success/error 与 review/failed:播一次后回落(气泡收尾由 use-bubble 管理)。
- */
-export function isLoopingAnimation(activity: string): boolean {
- return activity === 'idle' || activity === 'running'
- || activity === 'thinking' || activity === 'working' || activity === 'result' || activity === 'waiting'
- || activity === 'moving-left' || activity === 'moving-right'
- || activity === 'dragging'
-}
-
-/**
- * 自定义 Codex v2 图集没有细分档位行(固定 8×11,无思考/工作/整理/庆祝行):
- * 细分档播放时近似映射到既有行,避免播到错误 sprite(保留会话状态近似观感)。
- */
-export function spriteStatusFallback(activity: string): string {
- return activity === 'thinking'
- ? 'waiting'
- : activity === 'working'
- ? 'running'
- : activity === 'result'
- ? 'review'
- : activity === 'success'
- ? 'waving'
- : activity === 'error'
- ? 'failed'
- : activity
-}
-
-/** 从字符串池等概率抽一个;exclude 排除某个名字(避免连续重复)。 */
-export function pick<T>(pool: readonly T[], exclude?: T): T {
- const entries = exclude === undefined ? pool : pool.filter(item => item !== exclude)
- // 排除后池空(单元素池 + 排除自己):退回原池抽——宁可重复,也不要返回 undefined
- const source = entries.length > 0 ? entries : pool
- return source[Math.floor(Math.random() * source.length)] ?? source[0]
-}
-
-/**
- * 按权重掷骰:roll ∈ [0,1) → 下一个动画类别(纯函数,可单测)。
- * topEnd = (idle+turn+move)/100:三档权重占比之和,剩余概率归入 'action'。
- */
-export function rollKind(roll: number, weights: PetWeights): PetRollKind {
- const total = weights.idle + weights.turn + weights.move
- if (total <= 0)
- return 'action'
- const topEnd = total / 100
- if (roll < weights.idle / 100)
- return 'idle'
- if (roll < (weights.idle + weights.turn) / 100)
- return 'turn'
- if (roll < topEnd)
- return 'move'
- return 'action'
-}
-
-/**
- * 按权重在分类池中选一个分类;noMirror 分类在镜像(facing=right)时被排除,
- * 剩余权重自动归一化。分类池为空时返回 null。
- */
-export function pickWeightedCategory(categories: PetCategory[], facing: 'left' | 'right'): PetCategory | null {
- const cats = categories.filter(category => category.actions.length > 0)
- if (cats.length === 0)
- return null
- const filtered = cats.filter(category => !(category.noMirror === true && facing === 'right'))
- const eligible = filtered.length > 0 ? filtered : cats
- const totalWeight = eligible.reduce((sum, category) => sum + Math.max(0, category.weight), 0) || 1
- let target = Math.random() * totalWeight
- for (const category of eligible) {
- target -= Math.max(0, category.weight)
- if (target <= 0)
- return category
- }
- return eligible[eligible.length - 1]
-}
-
-/** 从分类池选一个动作;无可用分类时回退 idle 池(返回 {id, name},纯函数)。 */
-export function pickCategoryAction(
- categories: PetCategory[],
- idlePool: readonly string[],
- facing: 'left' | 'right',
- current: string,
-): { id: string, name: string } {
- const category = pickWeightedCategory(categories, facing)
- if (category === null)
- return { id: 'FALLBACK', name: pick(idlePool, current) }
- return { id: category.id, name: pick(category.actions, current) }
-}
-
-/**
- * 把动画池条目(内置资产键)映射为播放状态:唯一需要归一化的是点击/分类池里的
- * 'wave'(资产键)→ 'waving'(播放状态);其余键与播放状态同名。
- */
-export function poolEntryToStatus(entry: string): string {
- return entry === 'wave' ? 'waving' : entry
-}
-
-/**
- * DSH 会话状态 → dsh-pet 动画名(动画文件名主名)的叠加映射。
- *
- * 两族状态:
- * 1. 细分工作状态档位(workStatus,host reducer 输出):thinking/working/result/
- * waiting/success/error,对齐 dsh-pet config.jsonc animations.events.workStatus
- * 数组(索引即档位)——turn/start→thinking、tool/call→working、tool/result→result、
- * approval/asked 等→waiting、turn/end completed→success、error/max-tokens→error。
- * 这些档位优先映射到工作状态系列动画(思考冒泡/忙碌点按/清点归档/踱步张望/
- * 雀跃庆祝/垂头叹气冒汗,e1ff8c1 起的新预设资产)。
- * 2. 旧粗态兼容(无细分档的会话展示路径):running 写代码、review 轻快记录、
- * failed 玩游戏气急败坏、bubble 鲸鱼吐泡泡特效。
- * 资产缺失时 resolvePresetName 仍返回 null:会话状态(override/props 驱动)由调用方
- * 走 fallbackPresetName 降级(避免卡在旧循环),adHoc(点击回应/待机插播)保持当前动画。
- */
-export const PRESET_SESSION_ANIMATIONS: Record<string, string> = {
- // 细分工作状态档位(workStatus)
- thinking: '工作状态-思考冒泡',
- working: '工作状态-忙碌点按',
- result: '工作状态-清点归档',
- waiting: '工作状态-原地踱步张望',
- success: '工作状态-雀跃庆祝',
- error: '工作状态-垂头叹气冒汗',
- // 旧粗态兼容
- running: '写代码',
- review: '轻快记录',
- failed: '玩游戏气急败坏',
- bubble: '鲸鱼吐泡泡特效',
-}
-
-/**
- * 预设宠物:把播放状态解析为实际动画名(动画文件名主名,如 待机呼吸休闲)。
- * - 活动名本身就是可播放动画名(adHoc 池条目 / 会话状态映射名)时直接命中资产;
- * - 会话状态(waiting/running/review/failed/bubble)经 PRESET_SESSION_ANIMATIONS
- * 叠加映射到具体动画名;映射名没有对应资产时返回 null(保持当前动画);
- * - 状态档(idle/dragging/turn/waving)从对应池等概率抽一个名字。
- */
-export function resolvePresetName(
- activity: string,
- pools: {
- idlePool: readonly string[]
- turnPool: readonly string[]
- dragPool: readonly string[]
- clicksPool: readonly string[]
- },
- assets: Record<string, string>,
-): string | null {
- if (assets[activity] !== undefined)
- return activity
- const sessionName = PRESET_SESSION_ANIMATIONS[activity]
- if (sessionName !== undefined && assets[sessionName] !== undefined)
- return sessionName
- const pool = activity === 'idle'
- ? pools.idlePool
- : activity === 'dragging'
- ? pools.dragPool
- : activity === 'turn'
- ? pools.turnPool
- : activity === 'waving'
- ? pools.clicksPool
- : null
- if (pool === null || pool.length === 0)
- return null
- const name = pick(pool)
- return assets[name] !== undefined ? name : null
-}
-
-/**
- * 会话状态解析不到资产时的降级动画名(与 resolvePresetName 的「保持当前动画」
- * 语义互补):resolve 失败若不切换,宠物会永久卡在上一个循环动画上 —— 典型故障
- * 是细分工作档(thinking/working/result/waiting)资产缺失的旧预设中,会话运行
- * 显示待机、拖拽结束后永远循环拖拽动画。
- *
- * 降级链:
- * 1. 细分工作档/粗态 running → 粗态「写代码」(旧预设普遍存在,保留「在干活」
- * 的观感,而非退回待机);
- * 2. 其余状态(终态档/待机链)→ 待机池兜底;
- * 3. 无可播资产时返回 null(调用方保持当前动画)。
- *
- * 仅用于会话状态(override/props 驱动);adHoc(点击回应/待机插播)缺失时
- * 仍保持当前动画 —— 一次性风味动画不应被错播成工作/待机动画。
- */
-export function fallbackPresetName(
- activity: string,
- pools: { idlePool: readonly string[] },
- assets: Record<string, string>,
-): string | null {
- if (activity === 'thinking' || activity === 'working'
- || activity === 'result' || activity === 'waiting' || activity === 'running') {
- const running = PRESET_SESSION_ANIMATIONS.running
- if (running !== undefined && assets[running] !== undefined)
- return running
- }
- if (pools.idlePool.length > 0) {
- const name = pick(pools.idlePool)
- if (assets[name] !== undefined)
- return name
- }
- return null
-}
-
-/**
- * 动画播放目标:真正决定「播放哪个媒体、怎么播」的三要素。
- * - src:解析后的动画资源 URL(不是动画名——切换宠物时同名动画的 URL 不同,必须重载);
- * - once:一次性/循环语义(决定视频 loop 与 ended 回落);
- * - seq:显式重播序号(点击回应等 adHoc 每触发一次就递增,对应 dsh-pet 的 seq 重放)。
- *
- * 会话档位(thinking/working/result/…)刻意【不在】目标里:档位只是解析目标的输入,
- * 不是重播依据。
- */
-export interface PetAnimationTarget {
- once: boolean
- seq: number
- src: string
-}
-
-/**
- * 是否需要重载视频来切换动画(纯函数,可单测)。
- *
- * 【为什么存在】会话档位反复下发时(同一档位重复到达、或多会话交错让聚合档位在
- * 解析结果相同的动画之间来回切),旧实现按 override.revision 递增重载同一个视频
- * 并从头播放——用户看到的现象是「气泡信息明明是同一个『整理结果中』,动画却一直
- * 重新播放」。动画是否重播只由播放目标决定:
- * - 目标资源变化(真换了动画 / 换了宠物)→ 重载;
- * - once(循环语义)变化 → 重载,因为要重新设置 video.loop;
- * - seq(点击回应等显式重播)变化 → 重载,用户重新点击就是要再看一次。
- * 三者都不变 = 同一个动画目标,继续播放,不刷新。
- */
-export function shouldReloadAnimation(
- previous: PetAnimationTarget | null,
- next: PetAnimationTarget,
-): boolean {
- if (previous === null)
- return true
- return previous.src !== next.src
- || previous.once !== next.once
- || previous.seq !== next.seq
-}
diff --git a/src/pet/constants.ts b/src/pet/constants.ts
new file mode 100644
index 00000000..7e106638
--- /dev/null
+++ b/src/pet/constants.ts
@@ -0,0 +1,31 @@
+/**
+ * constants.ts — 桌宠窗口的几何常量。
+ *
+ * 与 Rust 侧 `desktop::pet`(`PET_SPRITE_BASE_WIDTH` / `PET_WINDOW_PAD_X` /
+ * `PET_WINDOW_TOP_PAD` / `PET_WINDOW_BOTTOM_PAD` / `PET_WINDOW_MIN_WIDTH`)保持
+ * 一致:Rust 负责窗口创建与 DPI 变化时的初始尺寸,pet WebView 拿到真实画布比例后
+ * 实时修正,两处必须同源,否则缩放时会来回打架(issue #308)。
+ */
+
+/** 宠物基准渲染宽度(px,100% 档位)。 */
+export const PET_BASE_WIDTH = 220
+
+/** 窗口右侧留白(逻辑像素)。 */
+export const PET_WINDOW_PAD_X = 32
+
+/** 顶部 Toast 区 + 底部留白(逻辑像素)。 */
+export const PET_WINDOW_PAD_Y = 82
+
+/** 顶栏 Toast 区的最小窗口宽度(逻辑像素):桌宠较小时仍保证气泡可读。 */
+export const PET_BUBBLE_MIN_WIDTH = 420
+
+/** 宠物大小百分比缺省值与合法区间(与设置页滑条一致)。 */
+export const PET_SIZE_DEFAULT_PERCENT = 100
+export const PET_SIZE_MIN_PERCENT = 50
+export const PET_SIZE_MAX_PERCENT = 200
+
+/** dsh-pet 透明视频画布比例(高/宽 = 9/16)。 */
+export const PET_DSH_ASPECT = 9 / 16
+
+/** Codex 图集画布比例(8 列 × 11 行,格子 192×208)。 */
+export const PET_CODEX_ASPECT = 208 / 192
diff --git a/src/pet/hooks/use-bubble.ts b/src/pet/hooks/use-bubble.ts
index 060a972f..154227fc 100644
--- a/src/pet/hooks/use-bubble.ts
+++ b/src/pet/hooks/use-bubble.ts
@@ -1,5 +1,5 @@
import type { ToastContentValue } from '@heroui/react'
-import type { PetStatus } from './use-pet'
+import type { Motion } from 'dsh-pet-component'
import { listen } from '@tauri-apps/api/event'
import { useEffect, useState } from 'react'
import { toast } from '@/utils/toast'
@@ -11,7 +11,11 @@ export interface BubbleSession {
}
export interface BubbleHandle {
- readonly status: PetStatus | undefined
+ /**
+ * 多会话聚合出的动作档位(`dsh-pet-component` 的 14 个 Motion 之一);
+ * `undefined` = 无会话需要展示(调用方 `pet.clear()` 回落待机)。
+ */
+ readonly motion: Motion | undefined
}
type SessionAction = 'create' | 'remove' | 'update'
@@ -99,23 +103,23 @@ const STATUS_PRIORITY: Record<string, number> = {
/** 桌宠窗口的会话气泡:DSH 发送原始会话快照,本 hook 私有管理会话→toast key 映射,仅暴露聚合宠物状态。 */
export function useBubble(): BubbleHandle {
- const [status, setStatus] = useState<PetStatus | undefined>(undefined)
+ const [status, setStatus] = useState<Motion | undefined>(undefined)
useEffect(() => {
// 状态容器定义
const sessions = new Map<string, BubbleSession>()
const toastKeys = new Map<string, string>()
const hideTimers = new Map<string, number>()
- const previousStatus = new Map<string, PetStatus | undefined>()
+ const previousStatus = new Map<string, Motion | undefined>()
const failedUntil = new Map<string, number>()
const pulseTimers = new Map<string, number>()
const consumedFailed = new Set<string>()
const dismissed = new Set<string>()
const pruneTimers = new Map<string, number>()
- let lastAgg: PetStatus | undefined
+ let lastAgg: Motion | undefined
/** 合并窗口内最新计算出的聚合态(未下发前持续被更新,窗口到期统一下发)。 */
- let pendingAgg: PetStatus | undefined
+ let pendingAgg: Motion | undefined
/** pendingAgg 是否有待下发的变更(区分「待下发 undefined 态」与「无变更」)。 */
let hasPendingAgg = false
let aggFlushTimer: number | undefined
@@ -209,7 +213,7 @@ export function useBubble(): BubbleHandle {
pruneTimers.set(id, timer)
}
- const scheduleHide = (id: string, current: PetStatus) => {
+ const scheduleHide = (id: string, current: Motion) => {
clearTimer(hideTimers, id)
const timeout = current === 'failed' || current === 'error'
? FAILED_BUBBLE_TIMEOUT
@@ -391,7 +395,7 @@ export function useBubble(): BubbleHandle {
}
}, [])
- return { status }
+ return { motion: status }
}
/** 统一解析原始会话对象 */
@@ -404,20 +408,20 @@ function rawSession(payload: unknown): BubbleSession | undefined {
return typeof id === 'string' && id.length > 0 ? { ...session, id } : undefined
}
-/** 细分工作状态档位(host reducer workStatus 输出;动画名映射见 pet-config)。 */
+/** 细分工作档位(host reducer workStatus 输出):与 `dsh-pet-component` 的动作名同名。 */
const WORK_STATUSES = ['thinking', 'working', 'result', 'waiting', 'success', 'error'] as const
type WorkStatus = (typeof WORK_STATUSES)[number]
/** 提取单个会话的状态(细分档优先,忽略底层恢复逻辑)。 */
-function sessionStatus(session: BubbleSession, ignoreError = false): PetStatus | undefined {
+function sessionStatus(session: BubbleSession, ignoreError = false): Motion | undefined {
// 细分工作档位(host reducer 权威):thinking/working/result/waiting/success/error
const work = session.workStatus as unknown
if (WORK_STATUSES.includes(work as WorkStatus)) {
// error/success 是终态档;pulse 过期(ignoreError)后回落底层推导,不残留失败/成功视觉。
if (ignoreError && (work === 'error' || work === 'success'))
return undefined
- return work as PetStatus
+ return work as Motion
}
const value = session.status ?? session.activity ?? session.phase
@@ -454,8 +458,8 @@ function statusOf(
sessions: ReadonlyMap<string, BubbleSession>,
failedUntil: ReadonlyMap<string, number>,
now: number,
-): PetStatus | undefined {
- let highestStatus: PetStatus | undefined
+): Motion | undefined {
+ let highestStatus: Motion | undefined
let maxPriority = 0
for (const session of sessions.values()) {
@@ -517,7 +521,7 @@ function toolArgDetail(tool: string, args: unknown): string | undefined {
}
/** 生成 Toast 渲染数据(对齐 dsh-dafeiyu:优先失败详情 → 任务文案 → 工具/思考活动 → 档位状态文案)。 */
-function toastContent(session: BubbleSession, status: PetStatus) {
+function toastContent(session: BubbleSession, status: Motion) {
const getFirstString = (...items: unknown[]): string | undefined => {
for (const item of items) {
if (typeof item === 'string' && item.trim().length > 0) {
diff --git a/src/pet/hooks/use-drag.ts b/src/pet/hooks/use-drag.ts
index dd23d4e4..2de5d6fa 100644
--- a/src/pet/hooks/use-drag.ts
+++ b/src/pet/hooks/use-drag.ts
@@ -1,39 +1,29 @@
-import type { RefObject } from 'react'
+import { useEventListener, useTimeoutFn } from '@reause/core'
import { getCurrentWindow } from '@tauri-apps/api/window'
import { useEffect, useRef, useState } from 'react'
/** 拖拽的水平方向。 */
-export type DragDirection = 'left' | 'right'
+type DragDirection = 'left' | 'right'
export interface UseDragResult {
- /** 原生拖拽会话进行中(按下后开始,结束/超时后为 false)。 */
+ /** 原生拖拽会话进行中(按下后位移超过阈值才算,结束/超时后为 false)。 */
dragging: boolean
/** 当前拖拽方向;未拖拽、位移不足或拖拽停顿时为 undefined。 */
direction: DragDirection | undefined
- /**
- * 双击计次(两次按下间隔 < DOUBLE_CLICK_MS 且期间未进入拖拽):驱动点击回应动画
- * (waving)。不依赖 DOM click/dblclick 事件合成——Windows 原生拖拽会吞掉
- * pointerup,click/dblclick 永远不触发;改用 pointerdown 时间戳判定双击,
- * 三条平台路径全部可靠。
- */
- clickCount: number
}
/** 判定方向的水平位移阈值(物理像素),滤除拖拽起始时刻的抖动/初始跳变。 */
const DRAG_DIRECTION_THRESHOLD = 3
/**
- * 判定「真正开始拖拽」的累计位移阈值(物理像素),对应 dsh-pet 的 DRAG_THRESHOLD
- * (shared/constants.ts:10,逻辑像素 5):按下后累计位移未达阈值不算拖拽——
- * 单击、双击不进入拖拽、不播放拖动动画(点击回应由双击判定驱动)。
- * 位移按 X/Y 双轴累计(Math.hypot):垂直拖拽 X 位移可能很小,但不能因此
- * 把拖拽误判为点击。方向采样仍然基于逐次 dx,位移基准独立于方向采样基准。
+ * 判定「真正开始拖拽」的累计位移阈值(物理像素,逻辑像素 5 的同量级):按下后累计
+ * 位移未达阈值不算拖拽 —— 单击不进入拖拽、不播放拖动动画(点击回应由 `<Pet>` 内置
+ * 的双击判定驱动)。位移按 X/Y 双轴累计(Math.hypot):垂直拖拽 X 位移可能很小,
+ * 不能因此把拖拽误判为点击。
*/
const DRAG_START_THRESHOLD = 8
-/** 双击判定窗口(ms):两次 pointerdown 间隔小于该值且期间未拖拽,视为双击。 */
-const DOUBLE_CLICK_MS = 500
/**
- * 方向停摆阈值:超过此时长没有新的窗口 Moved 事件,方向归零(宠物回到
- * idle/会话动画)。拖拽中短暂停顿(重新抓握)后继续移动会重新产生方向。
+ * 方向停摆阈值:超过此时长没有新的窗口 Moved 事件,方向归零(宠物回到 idle/会话动画)。
+ * 拖拽中短暂停顿(重新抓握)后继续移动会重新产生方向。
*/
const DRAG_DIRECTION_IDLE_TIMEOUT = 350
/**
@@ -44,147 +34,117 @@ const DRAG_DIRECTION_IDLE_TIMEOUT = 350
const DRAG_SESSION_TIMEOUT = 1500
/**
- * 桌宠窗口拖拽 Hook:用 Tauri 原生窗口拖动移动桌宠,并借用窗口 Moved 事件
- * 采样位移方向(原生拖拽期间 webview 收不到 pointermove),供上层切换
- * moving-left / moving-right 动画。
+ * 桌宠窗口拖拽:用 Tauri 原生窗口拖动移动桌宠,并借用窗口 `Moved` 事件采样位移
+ * 方向(原生拖拽期间 webview 收不到 pointermove),供上层切换 moving-left/right。
*
- * 生命周期不依赖 `startDragging()` 的 Promise 时机:
- * - tao 0.35(Windows)用 `PostMessageW(WM_NCLBUTTONDOWN, HTCAPTION)` 发起
- * 原生拖拽后立即返回,Promise 瞬间 resolve —— 它不代表拖拽结束,不能
- * 在 await 后清理拖拽态;
- * - 因此「拖拽进行中」= 按下后 Moved 事件持续到来。「结束」由两级停歇判断:
- * 方向停摆(DRAG_DIRECTION_IDLE_TIMEOUT)只清方向,会话仍存活,停顿后
- * 继续移动方向会恢复;会话硬超时(DRAG_SESSION_TIMEOUT)才真正结束整场
- * 拖拽;pointerup / pointercancel 作兜底。
+ * # 为什么监听 window 而不是命中箱
+ *
+ * 桌宠窗口平时按命中箱矩形对光标穿透(`useOmitIgnoreCursorEvents`),能到达页面的
+ * 指针事件本来就只发生在命中箱附近,因此 `window` 级监听与命中箱监听效果等价;而
+ * reause 的 `useEventListener` 在渲染期解析 ref 目标,命中箱由 `<Pet>` 在提交阶段
+ * 才挂上,用 ref 当目标会漏绑定。
+ *
+ * # 生命周期不依赖 `startDragging()` 的 Promise 时机
+ *
+ * tao(Windows)用 `PostMessageW(WM_NCLBUTTONDOWN, HTCAPTION)` 发起原生拖拽后立即
+ * 返回,Promise 瞬间 resolve —— 它不代表拖拽结束,不能在 await 后清理拖拽态;
+ * 因此「拖拽进行中」= 按下后 Moved 事件持续到来,由两级停歇判断收尾(见上方两个
+ * 超时常量),pointerup / pointercancel 仅作兜底。
*/
-export function useDrag(dragRef: RefObject<HTMLElement | null>): UseDragResult {
- const draggingRef = useRef(false)
+export function useDrag(): UseDragResult {
+ const activeRef = useRef(false)
const engagedRef = useRef(false)
+ const originRef = useRef<{ x: number, y: number } | undefined>(undefined)
const moveXRef = useRef<number | undefined>(undefined)
- const moveStartXRef = useRef<number | undefined>(undefined)
- const moveStartYRef = useRef<number | undefined>(undefined)
- const lastDownRef = useRef<number | undefined>(undefined)
- const directionTimerRef = useRef<number | undefined>(undefined)
- const sessionTimerRef = useRef<number | undefined>(undefined)
const [dragging, setDragging] = useState(false)
const [direction, setDirection] = useState<DragDirection | undefined>(undefined)
- const [clickCount, setClickCount] = useState(0)
- useEffect(() => {
- const element = dragRef.current
- if (element === null)
- return undefined
- const appWindow = getCurrentWindow()
- let disposed = false
- let unlisten: (() => void) | undefined
+ // reause 的 `useTimeoutFn` 缺省在挂载时就开始计时,这里必须 `immediate: false`:
+ // 只有窗口 Moved 事件才重新 `start()`(等价于「重置计时」)。回调始终读取最新闭包,
+ // 且只操作 ref 与 setState,因此不需要额外的 clearTimeout 记账。
+ const { start: armDirectionTimer, stop: stopDirectionTimer } = useTimeoutFn(
+ parkDirection,
+ DRAG_DIRECTION_IDLE_TIMEOUT,
+ { immediate: false },
+ )
+ const { start: armSessionTimer, stop: stopSessionTimer } = useTimeoutFn(
+ endDrag,
+ DRAG_SESSION_TIMEOUT,
+ { immediate: false },
+ )
- function clearTimer(ref: { current: number | undefined }): void {
- if (ref.current !== undefined) {
- window.clearTimeout(ref.current)
- ref.current = undefined
- }
- }
+ /** 暂停移动:方向与位移基准归零,但拖拽会话保持存活。 */
+ function parkDirection(): void {
+ moveXRef.current = undefined
+ setDirection(undefined)
+ }
- /** 暂停移动:方向与位移基准归零,但拖拽会话保持存活。 */
- function parkDirection(): void {
- moveXRef.current = undefined
- setDirection(undefined)
- }
+ function endDrag(): void {
+ activeRef.current = false
+ engagedRef.current = false
+ originRef.current = undefined
+ moveXRef.current = undefined
+ stopDirectionTimer()
+ stopSessionTimer()
+ setDragging(false)
+ setDirection(undefined)
+ }
- function endDrag(): void {
- clearTimer(directionTimerRef)
- clearTimer(sessionTimerRef)
- draggingRef.current = false
- engagedRef.current = false
- setDragging(false)
- moveXRef.current = undefined
- moveStartXRef.current = undefined
- moveStartYRef.current = undefined
- setDirection(undefined)
- }
+ function handlePointerDown(event: PointerEvent): void {
+ if (event.button !== 0)
+ return
+ // 不调用 preventDefault:取消 pointerdown 会抑制兼容鼠标事件,文本选择/触屏滚动
+ // 已由样式(select-none / touch-none)防护。先清理残留状态(快速连续拖拽时上一轮
+ // 的空闲计时可能还没到)。
+ endDrag()
+ activeRef.current = true
+ // 参考 dsh-pet:按下仅记录会话,不立即进入拖拽动画(单击不播放拖动浮动),
+ // 位移超过 DRAG_START_THRESHOLD 后才把 dragging 置 true。
+ void getCurrentWindow().startDragging().catch(() => {})
+ }
- /** 新的位移说明拖拽仍在进行:重置两级停歇计时。 */
- function armTimers(): void {
- clearTimer(directionTimerRef)
- clearTimer(sessionTimerRef)
- // 计时器句柄存 ref、由 cleanup 经 clearTimer 统一清理;规则无法追踪 ref 间接清理。
- // eslint-disable-next-line react/web-api-no-leaked-timeout
- directionTimerRef.current = window.setTimeout(parkDirection, DRAG_DIRECTION_IDLE_TIMEOUT)
- // eslint-disable-next-line react/web-api-no-leaked-timeout
- sessionTimerRef.current = window.setTimeout(endDrag, DRAG_SESSION_TIMEOUT)
- }
+ function handlePointerUp(): void {
+ endDrag()
+ }
- async function handlePointerDown(event: PointerEvent): Promise<void> {
- if (event.button !== 0)
- return
- // 双击判定(必须先于 endDrag 读取 engagedRef:它反映「自上次按下以来是否拖拽过」)。
- // 不依赖 DOM dblclick:Windows 原生拖拽的模态循环会吞掉第一次 pointerup,
- // click/dblclick 事件无法合成;这里直接用两次 pointerdown 的间隔 + 未拖拽
- // 判定双击,跨平台可靠。单击/拖拽结束均不会计次(上次会话拖拽过则不算双击)。
- const now = performance.now()
- const isDoubleClick = lastDownRef.current !== undefined
- && now - lastDownRef.current < DOUBLE_CLICK_MS
- && engagedRef.current === false
- lastDownRef.current = now
- // 不调用 preventDefault:取消 pointerdown 会抑制兼容鼠标事件(click/dblclick),
- // 文本选择/触屏滚动已由 CSS(select-none/touch-none)防护。
- // 先清理残留状态(快速连续拖拽时上一轮的空闲计时可能还没到)。
- endDrag()
- draggingRef.current = true
- engagedRef.current = false
- // 参考 dsh-pet:按下仅记录会话,不立即进入拖拽动画(点击不播放拖动浮动),
- // 位移超过 DRAG_START_THRESHOLD 后 onMoved 才把 dragging 置 true。
- setDragging(false)
- moveXRef.current = undefined
- moveStartXRef.current = undefined
- moveStartYRef.current = undefined
- setDirection(undefined)
- if (isDoubleClick)
- setClickCount(count => count + 1)
- void appWindow.startDragging().catch(() => {})
- }
-
- function handlePointerUp(): void {
- // Windows 原生拖拽结束时 webview 收不到 pointerup(按钮事件被系统模态循环
- // 吞掉),会话由 DRAG_SESSION_TIMEOUT 超时兜底结束。
- endDrag()
- }
+ useEventListener('pointerdown', handlePointerDown)
+ useEventListener('pointerup', handlePointerUp)
+ useEventListener('pointercancel', handlePointerUp)
- element.addEventListener('pointerdown', handlePointerDown)
- element.addEventListener('pointerup', handlePointerUp)
- element.addEventListener('pointercancel', handlePointerUp)
-
- void appWindow.onMoved((event) => {
- // 只依赖共享 ref 判断拖拽态:startDragging 的 resolve 时机(平台差异)
- // 与 effect 重建(StrictMode)都不应影响方向采样。
- if (!draggingRef.current)
+ useEffect(() => {
+ let disposed = false
+ let unlisten: (() => void) | undefined
+ void getCurrentWindow().onMoved((event) => {
+ // 只依赖共享 ref 判断拖拽态:startDragging 的 resolve 时机(平台差异)与
+ // effect 重建(StrictMode)都不应影响方向采样。
+ if (!activeRef.current)
return
- armTimers()
- const x = event.payload.x
- const y = event.payload.y
- if (moveStartXRef.current === undefined || moveStartYRef.current === undefined) {
+ // 新的位移说明拖拽仍在进行:重置两级停歇计时。
+ armDirectionTimer()
+ armSessionTimer()
+ const { x, y } = event.payload
+ const origin = originRef.current
+ if (origin === undefined) {
// 首个 Moved 事件作为位移基准:吞掉 startDragging 可能带来的初始跳变,
// 以及暂停与恢复之间的坐标不连续。方向采样同样以它起步。
- moveStartXRef.current = x
- moveStartYRef.current = y
+ originRef.current = { x, y }
moveXRef.current = x
return
}
if (!engagedRef.current) {
- // 未达拖拽阈值:单击/双击/轻微抖动不算拖拽,不采样方向(基准保持不动)。
- // 位移按 X/Y 双轴累计:垂直拖拽 X 位移较小,不能因此误判为点击。
- if (Math.hypot(x - moveStartXRef.current, y - moveStartYRef.current) < DRAG_START_THRESHOLD)
+ // 未达拖拽阈值:单击/轻微抖动不算拖拽,不采样方向(基准保持不动)。
+ if (Math.hypot(x - origin.x, y - origin.y) < DRAG_START_THRESHOLD)
return
engagedRef.current = true
setDragging(true)
}
- if (moveXRef.current === undefined) {
+ const lastX = moveXRef.current
+ moveXRef.current = x
+ if (lastX === undefined) {
// 停顿(parkDirection)后恢复移动:重新建立方向采样基准。
- moveXRef.current = x
return
}
- const dx = x - moveXRef.current
- moveXRef.current = x
+ const dx = x - lastX
if (Math.abs(dx) >= DRAG_DIRECTION_THRESHOLD)
setDirection(dx > 0 ? 'right' : 'left')
}).then((dispose) => {
@@ -193,24 +153,11 @@ export function useDrag(dragRef: RefObject<HTMLElement | null>): UseDragResult {
else
unlisten = dispose
}).catch(() => {})
-
return () => {
disposed = true
unlisten?.()
- element.removeEventListener('pointerdown', handlePointerDown)
- element.removeEventListener('pointerup', handlePointerUp)
- element.removeEventListener('pointercancel', handlePointerUp)
- clearTimer(directionTimerRef)
- clearTimer(sessionTimerRef)
- draggingRef.current = false
- engagedRef.current = false
- setDragging(false)
- moveXRef.current = undefined
- moveStartXRef.current = undefined
- moveStartYRef.current = undefined
- setDirection(undefined)
}
- }, [dragRef])
+ }, [armDirectionTimer, armSessionTimer])
- return { dragging, direction, clickCount }
+ return { dragging, direction }
}
diff --git a/src/pet/hooks/use-omit-ignore-cursor-events.ts b/src/pet/hooks/use-omit-ignore-cursor-events.ts
index fde1d8d5..f4f2a5d6 100644
--- a/src/pet/hooks/use-omit-ignore-cursor-events.ts
+++ b/src/pet/hooks/use-omit-ignore-cursor-events.ts
@@ -93,7 +93,11 @@ export function useOmitIgnoreCursorEvents(elementRef: RefObject<HTMLElement | nu
function isCursorInElement(x: number, y: number): boolean | undefined {
const element = elementRef.current
- if (element === null || windowPosition === undefined)
+ // 未选择宠物(或渲染层尚未挂载)时没有可交互面:整窗穿透,避免一个空的
+ // 透明置顶窗口吞掉桌面点击。
+ if (element === null)
+ return false
+ if (windowPosition === undefined)
return undefined
const rect = element.getBoundingClientRect()
diff --git a/src/pet/hooks/use-pet-source.ts b/src/pet/hooks/use-pet-source.ts
new file mode 100644
index 00000000..08e92b21
--- /dev/null
+++ b/src/pet/hooks/use-pet-source.ts
@@ -0,0 +1,150 @@
+import type { CodexPetConfig, PetConfig } from 'dsh-pet-component'
+import { invoke } from '@tauri-apps/api/core'
+import { useEffect, useState } from 'react'
+import { PET_CODEX_ASPECT, PET_DSH_ASPECT } from '../constants'
+import { reportPetIssue } from '../utils/log'
+
+/**
+ * `resources/preset-pets.json` 的条目(Rust `list_preset_pets` 原样返回)。
+ *
+ * 条目字段即 `dsh-pet-component` 的 `<Pet>` props:预设宠物不再下载/安装到本地,
+ * 组件直连条目里的远端素材地址播放。
+ */
+interface PresetPetItem {
+ id: string
+ name: string
+ desc?: string
+ /** 设置页卡片预览图。 */
+ image?: string
+ /** 渲染器协议;缺省由组件按 config 形状自动判定。 */
+ kind?: 'dsh' | 'codex'
+ /** 渲染宽度 px(100% 档位)。 */
+ size?: number
+ /** 配置文件地址(dsh-pet `config.jsonc` / Codex `pet.json`)。 */
+ config: string
+ /** 素材基地址;`mac` 为 Apple 平台覆盖(HEVC-alpha `.mov`)。 */
+ uri: { default: string, mac?: string }
+ /** 素材后缀;缺省 `{ default: 'webm', mac: 'mov' }`。 */
+ ext?: { default: string, mac?: string }
+}
+
+/** 导入的 Codex 宠物资源(Rust `get_pet_asset`,精灵图以 data URL 直接渲染)。 */
+interface PetAsset {
+ id: string
+ spritesheet: string
+ sprite_version_number: number
+ columns: number
+ rows: number
+}
+
+/**
+ * 渲染一个宠物所需的全部参数 —— `<Pet>` 的渲染 props 加上窗口推导所需的比例。
+ *
+ * 两种来源走同一条出口:清单里的预设宠物(远端 dsh-pet 视频 / Codex 图集)与
+ * 用户导入的 chat/codex 宠物(本地图集,Rust 侧转 data URL)。
+ */
+export interface PetSource {
+ /** 渲染器协议(显式指定,避免组件按 config 形状误判)。 */
+ kind: 'dsh' | 'codex'
+ config: string | PetConfig
+ uri: string | { default: string, mac?: string }
+ ext?: { default: string, mac?: string }
+ /** 画布比例(高 / 宽),窗口尺寸推导用。 */
+ aspect: number
+ /** 100% 档位的渲染宽度 px。 */
+ width: number
+}
+
+/**
+ * `usePetSource` 的结果:渲染参数 + 「选中的宠物解析不出来」的原因。
+ *
+ * `error` 非空时调用方必须给出可见提示:桌宠窗口是透明的,"什么都没有" 与
+ * "宠物正在加载" 在观感上完全一样,用户只会认为宠物坏了。
+ */
+export interface PetSourceState {
+ source: PetSource | null
+ /** 解析失败的诊断串(id 不存在或命令报错);`null` = 成功或仍在解析。 */
+ error: string | null
+}
+
+function presetSource(item: PresetPetItem): PetSource {
+ const kind = item.kind ?? 'dsh'
+ return {
+ kind,
+ config: item.config,
+ uri: item.uri,
+ ext: item.ext,
+ aspect: kind === 'codex' ? PET_CODEX_ASPECT : PET_DSH_ASPECT,
+ width: item.size ?? 220,
+ }
+}
+
+function assetSource(asset: PetAsset): PetSource {
+ const config: CodexPetConfig = {
+ spriteVersionNumber: asset.sprite_version_number === 1 ? 1 : 2,
+ columns: asset.columns,
+ rows: asset.rows,
+ }
+ return {
+ kind: 'codex',
+ config,
+ uri: asset.spritesheet,
+ aspect: PET_CODEX_ASPECT,
+ width: 220,
+ }
+}
+
+/**
+ * 把当前激活宠物 id 解析成渲染参数。
+ *
+ * - 空 id(未选择宠物)→ `null`;
+ * - 来源限定 id(`chat:` / `codex:`,用户导入)→ `get_pet_asset`;
+ * - 未限定 id → `list_preset_pets` 里的条目(预设宠物直连远端,无安装态)。
+ *
+ * 切换宠物时旧资源在异步结果回来前保持不变(避免闪烁)。解析失败(导入的宠物已被
+ * 删除、清单里没有这个 id、命令报错)不只记日志:把原因交给调用方渲染可见提示 ——
+ * 静默留一个空窗口时用户看到的是「宠物加载不出来」,无从判断该去设置页重选。
+ */
+export function usePetSource(activePet: string): PetSourceState {
+ const [resolved, setResolved] = useState<{
+ id: string
+ value: PetSource | null
+ error: string | null
+ } | null>(null)
+
+ useEffect(() => {
+ if (activePet === '')
+ return undefined
+ let disposed = false
+ const task = activePet.includes(':')
+ ? invoke<PetAsset>('get_pet_asset', { id: activePet }).then(assetSource)
+ : invoke<PresetPetItem[]>('list_preset_pets')
+ .then(catalog => catalog.find(item => item.id === activePet))
+ .then(item => (item === undefined ? null : presetSource(item)))
+ void task
+ .then((value) => {
+ if (disposed)
+ return
+ setResolved({
+ id: activePet,
+ value,
+ error: value === null ? `PET_NOT_FOUND: ${activePet}` : null,
+ })
+ })
+ .catch((error) => {
+ reportPetIssue(`resolve ${activePet}`, error)
+ if (!disposed)
+ setResolved({ id: activePet, value: null, error: String(error) })
+ })
+ return () => {
+ disposed = true
+ }
+ }, [activePet])
+
+ // 尚未拿到当前 id 的结果(加载中)时不报错:避免切换宠物瞬间闪一帧「不可用」。
+ const current = resolved !== null && resolved.id === activePet ? resolved : null
+ return {
+ source: current?.value ?? null,
+ error: current?.error ?? null,
+ }
+}
diff --git a/src/pet/hooks/use-pet-status.ts b/src/pet/hooks/use-pet-status.ts
new file mode 100644
index 00000000..a3a63299
--- /dev/null
+++ b/src/pet/hooks/use-pet-status.ts
@@ -0,0 +1,62 @@
+import { invoke } from '@tauri-apps/api/core'
+import { listen } from '@tauri-apps/api/event'
+import { useEffect, useState } from 'react'
+import { PET_SIZE_DEFAULT_PERCENT, PET_SIZE_MAX_PERCENT, PET_SIZE_MIN_PERCENT } from '../constants'
+
+/** Rust `PetStatus`(`get_pet_status` 返回值 / `pet://status` 事件载荷)。 */
+export interface PetStatus {
+ /** 桌宠能力是否永久启用。 */
+ enabled: boolean
+ /** 桌宠窗口当前是否应显示。 */
+ visible: boolean
+ /** 当前桌宠 id;空串 = 未选择任何宠物。 */
+ active_pet: string
+ /** 宠物大小百分比(50–200;None = 未设置,按 100 处理)。 */
+ pet_size?: number | null
+}
+
+/**
+ * 读取桌宠设置状态:挂载时拉一次 `get_pet_status`,此后跟随 `pet://status` 事件
+ * (Rust 在开关/选择/大小变化时推送)。
+ *
+ * 返回 `null` 表示「尚未拿到状态」:调用方据此避免用缺省值闪一帧错误尺寸,
+ * 也不要把 `null` 当作「已停用」。
+ */
+export function usePetStatus(): PetStatus | null {
+ const [status, setStatus] = useState<PetStatus | null>(null)
+
+ useEffect(() => {
+ let disposed = false
+ let unlisten: (() => void) | undefined
+ void listen<PetStatus>('pet://status', (event) => {
+ if (!disposed)
+ setStatus(event.payload)
+ }).then((dispose) => {
+ if (disposed)
+ dispose()
+ else
+ unlisten = dispose
+ }).catch(() => {})
+ void invoke<PetStatus>('get_pet_status')
+ .then((value) => {
+ if (!disposed)
+ setStatus(value)
+ })
+ .catch((error) => {
+ console.warn('[pet] PET_STATUS_LOAD_FAILED:', error)
+ })
+ return () => {
+ disposed = true
+ unlisten?.()
+ }
+ }, [])
+
+ return status
+}
+
+/** 归一化宠物大小百分比(缺省 / 非法 / 越界一律收敛进合法区间)。 */
+export function normalizeSizePercent(value: number | null | undefined): number {
+ if (typeof value !== 'number' || !Number.isFinite(value))
+ return PET_SIZE_DEFAULT_PERCENT
+ return Math.min(PET_SIZE_MAX_PERCENT, Math.max(PET_SIZE_MIN_PERCENT, value))
+}
diff --git a/src/pet/hooks/use-pet-window.ts b/src/pet/hooks/use-pet-window.ts
new file mode 100644
index 00000000..6d457618
--- /dev/null
+++ b/src/pet/hooks/use-pet-window.ts
@@ -0,0 +1,35 @@
+import { invoke } from '@tauri-apps/api/core'
+import { getCurrentWindow, LogicalSize } from '@tauri-apps/api/window'
+import { useEffect } from 'react'
+import { PET_BUBBLE_MIN_WIDTH, PET_WINDOW_PAD_X, PET_WINDOW_PAD_Y } from '../constants'
+
+/**
+ * 让桌宠窗口跟随宠物真实画布尺寸缩放(设置页大小滑条实时生效)。
+ *
+ * Rust 只按「预设 16:9 / 图集 208:192」的近似比例创建窗口;真实比例由渲染层决定
+ * (Codex 图集的实际格子比例、清单里的 size 都可能不同),所以尺寸的统一出口在这里,
+ * 避免两处 set_size 互相打架(issue #308)。加宽窗口只向左扩展透明区,宠物锚定
+ * 右下角,屏幕位置保持不变。
+ *
+ * @param width 宠物渲染宽度(px)
+ * @param aspect 画布比例(高 / 宽)
+ * @param visible 窗口当前是否可见;不可见时不折腾几何
+ */
+export function usePetWindowSize(width: number, aspect: number, visible: boolean): void {
+ useEffect(() => {
+ if (!visible)
+ return undefined
+ const windowWidth = Math.max(width + PET_WINDOW_PAD_X, PET_BUBBLE_MIN_WIDTH)
+ const windowHeight = width * aspect + PET_WINDOW_PAD_Y
+ void getCurrentWindow()
+ .setSize(new LogicalSize(windowWidth, windowHeight))
+ .then(() => {
+ // 放大后把窗口夹回可见显示器,避免右侧/底部被推出屏幕。
+ void invoke<void>('move_pet_window', { deltaX: 0, deltaY: 0 }).catch(() => {})
+ })
+ .catch((error) => {
+ console.warn('[pet] PET_WINDOW_RESIZE_FAILED:', error)
+ })
+ return undefined
+ }, [aspect, visible, width])
+}
diff --git a/src/pet/hooks/use-pet.ts b/src/pet/hooks/use-pet.ts
deleted file mode 100644
index 9ef52f0f..00000000
--- a/src/pet/hooks/use-pet.ts
+++ /dev/null
@@ -1,55 +0,0 @@
-import type { RefObject } from 'react'
-import { useRef } from 'react'
-
-export const PET_STATUSES = [
- 'idle',
- 'turn',
- 'moving-left',
- 'moving-right',
- 'waving',
- // 细分工作状态档位(host reducer workStatus;动画名映射见 pet-config PRESET_SESSION_ANIMATIONS)
- 'thinking',
- 'working',
- 'result',
- 'waiting',
- 'running',
- 'review',
- 'failed',
- 'success',
- 'error',
-] as const
-
-export type PetStatus = (typeof PET_STATUSES)[number]
-
-export interface PetChangeOptions {
- loop?: boolean
- status: PetStatus
-}
-
-export interface PetHandle {
- change: (options: PetChangeOptions) => void
- clear: () => void
- readonly status: PetStatus
-}
-
-/**
- * 提供桌宠的命令面。组件内部通过同一个 ref 暴露真正的播放器,调用方不接触
- * 资源、Codex 精灵图或动画结束事件;ref 命令优先于 status 属性。
- */
-export function usePet(petRef?: RefObject<PetHandle | null>): PetHandle {
- const handleRef = useRef<PetHandle | null>(null)
- if (handleRef.current === null) {
- handleRef.current = {
- change(options) {
- petRef?.current?.change(options)
- },
- clear() {
- petRef?.current?.clear()
- },
- get status() {
- return petRef?.current?.status ?? 'idle'
- },
- }
- }
- return handleRef.current
-}
diff --git a/src/pet/main.tsx b/src/pet/main.tsx
index e662c4c3..44d2e6d8 100644
--- a/src/pet/main.tsx
+++ b/src/pet/main.tsx
@@ -1,9 +1,45 @@
+import { fetch as tauriFetch } from '@tauri-apps/plugin-http'
import React from 'react'
import ReactDOM from 'react-dom/client'
import { disableWakeLock } from '@/utils/disable-wake-lock'
import { App } from './app'
+import { reportPetIssue } from './utils/log'
import './main.css'
+/**
+ * 把**远端 https 请求**交给 Tauri HTTP 插件,其余请求原样走原生 `fetch`。
+ *
+ * 目的:预设宠物素材直连 `raw.githubusercontent.com`。该主机其实返回
+ * `Access-Control-Allow-Origin: *`,但插件版由 Rust 发起请求,不受同源策略、
+ * CSP connect-src 与企业代理拦截影响,行为更可控。
+ *
+ * 为什么必须限定 `https://`:整体替换 `window.fetch` 会连带劫持**同源请求** ——
+ * 开发模式下 Vite 客户端用 `fetch` 拉取热更新后的样式文本(`http://localhost:1420/...`),
+ * 而插件 scope 只允许素材主机,请求被拒 → 样式热更新失败并触发整页重载,桌宠窗口在
+ * 开发时被反复重建。生产环境同样不该让桌宠窗口失去同源 fetch 能力。
+ */
+const nativeFetch = globalThis.fetch
+const pluginFetch = tauriFetch as unknown as typeof globalThis.fetch
+globalThis.fetch = ((input: RequestInfo | URL, init?: RequestInit) => {
+ const url = typeof input === 'string'
+ ? input
+ : input instanceof URL
+ ? input.href
+ : input.url
+ return url.startsWith('https://')
+ ? pluginFetch(input, init)
+ : nativeFetch(input, init)
+}) as typeof globalThis.fetch
+
+// 桌宠窗口没有任何日志出口:把未捕获异常与未处理的 Promise 拒绝转发进应用日志,
+// 否则「窗口空白 / 页面崩溃」在日志里完全不可见,只能靠手动 F12。
+globalThis.addEventListener('error', (event) => {
+ reportPetIssue('window error', `${event.message} @ ${event.filename}:${event.lineno}`)
+})
+globalThis.addEventListener('unhandledrejection', (event) => {
+ reportPetIssue('unhandled rejection', (event as PromiseRejectionEvent).reason)
+})
+
const root = document.getElementById('root') as HTMLElement
root.className = 'h-full w-full'
@@ -11,10 +47,6 @@ root.className = 'h-full w-full'
// (issue #469)。渲染前禁用屏幕唤醒锁,收起宠物/窗口隐藏时都不会再阻止息屏。
disableWakeLock()
-// 禁用桌宠窗口右键菜单:桌宠窗口是装饰性的透明置顶小窗,右键不应弹出
-// WebView 默认 context menu(Chromium/WebView2 尊重 contextmenu 的 preventDefault)。
-window.addEventListener('contextmenu', event => event.preventDefault(), { capture: true })
-
ReactDOM.createRoot(root).render(
<React.StrictMode>
<App />
diff --git a/src/pet/utils/log.ts b/src/pet/utils/log.ts
new file mode 100644
index 00000000..385ad824
--- /dev/null
+++ b/src/pet/utils/log.ts
@@ -0,0 +1,33 @@
+import { invoke } from '@tauri-apps/api/core'
+
+/**
+ * 把桌宠窗口的异常转发到应用日志(`logs/desktop.log`)。
+ *
+ * 桌宠窗口是独立 webview,默认没有任何日志出口:它的 console 只有在手动 F12 时才可见,
+ * 出问题时只能靠猜(「窗口是空的」既可能是没选宠物、也可能是资源没拉下来)。
+ * 这里统一走壳层的 `log_frontend` 命令,把异常落进主日志,便于事后定位。
+ *
+ * 失败静默:日志本身绝不能再抛错(命令不存在时应只是没有日志,而不是让桌宠窗口崩掉)。
+ */
+export function reportPetIssue(scope: string, detail: unknown): void {
+ const message = `[pet] ${scope}: ${formatDetail(detail)}`
+ console.warn(message)
+ void invoke('log_frontend', {
+ level: 'error',
+ target: 'pet',
+ message: message.slice(0, 4000),
+ }).catch(() => {})
+}
+
+function formatDetail(detail: unknown): string {
+ if (detail instanceof Error)
+ return `${detail.name}: ${detail.message}`
+ if (typeof detail === 'string')
+ return detail
+ try {
+ return JSON.stringify(detail)
+ }
+ catch {
+ return String(detail)
+ }
+}
diff --git a/test/disable-wake-lock.test.ts b/test/disable-wake-lock.test.ts
index 96f712c6..aaeb3fe8 100644
--- a/test/disable-wake-lock.test.ts
+++ b/test/disable-wake-lock.test.ts
@@ -93,12 +93,13 @@ describe('pet window wake lock contract', () => {
})
it('keeps every pet animation video muted', () => {
- const source = readFileSync(new URL('../src/pet/components/pet.tsx', import.meta.url), 'utf8')
- const videos = source.match(/<video[\s\S]*?\/>/g) ?? []
-
- // 双 video 缓冲(前台/后台)各一个;两个都不能出声,否则桌宠动画会突然发声。
- expect(videos).toHaveLength(2)
- for (const video of videos)
- expect(video).toMatch(/\bmuted\b/)
+ // 视频层已整体交给 dsh-pet-component(src/pet 不再自带 <video>):断言渲染器的
+ // 双缓冲视频都显式静音 —— 桌宠动画一旦出声就是回归(与 #469 同源的常驻播放契约)。
+ const bundle = readFileSync(
+ new URL('../node_modules/dsh-pet-component/dist/index.mjs', import.meta.url),
+ 'utf8',
+ )
+ const muted = bundle.match(/muted:\s*true/g) ?? []
+ expect(muted.length).toBeGreaterThanOrEqual(2)
})
})