Skip to content

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

feat(pets): remote repository registration and video pets (#1030)

Mao Mr8eb778bc83e9
diff --git a/packages/dsh-tauri-pet/skills/hatch-dsh-pet/SKILL.md b/packages/dsh-tauri-pet/skills/hatch-dsh-pet/SKILL.md
index 077875bd..164be340 100644
--- a/packages/dsh-tauri-pet/skills/hatch-dsh-pet/SKILL.md
+++ b/packages/dsh-tauri-pet/skills/hatch-dsh-pet/SKILL.md
@@ -1,179 +1,90 @@
---
name: hatch-dsh-pet
-description: Hatch a custom desktop pet for the dsh-tauri-pet plugin by following the upstream dsh-pet generation flow — prompt recipe → 10-second green-screen AI video → keying and normalization → transparent animation — then baking the result into a pet folder (pet.json plus an 8-column sprite atlas) under the DSH data directory and validating it against the host contract so it shows up in Settings → 宠物. Use when the user asks to create, hatch, import, replace or repair a custom pet, wants it generated the way upstream PC2005-cloud/dsh-pet describes, or when a pet folder they added does not appear in the pet list.
+description: Create, hatch, import, replace or repair a custom desktop pet for dsh-tauri-pet. Default to a local Pets video package (pet.json, config.jsonc, transparent WebM animations and a square GIF preview), reuse supplied transparent assets, or follow the upstream green-screen generation flow when needed. Use an 8-column sprite atlas only when the user explicitly requests Codex. Validate the package and state host-version and macOS playback limitations honestly.
metadata:
author: Hairyf
- version: "2026.10.03"
+ version: "2026.10.12"
---
# Hatch DSH Pet
-把一只自定义宠物养进 `dsh-tauri-pet`:**素材按上游 [`PC2005-cloud/dsh-pet`](https://github.com/PC2005-cloud/dsh-pet) 的生成流程产出,落点用本机认的图集**。
+默认交付 **Pets 视频宠物**,不是 Codex 图集。保留完整动画时序;不要把十秒视频抽成六帧图集后声称是完整动画。只有用户明确要求 Codex 才读 `references/atlas-layout.md` 与 `references/atlas-compose.md`。
-| 阶段 | 做什么 | 产物 |
-| --- | --- | --- |
-| ① | 提示词 → 源视频 | `video/<动作>.mp4`(10 秒绿幕,一个动作一段) |
-| ② | 源视频 → 透明动画 | `step02/` 抠像 → `step03/` 归一化 → `step04/` 播放变体(透明 webm) |
-| ③ | 动画 → 宠物 | 本机落点:`spritesheet.png/webp` + `pet.json` → `<DSH_HOME>/pets/<petId>/` |
+## 先确认能力与素材
-上游的 ③ 是把 webm `cp` 进它自己的插件包(`dsh-pet/assets/webm/`);本仓的 ③ 换成把透明帧**烘焙成 8 列 × 11 行图集**,因为本机只认图集。①② 完全照上游走:配方、命令与约束见 `references/dsh-pet-video-flow.md`(上游 `README.md:430-528` 的逐条转述),烘焙命令见 `references/atlas-compose.md`。
+1. 确认当前宿主支持本地 `kind: "dsh"` 契约。旧宿主不支持时明确报出阻塞,不能自行改成交付 Codex。修改宿主须先获用户许可;修技能本身不等于获准改宿主。
+2. 清点用户已提供的透明 WebM/MOV、动作与许可。可复用的透明素材直接整理、校验和生成预览,不要无谓 clone 上游、重新生成绿幕或重复抠像。
+3. 只有从零生成或绿幕抠像时才读 `references/dsh-pet-video-flow.md`;沿用其中有用的提示词、Python/ffmpeg 抠像与归一化流程。缺视频生成工具或转码能力就明示,不用生图图集冒充视频。
+4. 确认落点、id 与覆盖许可。环境注入的非空 `DSH_HOME` 优先,否则发行版通常用 `~/.dsh`;调试宿主可能用 `~/.dsh.dev`,以正在运行的宿主实际数据目录为准,不猜安装盘符。
-## 两条产线,先分清
+## Pets 视频包契约
-| | 上游插件 `PC2005-cloud/dsh-pet` | 本机 `dsh-tauri-pet` |
-| --- | --- | --- |
-| 宠物形态 | `$DSH_HOME/dsh-pet/` 下的 webm/mov 视频包(`main-animation/`、`pet/<种类>-animation/`) | `<DSH_HOME>/pets/<petId>/pet.json` + 8 列静态图集(PNG/WebP) |
-| 谁加载 | 上游插件自己的宿主路由 | 主程序 `src-tauri/src/bridge/pet.rs:629` 扫 `pets/` 的**直接子目录** |
-| 能否本地注册视频宠物 | 能(「方式四 pet pack」,自动扫描) | **不能**:视频宠物只能来自 `src-tauri/resources/manifest.jsonc` 的 `pets.built-in` 远端 https 资产,`src-tauri/src/bridge/preset_pet.rs` 的出厂校验强制这一点 |
+宿主枚举 `<DSH_HOME>/pets/` 的直接子目录,不要再套一层。id 为 1~64 个 ASCII 字母、数字、`-`、`_`,列表限定 id 为 `chat:<id>`。
-结论:**素材链照搬上游,落点换成本机图集**。把 `$DSH_HOME/dsh-pet/` 那套视频包原样搬到本机,设置页不会出现这只宠物。
-
-## 何时使用
-
-- 用户说「养一只宠物」「创建宠物」「做一个自定义桌宠」「换成我自己的形象」。
-- 用户想按上游 dsh-pet 的方式生成宠物(写提示词 → 出绿幕视频 → 抠像 → 变成桌宠动画)。
-- 用户已经把素材放进 `pets/` 目录,但设置页的宠物列表里看不到它。
-- 用户想替换、修复或重新烘焙一只已有自定义宠物。
-- 用户的宠物在列表里可见但选中后桌宠窗口不显示(通常是图集尺寸或格式不合约)。
-
-不要用于:Codex 宠物的 `.zip` 导入(走设置页 Codex 标签页的「导入」按钮,落点在 `~/.codex/pets`);也不要用于修改内置预设宠物(在 `src-tauri/resources/manifest.jsonc` 里,由主程序提供,且必须是远端资产)。
-
-## 落点
-
-DSH 数据目录按以下顺序确定,先取用户环境里已有的值再动手:
-
-1. 非空环境变量 `DSH_HOME`(主程序为内核注入的就是它)。
-2. 否则 `~/.dsh`(发行版默认)。
-3. 调试构建固定用 `~/.dsh.dev`,不看 `DSH_HOME`。
-
-宠物根目录 = `<DSH_HOME>/pets`,每只宠物一个**直接子目录**:`<DSH_HOME>/pets/<petId>/`。宿主只枚举直接子目录,不递归、不跟随符号链接,所以不要套一层 `my-pet/pet/`;目录名与 `pet.json` 里的 `id` 不必一致,`id` 才是标识。
-
-`<petId>` 规则:1~64 个字符,只允许 ASCII 字母、数字、`-`、`_`。列表里展示的 id 是 `chat:<petId>`。
-
-宠物文件夹至少两个文件:
-
-```
-<DSH_HOME>/pets/<petId>/
+```text
+<DSH_HOME>/pets/my-pet/
├── pet.json
-└── spritesheet.webp # 文件名任意,PNG 或 WebP 都行
+├── config.jsonc
+├── webm/
+│ ├── idle.webm
+│ └── working.webm
+└── preview/
+ └── preview.gif
```
-## pet.json
-
-camelCase 字段,只有 `id` 与 `spritesheetPath` 必填;`pet.json` 本身不得超过 64 KiB。
-
```json
{
+ "kind": "dsh",
"id": "my-pet",
"displayName": "My Pet",
- "description": "在会话里陪我的桌宠",
- "spriteVersionNumber": 2,
- "spritesheetPath": "spritesheet.webp"
+ "description": "透明视频桌宠;本包不支持 macOS",
+ "configPath": "config.jsonc",
+ "uriPath": "webm",
+ "previewPath": "preview/preview.gif",
+ "ext": { "default": "webm", "mac": "webm" },
+ "size": 220
}
```
-- `displayName` 省略时列表回落到 `id`;`description` 可选。
-- `spriteVersionNumber` 只能是 `1` 或 `2`,其他值会让这只宠物被整个跳过。`2` 表示 11 行图集(含两个朝向行),`1` 表示 9 行图集。**新宠物一律写 `2`。**
-- `spritesheetPath` 必须是相对路径、使用正斜杠,且不含 `..`、不绝对、不含 `\`、不含 `:`。
-
-## 图集契约
-
-宿主按固定网格切帧,**不看像素内容,只校验头部尺寸**:
+`size` 可省略,是大于 0 且不超过 4096 的渲染宽度,而非文件大小;视频包必须声明 `ext.default: "webm"`。`pet.json` 用严格 JSON;`config.jsonc` 为对象,允许注释与尾逗号。所有文件/目录路径为包内正斜杠相对路径,不允许绝对路径、`..`、反斜杠、冒号或符号链接越界。清单最多 64 KiB、配置 1 MiB、每个视频 512 MiB、GIF 8 MiB 且边长 1~4096 像素。清单、配置、预览与配置所引用的视频均须实际存在。
-- 格式:PNG 或 WebP,透明背景。
-- 列数固定 8;行数 9(v1)或 11(v2)。
-- 宽必须是 8 的倍数;高必须是 9 的倍数或 11 的倍数。
-- 单边不超过 16384 像素,总像素不超过 64 Mi;图集文件不超过 8 MiB。
-- 推荐规格:8 列 × 11 行,每格 192×208,整图 **1536×2288**,`spriteVersionNumber: 2`。
+新包优先使用 `motions`,每个动作值为动作名字符串或非空字符串数组;动作名不带扩展名,宿主在 `uriPath` 下按 `ext.default` 找到视频:
-行序、每行动作帧数与逐帧时长见 `references/atlas-layout.md`,导出素材时按那张表对齐。行的用途由宿主固定:第 0 行是待机,第 1/2 行是移动,其后各行分别对应挥手、跳跃、失败、等待、运行、复查,最后两行是按角度采样朝向的 look 行。
-
-标准动作行只用到左侧若干格,**末帧之后的格子必须完全透明**,否则会露出脏像素。look 行则要填满 8 格。
-
-## 阶段
-
-### 0. 准备
-
-1. 确认落点与 id,检查 `<DSH_HOME>/pets/<petId>/` 是否已存在(已存在就先和用户确认是覆盖还是换 id)。
-2. 取上游配方。`web_fetch` 在部分网络环境会被拒(DNS 落到代理段,报 `non-public IP address`),用 git 拿:
- `git clone --depth 1 https://github.com/PC2005-cloud/dsh-pet`
- 需要的是 `prompts/桌面宠物 10 秒动作提示词.md`(通用前缀 + 每个动作的按秒分解)与 `scripts/` 素材链,细节见 `references/dsh-pet-video-flow.md`。
-3. 清点工具链:① 需要用户自己的 AI 视频生成工具(可灵 / Runway / 豆包等,上游素材即由豆包生成);② 需要 Python 3 + ffmpeg + numpy + scipy;③ 只需要 ffmpeg(或 Node 内置模块)拼图集。**缺哪一环就直说缺哪一环,不要用「让生图模型画一版图集」冒充视频流程。**
-4. 版权约束:上游素材(动画 / 提示词 / 源视频)允许开源使用但**禁止商用**;基于上游的二创作品必须在**任何介绍、展示、分发该作品的地方**附上 <https://github.com/PC2005-cloud/dsh-pet>。这一条要写进交付说明。
-
-### 1. 提示词 → 源视频
+```jsonc
+{
+ "motions": {
+ "idle": "idle",
+ "working": ["working"],
+ }
+}
+```
-按 `prompts/桌面宠物 10 秒动作提示词.md` 的配方,**一个动作生成一段 10 秒绿幕视频**:
+也兼容上游传统 `animations` 池(`idle`、`turn`、`drag`、`clicks`、`moves.actions`、`categories[].actions`、`events`),不必为了导入已有素材重写整个池。只配置真实存在的动作;缺少丰富动作时可以交付一个静态待机视频,明确它不会动,而不是伪造完整动作。鼠标方向变化不应切换待机素材或触发转向;不要为了追踪鼠标把多份待机/turn 素材塞入包。
-- 比例 16:9,背景纯绿 `#00FF00`,无阴影杂物,各段绿幕色值完全一致。
-- 人物位置/大小固定:头顶 ≈ 20% 高度、脚底 ≈ 85% 高度、左右边缘 ≈ 25% / 75%,画幅四边留 10% 安全缓冲;双脚落点恒定在画面正中,禁止整体平移。
-- 动作全程在画幅内;**首帧与第 10 秒末帧都必须是同一张标准正面站立**(动作闭环,便于循环与取帧)。
-- 大物件与道具遵守「无 → 有 → 无」闭环;需要侧身互动时只允许原地轴转。
-- 每段按秒分解(0~3s / 3~7s / 7~10s 各阶段),配方文件里每个动作都有现成的分段描述,直接引用即可。
+## 编码与平台支持
-结果按动作名各存一个 mp4 放进工作目录的 `video/`。上游为了控制仓库体积不把 `video/` 入库,Release 提供 `assets-videos.zip`,我们本地工作目录同样不要提交源视频。
+- Windows/Linux 播放资产:透明 **WebM VP9-alpha**,保留真实动作的完整帧与时序。仅文件后缀、容器头或 `pix_fmt` 标签不能证明 alpha 解码正确,须在目标播放器实测。
+- **MOV ProRes 4444 alpha** 可以作高质量透明归档/转码源,但不是 macOS WKWebView 的 **HEVC-with-Alpha MOV** 播放替代品;不要把归档目录填入 `macUriPath`。
+- 真正有 mac 可播 HEVC-alpha 文件时,添加 `macUriPath: "mov"` 与 `ext.mac: "mov"`,按相同动作名放 `mov/<动作>.mov`,并在目标 macOS 宿主验证。Windows 无法产出原生 HEVC-alpha 时直说;不要用普通 HEVC、ProRes 或改后缀冒充。
+- 没有 mac 可播文件就**省略 `macUriPath`**,在包描述与交付说明明确「本包不支持 macOS」。无 mac 素材时可显式 `ext.mac: "webm"` 避免组件缺省在 WebM 目录请求 MOV,但不代表 WKWebView 能播放其透明通道;扩展名约定本身不证明可播。
+- `previewPath` 必须是真正的**方形 GIF**(宽等于高),不是 PNG 改名或 16:9 视频截图。预览可裁切或补边,不改变播放视频构图;生成后检查 GIF 头尺寸和实际预览效果。
-### 2. 源视频 → 透明动画
+## 完成与验证
-在 `scripts/` 下跑素材链,两条路线二选一,产出同级 `step02/`:
+先在本地暂存目录整理,再校验;写入真实宠物目录前取得覆盖许可。运行:
```sh
-cd scripts
-# 路线 A(默认,全自动可复现):绿幕抠像
-python watermark_step01.py # 水印遮罩填充 → step01/
-python chroma_step02.py # HSV 绿幕抠像转透明 → step02/
-
-# 路线 B(可选,上游自己的全部动作都用这条):PR 手工抠像
-# 1. 在 PR 里手工抠像,导出带 alpha 的透明 .mov(如 ProRes 4444 with Alpha)
-# 2. 放入 pr/,文件名与动作名一致(如 吃白饭.mov)
-python pr_import_step02.py # pr/*.mov → step02/,覆盖该动作的自动抠像结果
-
-# 两条路线共用:
-python normalize_step03.py # 归一化 2160×1215、统一站立居中 → step03/
-python encode_thumbs.py # 转码 640×360 播放变体 → step04/
+node "<skill 基目录>/references/validate-pet.mjs" "<宠物目录>"
```
-含第三方物品、透明边缘复杂的动作,自动 HSV 抠像容易残边或误抠,用路线 B 手工遮罩;`chroma_step02.py` 作为自动化兜底随时保留。中间产物 `step01~04/` 不入库。
-
-### ① 与 ② 之间:不要做 macOS HEVC mov
-
-上游 ②.5 讲的是 VP9-alpha webm 在 Safari/WKWebView 黑底,所以给**它自己的插件**准备了 HEVC-with-Alpha `.mov` 并把 `ANIMATION_EXT` 改成 `.mov`。本机图集是 PNG/WebP,双端一致,**这一步与本技能无关,不要为它折腾 mov**。
-
-### 3. 透明动画 → 本机图集
-
-1. 读 `references/atlas-layout.md`(行序 / 每行帧数 / 逐帧时长)与 `references/atlas-compose.md`(上游动作 → 本机行的映射 + 取帧烘焙命令)。
-2. 从 `step03/<动作>.webm`(2160×1215,质量最高)取帧;`step04/` 是 640×360 播放变体,只用于兜底。
-3. 取帧数必须**正好等于**该行的帧数(多出来的格子必须完全透明):逐帧时长写死在 `dsh-pet-component` 里,改图集不会改节奏,多给的帧会被当成动作的一部分播出来。
-4. 所有动作、所有帧共用一个裁切框,再等比缩放进 192×208 的格子并统一脚底基线,否则宠物会在换行时忽大忽小、上下跳。
-5. 第 2 行(向左移动)可以直接用第 1 行的水平镜像,不必单独生成素材。
-6. look 行(第 9、10 行)要填满 8 格、共 16 个朝向,素材取自上游 `animations.turn` 的动作(如 `东张西望`)。两行各拿 8 档:行 9 是 `000°~157.5°`、行 10 是 `180°~337.5°`;**行 10 必须另取一条扫视程,别用行 9 的水平镜像顶替**——镜像给不出 `180°` 那一档。
-7. 按行优先顺序拼成 1536×2288 的整图,导出 PNG 或 WebP。
-8. 如果用户机器上 ffmpeg 实在不可用,可以用 Node 内置模块(`node:zlib` 足以手写 PNG、`node:fs` 足以拼接 WebP 分块)拼图集;**不要依赖 PIL、sharp、ImageMagick,宿主和内核都不保证它们在场。** 宠物文件夹本身(交付物)只含 `pet.json` + 图集,运行时不需要任何外部工具。
-
-### 4. 写 pet.json 并校验
-
-1. 写好 `pet.json`,把图集放进同一个目录。
-2. 用本技能自带的校验脚本核对契约:
-
- ```bash
- node "<skill 基目录>/references/validate-pet.mjs" "<DSH_HOME>/pets/<petId>"
- ```
+校验器兼容旧 Codex 清单,视频模式检查 JSONC 配置、方形 GIF、引用路径、文件存在与大小和越界。它**不是播放器**,通过仅代表静态包校验通过,不代表视频可解码、透明度已验证或 mac 可播。把真实输出与目标播放器实测结果分别报告,不混为一谈。
- 脚本会按宿主同一套规则报错:id 非法、路径不可移植、清单超限、格式不可解析、宽高不整除、尺寸超限、声明版本与尺寸推定不一致。全部通过时打印解析出的网格(版本 / 列 / 行)。
-3. 让用户确认:打开 设置 → 宠物,新宠物出现在 Pets 列表里;点「选择」即可启用。列表是在设置页挂载时重新枚举的,无需重启主程序。
+打开 设置 → 宠物 → Pets,确认列表、GIF 预览、选择与播放。无法显示时检查实际宿主版本、数据目录、配置引用与平台编码;不要改模式掩盖不支持,也不要擅改宿主/前端/内置资源清单。Codex `.zip` 导入走设置页 Codex 标签,不动 `~/.codex/pets`。
-## 失效时的表现
+如果使用上游素材/提示词,遵守 `references/dsh-pet-video-flow.md` 的许可与署名约定;用户自有素材不自动套用上游许可。
-- **完全不在列表里**:`pet.json` 读不出、id 非法、或目录不是 `pets/` 的直接子目录。宿主会静默跳过读不出清单的目录,不报错。
-- **在列表里但缩略图是占位方块**:图集读不出或格式/尺寸不合约,列表项仍会保留,缩略图生成失败。
-- **能选中但桌宠窗口不显示**:`get_pet_asset` 校验失败的典型症状,多半是宽不是 8 的倍数,或高既不是 9 的倍数也不是 11 的倍数。行数由**图集高度**推定,不看你写的 `spriteVersionNumber`:1536×2288 只会解析成 11 行,声明成 `1` 不会让它变成 9 行图集,只会被校验脚本记为一条 note。
-- **选择后状态回落到预设宠物**:写入的 active id 不是合法限定 id;自定义宠物必须是 `chat:<petId>`。
-- **动作播完闪出残帧**:该行末帧之后的格子没清空,留了旧像素。
+本目录是**技能源码**,修改不会自动更新已安装技能。需要通过安装更新让新版本生效;未经许可不直接修改安装目录。
-## 边界
+## 明确要求 Codex 时
-- 不要把上游 `$DSH_HOME/dsh-pet/` 那套视频包(`main-config.jsonc` + `main-animation/`、`pet/<种类>-animation/`)当成本机宠物的产物交付——本机读不到它。
-- 不要动 `~/.codex/pets`,那是 Codex 宠物的落点,由导入流程管理。
-- 不要在宠物目录里放符号链接;宿主拒绝跟随。
-- 不要为了「让它显示」去改宿主的 Rust 代码或 patch `src-tauri`:契约已经支持任意数量的自定义宠物目录。
-- 交付前必须跑校验脚本,并把真实输出贴给用户;不要凭肉眼断言尺寸。素材链没跑通就如实说停在哪一步,不要声称「视频已生成」而实际只给了图集。
+使用 `pet.json` 的 `spritesheetPath` 与可选 `spriteVersionNumber: 1|2`,保留旧图集契约:8 列,v1 为 9 行、v2 为 11 行,PNG/WebP,最多 8 MiB、单边 16384 像素、总像素 64 Mi。新图集推荐 v2、1536×2288;布局与烘焙参考只适用于这个分支。转为固定帧图集会丢失视频帧数与原始时序,须明确告知,不能声称与完整视频等价。
diff --git a/packages/dsh-tauri-pet/skills/hatch-dsh-pet/references/atlas-compose.md b/packages/dsh-tauri-pet/skills/hatch-dsh-pet/references/atlas-compose.md
index dfa93144..e5e5f8bf 100644
--- a/packages/dsh-tauri-pet/skills/hatch-dsh-pet/references/atlas-compose.md
+++ b/packages/dsh-tauri-pet/skills/hatch-dsh-pet/references/atlas-compose.md
@@ -1,6 +1,6 @@
-# 透明动画 → 本机图集(烘焙配方)
+# 透明动画 → Codex 图集(仅用户明确要求时)
-把上游素材链产出的透明动画(`step03/<动作>.webm`,2160×1215 VP9-alpha)烘焙成本机 `dsh-tauri-pet` 认的 **8 列 × 11 行图集**。行序、每行帧数、逐帧时长见 `atlas-layout.md`,这里只讲「哪段动画进哪一行」和「怎么拼」。
+Pets 默认交付完整视频包,不执行本配方。只有用户明确要求 Codex 才把透明动画烘焙为 **8 列 × 11 行图集**;抽帧会丢失原视频帧数与时序,不能冒充完整动画。行序、每行帧数、逐帧时长见 `atlas-layout.md`,这里只讲「哪段动画进哪一行」和「怎么拼」。
## 一、上游动作 → 本机行
diff --git a/packages/dsh-tauri-pet/skills/hatch-dsh-pet/references/atlas-layout.md b/packages/dsh-tauri-pet/skills/hatch-dsh-pet/references/atlas-layout.md
index 4839d24b..b7d90ef7 100644
--- a/packages/dsh-tauri-pet/skills/hatch-dsh-pet/references/atlas-layout.md
+++ b/packages/dsh-tauri-pet/skills/hatch-dsh-pet/references/atlas-layout.md
@@ -1,4 +1,6 @@
-# 图集布局
+# Codex 图集布局(仅用户明确要求时)
+
+Pets 视频包不使用此布局,也不因旧宿主不支持视频就改用此分支。
dsh-tauri-pet 的 Codex 图集是固定网格:**8 列 × 11 行**,每格 192×208,整图 **1536×2288**,`spriteVersionNumber: 2`。
diff --git a/packages/dsh-tauri-pet/skills/hatch-dsh-pet/references/dsh-pet-video-flow.md b/packages/dsh-tauri-pet/skills/hatch-dsh-pet/references/dsh-pet-video-flow.md
index 89d2cd63..c9dca639 100644
--- a/packages/dsh-tauri-pet/skills/hatch-dsh-pet/references/dsh-pet-video-flow.md
+++ b/packages/dsh-tauri-pet/skills/hatch-dsh-pet/references/dsh-pet-video-flow.md
@@ -7,7 +7,7 @@
## 取用上游仓库
-`web_fetch` 在部分网络环境下会被拒(DNS 落到代理段,报 `non-public IP address`),改用 git:
+仅从零生成且确实需要上游提示词/脚本时才获取仓库;用户已提供可用透明素材时跳过 clone 与绿幕链。`web_fetch` 在部分网络环境下会被拒(DNS 落到代理段,报 `non-public IP address`),可改用 git:
```sh
git clone --depth 1 https://github.com/PC2005-cloud/dsh-pet
@@ -58,7 +58,7 @@ python encode_thumbs.py # 转码 640×360 播放变体 → step04/
- 同目录还有 `encode_preview_gifs.py`(预览 GIF)、`check_alpha.py`(alpha 自检)、`fill_nn.py`、`make_mask_black.py`、`encode_hevc_alpha.sh`、`hevc_alpha_encoder.swift`,以及 `video/watermark_mask_v5.mkv`(水印遮罩素材)。
- 中间产物 `step01~04/` 由脚本生成、不入仓库;`video/` 源视频与 `scripts/` 入库维护。
-## ②.5 macOS / Safari 的 HEVC-alpha mov(只与上游插件有关)
+## ②.5 macOS / Safari 的 HEVC-alpha mov
插件默认只发布 `.webm`(VP9-alpha),Safari/WKWebView 不认 webm alpha(黑底),macOS 需要官方转码的 **HEVC-with-Alpha `.mov`**:
@@ -68,7 +68,7 @@ python encode_thumbs.py # 转码 640×360 播放变体 → step04/
宿主路由已固定双扩展名兜底(白名单 `webm|mov`、MIME、素材根按扩展名分派),无需改宿主。
-**本机 `dsh-tauri-pet` 的图集宠物用不到这一步**:PNG/WebP 图集双端一致,没有 webm alpha 解码问题。
+**本机 Pets 视频包也有这个平台限制**:有原生 HEVC-alpha MOV 才填写 `macUriPath` 与 `ext.mac: "mov"`;ProRes 4444 alpha MOV 只是归档/转码源,不是 WKWebView 播放格式。Windows 不能产出原生 HEVC-alpha 时明示,不用普通 HEVC 冒充。没有可播文件就省略 `macUriPath`,明确本包不支持 macOS;只有用户明确选 Codex 时,PNG/WebP 图集分支不涉及视频解码。上面修改 ANIMATION_EXT 的步骤属于上游插件安装,不适用于本机视频包,也不是授权修改安装文件。
## ③ 动画 → 插件(上游落点)
@@ -82,7 +82,7 @@ dsh plugin --profile desktop add file:D:/path/to/dsh-pet/dsh-pet
发布:单一 npm 包、单一素材格式(webm),`npm publish --tag latest` 触发 `prepare.js`(构建产物 + 收敛 `files`:lib / src / assets/webm / runtime/electron-helper / assets/fonts / assets/pic / assets/config.jsonc / scripts/ensure-electron.mjs / cordis.patch.yml)。
-**本机 `dsh-tauri-pet` 不用这条**:本机自定义宠物的落点是 `<DSH_HOME>/pets/<petId>/` 的图集,见 SKILL.md「落点」与 `atlas-compose.md`。
+**本机 `dsh-tauri-pet` 不用这条插件安装流程**:将完整透明 WebM、实际方形 GIF 与配置整理为 `<DSH_HOME>/pets/<petId>/` 的 `kind: "dsh"` 视频包,见 SKILL.md。不要为了导入已有透明素材构建或重新安装上游插件。
## 上游的另一种宠物:pet pack(方式四)
@@ -116,7 +116,7 @@ $DSH_HOME/dsh-pet/
| 余额 | `events.balance[0..5]` | `余额-钱袋满溢`、`余额-金袋叮当`、`余额-钱袋如常`、`余额-数金皱眉`、`余额-袋空如洗`、`余额-分文不剩` |
| 碎碎念 | `events.whisper[]` | `碎碎念-擦桌碎碎念`、`碎碎念-发呆碎碎念`、`碎碎念-对屏碎碎念` |
-本机图集只有 9 个动作行,从这份池子里每个行挑 1 个最贴近的动作即可,不需要(也没法)把上游上百个动作全搬进来。
+本机 Pets 视频包可复用传统 animations 池或 motions 映射,只保留实际提供的动作引用;静态待机视频也可用,鼠标方向不同不切换待机。只有明确选择 Codex 图集时才受固定动作行限制。
## 上游项目结构
diff --git a/packages/dsh-tauri-pet/skills/hatch-dsh-pet/references/validate-pet.mjs b/packages/dsh-tauri-pet/skills/hatch-dsh-pet/references/validate-pet.mjs
index d435e52a..ee8cc864 100644
--- a/packages/dsh-tauri-pet/skills/hatch-dsh-pet/references/validate-pet.mjs
+++ b/packages/dsh-tauri-pet/skills/hatch-dsh-pet/references/validate-pet.mjs
@@ -1,6 +1,6 @@
#!/usr/bin/env node
import { readFileSync, realpathSync, statSync } from 'node:fs'
-import { basename, isAbsolute, join, resolve, sep } from 'node:path'
+import { basename, isAbsolute, relative, resolve, sep } from 'node:path'
const MANIFEST_MAX_BYTES = 64 * 1024
const SPRITESHEET_MAX_BYTES = 8 * 1024 * 1024
@@ -26,9 +26,9 @@ function checkId(id) {
return true
}
-function portableRelative(value) {
+function portableRelative(value, field = 'path') {
if (typeof value !== 'string' || value.length === 0) {
- fail('PET_PATH_INVALID: spritesheetPath must be a non-empty string')
+ fail(`PET_PATH_INVALID: ${field} must be a non-empty string`)
return undefined
}
if (value.includes('\0') || value.includes('\\') || value.includes(':')) {
@@ -48,24 +48,193 @@ function portableRelative(value) {
return normalized
}
-function readBounded(path, limit, prefix) {
- let stats
+function containedPath(directory, value, field, directoryOnly = false) {
+ const portable = portableRelative(value, field)
+ if (portable === undefined)
+ return undefined
try {
- stats = statSync(path)
+ const root = realpathSync(directory)
+ const candidate = realpathSync(resolve(directory, portable))
+ const inside = relative(root, candidate)
+ if (!inside || inside === '..' || inside.startsWith(`..${sep}`) || isAbsolute(inside)) {
+ fail(`PET_PATH_INVALID: ${field} escapes the pet directory`)
+ return undefined
+ }
+ const stats = statSync(candidate)
+ if (directoryOnly ? !stats.isDirectory() : !stats.isFile()) {
+ fail(`PET_ASSET_READ_FAILED: ${field} must be a ${directoryOnly ? 'directory' : 'file'}`)
+ return undefined
+ }
+ return candidate
}
catch (error) {
- fail(`${prefix}: failed to read ${path}: ${error.message}`)
+ fail(`PET_ASSET_READ_FAILED: ${field}: ${error.message}`)
return undefined
}
- if (!stats.isFile()) {
- fail(`${prefix}: ${path} is not a file`)
+}
+
+function readBounded(path, limit, prefix, read = true) {
+ if (path === undefined)
return undefined
+ try {
+ const stats = statSync(path)
+ if (!stats.isFile() || stats.size === 0 || stats.size > limit) {
+ fail(`${prefix}: ${path} must be a non-empty file of at most ${limit} bytes`)
+ return undefined
+ }
+ if (!read)
+ return stats.size
+ const bytes = readFileSync(path)
+ if (bytes.length > limit) {
+ fail(`${prefix}: ${path} exceeds the ${limit} byte limit`)
+ return undefined
+ }
+ return bytes
}
- if (stats.size > limit) {
- fail(`${prefix}: ${path} exceeds the ${limit} byte limit`)
+ catch (error) {
+ fail(`${prefix}: failed to read ${path}: ${error.message}`)
return undefined
}
- return readFileSync(path)
+}
+
+function parseJsonc(bytes) {
+ const text = bytes.toString('utf8').replace(/^\uFEFF/, '')
+ const stripped = text.replace(/"(?:\\[\s\S]|[^"\\])*"|\/\/[^\r\n]*|\/\*[\s\S]*?\*\//g, token => token.startsWith('"') ? token : ' ')
+ return JSON.parse(stripped.replace(/"(?:\\[\s\S]|[^"\\])*"|,\s*(?=[}\]])/g, token => token.startsWith('"') ? token : ''))
+}
+
+function object(value) {
+ return value !== null && typeof value === 'object' && !Array.isArray(value)
+}
+
+function animationNames(config) {
+ const names = new Set()
+ function slot(value, field, empty = false) {
+ const entries = typeof value === 'string' ? [value] : value
+ if (!Array.isArray(entries) || (!empty && entries.length === 0)) {
+ fail(`PET_CONFIG_INVALID: ${field} must be a string or ${empty ? '' : 'non-empty '}string array`)
+ return
+ }
+ for (const name of entries) {
+ if (portableRelative(name, field) === undefined || name.includes('/')) {
+ fail(`PET_CONFIG_INVALID: ${field} must contain plain animation names`)
+ continue
+ }
+ names.add(name)
+ }
+ }
+ function motions(value, field) {
+ if (!object(value)) {
+ fail(`PET_CONFIG_INVALID: ${field} must be an object`)
+ return
+ }
+ for (const [motion, entry] of Object.entries(value))
+ slot(entry, `${field}.${motion}`)
+ }
+ if (config.motions !== undefined)
+ motions(config.motions, 'motions')
+ if (config.animations !== undefined) {
+ const pools = config.animations
+ if (!object(pools)) {
+ fail('PET_CONFIG_INVALID: animations must be an object')
+ return names
+ }
+ for (const key of ['idle', 'turn', 'drag', 'clicks']) {
+ if (pools[key] !== undefined)
+ slot(pools[key], `animations.${key}`, true)
+ }
+ if (pools.motions !== undefined)
+ motions(pools.motions, 'animations.motions')
+ if (pools.moves !== undefined) {
+ if (!object(pools.moves) || !Array.isArray(pools.moves.actions)) {
+ fail('PET_CONFIG_INVALID: animations.moves.actions must be an array')
+ }
+ else {
+ for (const action of pools.moves.actions)
+ slot(action?.name, 'animations.moves.actions.name')
+ }
+ }
+ if (pools.categories !== undefined) {
+ if (!Array.isArray(pools.categories)) {
+ fail('PET_CONFIG_INVALID: animations.categories must be an array')
+ }
+ else {
+ for (const category of pools.categories)
+ slot(category?.actions, 'animations.categories.actions', true)
+ }
+ }
+ if (pools.events !== undefined) {
+ if (!object(pools.events)) {
+ fail('PET_CONFIG_INVALID: animations.events must be an object')
+ }
+ else {
+ for (const [event, slots] of Object.entries(pools.events)) {
+ if (!Array.isArray(slots)) {
+ fail(`PET_CONFIG_INVALID: animations.events.${event} must be an array`)
+ }
+ else {
+ for (const value of slots)
+ slot(value, `animations.events.${event}`, true)
+ }
+ }
+ }
+ }
+ }
+ if (names.size === 0)
+ fail('PET_CONFIG_INVALID: motions or animations must reference at least one video')
+ return names
+}
+
+function validateVideo(directory, manifest) {
+ if (!object(manifest.ext) || manifest.ext.default !== 'webm' || (manifest.ext.mac !== undefined && !['webm', 'mov'].includes(manifest.ext.mac)))
+ fail('PET_MANIFEST_INVALID: ext.default must be webm and ext.mac must be webm or mov')
+ if (manifest.size !== undefined && (typeof manifest.size !== 'number' || !Number.isFinite(manifest.size) || manifest.size <= 0 || manifest.size > 4096))
+ fail('PET_MANIFEST_INVALID: size must be a finite number greater than 0 and at most 4096')
+ const configBytes = readBounded(containedPath(directory, manifest.configPath, 'configPath'), 1024 * 1024, 'PET_CONFIG_READ_FAILED')
+ let config
+ if (configBytes !== undefined) {
+ try {
+ config = parseJsonc(configBytes)
+ if (!object(config))
+ fail('PET_CONFIG_INVALID: config must be a JSONC object')
+ }
+ catch (error) {
+ fail(`PET_CONFIG_INVALID: ${error.message}`)
+ }
+ }
+ const preview = readBounded(containedPath(directory, manifest.previewPath, 'previewPath'), 8 * 1024 * 1024, 'PET_PREVIEW_READ_FAILED')
+ if (preview !== undefined) {
+ if (preview.length < 13 || !['GIF87a', 'GIF89a'].includes(preview.subarray(0, 6).toString('ascii'))) {
+ fail('PET_PREVIEW_INVALID: preview must have a GIF87a or GIF89a header')
+ }
+ else {
+ const width = preview.readUInt16LE(6)
+ const height = preview.readUInt16LE(8)
+ if (width === 0 || width > 4096 || width !== height)
+ fail('PET_PREVIEW_INVALID: GIF must be square with dimensions 1..4096')
+ else
+ notes.push(`GIF preview ${width}x${height} (header only)`)
+ }
+ }
+ const videoRoot = containedPath(directory, manifest.uriPath, 'uriPath', true)
+ const macRoot = manifest.macUriPath === undefined ? undefined : containedPath(directory, manifest.macUriPath, 'macUriPath', true)
+ if (manifest.macUriPath !== undefined && manifest.ext?.mac !== 'mov')
+ fail('PET_MANIFEST_INVALID: macUriPath requires ext.mac mov')
+ if (manifest.ext?.mac === 'mov' && manifest.macUriPath === undefined)
+ fail('PET_MANIFEST_INVALID: ext.mac mov requires macUriPath')
+ if (object(config)) {
+ const names = animationNames(config)
+ for (const name of names) {
+ if (videoRoot !== undefined)
+ readBounded(containedPath(directory, `${manifest.uriPath}/${name}.webm`, `video ${name}`), 512 * 1024 * 1024, 'PET_VIDEO_READ_FAILED', false)
+ if (macRoot !== undefined)
+ readBounded(containedPath(directory, `${manifest.macUriPath}/${name}.mov`, `mac video ${name}`), 512 * 1024 * 1024, 'PET_VIDEO_READ_FAILED', false)
+ }
+ notes.push(`video configuration references ${names.size} animation(s)`)
+ }
+ if (manifest.macUriPath === undefined)
+ notes.push('macOS unsupported by this package: macUriPath is absent')
+ notes.push('static package checks only; video decoding, alpha and macOS playback are NOT verified')
}
function grid(declared, width, height) {
@@ -166,7 +335,7 @@ function main() {
notes.push(`${directory} is not a direct child of a "pets" directory; the host enumerates only <DSH_HOME>/pets/*`)
}
- const manifestBytes = readBounded(join(directory, 'pet.json'), MANIFEST_MAX_BYTES, 'PET_MANIFEST_READ_FAILED')
+ const manifestBytes = readBounded(containedPath(directory, 'pet.json', 'pet.json'), MANIFEST_MAX_BYTES, 'PET_MANIFEST_READ_FAILED')
if (manifestBytes === undefined) {
report()
return
@@ -187,6 +356,18 @@ function main() {
}
checkId(manifest.id)
+ for (const field of ['displayName', 'description']) {
+ if (manifest[field] !== undefined && manifest[field] !== null && typeof manifest[field] !== 'string')
+ fail(`PET_MANIFEST_INVALID: ${field} must be a string`)
+ }
+ if (manifest.kind === 'dsh') {
+ notes.push(`id resolves to chat:${manifest.id}`)
+ validateVideo(directory, manifest)
+ report()
+ return
+ }
+ if (manifest.kind !== undefined && manifest.kind !== 'codex')
+ fail('PET_MANIFEST_INVALID: kind must be dsh or codex')
let declared
if (manifest.spriteVersionNumber !== undefined && manifest.spriteVersionNumber !== null) {
@@ -202,37 +383,7 @@ function main() {
report()
return
}
- const relativePath = portableRelative(manifest.spritesheetPath)
- if (relativePath === undefined) {
- report()
- return
- }
-
- let root
- try {
- root = realpathSync(directory)
- }
- catch (error) {
- fail(`PET_ASSET_READ_FAILED: failed to resolve ${directory}: ${error.message}`)
- report()
- return
- }
-
- let assetPath
- try {
- assetPath = realpathSync(resolve(directory, relativePath))
- }
- catch (error) {
- fail(`PET_ASSET_READ_FAILED: failed to resolve asset: ${error.message}`)
- report()
- return
- }
- if (!assetPath.startsWith(root + sep)) {
- fail('PET_PATH_INVALID: spritesheetPath escapes the pet directory')
- report()
- return
- }
-
+ const assetPath = containedPath(directory, manifest.spritesheetPath, 'spritesheetPath')
const assetBytes = readBounded(assetPath, SPRITESHEET_MAX_BYTES, 'PET_ASSET_READ_FAILED')
if (assetBytes === undefined) {
report()
@@ -253,7 +404,7 @@ function report() {
console.log(`note: ${note}`)
}
if (problems.length === 0) {
- console.log('ok: pet satisfies the host contract')
+ console.log('ok: static pet package validation passed (media decoding and alpha not verified)')
process.exitCode = 0
return
}
diff --git a/packages/dsh-tauri-pet/skills/hatch-dsh-pet/references/validate-pet.test.mjs b/packages/dsh-tauri-pet/skills/hatch-dsh-pet/references/validate-pet.test.mjs
new file mode 100644
index 00000000..af38be43
--- /dev/null
+++ b/packages/dsh-tauri-pet/skills/hatch-dsh-pet/references/validate-pet.test.mjs
@@ -0,0 +1,47 @@
+import { Buffer } from 'node:buffer'
+import { spawnSync } from 'node:child_process'
+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
+import { fileURLToPath } from 'node:url'
+import { afterEach, beforeEach, expect, it } from 'vitest'
+
+const validator = fileURLToPath(new URL('./validate-pet.mjs', import.meta.url))
+let root
+let manifest
+beforeEach(() => {
+ root = mkdtempSync(join(tmpdir(), 'dsh-pet-validator-'))
+ mkdirSync(join(root, 'webm'))
+ mkdirSync(join(root, 'preview'))
+ manifest = { kind: 'dsh', id: 'fixture', configPath: 'config.jsonc', uriPath: 'webm', previewPath: 'preview/preview.gif', ext: { default: 'webm', mac: 'webm' } }
+ writeFileSync(join(root, 'config.jsonc'), '{ /* config */ "motions": { "idle": "idle", }, }')
+ writeFileSync(join(root, 'webm/idle.webm'), 'static existence fixture, not decoded media')
+ writeFileSync(join(root, 'preview/preview.gif'), Buffer.from('R0lGODlhAQABAIAAAAAAAP///ywAAAAAAQABAAACAUwAOw==', 'base64'))
+})
+afterEach(() => rmSync(root, { recursive: true, force: true }))
+
+function validate() {
+ writeFileSync(join(root, 'pet.json'), JSON.stringify(manifest))
+ return spawnSync(process.execPath, [validator, root], { encoding: 'utf8', timeout: 5000 })
+}
+
+it('accepts a local WebM package with JSONC and a square GIF without claiming decoded playback', () => {
+ const result = validate()
+ expect(result.status).toBe(0)
+ expect(result.stdout).toContain('video configuration references 1 animation(s)')
+ expect(result.stdout).toContain('video decoding, alpha and macOS playback are NOT verified')
+})
+
+it('rejects a MOV platform extension without a mac video directory', () => {
+ manifest.ext.mac = 'mov'
+ const result = validate()
+ expect(result.status).toBe(1)
+ expect(result.stderr).toContain('PET_MANIFEST_INVALID: ext.mac mov requires macUriPath')
+})
+
+it('rejects missing referenced video files', () => {
+ writeFileSync(join(root, 'config.jsonc'), '{"motions":{"idle":"missing"}}')
+ const result = validate()
+ expect(result.status).toBe(1)
+ expect(result.stderr).toContain('PET_ASSET_READ_FAILED: video missing')
+})
diff --git a/packages/dsh-tauri-pet/src/client/components/pet-card.tsx b/packages/dsh-tauri-pet/src/client/components/pet-card.tsx
index 1520c9b4..fe266703 100644
--- a/packages/dsh-tauri-pet/src/client/components/pet-card.tsx
+++ b/packages/dsh-tauri-pet/src/client/components/pet-card.tsx
@@ -1,5 +1,5 @@
import type { ReactElement } from 'react'
-import { Button } from 'dsh-tauri-ui/client'
+import { Action, Button, Icon, TrashBin } from 'dsh-tauri-ui/client'
import { cn } from 'dsh-tauri/client'
const THUMB = 'flex-none w-[56px] h-[56px] flex items-center justify-center text-[28px] rounded-[10px] bg-layer-1 overflow-hidden object-cover [&>img]:block [&>img]:w-full [&>img]:h-full'
@@ -10,20 +10,24 @@ const THUMB_SPRITE = 'relative [&>img]:absolute [&>img]:w-[800%] [&>img]:h-[1100
export interface PetCardProps {
actionLabel: string
active: boolean
+ deleteLabel?: string
desc: string
disabled: boolean
name: string
onAction: () => void
+ onDelete?: () => void
+ onUpdate?: () => void
+ updateLabel?: string
thumbnail?: string
thumbnailType?: 'gif' | 'spritesheet'
}
-/** 桌宠卡片:缩略图 + 名称/描述 + 单个动作按钮(启用 / 选择 / 取消选择)。 */
+/** 桌宠卡片:缩略图 + 名称/描述 + 动作按钮(启用 / 选择 / 取消选择)与可选删除按钮。 */
export function PetCard(props: PetCardProps): ReactElement {
const thumbnailClassName = cn(THUMB, props.thumbnailType === 'spritesheet' && THUMB_SPRITE)
return (
- <div className="flex items-center gap-[12px] px-[14px] py-[12px] rounded-[12px] bg-hover">
+ <div className={cn('flex items-center gap-[12px] px-[14px] py-[12px] rounded-[12px]', props.active && 'bg-hover')}>
{props.thumbnail
? props.thumbnailType === 'spritesheet'
? (
@@ -40,6 +44,20 @@ export function PetCard(props: PetCardProps): ReactElement {
{props.desc ? <span className="text-[12px] leading-[18px] text-secondary">{props.desc}</span> : null}
</span>
<span className="flex-none flex items-center gap-[6px]">
+ {props.onDelete
+ ? (
+ <Action
+ variant="action"
+ className="text-tertiary hover:not-disabled:bg-hover hover:not-disabled:text-error"
+ aria-label={props.deleteLabel}
+ title={props.deleteLabel}
+ disabled={props.disabled}
+ onClick={props.onDelete}
+ >
+ <Icon as={TrashBin} size={14} />
+ </Action>
+ )
+ : null}
<Button
type="button"
variant={props.active ? 'primary' : 'outline'}
@@ -49,6 +67,13 @@ export function PetCard(props: PetCardProps): ReactElement {
>
{props.actionLabel}
</Button>
+ {props.onUpdate
+ ? (
+ <Button type="button" variant="outline" size="sm" disabled={props.disabled} onClick={props.onUpdate}>
+ {props.updateLabel}
+ </Button>
+ )
+ : null}
</span>
</div>
)
diff --git a/packages/dsh-tauri-pet/src/client/components/pet-settings.test.tsx b/packages/dsh-tauri-pet/src/client/components/pet-settings.test.tsx
index ade38dd2..635d355b 100644
--- a/packages/dsh-tauri-pet/src/client/components/pet-settings.test.tsx
+++ b/packages/dsh-tauri-pet/src/client/components/pet-settings.test.tsx
@@ -1,5 +1,5 @@
// @vitest-environment jsdom
-import type { ButtonHTMLAttributes, ReactNode } from 'react'
+import type { ButtonHTMLAttributes, InputHTMLAttributes, ReactNode } from 'react'
import type { PetActionResult } from '../service/pet.types'
import { act } from 'react'
import { createRoot } from 'react-dom/client'
@@ -18,10 +18,23 @@ vi.mock('dsh-tauri/client', async () => ({
}))
vi.mock('dsh-tauri-ui/client', () => ({
+ Action: ({ variant: _variant, icon: _icon, ...props }: ButtonHTMLAttributes<HTMLButtonElement> & { variant?: string, icon?: ReactNode }) => <button {...props} />,
ArrowRightFromSquare: () => null,
Globe: () => null,
Plus: () => null,
+ TrashBin: () => null,
Icon: () => null,
+ Input: (props: InputHTMLAttributes<HTMLInputElement>) => <input {...props} />,
+ Modal: ({ open, title, description, children, footer, onClose, closeLabel }: { open: boolean, title: string, description?: string, children: ReactNode, footer: ReactNode, onClose: () => void, closeLabel: string }) => open
+ ? (
+ <div role="dialog" aria-label={title}>
+ <button onClick={onClose}>{closeLabel}</button>
+ <p>{description}</p>
+ {children}
+ {footer}
+ </div>
+ )
+ : null,
Button: ({ variant: _variant, size: _size, icon: _icon, ...props }: ButtonHTMLAttributes<HTMLButtonElement> & { variant?: string, size?: string, icon?: ReactNode }) => <button {...props} />,
SegmentedControl: ({ value, onChange }: { value: string, onChange: (value: string) => void }) => (
<div>
@@ -36,16 +49,20 @@ vi.mock('dsh-tauri-ui/client', () => ({
vi.mock('../service/pet', () => ({
choosePet: vi.fn(),
clearPetSelection: vi.fn(),
+ deletePet: vi.fn(),
enablePet: vi.fn(),
importPetArchive: vi.fn(),
+ importPetRepository: vi.fn(),
loadForceXwayland: vi.fn(),
loadPetCatalog: vi.fn(),
loadPetOverlaySupported: vi.fn(),
+ loadPetUpdates: vi.fn(),
openCommunityShare: vi.fn(),
resizePet: vi.fn(),
toggleForceXwayland: vi.fn(),
togglePet: vi.fn(),
togglePetThrow: vi.fn(),
+ updatePetRepository: vi.fn(),
}))
let container: HTMLDivElement
@@ -73,6 +90,20 @@ function card(name: string): HTMLDivElement {
return result
}
+function deleteButton(name: string): HTMLButtonElement {
+ const result = card(name).querySelector<HTMLButtonElement>(`button[aria-label="${locale.text('delete')}"]`)
+ if (!result)
+ throw new Error(`Missing delete button ${name}`)
+ return result
+}
+
+function actionButton(name: string, label: string): HTMLButtonElement {
+ const result = Array.from(card(name).querySelectorAll('button')).find(item => item.textContent === label)
+ if (!result)
+ throw new Error(`Missing ${label} button on ${name}`)
+ return result
+}
+
async function click(node: HTMLElement): Promise<void> {
await act(async () => {
node.click()
@@ -92,6 +123,7 @@ beforeEach(() => {
status: { active_pet: 'chat', enabled: false, visible: false, throw_enabled: false },
fetchRevision: 0,
catalogLoaded: true,
+ petUpdates: [],
presetPets: [{ id: 'preset', name: 'Preset', desc: 'Preset description', image: 'preset.gif' }],
chatPets: [{ id: 'chat', name: 'Chat', source: 'chat', description: 'Chat description', thumbnail: 'chat.png' }],
codexPets: [{ id: 'codex', name: 'Codex', source: 'codex', thumbnail: 'codex.png' }],
@@ -99,7 +131,7 @@ beforeEach(() => {
overlaySupported: false,
forceXwayland: false,
})
- for (const action of [petService.loadPetCatalog, petService.choosePet, petService.clearPetSelection, petService.enablePet, petService.togglePet, petService.toggleForceXwayland, petService.resizePet, petService.togglePetThrow, petService.importPetArchive, petService.openCommunityShare])
+ for (const action of [petService.loadPetCatalog, petService.choosePet, petService.clearPetSelection, petService.deletePet, petService.enablePet, petService.togglePet, petService.toggleForceXwayland, petService.resizePet, petService.togglePetThrow, petService.importPetArchive, petService.importPetRepository, petService.openCommunityShare, petService.loadPetUpdates, petService.updatePetRepository])
vi.mocked(action).mockResolvedValue({ ok: true })
container = document.createElement('div')
document.body.append(container)
@@ -116,24 +148,93 @@ afterEach(async () => {
})
describe('pet settings action boundaries', () => {
+ it('renders local dsh GIF thumbnails without spritesheet cropping', async () => {
+ store.pet.setCatalog({
+ presets: [],
+ chat: [{ id: 'chat:video', name: 'Video', source: 'chat', kind: 'dsh', thumbnail_type: 'gif', thumbnail: 'data:image/gif;base64,R0lGODlh' }],
+ codex: [],
+ })
+ await mount()
+ const image = card('Video').querySelector('img')!
+ expect(image.getAttribute('src')).toBe('data:image/gif;base64,R0lGODlh')
+ expect(image.parentElement).toBe(card('Video'))
+ expect(image.className).not.toContain('800%')
+ })
+
it('renders preset images separately from identical Chat/Codex spritesheet cards and keeps active clear actions', async () => {
await mount()
expect(card('Preset').querySelector('img')?.parentElement).toBe(card('Preset'))
expect(card('Preset').textContent).toContain('Preset description')
- expect(card('Preset').querySelector('button')?.textContent).toBe(locale.text('enable'))
+ expect(actionButton('Preset', locale.text('enable'))).toBeInstanceOf(HTMLButtonElement)
expect(card('Chat').querySelector('img')?.parentElement?.tagName).toBe('SPAN')
expect(card('Chat').textContent).toContain('Chat description')
- expect(card('Chat').querySelector('button')?.textContent).toBe(locale.text('clear'))
- await click(card('Chat').querySelector('button')!)
+ await click(actionButton('Chat', locale.text('clear')))
expect(petService.clearPetSelection).toHaveBeenCalledExactlyOnceWith()
expect(petService.choosePet).not.toHaveBeenCalled()
await click(button('codex'))
expect(card('Codex').querySelector('img')?.parentElement?.tagName).toBe('SPAN')
- expect(card('Codex').querySelector('button')?.textContent).toBe(locale.text('select'))
- await click(card('Codex').querySelector('button')!)
+ await click(actionButton('Codex', locale.text('select')))
expect(petService.choosePet).toHaveBeenCalledExactlyOnceWith({ id: 'codex' })
})
+ it('offers delete only on imported pets and reports its own failure without selecting', async () => {
+ await mount()
+ expect(card('Preset').querySelector(`button[aria-label="${locale.text('delete')}"]`)).toBeNull()
+ store.pet.setPresetPets([
+ ...store.pet.$state.presetPets,
+ { id: 'remote-pet', name: 'Remote', image: 'remote.gif', remote: true },
+ ])
+ await act(async () => {})
+ expect(card('Remote').querySelector(`button[aria-label="${locale.text('delete')}"]`)).toBeInstanceOf(HTMLButtonElement)
+
+ vi.mocked(petService.deletePet).mockResolvedValueOnce({ ok: false, error: 'native failure' })
+ await click(deleteButton('Remote'))
+ expect(petService.deletePet).toHaveBeenCalledExactlyOnceWith({ id: 'remote-pet' })
+ expect(container.querySelector('[role="alert"]')?.textContent).toBe(locale.text('deleteFailed'))
+ expect(petService.choosePet).not.toHaveBeenCalled()
+
+ await click(deleteButton('Remote'))
+ expect(container.querySelector('[role="alert"]')).toBeNull()
+ await click(button('codex'))
+ await click(deleteButton('Codex'))
+ expect(petService.deletePet).toHaveBeenLastCalledWith({ id: 'codex' })
+ })
+
+ it('shows updates only for changed remote pets to the right of enable and keeps retry available after failure', async () => {
+ store.pet.setPresetPets([
+ { id: 'preset', name: 'Preset' },
+ { id: 'remote', name: 'Remote', remote: true },
+ { id: 'unchanged', name: 'Unchanged', remote: true },
+ ])
+ store.pet.setPetUpdates(['preset', 'remote'])
+ const pending = deferred()
+ vi.mocked(petService.updatePetRepository).mockReturnValueOnce(pending.promise)
+ await mount()
+ expect(petService.loadPetUpdates).toHaveBeenCalledExactlyOnceWith()
+ expect(card('Preset').textContent).not.toContain(locale.text('update'))
+ expect(card('Unchanged').textContent).not.toContain(locale.text('update'))
+ const update = actionButton('Remote', locale.text('update'))
+ expect(actionButton('Remote', locale.text('enable')).nextElementSibling).toBe(update)
+ await click(update)
+ expect(petService.updatePetRepository).toHaveBeenCalledExactlyOnceWith({ id: 'remote' })
+ expect(update.disabled).toBe(true)
+ await click(update)
+ expect(petService.updatePetRepository).toHaveBeenCalledTimes(1)
+ await act(async () => {
+ pending.resolve({ ok: false, error: 'network' })
+ })
+ expect(update.disabled).toBe(false)
+ expect(container.querySelector('[role="alert"]')?.textContent).toBe(locale.text('updateFailed'))
+ vi.mocked(petService.updatePetRepository).mockImplementationOnce(async () => {
+ store.pet.replacePresetPet({ id: 'remote', name: 'Updated', remote: true })
+ return { ok: true }
+ })
+ await click(update)
+ expect(Array.from(card('Updated').querySelectorAll('button')).map(button => button.textContent)).not.toContain(locale.text('update'))
+ expect(container.querySelector('[role="alert"]')).toBeNull()
+ expect(petService.enablePet).not.toHaveBeenCalled()
+ })
+
it.each([
{ kind: 'preset', errorKey: 'setPetFailed', mock: 'enablePet' },
{ kind: 'chat', errorKey: 'clearFailed', mock: 'clearPetSelection' },
@@ -147,11 +248,11 @@ describe('pet settings action boundaries', () => {
if (kind === 'codex')
await click(button('codex'))
const action = kind === 'preset'
- ? card('Preset').querySelector('button')!
+ ? actionButton('Preset', locale.text('enable'))
: kind === 'chat'
- ? card('Chat').querySelector('button')!
+ ? actionButton('Chat', locale.text('clear'))
: kind === 'codex'
- ? card('Codex').querySelector('button')!
+ ? actionButton('Codex', locale.text('select'))
: button(locale.text(kind === 'toggle' ? 'enablePet' : 'xwaylandEnable'))
await click(action)
expect(action.disabled).toBe(true)
@@ -275,6 +376,80 @@ describe('pet settings action boundaries', () => {
expect(input.value).toBe('')
})
+ it('repository import opens an input directly and blocks duplicate submits until success without selecting', async () => {
+ const pending = deferred()
+ vi.mocked(petService.importPetRepository).mockReturnValueOnce(pending.promise)
+ await mount()
+ const create = button(locale.text('create'))
+ const trigger = button(locale.text('importRepository'))
+ expect(create.nextElementSibling).toBe(trigger)
+ await click(trigger)
+ const dialog = container.querySelector('[role="dialog"]')!
+ const input = dialog.querySelector<HTMLInputElement>('input')!
+ expect(input.id).toBe(dialog.querySelector('label')?.htmlFor)
+ expect(input.hasAttribute('data-modal-autofocus')).toBe(true)
+ expect(dialog.textContent).toContain(locale.text('repositoryHint'))
+ await act(async () => {
+ Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value')!.set!.call(input, 'https://github.com/owner/repo')
+ input.dispatchEvent(new Event('input', { bubbles: true }))
+ })
+ const form = dialog.querySelector('form')!
+ const confirm = dialog.querySelector<HTMLButtonElement>('button[type="submit"]')!
+ expect(confirm.form).toBe(form)
+ await act(async () => {
+ confirm.click()
+ form.dispatchEvent(new Event('submit', { bubbles: true, cancelable: true }))
+ })
+ expect(petService.importPetRepository).toHaveBeenCalledExactlyOnceWith({ repository: 'https://github.com/owner/repo' })
+ expect(input.disabled).toBe(true)
+ expect(dialog.textContent).toContain(locale.text('repositoryImporting'))
+ await click(button(locale.text('close')))
+ expect(container.querySelector('[role="dialog"]')).toBe(dialog)
+ await act(async () => {
+ store.pet.setPresetPets([
+ ...store.pet.$state.presetPets,
+ { id: 'owner/repo', name: 'Remote', image: 'https://raw.githubusercontent.com/owner/repo/main/cover.gif' },
+ ])
+ pending.resolve({ ok: true })
+ })
+ expect(container.querySelector('[role="dialog"]')).toBeNull()
+ expect(card('Remote').querySelector('img')?.getAttribute('src')).toBe('https://raw.githubusercontent.com/owner/repo/main/cover.gif')
+ expect(card('Remote').querySelector('button')?.textContent).toBe(locale.text('enable'))
+ expect(store.pet.status?.active_pet).toBe('chat')
+ expect(petService.enablePet).not.toHaveBeenCalled()
+ expect(trigger.disabled).toBe(false)
+ expect(petService.choosePet).not.toHaveBeenCalled()
+ await click(button(locale.text('importRepository')))
+ expect(container.querySelector<HTMLInputElement>('[role="dialog"] input')?.value).toBe('')
+ await click(button(locale.text('cancel')))
+ await click(button('codex'))
+ expect(container.textContent).not.toContain(locale.text('importRepository'))
+ })
+
+ it.each([
+ { error: 'PET_REPOSITORY_INVALID', key: 'repositoryInvalid' },
+ { error: 'NETWORK_ERROR: secret filesystem path', key: 'repositoryImportFailed' },
+ ] as const)('repository error $error stays local and permits retry without displaying technical details', async ({ error, key }) => {
+ vi.mocked(petService.importPetRepository).mockResolvedValueOnce({ ok: false, error })
+ await mount()
+ await click(button(locale.text('importRepository')))
+ const dialog = container.querySelector('[role="dialog"]')!
+ const form = dialog.querySelector('form')!
+ await act(async () => {
+ form.dispatchEvent(new Event('submit', { bubbles: true, cancelable: true }))
+ })
+ expect(dialog.querySelector('[role="alert"]')?.textContent).toBe(locale.text(key))
+ expect(container.textContent).not.toContain(error)
+ const input = dialog.querySelector<HTMLInputElement>('input')!
+ expect(input.disabled).toBe(false)
+ expect(input.getAttribute('aria-invalid')).toBe('true')
+ await act(async () => {
+ form.dispatchEvent(new Event('submit', { bubbles: true, cancelable: true }))
+ })
+ expect(petService.importPetRepository).toHaveBeenCalledTimes(2)
+ expect(container.querySelector('[role="dialog"]')).toBeNull()
+ })
+
it('community share sits in the Codex tab, opens the site and reports its own failure', async () => {
vi.mocked(petService.openCommunityShare).mockResolvedValueOnce({ ok: false, error: 'no browser' })
await mount()
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 40b117c9..18ef4b42 100644
--- a/packages/dsh-tauri-pet/src/client/components/pet-settings.tsx
+++ b/packages/dsh-tauri-pet/src/client/components/pet-settings.tsx
@@ -1,6 +1,6 @@
import type { ChangeEvent, ReactElement } from 'react'
import type { PetActionResult, PetListItem } from '../service/pet.types'
-import { ArrowRightFromSquare, Button, Globe, Icon, Plus, SegmentedControl, Switch } from 'dsh-tauri-ui/client'
+import { ArrowRightFromSquare, Button, Globe, Icon, Input, Modal, Plus, SegmentedControl, Switch } from 'dsh-tauri-ui/client'
import { useStore, useWatchImmediate } from 'dsh-tauri/client'
import { useEffect, useId, useRef, useState } from 'react'
import { PET_DEFAULT_SIZE, PET_SIZE_MAX, PET_SIZE_MIN, PET_SIZE_STEP } from '../constants'
@@ -8,16 +8,20 @@ import { locale } from '../locales'
import {
choosePet,
clearPetSelection,
+ deletePet,
enablePet,
importPetArchive,
+ importPetRepository,
loadForceXwayland,
loadPetCatalog,
loadPetOverlaySupported,
+ loadPetUpdates,
openCommunityShare,
resizePet,
toggleForceXwayland,
togglePet,
togglePetThrow,
+ updatePetRepository,
} from '../service/pet'
import { store } from '../store'
import { PetCard } from './pet-card'
@@ -50,10 +54,15 @@ function readAsBase64(file: File): Promise<string> {
/** 桌宠设置页:预设 / Chat / Codex 三类宠物卡片(选择、启用、取消选择)、开关、大小滑条与导入。 */
export function PetSettings(props: PetSettingsProps): ReactElement {
locale.useLocale()
- const { status, presetPets, chatPets, codexPets, catalogLoaded, overlaySupported, forceXwayland } = useStore(store.pet)
+ const { status, presetPets, petUpdates, chatPets, codexPets, catalogLoaded, overlaySupported, forceXwayland } = useStore(store.pet)
const [tab, setTab] = useState<'pets' | 'codex'>('pets')
const [busy, setBusy] = useState(() => !catalogLoaded)
const [error, setError] = useState<string | null>(null)
+ const [repositoryOpen, setRepositoryOpen] = useState(false)
+ const [repository, setRepository] = useState('')
+ const [repositoryError, setRepositoryError] = useState<string | null>(null)
+ const repositoryPendingRef = useRef(false)
+ const repositoryId = useId()
const [size, setSize] = useState(status?.pet_size ?? PET_DEFAULT_SIZE)
// 切换只落盘,本次进程不会有任何变化,提示重启是用户唯一能看到的反馈。
const [xwaylandRestart, setXwaylandRestart] = useState(false)
@@ -91,6 +100,8 @@ export function PetSettings(props: PetSettingsProps): ReactElement {
setBusy(false)
if (!result.ok)
setError(locale.text('listFailed'))
+ else
+ void loadPetUpdates()
})
return () => {
cancelled = true
@@ -123,6 +134,11 @@ export function PetSettings(props: PetSettingsProps): ReactElement {
await run(clearPetSelection, 'clearFailed')
}
+ /** 删除导入的宠物:预设页删的是远端登记,Chat / Codex 页删的是本地目录。 */
+ async function remove(id: string): Promise<void> {
+ await run(() => deletePet({ id }), 'deleteFailed')
+ }
+
async function toggleEnabled(): Promise<void> {
await run(() => togglePet({ enabled: !enabled }), 'toggleFailed')
}
@@ -168,6 +184,32 @@ export function PetSettings(props: PetSettingsProps): ReactElement {
}
}
+ async function importRepository(): Promise<void> {
+ if (busy || repositoryPendingRef.current)
+ return
+ repositoryPendingRef.current = true
+ setBusy(true)
+ setRepositoryError(null)
+ setError(null)
+ try {
+ const result = await importPetRepository({ repository })
+ if (result.ok) {
+ setRepositoryOpen(false)
+ setRepository('')
+ }
+ else {
+ setRepositoryError(locale.text(result.error === 'PET_REPOSITORY_INVALID' ? 'repositoryInvalid' : 'repositoryImportFailed'))
+ }
+ }
+ catch {
+ setRepositoryError(locale.text('repositoryImportFailed'))
+ }
+ finally {
+ repositoryPendingRef.current = false
+ setBusy(false)
+ }
+ }
+
async function onImport(event: ChangeEvent<HTMLInputElement>): Promise<void> {
const file = event.target.files?.[0]
event.target.value = ''
@@ -193,13 +235,15 @@ export function PetSettings(props: PetSettingsProps): ReactElement {
<PetCard
key={item.id}
thumbnail={item.thumbnail}
- thumbnailType={item.thumbnail ? 'spritesheet' : undefined}
+ thumbnailType={item.thumbnail_type ?? 'spritesheet'}
name={item.name}
desc={item.description ?? ''}
active={active === item.id}
disabled={busy}
actionLabel={locale.text(active === item.id ? 'clear' : 'select')}
onAction={() => { void (active === item.id ? clearSelection() : choose(item.id)) }}
+ deleteLabel={locale.text('delete')}
+ onDelete={() => { void remove(item.id) }}
/>
))
@@ -219,6 +263,10 @@ export function PetSettings(props: PetSettingsProps): ReactElement {
disabled={busy}
actionLabel={locale.text(active === item.id ? 'clear' : 'enable')}
onAction={() => { void (active === item.id ? clearSelection() : enablePreset(item.id)) }}
+ deleteLabel={item.remote ? locale.text('delete') : undefined}
+ onDelete={item.remote ? () => { void remove(item.id) } : undefined}
+ updateLabel={locale.text('update')}
+ onUpdate={item.remote && petUpdates.includes(item.id) ? () => { void run(() => updatePetRepository({ id: item.id }), 'updateFailed') } : undefined}
/>
))}
{cards(chatPets)}
@@ -285,6 +333,18 @@ export function PetSettings(props: PetSettingsProps): ReactElement {
>
{locale.text('create')}
</Button>
+ <Button
+ type="button"
+ variant="outline"
+ size="sm"
+ disabled={busy}
+ onClick={() => {
+ setRepositoryError(null)
+ setRepositoryOpen(true)
+ }}
+ >
+ {locale.text('importRepository')}
+ </Button>
<Button
type="button"
variant="outline"
@@ -336,6 +396,50 @@ export function PetSettings(props: PetSettingsProps): ReactElement {
<div id={`${tabsId}-${tab}-panel`} role="tabpanel" aria-labelledby={`${tabsId}-${tab}`}>
{tab === 'pets' ? petsPanel : codexPanel}
</div>
+ <Modal
+ open={repositoryOpen}
+ title={locale.text('importRepository')}
+ description={locale.text('repositoryHint')}
+ closeLabel={locale.text('close')}
+ onClose={() => {
+ if (!repositoryPendingRef.current)
+ setRepositoryOpen(false)
+ }}
+ footer={(
+ <>
+ <Button variant="outline" disabled={busy} onClick={() => setRepositoryOpen(false)}>{locale.text('cancel')}</Button>
+ <Button type="submit" form={repositoryId} variant="primary" disabled={busy}>
+ {locale.text(busy ? 'repositoryImporting' : 'importRepository')}
+ </Button>
+ </>
+ )}
+ >
+ <form
+ id={repositoryId}
+ className="flex flex-col gap-[12px]"
+ aria-busy={busy}
+ onSubmit={(event) => {
+ event.preventDefault()
+ void importRepository()
+ }}
+ >
+ <label htmlFor={`${repositoryId}-input`}>{locale.text('repositoryLabel')}</label>
+ <Input
+ id={`${repositoryId}-input`}
+ data-modal-autofocus
+ value={repository}
+ placeholder="owner/repo"
+ disabled={busy}
+ aria-invalid={Boolean(repositoryError)}
+ aria-describedby={repositoryError ? `${repositoryId}-error` : undefined}
+ onChange={(event) => {
+ setRepository(event.target.value)
+ setRepositoryError(null)
+ }}
+ />
+ {repositoryError ? <div id={`${repositoryId}-error`} className="text-[12px] leading-[18px] text-error" role="alert">{repositoryError}</div> : null}
+ </form>
+ </Modal>
{error ? <div className="text-[12px] leading-[18px] text-error" role="alert">{error}</div> : null}
<div className="flex items-center gap-[12px]">
<span className="flex-none font-medium">{locale.text('sizeLabel')}</span>
diff --git a/packages/dsh-tauri-pet/src/client/constants/index.ts b/packages/dsh-tauri-pet/src/client/constants/index.ts
index a7d55cde..5b73edc3 100644
--- a/packages/dsh-tauri-pet/src/client/constants/index.ts
+++ b/packages/dsh-tauri-pet/src/client/constants/index.ts
@@ -28,6 +28,10 @@ export const CMD_SET_PET_SIZE = 'set_pet_size'
export const CMD_SET_PET_THROW_ENABLED = 'set_pet_throw_enabled'
export const CMD_LIST_PETS = 'list_pets'
export const CMD_IMPORT_PET = 'import_pet'
+export const CMD_DELETE_PET = 'delete_pet'
+export const CMD_IMPORT_PET_REPOSITORY = 'import_pet_repository'
+export const CMD_CHECK_PET_UPDATES = 'check_pet_updates'
+export const CMD_UPDATE_PET_REPOSITORY = 'update_pet_repository'
export const CMD_LIST_PRESET_PETS = 'list_preset_pets'
export const CMD_OPEN_EXTERNAL_URL = 'open_external_url'
diff --git a/packages/dsh-tauri-pet/src/client/locales/index.ts b/packages/dsh-tauri-pet/src/client/locales/index.ts
index ca2f9500..3b548cce 100644
--- a/packages/dsh-tauri-pet/src/client/locales/index.ts
+++ b/packages/dsh-tauri-pet/src/client/locales/index.ts
@@ -3,6 +3,14 @@ import { PLUGIN_ID } from '../../shared/constants'
/** 桌宠设置分区的双语文案(`zh` 键集合为权威,`en` 缺键即编译错误)。 */
const zh = {
+ cancel: '取消',
+ close: '关闭',
+ importRepository: '导入仓库',
+ repositoryLabel: 'GitHub 仓库',
+ repositoryHint: '输入 owner/repo 或 https://github.com/owner/repo。仅登记远端资源地址,不下载视频包;选择宠物后按需播放。',
+ repositoryInvalid: '请输入有效的 GitHub 仓库:owner/repo 或 https://github.com/owner/repo。',
+ repositoryImporting: '导入中…',
+ repositoryImportFailed: '仓库登记失败,请检查仓库是否公开、包含有效宠物配置,以及网络连接后重试。',
clear: '取消选择',
clearFailed: '取消选择失败',
closePet: '关闭宠物',
@@ -10,6 +18,10 @@ const zh = {
communityShareFailed: '打开社区分享页面失败',
create: '创建',
createFailed: '创建宠物会话失败',
+ delete: '删除',
+ deleteFailed: '删除宠物失败',
+ update: '更新',
+ updateFailed: '更新宠物失败,已保留原内容,请稍后重试。',
emptyImported: '尚未导入宠物,点击右上角「导入」添加 .zip 资源包',
enable: '启用',
enablePet: '启用宠物',
@@ -38,6 +50,14 @@ const zh = {
}
const en: Record<keyof typeof zh, string> = {
+ cancel: 'Cancel',
+ close: 'Close',
+ importRepository: 'Import repository',
+ repositoryLabel: 'GitHub repository',
+ repositoryHint: 'Enter owner/repo or https://github.com/owner/repo. Only remote resource URLs are registered; no video package is downloaded. Select the pet to play it on demand.',
+ repositoryInvalid: 'Enter a valid GitHub repository: owner/repo or https://github.com/owner/repo.',
+ repositoryImporting: 'Importing…',
+ repositoryImportFailed: 'Could not register the repository. Check that it is public, contains valid pet configuration, and your connection is working, then retry.',
clear: 'Clear selection',
clearFailed: 'Failed to clear pet selection',
closePet: 'Close pet',
@@ -45,6 +65,10 @@ const en: Record<keyof typeof zh, string> = {
communityShareFailed: 'Failed to open the community share page',
create: 'Create',
createFailed: 'Failed to create a pet session',
+ delete: 'Delete',
+ deleteFailed: 'Failed to delete pet',
+ update: 'Update',
+ updateFailed: 'Failed to update pet. Previous content was kept; please retry later.',
emptyImported: 'No pets imported yet. Click “Import” to add a .zip package',
enable: 'Enable',
enablePet: 'Enable pet',
diff --git a/packages/dsh-tauri-pet/src/client/service/pet.test.ts b/packages/dsh-tauri-pet/src/client/service/pet.test.ts
index 6bfee6a2..a193bf30 100644
--- a/packages/dsh-tauri-pet/src/client/service/pet.test.ts
+++ b/packages/dsh-tauri-pet/src/client/service/pet.test.ts
@@ -7,17 +7,21 @@ import {
choosePet,
clearPetSelection,
createPetSession,
+ deletePet,
enablePet,
importPetArchive,
+ importPetRepository,
loadForceXwayland,
loadPetCatalog,
loadPetOverlaySupported,
loadPetStatus,
+ loadPetUpdates,
openCommunityShare,
resizePet,
toggleForceXwayland,
togglePet,
togglePetThrow,
+ updatePetRepository,
} from './pet'
const { invoke } = vi.hoisted(() => ({ invoke: vi.fn() }))
@@ -61,6 +65,7 @@ function resetStore(): void {
fetchRevision: 0,
catalogLoaded: false,
presetPets: [],
+ petUpdates: [],
chatPets: [],
codexPets: [],
prefills: {},
@@ -159,6 +164,39 @@ describe('pet service native command contracts', () => {
expect(store.pet.status).toEqual(status)
})
+ it('delete forwards the id, adopts the authoritative status and reloads every list', async () => {
+ const cleared = { ...status, active_pet: '', enabled: false, visible: false }
+ const chat = [{ id: 'chat-a', name: 'Chat', source: 'chat' }]
+ const presets = [{ id: 'builtin', name: 'Built in' }]
+ invoke.mockResolvedValueOnce(cleared).mockResolvedValueOnce(cleared).mockResolvedValueOnce(chat).mockResolvedValueOnce([]).mockResolvedValueOnce(presets)
+ expect(await deletePet({ id: 'chat:chat-a' })).toEqual({ ok: true })
+ expect(invoke.mock.calls).toEqual([
+ ['delete_pet', { id: 'chat:chat-a' }],
+ ['get_pet_status'],
+ ['list_pets', { source: 'chat' }],
+ ['list_pets', { source: 'codex' }],
+ ['list_preset_pets'],
+ ])
+ expect(store.pet.$state).toMatchObject({ status: cleared, catalogLoaded: true, chatPets: chat, codexPets: [], presetPets: presets })
+ })
+
+ it('delete reports success and drops the card when the catalog refresh fails', async () => {
+ vi.spyOn(console, 'error').mockImplementation(() => {})
+ store.pet.setCatalog({
+ presets: [{ id: 'builtin', name: 'Built in' }],
+ chat: [{ id: 'chat:chat-a', name: 'Chat', source: 'chat' }],
+ codex: [{ id: 'codex-a', name: 'Codex', source: 'codex' }],
+ })
+ invoke.mockResolvedValueOnce(status).mockRejectedValueOnce(new Error('catalog down'))
+ expect(await deletePet({ id: 'chat:chat-a' })).toEqual({ ok: true })
+ expect(store.pet.$state).toMatchObject({
+ status,
+ presetPets: [{ id: 'builtin', name: 'Built in' }],
+ chatPets: [],
+ codexPets: [{ id: 'codex-a', name: 'Codex', source: 'codex' }],
+ })
+ })
+
it('import forwards archive strings before refreshing only the Codex list', async () => {
const codex = [{ id: 'imported', name: 'Imported', source: 'codex' }]
invoke.mockResolvedValueOnce(codex[0]).mockResolvedValueOnce(codex)
@@ -168,6 +206,87 @@ describe('pet service native command contracts', () => {
expect(store.pet.catalogLoaded).toBe(false)
})
+ it.each(['owner/pet-repo', ' https://github.com/owner/pet-repo/ '])('repository registration normalizes %s and refreshes remote presets without selecting or reloading Chat', async (repository) => {
+ const remote = { id: 'owner/pet-repo', name: 'Remote', image: 'https://raw.githubusercontent.com/owner/pet-repo/main/cover.gif', kind: 'dsh' as const }
+ const presets = [{ id: 'builtin', name: 'Built in' }, remote]
+ const chat = [{ id: 'chat:existing', name: 'Existing', source: 'chat' as const }]
+ store.pet.setCatalog({ presets: [presets[0]], chat, codex: [{ id: 'codex', name: 'Codex', source: 'codex' }] })
+ store.pet.setStatus(status)
+ invoke.mockResolvedValueOnce(remote).mockResolvedValueOnce(presets)
+ expect(await importPetRepository({ repository })).toEqual({ ok: true })
+ expect(invoke.mock.calls).toEqual([
+ ['import_pet_repository', { repository: 'owner/pet-repo' }],
+ ['list_preset_pets'],
+ ])
+ expect(store.pet.presetPets).toEqual(presets)
+ expect(store.pet.chatPets).toEqual(chat)
+ expect(store.pet.status).toEqual(status)
+ expect(store.pet.codexPets).toEqual([{ id: 'codex', name: 'Codex', source: 'codex' }])
+ })
+
+ it.each(['', 'owner', 'owner/repo/tree/main', 'https://github.com.evil/owner/repo', 'http://github.com/owner/repo', 'owner/..', 'owner/repo?x=1', '-owner/repo'])('invalid repository %s fails before invoke', async (repository) => {
+ expect(await importPetRepository({ repository })).toEqual({ ok: false, error: 'PET_REPOSITORY_INVALID' })
+ expect(invoke).not.toHaveBeenCalled()
+ })
+
+ it.each(['import_pet_repository', 'list_preset_pets'])('repository failure at %s preserves preset cache and selection', async (failingCommand) => {
+ vi.spyOn(console, 'error').mockImplementation(() => {})
+ const presets = [{ id: 'builtin', name: 'Built in', image: 'https://example.com/cover.gif' }]
+ store.pet.setPresetPets(presets)
+ store.pet.setStatus(status)
+ invoke.mockImplementation(async (command) => {
+ if (command === failingCommand)
+ throw new Error('repository unavailable')
+ return { id: 'owner/repo', name: 'Remote' }
+ })
+ expect(await importPetRepository({ repository: 'owner/repo' })).toEqual({ ok: false, error: 'repository unavailable' })
+ expect(invoke.mock.calls).toEqual(failingCommand === 'import_pet_repository'
+ ? [['import_pet_repository', { repository: 'owner/repo' }]]
+ : [['import_pet_repository', { repository: 'owner/repo' }], ['list_preset_pets']])
+ expect(store.pet.presetPets).toEqual(presets)
+ expect(store.pet.status).toEqual(status)
+ })
+
+ it('update checks store native IDs and replacement clears only the updated flag without changing selection', async () => {
+ store.pet.setPresetPets([{ id: 'pet', name: 'Old', remote: true }, { id: 'other', name: 'Other' }])
+ store.pet.setStatus(status)
+ invoke.mockResolvedValueOnce(['pet', 'other']).mockResolvedValueOnce({ id: 'pet', name: 'New', image: 'pinned.gif' })
+ expect(await loadPetUpdates()).toEqual({ ok: true })
+ expect(store.pet.petUpdates).toEqual(['pet', 'other'])
+ expect(await updatePetRepository({ id: 'pet' })).toEqual({ ok: true })
+ expect(invoke.mock.calls).toEqual([['check_pet_updates'], ['update_pet_repository', { id: 'pet' }]])
+ expect(store.pet.presetPets).toEqual([{ id: 'pet', name: 'New', image: 'pinned.gif', remote: true }, { id: 'other', name: 'Other' }])
+ expect(store.pet.petUpdates).toEqual(['other'])
+ expect(store.pet.status).toEqual(status)
+ })
+
+ it('a delayed update check cannot restore flags after replacing a preset', async () => {
+ store.pet.setPresetPets([{ id: 'pet', name: 'Old', remote: true }])
+ let resolve!: (ids: string[]) => void
+ invoke.mockReturnValueOnce(new Promise<string[]>((done) => {
+ resolve = done
+ })).mockResolvedValueOnce({ id: 'pet', name: 'New' })
+ const pending = loadPetUpdates()
+ expect(await updatePetRepository({ id: 'pet' })).toEqual({ ok: true })
+ resolve(['pet'])
+ expect(await pending).toEqual({ ok: true })
+ expect(store.pet.petUpdates).toEqual([])
+ expect(store.pet.presetPets[0].name).toBe('New')
+ })
+
+ it('failed updates preserve the old card, selection and retry flag', async () => {
+ vi.spyOn(console, 'error').mockImplementation(() => {})
+ const presets = [{ id: 'pet', name: 'Old', remote: true }]
+ store.pet.setPresetPets(presets)
+ store.pet.setPetUpdates(['pet'])
+ store.pet.setStatus(status)
+ invoke.mockRejectedValue(new Error('download refused'))
+ expect(await updatePetRepository({ id: 'pet' })).toEqual({ ok: false, error: 'download refused' })
+ expect(store.pet.presetPets).toEqual(presets)
+ expect(store.pet.petUpdates).toEqual(['pet'])
+ expect(store.pet.status).toEqual(status)
+ })
+
it('community share opens the Codex pets site through the external URL command', async () => {
invoke.mockResolvedValue(undefined)
expect(await openCommunityShare()).toEqual({ ok: true })
@@ -199,6 +318,7 @@ describe('pet service native command contracts', () => {
{ label: 'toggle pet throw', action: () => togglePetThrow({ enabled: true }) },
{ label: 'resize pet', action: () => resizePet({ size: 140 }) },
{ label: 'import pet', action: () => importPetArchive({ name: 'bad.zip', data: 'bad' }) },
+ { label: 'delete pet', action: () => deletePet({ id: 'chat:chat-a' }) },
{ label: 'open community share', action: openCommunityShare },
])('$label preserves error messages and logging labels without changing cached values', async ({ label, action }) => {
const error = new Error('native refused')
diff --git a/packages/dsh-tauri-pet/src/client/service/pet.ts b/packages/dsh-tauri-pet/src/client/service/pet.ts
index c37e70e0..ae957a5e 100644
--- a/packages/dsh-tauri-pet/src/client/service/pet.ts
+++ b/packages/dsh-tauri-pet/src/client/service/pet.ts
@@ -2,10 +2,13 @@ import type { ClientAdapter } from 'dsh-tauri/client'
import type { PetActionResult, PetListItem, PetStatus, PresetPetItem } from './pet.types'
import { invoke } from 'dsh-tauri/client'
import {
+ CMD_CHECK_PET_UPDATES,
+ CMD_DELETE_PET,
CMD_GET_FORCE_XWAYLAND,
CMD_GET_PET_OVERLAY_SUPPORTED,
CMD_GET_PET_STATUS,
CMD_IMPORT_PET,
+ CMD_IMPORT_PET_REPOSITORY,
CMD_LIST_PETS,
CMD_LIST_PRESET_PETS,
CMD_OPEN_EXTERNAL_URL,
@@ -14,6 +17,7 @@ import {
CMD_SET_PET_ENABLED,
CMD_SET_PET_SIZE,
CMD_SET_PET_THROW_ENABLED,
+ CMD_UPDATE_PET_REPOSITORY,
PET_COMMUNITY_URL,
PET_HATCH_PROMPT,
} from '../constants'
@@ -184,6 +188,35 @@ export async function togglePetThrow(input: { enabled: boolean }): Promise<PetAc
})
}
+export async function loadPetUpdates(): Promise<PetActionResult> {
+ return guard('check pet updates', async () => {
+ const presets = store.pet.$state.presetPets
+ const ids = await invoke<string[]>(CMD_CHECK_PET_UPDATES)
+ if (presets === store.pet.$state.presetPets)
+ store.pet.setPetUpdates(ids)
+ return { ok: true }
+ })
+}
+
+export async function updatePetRepository(input: { id: string }): Promise<PetActionResult> {
+ return guard('update pet repository', async () => {
+ const item = await invoke<PresetPetItem>(CMD_UPDATE_PET_REPOSITORY, { id: input.id })
+ store.pet.replacePresetPet({ ...item, remote: true })
+ return { ok: true }
+ })
+}
+
+export async function importPetRepository(input: { repository: string }): Promise<PetActionResult> {
+ const match = /^(?:https:\/\/github\.com\/)?([a-z\d](?:[a-z\d-]{0,37}[a-z\d])?)\/([\w.-]{1,100})\/?$/i.exec(input.repository.trim())
+ if (!match || match[2] === '.' || match[2] === '..')
+ return { ok: false, error: 'PET_REPOSITORY_INVALID' }
+ return guard('import pet repository', async () => {
+ await invoke<PresetPetItem>(CMD_IMPORT_PET_REPOSITORY, { repository: `${match[1]}/${match[2]}` })
+ store.pet.setPresetPets(await invoke<PresetPetItem[]>(CMD_LIST_PRESET_PETS))
+ return { ok: true }
+ })
+}
+
/** Action:导入宠物压缩包(base64),成功后刷新 Codex 清单。 */
export async function importPetArchive(input: { name: string, data: string }): Promise<PetActionResult> {
return guard('import pet', async () => {
@@ -193,6 +226,21 @@ export async function importPetArchive(input: { name: string, data: string }): P
})
}
+/**
+ * Action:删除用户导入的宠物(来源限定 id 删目录,预设 id 反注册远端条目)。
+ *
+ * 先本地摘掉卡片再重装清单:删除已经落定,清单刷新失败不能把这次删除报成失败——
+ * 用户会重试一个已经不存在的 id,而卡片还留在列表里。
+ */
+export async function deletePet(input: { id: string }): Promise<PetActionResult> {
+ return guard('delete pet', async () => {
+ store.pet.setStatus(await invoke<PetStatus>(CMD_DELETE_PET, { id: input.id }))
+ store.pet.removePet(input.id)
+ await loadPetCatalog()
+ return { ok: true }
+ })
+}
+
/**
* Action:在系统浏览器中打开 Codex 宠物社区站点。
*
diff --git a/packages/dsh-tauri-pet/src/client/service/pet.types.ts b/packages/dsh-tauri-pet/src/client/service/pet.types.ts
index ecd8d534..85393d2c 100644
--- a/packages/dsh-tauri-pet/src/client/service/pet.types.ts
+++ b/packages/dsh-tauri-pet/src/client/service/pet.types.ts
@@ -19,7 +19,9 @@ export interface PetListItem {
id: string
name: string
source: PetSource
+ kind?: 'dsh' | 'codex'
thumbnail?: string
+ thumbnail_type?: 'gif' | 'spritesheet'
}
/**
@@ -34,5 +36,7 @@ export interface PresetPetItem {
image?: string | null
kind?: 'dsh' | 'codex' | null
name: string
+ /** 是否由用户登记远端资源;内置预设为 false,只有登记来的条目可删除。 */
+ remote?: boolean
size?: number | null
}
diff --git a/packages/dsh-tauri-pet/src/client/store/modules/pet.ts b/packages/dsh-tauri-pet/src/client/store/modules/pet.ts
index 06e65a02..4287a9a3 100644
--- a/packages/dsh-tauri-pet/src/client/store/modules/pet.ts
+++ b/packages/dsh-tauri-pet/src/client/store/modules/pet.ts
@@ -17,6 +17,7 @@ export const pet = defineStore({
/** 清单是否装载过(设置页首屏加载态判定)。 */
catalogLoaded: false,
presetPets: [] as PresetPetItem[],
+ petUpdates: [] as string[],
chatPets: [] as PetListItem[],
codexPets: [] as PetListItem[],
/** 待注入的新会话草稿(sessionId → 文本)。 */
@@ -56,9 +57,26 @@ export const pet = defineStore({
setForceXwayland(enabled: boolean): void {
this.forceXwayland = enabled
},
+ setPresetPets(list: PresetPetItem[]): void {
+ this.presetPets = list
+ },
+ setPetUpdates(ids: string[]): void {
+ this.petUpdates = ids
+ },
+ replacePresetPet(item: PresetPetItem): void {
+ this.presetPets = this.presetPets.map(pet => pet.id === item.id ? item : pet)
+ this.petUpdates = this.petUpdates.filter(id => id !== item.id)
+ },
setCodexPets(list: PetListItem[]): void {
this.codexPets = list
},
+ /** 摘掉已删除的条目;清单刷新失败时卡片不能继续留在列表里。 */
+ removePet(id: string): void {
+ this.presetPets = this.presetPets.filter(item => item.id !== id)
+ this.petUpdates = this.petUpdates.filter(item => item !== id)
+ this.chatPets = this.chatPets.filter(item => item.id !== id)
+ this.codexPets = this.codexPets.filter(item => item.id !== id)
+ },
setPrefill(sessionId: string, draft: string): void {
this.prefills[sessionId] = draft
},
diff --git a/packages/dsh-tauri-ui/src/client/styles/index.ts b/packages/dsh-tauri-ui/src/client/styles/index.ts
index 3113162f..6865c8c4 100644
--- a/packages/dsh-tauri-ui/src/client/styles/index.ts
+++ b/packages/dsh-tauri-ui/src/client/styles/index.ts
@@ -1953,6 +1953,15 @@ const TAILWINDCSS_GENERATED = `
}
}
}
+ .hover\\:not-disabled\\:text-error {
+ &:hover {
+ @media (hover: hover) {
+ &:not(*:disabled) {
+ color: var(--dsw-alias-state-error-primary);
+ }
+ }
+ }
+ }
.hover\\:not-disabled\\:text-primary {
&:hover {
@media (hover: hover) {
diff --git a/src-tauri/Cargo.lock b/src-tauri/Cargo.lock
index cfb9841a..c96e9ddf 100644
--- a/src-tauri/Cargo.lock
+++ b/src-tauri/Cargo.lock
@@ -2203,6 +2203,12 @@ dependencies = [
"pin-project-lite",
]
+[[package]]
+name = "http-range"
+version = "0.1.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "21dec9db110f5f872ed9699c3ecf50cf16f423502706ba5c72462e28d3157573"
+
[[package]]
name = "httparse"
version = "1.10.1"
@@ -5132,6 +5138,7 @@ dependencies = [
"gtk",
"heck 0.5.0",
"http",
+ "http-range",
"image",
"jni",
"libc",
diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.toml
index dfd72a51..9422c780 100644
--- a/src-tauri/Cargo.toml
+++ b/src-tauri/Cargo.toml
@@ -31,7 +31,8 @@ tauri = { version = "2", features = [
"tray-icon",
"image-png",
"devtools",
- "macos-private-api"
+ "macos-private-api",
+ "protocol-asset"
] }
# E2E:应用内嵌 WebDriver server(Tauri 官方推荐的 WebdriverIO 驱动方式)。
# 仅当进程环境带 TAURI_WEBDRIVER_PORT 时监听,正常运行不开放端口。
diff --git a/src-tauri/src/bridge/pet.rs b/src-tauri/src/bridge/pet.rs
index 464f44be..53f46a0a 100644
--- a/src-tauri/src/bridge/pet.rs
+++ b/src-tauri/src/bridge/pet.rs
@@ -14,7 +14,7 @@
use crate::config;
use crate::desktop::pet as pet_window;
use base64::{engine::general_purpose::STANDARD, Engine};
-use futures_util::StreamExt;
+use futures_util::{StreamExt, TryStreamExt};
use serde::{Deserialize, Serialize};
use serde_json::Value;
use std::collections::HashSet;
@@ -38,6 +38,9 @@ const PET_PACKAGE_MAX_UNCOMPRESSED_BYTES: u64 = 128 * 1024 * 1024;
/// 清单和单张精灵图的读取上限。
const PET_MANIFEST_MAX_BYTES: u64 = 64 * 1024;
const PET_SPRITESHEET_MAX_BYTES: u64 = 8 * 1024 * 1024;
+const PET_CONFIG_MAX_BYTES: u64 = 1024 * 1024;
+const PET_VIDEO_MAX_BYTES: u64 = 512 * 1024 * 1024;
+const PET_PREVIEW_MAX_DIMENSION: u16 = 4096;
const PET_SPRITESHEET_MAX_DIMENSION: u32 = 16_384;
const PET_SPRITESHEET_MAX_PIXELS: u64 = 64 * 1024 * 1024;
/// Codex 图集协议:列恒为 8,行数由 `spriteVersionNumber` 决定(v1=8x9 / v2=8x11)。
@@ -108,7 +111,22 @@ struct PetManifest {
description: Option<String>,
#[serde(default)]
sprite_version_number: Option<u8>,
+ #[serde(default)]
spritesheet_path: String,
+ #[serde(default)]
+ kind: Option<String>,
+ #[serde(default)]
+ config_path: Option<String>,
+ #[serde(default)]
+ uri_path: Option<String>,
+ #[serde(default)]
+ mac_uri_path: Option<String>,
+ #[serde(default)]
+ preview_path: Option<String>,
+ #[serde(default)]
+ ext: Option<config::manifest::PresetPetExt>,
+ #[serde(default)]
+ size: Option<f64>,
}
/// 列表项使用来源限定 id,避免 chat 与 codex 同名时互相覆盖。
@@ -119,16 +137,28 @@ pub struct PetListItem {
pub description: Option<String>,
pub thumbnail: Option<String>,
pub source: String,
-}
-
-/// 实际渲染精灵图;字段保持 snake_case,与其他桌宠命令一致。
-#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
-pub struct PetAsset {
- pub id: String,
- pub spritesheet: String,
- pub sprite_version_number: u8,
- pub columns: u8,
- pub rows: u8,
+ pub kind: String,
+ pub thumbnail_type: String,
+}
+
+#[derive(Debug, Clone, Serialize)]
+#[serde(tag = "kind", rename_all = "lowercase")]
+pub enum PetAsset {
+ Codex {
+ id: String,
+ spritesheet: String,
+ sprite_version_number: u8,
+ columns: u8,
+ rows: u8,
+ },
+ Dsh {
+ id: String,
+ config: Value,
+ uri: config::manifest::PresetPetUri,
+ ext: config::manifest::PresetPetExt,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ size: Option<f64>,
+ },
}
/// 全新安装(从未写过 `active_pet`)或旧版非法值默认选中的宠物:清单里的第一个预设
@@ -312,6 +342,51 @@ pub fn set_pet_throw_enabled(app: AppHandle, enabled: bool) -> Result<PetStatus,
Ok(status)
}
+/// 删除用户导入的宠物:来源限定 id 删除对应来源目录,预设 id 反注册远端条目(内置预设删不到)。
+///
+/// 被删的宠物正好是当前激活项时顺带清空选择——否则窗口会一直指向已经不存在的素材。
+#[tauri::command]
+pub fn delete_pet(app: AppHandle, id: String) -> Result<PetStatus, String> {
+ let id = id.trim().to_string();
+ match parse_qualified_id(&id) {
+ Ok((source, manifest_id)) => {
+ delete_pet_directory(&pets_dir(&app, source)?, source, manifest_id)?
+ }
+ Err(_) if crate::bridge::preset_pet::safe_preset_id(&id) => {
+ crate::bridge::preset_pet::unregister_remote_pet(&app, &id)?
+ }
+ Err(_) => {
+ return Err(
+ "PET_ID_INVALID: pet id must be a preset id or source-qualified".to_string(),
+ )
+ }
+ }
+ let setting = config::get_store_dat_setting(&app);
+ if setting.active_pet.as_deref() == Some(id.as_str()) {
+ return set_active_pet(app, String::new());
+ }
+ Ok(status_from_setting(&setting, &default_active_pet(&app)))
+}
+
+/// 删除来源目录中清单 id 匹配的宠物目录;目录名不一定等于清单 id,按清单反查真实路径。
+fn delete_pet_directory(root: &Path, source: PetSource, manifest_id: &str) -> Result<(), String> {
+ let _guard = pet_import_lock()
+ .lock()
+ .unwrap_or_else(|error| error.into_inner());
+ let (directory, _) = find_pet_directory(root, manifest_id)?.ok_or_else(|| {
+ format!(
+ "PET_NOT_FOUND: pet {} was not found",
+ qualified_id(source, manifest_id)
+ )
+ })?;
+ fs::remove_dir_all(&directory).map_err(|error| {
+ format!(
+ "PET_DELETE_FAILED: failed to remove {}: {error}",
+ directory.display()
+ )
+ })
+}
+
/// 将 DSH 会话原始数据推送到独立桌宠 WebView,不在桌面端构造宠物专用结构。
#[tauri::command]
pub fn push_pet_session(app: AppHandle, action: String, session: Value) -> Result<(), String> {
@@ -710,7 +785,22 @@ fn safe_relative_path(value: &str) -> Result<PathBuf, 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),
+ Component::Normal(part) if !part.is_empty() => {
+ let name = part.to_string_lossy();
+ let stem = name.split('.').next().unwrap_or("").to_ascii_uppercase();
+ if name.ends_with(['.', ' '])
+ || name.chars().any(|c| c < ' ' || "<>\"|?*".contains(c))
+ || matches!(stem.as_str(), "CON" | "PRN" | "AUX" | "NUL")
+ || (stem.len() == 4
+ && (stem.starts_with("COM") || stem.starts_with("LPT"))
+ && matches!(stem.as_bytes()[3], b'1'..=b'9'))
+ {
+ return Err(
+ "PET_PATH_INVALID: path contains a nonportable filename".to_string()
+ );
+ }
+ result.push(part);
+ }
_ => {
return Err(
"PET_PATH_INVALID: path must not be absolute or contain traversal".to_string(),
@@ -764,13 +854,55 @@ fn parse_manifest_bytes(bytes: &[u8]) -> Result<PetManifest, String> {
));
}
}
- safe_relative_path(&manifest.spritesheet_path)?;
+ match manifest.kind.as_deref() {
+ None | Some("codex") => {
+ safe_relative_path(&manifest.spritesheet_path)?;
+ }
+ Some("dsh") => {
+ for path in [
+ manifest.config_path.as_deref(),
+ manifest.uri_path.as_deref(),
+ manifest.preview_path.as_deref(),
+ ] {
+ safe_relative_path(path.ok_or_else(|| {
+ "PET_MANIFEST_INVALID: dsh requires configPath, uriPath and previewPath"
+ .to_string()
+ })?)?;
+ }
+ if let Some(path) = &manifest.mac_uri_path {
+ safe_relative_path(path)?;
+ }
+ let ext = manifest
+ .ext
+ .as_ref()
+ .ok_or_else(|| "PET_MANIFEST_INVALID: dsh requires ext".to_string())?;
+ if ext.default != "webm"
+ || ext
+ .mac
+ .as_deref()
+ .is_some_and(|ext| ext != "mov" && ext != "webm")
+ || (manifest.mac_uri_path.is_some() && ext.mac.as_deref() != Some("mov"))
+ || (ext.mac.as_deref() == Some("mov") && manifest.mac_uri_path.is_none())
+ {
+ return Err(
+ "PET_MANIFEST_INVALID: dsh ext must be webm (default) / mov (mac)".to_string(),
+ );
+ }
+ if manifest
+ .size
+ .is_some_and(|size| !size.is_finite() || size <= 0.0 || size > 4096.0)
+ {
+ return Err("PET_MANIFEST_INVALID: size must be within 0..=4096".to_string());
+ }
+ }
+ _ => return Err("PET_MANIFEST_INVALID: kind must be dsh or codex".to_string()),
+ }
Ok(manifest)
}
fn read_manifest(directory: &Path) -> Result<PetManifest, String> {
let bytes = read_bounded_file(
- &directory.join("pet.json"),
+ &contained_file(directory, "pet.json")?,
PET_MANIFEST_MAX_BYTES,
"PET_MANIFEST_READ_FAILED",
)?;
@@ -791,7 +923,7 @@ fn contained_file(directory: &Path, relative: &str) -> Result<PathBuf, String> {
.canonicalize()
.map_err(|error| format!("PET_ASSET_READ_FAILED: failed to resolve asset: {error}"))?;
if !candidate.starts_with(&root) {
- return Err("PET_PATH_INVALID: spritesheetPath escapes the pet directory".to_string());
+ return Err("PET_PATH_INVALID: path escapes the pet directory".to_string());
}
Ok(candidate)
}
@@ -919,6 +1051,201 @@ fn image_data_url(
read_spritesheet(directory, relative, declared).map(|(url, _)| url)
}
+fn validate_pet_source(source: PetSource, manifest: &PetManifest) -> Result<(), String> {
+ if source == PetSource::Codex && manifest.kind.as_deref() == Some("dsh") {
+ return Err("PET_KIND_FORBIDDEN: Codex pets must use spritesheets".to_string());
+ }
+ Ok(())
+}
+
+fn gif_data_url(directory: &Path, relative: &str) -> Result<String, String> {
+ let path = contained_file(directory, relative)?;
+ let bytes = read_bounded_file(&path, PET_SPRITESHEET_MAX_BYTES, "PET_PREVIEW_READ_FAILED")?;
+ if bytes.len() < 13 || (!bytes.starts_with(b"GIF87a") && !bytes.starts_with(b"GIF89a")) {
+ return Err("PET_PREVIEW_INVALID: preview must have a GIF header".to_string());
+ }
+ let width = u16::from_le_bytes([bytes[6], bytes[7]]);
+ let height = u16::from_le_bytes([bytes[8], bytes[9]]);
+ if width == 0 || width != height || width > PET_PREVIEW_MAX_DIMENSION {
+ return Err("PET_PREVIEW_INVALID: GIF must be square and within 1..=4096px".to_string());
+ }
+ Ok(format!("data:image/gif;base64,{}", STANDARD.encode(bytes)))
+}
+
+fn animation_names(config: &Value) -> Result<HashSet<String>, String> {
+ fn collect(value: &Value, names: &mut HashSet<String>) -> Result<(), String> {
+ let values = match value {
+ Value::String(_) => std::slice::from_ref(value),
+ Value::Array(values) => values.as_slice(),
+ _ => {
+ return Err(
+ "PET_CONFIG_INVALID: animation slot must be a string or string array"
+ .to_string(),
+ )
+ }
+ };
+ for value in values {
+ let name = value.as_str().ok_or_else(|| {
+ "PET_CONFIG_INVALID: animation pool must contain strings".to_string()
+ })?;
+ safe_relative_path(name)?;
+ names.insert(name.to_string());
+ }
+ Ok(())
+ }
+ fn collect_map(value: &Value, names: &mut HashSet<String>, events: bool) -> Result<(), String> {
+ let values = value
+ .as_object()
+ .ok_or_else(|| "PET_CONFIG_INVALID: motions/events must be objects".to_string())?;
+ for value in values.values() {
+ if events {
+ for slot in value.as_array().ok_or_else(|| {
+ "PET_CONFIG_INVALID: event must contain an array of animation slots".to_string()
+ })? {
+ collect(slot, names)?;
+ }
+ } else {
+ collect(value, names)?;
+ }
+ }
+ Ok(())
+ }
+ let mut names = HashSet::new();
+ if let Some(motions) = config.get("motions") {
+ collect_map(motions, &mut names, false)?;
+ }
+ if let Some(animations) = config.get("animations") {
+ if !animations.is_object() {
+ return Err("PET_CONFIG_INVALID: animations must be an object".to_string());
+ }
+ for key in ["idle", "turn", "drag", "clicks"] {
+ if let Some(pool) = animations.get(key) {
+ if !pool.is_array() {
+ return Err(format!(
+ "PET_CONFIG_INVALID: animations.{key} must be an array"
+ ));
+ }
+ collect(pool, &mut names)?;
+ }
+ }
+ for (key, events) in [("motions", false), ("events", true)] {
+ if let Some(pool) = animations.get(key) {
+ collect_map(pool, &mut names, events)?;
+ }
+ }
+ if let Some(moves) = animations.get("moves") {
+ if !moves.is_object() || !moves.get("actions").is_some_and(Value::is_array) {
+ return Err("PET_CONFIG_INVALID: moves requires an actions array".to_string());
+ }
+ }
+ if let Some(actions) = animations.pointer("/moves/actions") {
+ let actions = actions
+ .as_array()
+ .ok_or_else(|| "PET_CONFIG_INVALID: moves.actions must be an array".to_string())?;
+ for action in actions {
+ if !action.get("name").is_some_and(Value::is_string) {
+ return Err("PET_CONFIG_INVALID: move requires a string name".to_string());
+ }
+ collect(
+ action
+ .get("name")
+ .ok_or_else(|| "PET_CONFIG_INVALID: move requires name".to_string())?,
+ &mut names,
+ )?;
+ }
+ }
+ if let Some(categories) = animations.get("categories") {
+ let categories = categories
+ .as_array()
+ .ok_or_else(|| "PET_CONFIG_INVALID: categories must be an array".to_string())?;
+ for category in categories {
+ let actions = category
+ .get("actions")
+ .filter(|value| value.is_array())
+ .ok_or_else(|| {
+ "PET_CONFIG_INVALID: category requires an actions array".to_string()
+ })?;
+ collect(actions, &mut names)?;
+ }
+ }
+ }
+ if names.is_empty() {
+ return Err("PET_CONFIG_INVALID: config must reference at least one animation".to_string());
+ }
+ Ok(names)
+}
+
+fn read_dsh_asset(
+ directory: &Path,
+ manifest: &PetManifest,
+ id: String,
+) -> Result<(PetAsset, Vec<PathBuf>), String> {
+ let path = contained_file(directory, manifest.config_path.as_deref().unwrap())?;
+ let bytes = read_bounded_file(&path, PET_CONFIG_MAX_BYTES, "PET_CONFIG_READ_FAILED")?;
+ let raw =
+ std::str::from_utf8(&bytes).map_err(|error| format!("PET_CONFIG_INVALID: {error}"))?;
+ let config: Value = serde_json::from_str(&config::manifest::strip_jsonc(raw))
+ .map_err(|error| format!("PET_CONFIG_INVALID: {error}"))?;
+ if !config.is_object() {
+ return Err("PET_CONFIG_INVALID: config must be an object".to_string());
+ }
+ let names = animation_names(&config)?;
+ let ext = manifest.ext.as_ref().unwrap();
+ let mut files = Vec::new();
+ let mut uri = config::manifest::PresetPetUri {
+ default: String::new(),
+ mac: None,
+ };
+ for (relative, extension, mac) in [
+ (
+ manifest.uri_path.as_deref(),
+ Some(ext.default.as_str()),
+ false,
+ ),
+ (manifest.mac_uri_path.as_deref(), ext.mac.as_deref(), true),
+ ] {
+ let Some(relative) = relative else { continue };
+ let extension = extension.unwrap();
+ let base = contained_file(directory, relative)?;
+ if !base.is_dir() {
+ return Err("PET_PATH_INVALID: uriPath must be a directory".to_string());
+ }
+ for name in &names {
+ let path = contained_file(directory, &format!("{relative}/{name}.{extension}"))?;
+ let metadata =
+ fs::metadata(&path).map_err(|error| format!("PET_ASSET_READ_FAILED: {error}"))?;
+ if !metadata.is_file() || metadata.len() == 0 || metadata.len() > PET_VIDEO_MAX_BYTES {
+ return Err(
+ "PET_ASSET_INVALID: video must be a nonempty file within 512MiB".to_string(),
+ );
+ }
+ files.push(path);
+ }
+ let path = dunce::simplified(&base)
+ .to_str()
+ .ok_or_else(|| "PET_PATH_INVALID: asset directory must be UTF-8".to_string())?
+ .to_string();
+ if mac {
+ uri.mac = Some(path);
+ } else {
+ uri.default = path;
+ }
+ }
+ gif_data_url(directory, manifest.preview_path.as_deref().unwrap())?;
+ files.sort();
+ files.dedup();
+ Ok((
+ PetAsset::Dsh {
+ id,
+ config,
+ uri,
+ ext: ext.clone(),
+ size: manifest.size,
+ },
+ files,
+ ))
+}
+
fn manifest_to_list_item(
source: PetSource,
directory: &Path,
@@ -935,18 +1262,25 @@ fn manifest_to_list_item(
.description
.map(|value| value.trim().to_string())
.filter(|value| !value.is_empty());
- let thumbnail = image_data_url(
- directory,
- &manifest.spritesheet_path,
- manifest.sprite_version_number,
- )
- .ok();
+ let is_dsh = manifest.kind.as_deref() == Some("dsh");
+ let thumbnail = if is_dsh {
+ gif_data_url(directory, manifest.preview_path.as_deref().unwrap()).ok()
+ } else {
+ image_data_url(
+ directory,
+ &manifest.spritesheet_path,
+ manifest.sprite_version_number,
+ )
+ .ok()
+ };
PetListItem {
id: qualified_id(source, &manifest.id),
name,
description,
thumbnail,
source: source.as_str().to_string(),
+ kind: if is_dsh { "dsh" } else { "codex" }.to_string(),
+ thumbnail_type: if is_dsh { "gif" } else { "spritesheet" }.to_string(),
}
}
@@ -985,6 +1319,9 @@ pub fn list_pets(app: AppHandle, source: String) -> Result<Vec<PetListItem>, Str
let Ok(manifest) = read_manifest(&directory) else {
continue;
};
+ if validate_pet_source(source, &manifest).is_err() {
+ continue;
+ }
let id = qualified_id(source, &manifest.id);
if ids.insert(id) {
items.push(manifest_to_list_item(source, &directory, manifest));
@@ -1021,12 +1358,23 @@ pub fn get_pet_asset(app: AppHandle, id: String) -> Result<PetAsset, String> {
qualified_id(source, manifest_id)
)
})?;
+ validate_pet_source(source, &manifest)?;
+ if manifest.kind.as_deref() == Some("dsh") {
+ let (asset, files) = read_dsh_asset(&directory, &manifest, id.to_string())?;
+ let scope = app.asset_protocol_scope();
+ for file in files {
+ scope
+ .allow_file(file)
+ .map_err(|error| format!("PET_ASSET_SCOPE_FAILED: {error}"))?;
+ }
+ return Ok(asset);
+ }
let (spritesheet, grid) = read_spritesheet(
&directory,
&manifest.spritesheet_path,
manifest.sprite_version_number,
)?;
- Ok(PetAsset {
+ Ok(PetAsset::Codex {
id: qualified_id(source, &manifest.id),
spritesheet,
sprite_version_number: grid.version,
@@ -1235,6 +1583,7 @@ fn extract_pet_archive(bytes: &[u8], staging: &Path) -> Result<PetManifest, Stri
}
let manifest = read_manifest(staging)?;
+ validate_pet_source(PetSource::Codex, &manifest)?;
image_data_url(
staging,
&manifest.spritesheet_path,
@@ -1252,9 +1601,8 @@ fn unique_staging_path(staging_root: &Path) -> PathBuf {
}
fn prepare_staging_root(root: &Path) -> Result<PathBuf, String> {
- fs::create_dir_all(root).map_err(|error| {
- format!("PET_DIR_FAILED: failed to create Codex pets directory: {error}")
- })?;
+ fs::create_dir_all(root)
+ .map_err(|error| format!("PET_DIR_FAILED: failed to create pets directory: {error}"))?;
let staging_root = root.join(".staging");
match fs::symlink_metadata(&staging_root) {
Ok(metadata) if metadata.file_type().is_symlink() || !metadata.is_dir() => {
@@ -1336,6 +1684,342 @@ pub fn import_pet(app: AppHandle, name: String, data: String) -> Result<PetListI
result
}
+fn parse_pet_repository(repository: &str) -> Result<(String, String), String> {
+ let invalid =
+ || "PET_REPOSITORY_INVALID: use owner/repo or https://github.com/owner/repo".to_string();
+ let input = repository.trim();
+ let path = if input.contains("://") {
+ let url = reqwest::Url::parse(input).map_err(|_| invalid())?;
+ if url.scheme() != "https"
+ || url.host_str() != Some("github.com")
+ || !url.username().is_empty()
+ || url.password().is_some()
+ || url.port().is_some()
+ || url.query().is_some()
+ || url.fragment().is_some()
+ {
+ return Err(invalid());
+ }
+ url.path()
+ .trim_start_matches('/')
+ .trim_end_matches('/')
+ .to_string()
+ } else {
+ input.to_string()
+ };
+ let (owner, repo) = path.split_once('/').ok_or_else(invalid)?;
+ let repo = repo.strip_suffix(".git").unwrap_or(repo);
+ if owner.is_empty()
+ || owner.len() > 39
+ || owner.starts_with('-')
+ || owner.ends_with('-')
+ || !owner
+ .bytes()
+ .all(|c| c.is_ascii_alphanumeric() || c == b'-')
+ || repo.is_empty()
+ || repo.len() > 100
+ || matches!(repo, "." | "..")
+ || !repo
+ .bytes()
+ .all(|c| c.is_ascii_alphanumeric() || matches!(c, b'-' | b'_' | b'.'))
+ {
+ return Err(invalid());
+ }
+ Ok((owner.to_string(), repo.to_string()))
+}
+
+fn repository_asset_url(base: &str, relative: &str) -> Result<String, String> {
+ let path = safe_relative_path(relative)?;
+ let mut url =
+ reqwest::Url::parse(base).map_err(|error| format!("PET_REPOSITORY_INVALID: {error}"))?;
+ {
+ let mut segments = url
+ .path_segments_mut()
+ .map_err(|_| "PET_REPOSITORY_INVALID: invalid resource base".to_string())?;
+ segments.pop_if_empty();
+ for part in path.components() {
+ segments.push(
+ part.as_os_str()
+ .to_str()
+ .ok_or_else(|| "PET_PATH_INVALID: path must be UTF-8".to_string())?,
+ );
+ }
+ }
+ Ok(url.to_string())
+}
+
+fn repository_spec(
+ base: &str,
+ name: &str,
+ bytes: Option<&[u8]>,
+) -> Result<config::manifest::PresetPetSpec, String> {
+ let manifest = if let Some(bytes) = bytes {
+ parse_manifest_bytes(bytes)?
+ } else {
+ parse_manifest_bytes(
+ &serde_json::to_vec(&serde_json::json!({
+ "id": name, "kind": "dsh", "configPath": "config.jsonc", "uriPath": "webm",
+ "previewPath": "preview/preview.gif", "ext": {"default": "webm", "mac": "webm"}
+ }))
+ .map_err(|error| format!("PET_MANIFEST_INVALID: {error}"))?,
+ )?
+ };
+ if manifest.kind.as_deref() != Some("dsh") {
+ return Err("PET_KIND_FORBIDDEN: repository pets must use kind dsh".to_string());
+ }
+ let config = repository_asset_url(base, manifest.config_path.as_deref().unwrap())?;
+ let image = repository_asset_url(base, manifest.preview_path.as_deref().unwrap())?;
+ let uri = config::manifest::PresetPetUri {
+ default: repository_asset_url(base, manifest.uri_path.as_deref().unwrap())?,
+ mac: manifest
+ .mac_uri_path
+ .as_deref()
+ .map(|path| repository_asset_url(base, path))
+ .transpose()?,
+ };
+ Ok(config::manifest::PresetPetSpec {
+ name: manifest
+ .display_name
+ .filter(|name| !name.trim().is_empty())
+ .unwrap_or_else(|| manifest.id.clone()),
+ id: manifest.id,
+ desc: manifest.description,
+ image: Some(image),
+ kind: Some("dsh".to_string()),
+ size: manifest.size,
+ config,
+ uri,
+ ext: manifest.ext,
+ })
+}
+
+async fn repository_metadata(
+ client: &reqwest::Client,
+ url: &str,
+ limit: u64,
+ optional: bool,
+) -> Result<Option<Vec<u8>>, String> {
+ let mut response = client
+ .get(url)
+ .send()
+ .await
+ .map_err(|error| format!("PET_REPOSITORY_DOWNLOAD_FAILED: {error}"))?;
+ if optional && response.status() == reqwest::StatusCode::NOT_FOUND {
+ return Ok(None);
+ }
+ if !response.status().is_success() {
+ return Err(format!(
+ "PET_REPOSITORY_DOWNLOAD_FAILED: HTTP {}",
+ response.status()
+ ));
+ }
+ if response.content_length().is_some_and(|size| size > limit) {
+ return Err("PET_REPOSITORY_TOO_LARGE: metadata exceeds its byte limit".to_string());
+ }
+ let mut bytes = Vec::new();
+ while let Some(chunk) = response
+ .chunk()
+ .await
+ .map_err(|error| format!("PET_REPOSITORY_DOWNLOAD_FAILED: {error}"))?
+ {
+ if chunk.len() as u64 > limit.saturating_sub(bytes.len() as u64) {
+ return Err("PET_REPOSITORY_TOO_LARGE: metadata exceeds its byte limit".to_string());
+ }
+ bytes.extend_from_slice(&chunk);
+ }
+ Ok(Some(bytes))
+}
+
+async fn read_repository_spec(
+ client: &reqwest::Client,
+ base: &str,
+ name: &str,
+ check_media: bool,
+) -> Result<config::manifest::PresetPetSpec, String> {
+ let manifest = repository_metadata(
+ client,
+ &repository_asset_url(base, "pet.json")?,
+ PET_MANIFEST_MAX_BYTES,
+ true,
+ )
+ .await?;
+ let spec = repository_spec(base, name, manifest.as_deref())?;
+ let bytes = repository_metadata(client, &spec.config, PET_CONFIG_MAX_BYTES, false)
+ .await?
+ .unwrap();
+ let raw =
+ std::str::from_utf8(&bytes).map_err(|error| format!("PET_CONFIG_INVALID: {error}"))?;
+ let value: Value = serde_json::from_str(&config::manifest::strip_jsonc(raw))
+ .map_err(|error| format!("PET_CONFIG_INVALID: {error}"))?;
+ let names = animation_names(&value)?;
+ if check_media {
+ let ext = spec.ext.as_ref().unwrap();
+ let mut urls = vec![spec.image.clone().unwrap()];
+ for (uri, extension) in [
+ (Some(spec.uri.default.as_str()), Some(ext.default.as_str())),
+ (spec.uri.mac.as_deref(), ext.mac.as_deref()),
+ ] {
+ let Some(uri) = uri else { continue };
+ for name in &names {
+ urls.push(repository_asset_url(
+ &format!("{uri}/"),
+ &format!("{name}.{}", extension.unwrap()),
+ )?);
+ }
+ }
+ futures_util::stream::iter(urls.into_iter().map(|url| async move {
+ let response = client
+ .head(&url)
+ .send()
+ .await
+ .map_err(|error| format!("PET_REPOSITORY_DOWNLOAD_FAILED: {error}"))?;
+ if !response.status().is_success() {
+ return Err(format!(
+ "PET_ASSET_INVALID: HTTP {} for {url}",
+ response.status()
+ ));
+ }
+ Ok::<_, String>(())
+ }))
+ .buffer_unordered(4)
+ .try_collect::<Vec<_>>()
+ .await?;
+ }
+ Ok(spec)
+}
+
+fn repository_client(app: &AppHandle) -> Result<reqwest::Client, String> {
+ config::proxy::http_client_builder(app)?
+ .redirect(reqwest::redirect::Policy::none())
+ .user_agent("deepseek-harness-desktop")
+ .connect_timeout(Duration::from_secs(5))
+ .timeout(Duration::from_secs(12))
+ .build()
+ .map_err(|error| format!("PET_REPOSITORY_DOWNLOAD_FAILED: {error}"))
+}
+
+pub(super) fn pet_repository_revision(
+ spec: &config::manifest::PresetPetSpec,
+) -> Result<(String, String, String), String> {
+ let url = reqwest::Url::parse(&spec.config)
+ .map_err(|error| format!("PET_REPOSITORY_INVALID: {error}"))?;
+ let parts: Vec<_> = url.path_segments().into_iter().flatten().collect();
+ if url.scheme() != "https"
+ || url.host_str() != Some("raw.githubusercontent.com")
+ || !url.username().is_empty()
+ || url.password().is_some()
+ || url.port().is_some()
+ || url.query().is_some()
+ || url.fragment().is_some()
+ || parts.len() < 4
+ || !(parts[2] == "HEAD" || valid_commit(parts[2]))
+ {
+ return Err("PET_REPOSITORY_INVALID: pet is not a registered GitHub repository".into());
+ }
+ let (owner, name) = parse_pet_repository(&format!("{}/{}", parts[0], parts[1]))?;
+ Ok((owner, name, parts[2].to_string()))
+}
+
+fn valid_commit(value: &str) -> bool {
+ value.len() == 40 && value.bytes().all(|value| value.is_ascii_hexdigit())
+}
+
+async fn repository_head(
+ client: &reqwest::Client,
+ owner: &str,
+ name: &str,
+) -> Result<String, String> {
+ let bytes = repository_metadata(
+ client,
+ &format!("https://api.github.com/repos/{owner}/{name}/commits/HEAD"),
+ PET_CONFIG_MAX_BYTES,
+ false,
+ )
+ .await?
+ .unwrap();
+ let value: Value = serde_json::from_slice(&bytes)
+ .map_err(|error| format!("PET_REPOSITORY_INVALID: {error}"))?;
+ value
+ .get("sha")
+ .and_then(Value::as_str)
+ .filter(|sha| valid_commit(sha))
+ .map(|sha| sha.to_ascii_lowercase())
+ .ok_or_else(|| "PET_REPOSITORY_INVALID: missing commit SHA".into())
+}
+
+#[tauri::command]
+pub async fn check_pet_updates(app: AppHandle) -> Result<Vec<String>, String> {
+ let entries = crate::bridge::preset_pet::list_preset_pets(app.clone())?;
+ let client = repository_client(&app)?;
+ // ponytail: 仓库提交变化都提示更新;需要排除纯文档提交时改用资源树 SHA。
+ Ok(futures_util::stream::iter(
+ entries
+ .into_iter()
+ .filter(|entry| entry.remote)
+ .map(|entry| {
+ let client = &client;
+ async move {
+ let (owner, name, current) = pet_repository_revision(&entry.spec).ok()?;
+ let latest = repository_head(client, &owner, &name).await.ok()?;
+ (current.to_ascii_lowercase() != latest).then_some(entry.spec.id)
+ }
+ }),
+ )
+ .buffer_unordered(4)
+ .filter_map(|id| async { id })
+ .take_until(tokio::time::sleep(Duration::from_secs(12)))
+ .collect()
+ .await)
+}
+
+#[tauri::command]
+pub async fn update_pet_repository(
+ app: AppHandle,
+ id: String,
+) -> Result<config::manifest::PresetPetSpec, String> {
+ let entry = crate::bridge::preset_pet::list_preset_pets(app.clone())?
+ .into_iter()
+ .find(|entry| entry.remote && entry.spec.id == id)
+ .ok_or_else(|| format!("PET_NOT_FOUND: preset {id} is not registered"))?;
+ let (owner, name, _) = pet_repository_revision(&entry.spec)?;
+ let spec = tokio::time::timeout(Duration::from_secs(12), async {
+ let client = repository_client(&app)?;
+ let commit = repository_head(&client, &owner, &name).await?;
+ read_repository_spec(
+ &client,
+ &format!("https://raw.githubusercontent.com/{owner}/{name}/{commit}/"),
+ &name,
+ true,
+ )
+ .await
+ })
+ .await
+ .map_err(|_| "PET_REPOSITORY_TIMEOUT: update exceeded 12 seconds".to_string())??;
+ let spec = crate::bridge::preset_pet::update_remote_pet(
+ &app,
+ config::manifest::PresetPetSpec { id, ..spec },
+ )?;
+ let _ = app.emit_to(pet_window::PET_WINDOW_LABEL, "pet://catalog", &spec.id);
+ Ok(spec)
+}
+
+#[tauri::command]
+pub async fn import_pet_repository(
+ app: AppHandle,
+ repository: String,
+) -> Result<config::manifest::PresetPetSpec, String> {
+ let (owner, name) = parse_pet_repository(&repository)?;
+ tokio::time::timeout(Duration::from_secs(12), async {
+ let client = repository_client(&app)?;
+ let commit = repository_head(&client, &owner, &name).await?;
+ let base = format!("https://raw.githubusercontent.com/{owner}/{name}/{commit}/");
+ let spec = read_repository_spec(&client, &base, &name, false).await?;
+ crate::bridge::preset_pet::register_remote_pet(&app, spec)
+ })
+ .await
+ .map_err(|_| "PET_REPOSITORY_TIMEOUT: metadata registration exceeded 12 seconds".to_string())?
+}
+
#[cfg(test)]
mod tests {
use super::*;
@@ -1344,6 +2028,246 @@ mod tests {
struct TestDirectory(PathBuf);
+ #[tokio::test]
+ async fn repository_metadata_skips_media_on_import_and_checks_it_before_update() {
+ for (manifest, check_media, missing_media) in [
+ (None, false, false),
+ (
+ Some(
+ r#"{"id":"declared","kind":"dsh","configPath":"assets/config.jsonc","uriPath":"webm","previewPath":"preview/preview.gif","ext":{"default":"webm","mac":"webm"}}"#,
+ ),
+ false,
+ false,
+ ),
+ (None, true, false),
+ (None, true, true),
+ ] {
+ let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
+ let base = format!("http://{}/", listener.local_addr().unwrap());
+ let handle = std::thread::spawn(move || {
+ let mut paths = Vec::new();
+ for index in 0..if check_media { 4 } else { 2 } {
+ let (mut socket, _) = listener.accept().unwrap();
+ let mut request = [0u8; 4096];
+ let count = socket.read(&mut request).unwrap();
+ paths.push(
+ String::from_utf8_lossy(&request[..count])
+ .lines()
+ .next()
+ .unwrap()
+ .to_string(),
+ );
+ let (status, body) = if index == 0 {
+ (
+ if manifest.is_some() {
+ "200 OK"
+ } else {
+ "404 Not Found"
+ },
+ manifest.unwrap_or(""),
+ )
+ } else if index == 1 {
+ ("200 OK", r#"{"animations":{"idle":["idle"]}}"#)
+ } else {
+ (
+ if missing_media && index == 3 {
+ "404 Not Found"
+ } else {
+ "200 OK"
+ },
+ "",
+ )
+ };
+ write!(socket, "HTTP/1.1 {status}\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}", body.len()).unwrap();
+ }
+ paths
+ });
+ let client = reqwest::Client::builder()
+ .no_proxy()
+ .redirect(reqwest::redirect::Policy::none())
+ .timeout(Duration::from_secs(2))
+ .build()
+ .unwrap();
+ let result = read_repository_spec(&client, &base, "pet", check_media).await;
+ let paths = handle.join().unwrap();
+ if check_media {
+ let mut media = paths[2..].to_vec();
+ media.sort();
+ assert_eq!(
+ media,
+ [
+ "HEAD /preview/preview.gif HTTP/1.1",
+ "HEAD /webm/idle.webm HTTP/1.1"
+ ]
+ );
+ }
+ if missing_media {
+ assert!(result
+ .unwrap_err()
+ .starts_with("PET_ASSET_INVALID: HTTP 404"));
+ continue;
+ }
+ let spec = result.unwrap();
+ assert_eq!(
+ paths[..2],
+ [
+ "GET /pet.json HTTP/1.1",
+ if manifest.is_some() {
+ "GET /assets/config.jsonc HTTP/1.1"
+ } else {
+ "GET /config.jsonc HTTP/1.1"
+ }
+ ]
+ );
+ assert_eq!(
+ spec.config,
+ format!(
+ "{base}{}",
+ if manifest.is_some() {
+ "assets/config.jsonc"
+ } else {
+ "config.jsonc"
+ }
+ )
+ );
+ assert_eq!(spec.uri.default, format!("{base}webm"));
+ assert_eq!(spec.image, Some(format!("{base}preview/preview.gif")));
+ }
+ }
+
+ #[test]
+ fn repository_registration_without_manifest_contains_only_remote_resource_urls() {
+ let spec = repository_spec(
+ "https://raw.githubusercontent.com/owner/pet/HEAD/",
+ "pet",
+ None,
+ )
+ .unwrap();
+ assert_eq!(spec.id, "pet");
+ assert_eq!(spec.kind.as_deref(), Some("dsh"));
+ assert_eq!(
+ spec.config,
+ "https://raw.githubusercontent.com/owner/pet/HEAD/config.jsonc"
+ );
+ assert_eq!(
+ spec.uri.default,
+ "https://raw.githubusercontent.com/owner/pet/HEAD/webm"
+ );
+ assert_eq!(
+ spec.image.as_deref(),
+ Some("https://raw.githubusercontent.com/owner/pet/HEAD/preview/preview.gif")
+ );
+ assert_eq!(spec.ext.unwrap().mac.as_deref(), Some("webm"));
+ assert!(spec.uri.mac.is_none());
+ assert!(repository_spec(
+ "https://raw.githubusercontent.com/o/r/HEAD/",
+ "unsafe.name",
+ None
+ )
+ .unwrap_err()
+ .starts_with("PET_ID_INVALID:"));
+ }
+
+ #[test]
+ fn repository_registration_respects_manifest_paths_and_encodes_resource_names() {
+ let raw = br#"{"id":"declared","displayName":"Pet","kind":"dsh","configPath":"assets/config.jsonc","uriPath":"assets/webm","macUriPath":"assets/mov","previewPath":"preview/pet.gif","ext":{"default":"webm","mac":"mov"},"size":200}"#;
+ let base = "https://raw.githubusercontent.com/o/r/HEAD/";
+ let spec = repository_spec(base, "ignored", Some(raw)).unwrap();
+ assert_eq!(spec.id, "declared");
+ assert_eq!(spec.name, "Pet");
+ assert_eq!(spec.size, Some(200.0));
+ assert_eq!(
+ spec.config,
+ "https://raw.githubusercontent.com/o/r/HEAD/assets/config.jsonc"
+ );
+ assert_eq!(
+ spec.uri.mac.as_deref(),
+ Some("https://raw.githubusercontent.com/o/r/HEAD/assets/mov")
+ );
+ assert_eq!(
+ repository_asset_url(base, "preview/pet #1.gif").unwrap(),
+ "https://raw.githubusercontent.com/o/r/HEAD/preview/pet%20%231.gif"
+ );
+ for path in [
+ "../outside",
+ "https://evil.test/c",
+ "C:/private",
+ "\\private",
+ ] {
+ assert!(repository_asset_url(base, path)
+ .unwrap_err()
+ .starts_with("PET_PATH_INVALID:"));
+ }
+ assert!(repository_spec(
+ base,
+ "pet",
+ Some(br#"{"id":"pet","spritesheetPath":"sprite.webp"}"#)
+ )
+ .unwrap_err()
+ .starts_with("PET_KIND_FORBIDDEN:"));
+ }
+
+ #[test]
+ fn repository_updates_recover_origin_from_pinned_urls_and_reject_untrusted_targets() {
+ let base =
+ "https://raw.githubusercontent.com/owner/pet/0123456789abcdef0123456789abcdef01234567/";
+ let mut spec = repository_spec(base, "pet", None).unwrap();
+ assert_eq!(
+ pet_repository_revision(&spec).unwrap(),
+ (
+ "owner".into(),
+ "pet".into(),
+ "0123456789abcdef0123456789abcdef01234567".into()
+ )
+ );
+ spec.config = "https://raw.githubusercontent.com/owner/pet/HEAD/config.jsonc".into();
+ assert_eq!(pet_repository_revision(&spec).unwrap().2, "HEAD");
+ for url in [
+ "https://evil.test/o/r/HEAD/c",
+ "http://raw.githubusercontent.com/o/r/HEAD/c",
+ "https://[email protected]/o/r/HEAD/c",
+ "https://raw.githubusercontent.com/o/r/main/c",
+ "https://raw.githubusercontent.com/o/r/HEAD/c?x=1",
+ ] {
+ spec.config = url.into();
+ assert!(pet_repository_revision(&spec)
+ .unwrap_err()
+ .starts_with("PET_REPOSITORY_INVALID:"));
+ }
+ }
+
+ #[test]
+ fn repository_input_accepts_only_github_repository_names() {
+ for input in ["owner/pet-name", " https://github.com/owner/pet-name.git/ "] {
+ assert_eq!(
+ parse_pet_repository(input).unwrap(),
+ ("owner".to_string(), "pet-name".to_string())
+ );
+ }
+ for input in [
+ "",
+ "http://github.com/a/b",
+ "https://github.com.evil/a/b",
+ "https://127.0.0.1/a/b",
+ "https://[email protected]/a/b",
+ "https://github.com:8080/a/b",
+ "https://github.com/a/b?x=1",
+ "https://github.com/a/b#main",
+ "a/b/tree/main",
+ "a/../b",
+ "a/b%2fc",
+ "a\\b",
+ "a/..",
+ ] {
+ assert!(
+ parse_pet_repository(input)
+ .unwrap_err()
+ .starts_with("PET_REPOSITORY_INVALID:"),
+ "{input}"
+ );
+ }
+ }
+
// ---- 重连日志节流(宿主不可用期间每 2s 一次失败不能刷满日志)----
#[test]
@@ -1873,6 +2797,29 @@ mod tests {
assert!(!directory.0.join(".DS_Store").exists());
}
+ #[test]
+ fn delete_pet_directory_removes_the_manifest_match_and_keeps_siblings() {
+ let root = TestDirectory::new("delete-pet");
+ for (folder, id) in [("folder-a", "alpha"), ("folder-b", "beta")] {
+ fs::create_dir_all(root.0.join(folder)).unwrap();
+ fs::write(
+ root.0.join(folder).join("pet.json"),
+ format!(r#"{{"id":"{id}","spritesheetPath":"spritesheet.webp"}}"#),
+ )
+ .unwrap();
+ }
+
+ assert!(delete_pet_directory(&root.0, PetSource::Codex, "missing")
+ .unwrap_err()
+ .starts_with("PET_NOT_FOUND:"));
+ assert_eq!(
+ delete_pet_directory(&root.0, PetSource::Codex, "alpha"),
+ Ok(())
+ );
+ assert!(!root.0.join("folder-a").exists());
+ assert!(root.0.join("folder-b").join("pet.json").is_file());
+ }
+
#[test]
fn bare_pets_directory_entries_list_without_preset_catalog() {
// 落点是纯文件系统扫描:`$DSH_HOME/pets/<dir>/pet.json` 齐备就会被列出,
@@ -1898,7 +2845,10 @@ mod tests {
vec![empty.clone(), pet.clone()],
"只枚举直接子目录,普通文件不进列表"
);
- assert!(read_manifest(&empty).is_err(), "缺少 pet.json 的目录应被跳过");
+ assert!(
+ read_manifest(&empty).is_err(),
+ "缺少 pet.json 的目录应被跳过"
+ );
let item = manifest_to_list_item(PetSource::Chat, &pet, read_manifest(&pet).unwrap());
assert_eq!(item.id, "chat:my-pet");
@@ -1908,6 +2858,341 @@ mod tests {
assert!(validate_active_pet_id(&item.id).is_ok());
}
+ fn dsh_fixture(directory: &Path) -> PetManifest {
+ fs::create_dir_all(directory.join("webm")).unwrap();
+ fs::create_dir_all(directory.join("preview")).unwrap();
+ fs::write(directory.join("pet.json"), br#"{"id":"video-pet","kind":"dsh","configPath":"config.jsonc","uriPath":"webm","previewPath":"preview/preview.gif","ext":{"default":"webm","mac":"webm"},"size":220}"#).unwrap();
+ fs::write(
+ directory.join("config.jsonc"),
+ br#"{
+ // JSONC must retain comment markers inside strings
+ "motions": {"idle": "idle", "working": ["work"],},
+ "whisperPrompt": "https://example.test/*not a comment*/",
+ }"#,
+ )
+ .unwrap();
+ fs::write(directory.join("webm/idle.webm"), b"video-idle").unwrap();
+ fs::write(directory.join("webm/work.webm"), b"video-work").unwrap();
+ fs::write(directory.join("webm/unreferenced.webm"), b"private-video").unwrap();
+ fs::write(directory.join("webm/private.txt"), b"private").unwrap();
+ fs::write(
+ directory.join("preview/preview.gif"),
+ b"GIF89a\x10\x00\x10\x00\x00\x00\x00",
+ )
+ .unwrap();
+ read_manifest(directory).unwrap()
+ }
+
+ #[test]
+ fn dsh_asset_preserves_jsonc_object_and_only_authorizes_referenced_videos() {
+ let root = tempfile::tempdir().unwrap();
+ let manifest = dsh_fixture(root.path());
+ let (asset, files) =
+ read_dsh_asset(root.path(), &manifest, "chat:video-pet".to_string()).unwrap();
+ let value = serde_json::to_value(asset).unwrap();
+ assert_eq!(value["kind"], "dsh");
+ assert_eq!(value["id"], "chat:video-pet");
+ assert_eq!(
+ value["config"]["motions"]["working"],
+ serde_json::json!(["work"])
+ );
+ assert_eq!(
+ value["config"]["whisperPrompt"],
+ "https://example.test/*not a comment*/"
+ );
+ assert_eq!(
+ value["ext"],
+ serde_json::json!({"default":"webm","mac":"webm"})
+ );
+ assert_eq!(value["size"], 220.0);
+ assert!(Path::new(value["uri"]["default"].as_str().unwrap()).is_absolute());
+ assert_eq!(
+ Path::new(value["uri"]["default"].as_str().unwrap()),
+ dunce::simplified(&root.path().join("webm").canonicalize().unwrap())
+ );
+ assert!(value["uri"].get("mac").is_none());
+ assert!(value.get("spritesheet").is_none());
+ assert_eq!(
+ files,
+ vec![
+ root.path().join("webm/idle.webm").canonicalize().unwrap(),
+ root.path().join("webm/work.webm").canonicalize().unwrap()
+ ]
+ );
+ let app = tauri::test::mock_app();
+ let scope = tauri::scope::fs::Scope::new(
+ &app,
+ &tauri::utils::config::FsScope::AllowedPaths(Vec::new()),
+ )
+ .unwrap();
+ for file in files {
+ scope.allow_file(file).unwrap();
+ }
+ assert!(scope.is_allowed(root.path().join("webm/idle.webm")));
+ for file in [
+ "pet.json",
+ "config.jsonc",
+ "preview/preview.gif",
+ "webm/private.txt",
+ "webm/unreferenced.webm",
+ ] {
+ assert!(
+ !scope.is_allowed(root.path().join(file)),
+ "must not authorize {file}"
+ );
+ }
+ assert!(!scope.is_allowed(root.path()));
+ let item = manifest_to_list_item(PetSource::Chat, root.path(), manifest);
+ assert_eq!(item.kind, "dsh");
+ assert_eq!(item.thumbnail_type, "gif");
+ assert_eq!(
+ item.thumbnail.unwrap(),
+ "data:image/gif;base64,R0lGODlhEAAQAAAAAA=="
+ );
+ }
+
+ #[test]
+ fn dsh_reference_enumeration_covers_component_pools_without_metadata() {
+ let config = serde_json::json!({
+ "motions": {"idle": "idle"},
+ "animations": {
+ "idle": ["breathe"], "turn": ["turn"], "drag": ["drag"], "clicks": ["click"],
+ "motions": {"working": ["work"]},
+ "moves": {"default": {"speed": 2}, "actions": [{"name": "walk", "params": {"speed": 2}}]},
+ "categories": [{"id": "not-a-video", "weight": 1, "actions": ["jump"]}],
+ "events": {"workStatus": ["think", ["code", "write"]]}
+ }
+ });
+ let mut names: Vec<_> = animation_names(&config).unwrap().into_iter().collect();
+ names.sort();
+ assert_eq!(
+ names,
+ [
+ "breathe", "click", "code", "drag", "idle", "jump", "think", "turn", "walk",
+ "work", "write"
+ ]
+ );
+ }
+
+ #[test]
+ fn dsh_assets_reject_missing_traversing_or_oversized_files() {
+ let root = tempfile::tempdir().unwrap();
+ let manifest = dsh_fixture(root.path());
+ for raw in [
+ r#"[]"#,
+ r#"{}"#,
+ r#"{"motions":{"idle":"../private"}}"#,
+ r#"{"motions":{"idle":"C:/private"}}"#,
+ r#"{"motions":{"idle":"missing"}}"#,
+ ] {
+ fs::write(root.path().join("config.jsonc"), raw).unwrap();
+ assert!(
+ read_dsh_asset(root.path(), &manifest, "chat:video-pet".to_string()).is_err(),
+ "must reject {raw}"
+ );
+ }
+ fs::write(
+ root.path().join("config.jsonc"),
+ r#"{"motions":{"idle":"idle"}}"#,
+ )
+ .unwrap();
+ let video = fs::OpenOptions::new()
+ .write(true)
+ .open(root.path().join("webm/idle.webm"))
+ .unwrap();
+ video.set_len(PET_VIDEO_MAX_BYTES + 1).unwrap();
+ assert!(
+ read_dsh_asset(root.path(), &manifest, "chat:video-pet".to_string())
+ .unwrap_err()
+ .starts_with("PET_ASSET_INVALID:")
+ );
+ video.set_len(0).unwrap();
+ assert!(
+ read_dsh_asset(root.path(), &manifest, "chat:video-pet".to_string())
+ .unwrap_err()
+ .starts_with("PET_ASSET_INVALID:")
+ );
+ let config = fs::OpenOptions::new()
+ .write(true)
+ .open(root.path().join("config.jsonc"))
+ .unwrap();
+ config.set_len(PET_CONFIG_MAX_BYTES + 1).unwrap();
+ assert!(
+ read_dsh_asset(root.path(), &manifest, "chat:video-pet".to_string())
+ .unwrap_err()
+ .starts_with("PET_CONFIG_READ_FAILED:")
+ );
+ }
+
+ #[test]
+ fn dsh_preview_rejects_nonsquare_bad_header_and_oversized_gif() {
+ let root = tempfile::tempdir().unwrap();
+ dsh_fixture(root.path());
+ for bytes in [
+ b"not-a-gif-header".as_slice(),
+ b"GIF89a\x10\x00\x11\x00\x00\x00\x00",
+ b"GIF89a\x00\x00\x00\x00\x00\x00\x00",
+ b"GIF89a\x01\x10\x01\x10\x00\x00\x00",
+ ] {
+ fs::write(root.path().join("preview/preview.gif"), bytes).unwrap();
+ assert!(gif_data_url(root.path(), "preview/preview.gif")
+ .unwrap_err()
+ .starts_with("PET_PREVIEW_INVALID:"));
+ }
+ let gif = fs::OpenOptions::new()
+ .write(true)
+ .open(root.path().join("preview/preview.gif"))
+ .unwrap();
+ gif.set_len(PET_SPRITESHEET_MAX_BYTES + 1).unwrap();
+ assert!(gif_data_url(root.path(), "preview/preview.gif")
+ .unwrap_err()
+ .starts_with("PET_PREVIEW_READ_FAILED:"));
+ }
+
+ #[test]
+ fn dsh_mac_directory_requires_mov_and_checks_every_reference() {
+ let root = tempfile::tempdir().unwrap();
+ let mut manifest = dsh_fixture(root.path());
+ manifest.mac_uri_path = Some("mov".to_string());
+ manifest.ext.as_mut().unwrap().mac = Some("mov".to_string());
+ fs::create_dir(root.path().join("mov")).unwrap();
+ fs::write(root.path().join("mov/idle.mov"), b"idle-mov").unwrap();
+ assert!(
+ read_dsh_asset(root.path(), &manifest, "chat:video-pet".to_string())
+ .unwrap_err()
+ .starts_with("PET_ASSET_READ_FAILED:")
+ );
+ fs::write(root.path().join("mov/work.mov"), b"work-mov").unwrap();
+ let (asset, files) =
+ read_dsh_asset(root.path(), &manifest, "chat:video-pet".to_string()).unwrap();
+ let value = serde_json::to_value(asset).unwrap();
+ assert!(Path::new(value["uri"]["mac"].as_str().unwrap()).is_absolute());
+ assert_eq!(value["ext"]["mac"], "mov");
+ assert_eq!(files.len(), 4);
+ assert!(parse_manifest_bytes(br#"{"id":"x","kind":"dsh","configPath":"c.jsonc","uriPath":"webm","macUriPath":"mov","previewPath":"p.gif","ext":{"default":"webm","mac":"webm"}}"#).unwrap_err().starts_with("PET_MANIFEST_INVALID:"));
+ }
+
+ #[test]
+ fn dsh_manifest_rejects_mac_mov_without_mac_directory() {
+ assert!(parse_manifest_bytes(br#"{"id":"x","kind":"dsh","configPath":"config.jsonc","uriPath":"webm","previewPath":"preview/preview.gif","ext":{"default":"webm","mac":"mov"}}"#)
+ .unwrap_err().starts_with("PET_MANIFEST_INVALID:"));
+ }
+
+ #[test]
+ fn dsh_is_forbidden_in_codex_source_and_zip_import() {
+ let root = tempfile::tempdir().unwrap();
+ let manifest = dsh_fixture(root.path());
+ assert!(validate_pet_source(PetSource::Chat, &manifest).is_ok());
+ assert!(validate_pet_source(PetSource::Codex, &manifest)
+ .unwrap_err()
+ .starts_with("PET_KIND_FORBIDDEN:"));
+ let bytes = fs::read(root.path().join("pet.json")).unwrap();
+ let archive = build_archive(&[("pet.json", &bytes)]);
+ let staging = root.path().join("staging");
+ assert!(extract_pet_archive(&archive, &staging)
+ .unwrap_err()
+ .starts_with("PET_KIND_FORBIDDEN:"));
+ let legacy =
+ parse_manifest_bytes(br#"{"id":"old","spritesheetPath":"sprite.webp"}"#).unwrap();
+ assert!(validate_pet_source(PetSource::Codex, &legacy).is_ok());
+ let value = serde_json::to_value(PetAsset::Codex {
+ id: "codex:old".to_string(),
+ spritesheet: "data:image/webp;base64,eA==".to_string(),
+ sprite_version_number: 1,
+ columns: 8,
+ rows: 9,
+ })
+ .unwrap();
+ assert_eq!(
+ value,
+ serde_json::json!({"kind":"codex","id":"codex:old","spritesheet":"data:image/webp;base64,eA==","sprite_version_number":1,"columns":8,"rows":9})
+ );
+ }
+
+ #[cfg(windows)]
+ #[test]
+ fn dsh_junctioned_config_preview_and_video_cannot_escape_root() {
+ use std::os::windows::process::CommandExt;
+ let root = tempfile::tempdir().unwrap();
+ let outside = tempfile::tempdir().unwrap();
+ let mut manifest = dsh_fixture(root.path());
+ dsh_fixture(outside.path());
+ let junction = root.path().join("external");
+ let status = std::process::Command::new("cmd")
+ .args(["/C", "mklink", "/J"])
+ .arg(&junction)
+ .arg(outside.path())
+ .creation_flags(0x08000000)
+ .status()
+ .unwrap();
+ assert!(status.success(), "must create isolated junction");
+ for relative in [
+ "external/pet.json",
+ "external/config.jsonc",
+ "external/preview/preview.gif",
+ "external/webm/idle.webm",
+ ] {
+ assert!(contained_file(root.path(), relative)
+ .unwrap_err()
+ .starts_with("PET_PATH_INVALID:"));
+ }
+ for field in ["config", "preview", "video"] {
+ match field {
+ "config" => manifest.config_path = Some("external/config.jsonc".to_string()),
+ "preview" => {
+ manifest.preview_path = Some("external/preview/preview.gif".to_string())
+ }
+ "video" => manifest.uri_path = Some("external/webm".to_string()),
+ _ => unreachable!(),
+ }
+ assert!(
+ read_dsh_asset(root.path(), &manifest, "chat:video-pet".to_string())
+ .unwrap_err()
+ .starts_with("PET_PATH_INVALID:")
+ );
+ manifest = read_manifest(root.path()).unwrap();
+ }
+ fs::remove_dir(&junction).unwrap();
+ assert!(outside.path().join("pet.json").is_file());
+ }
+
+ #[cfg(unix)]
+ #[test]
+ fn dsh_symlinked_manifest_config_preview_and_video_cannot_escape_root() {
+ let root = tempfile::tempdir().unwrap();
+ let outside = tempfile::tempdir().unwrap();
+ let manifest = dsh_fixture(root.path());
+ for relative in [
+ "pet.json",
+ "config.jsonc",
+ "preview/preview.gif",
+ "webm/idle.webm",
+ ] {
+ let path = root.path().join(relative);
+ let original = fs::read(&path).unwrap();
+ let target = outside.path().join("external");
+ fs::write(&target, &original).unwrap();
+ fs::remove_file(&path).unwrap();
+ std::os::unix::fs::symlink(&target, &path).unwrap();
+ assert!(contained_file(root.path(), relative)
+ .unwrap_err()
+ .starts_with("PET_PATH_INVALID:"));
+ if relative == "pet.json" {
+ assert!(read_manifest(root.path())
+ .unwrap_err()
+ .starts_with("PET_PATH_INVALID:"));
+ } else {
+ assert!(
+ read_dsh_asset(root.path(), &manifest, "chat:video-pet".to_string())
+ .unwrap_err()
+ .starts_with("PET_PATH_INVALID:")
+ );
+ }
+ fs::remove_file(&path).unwrap();
+ fs::write(path, original).unwrap();
+ }
+ }
+
#[test]
fn extraction_rejects_traversal_before_creating_staging() {
let archive = build_archive(&[
diff --git a/src-tauri/src/bridge/preset_pet.rs b/src-tauri/src/bridge/preset_pet.rs
index e3dd2530..b4d3ac64 100644
--- a/src-tauri/src/bridge/preset_pet.rs
+++ b/src-tauri/src/bridge/preset_pet.rs
@@ -5,15 +5,25 @@
//! 当前激活 id 取到条目后直连远端素材播放(macOS 用 `uri.mac` / `ext.mac`
//! 指向 HEVC-with-Alpha 的 `.mov` 素材:WKWebView 不认 VP9-alpha WebM)。
//!
-//! 于是本模块只剩两件事,全部与「下载/解压/安装」无关:
-//! 1. 从资源清单取 `pets.built-in`;
-//! 2. 校验形状(id 安全 + 唯一、地址非空、kind 合法)后原样交给前端。
+//! 内置清单与用户登记的远端条目合并返回;store 只持久化资源地址与元信息。
use std::collections::HashSet;
+use std::sync::{Mutex, OnceLock};
use tauri::AppHandle;
+use tauri_plugin_store::StoreExt;
+
+const REMOTE_PET_CATALOG_KEY: &str = "remote_pet_catalog";
use crate::config::manifest::{self, PresetPetSpec};
+/// 清单条目 + 是否由用户登记:只有登记来的条目能在设置页删除,内置条目不可删。
+#[derive(Debug, Clone, serde::Serialize)]
+pub struct PresetPetEntry {
+ #[serde(flatten)]
+ pub spec: PresetPetSpec,
+ pub remote: bool,
+}
+
/// 预设 id 是否安全(直接进入设置持久化与命令参数,只允许 ASCII 字母数字与 `-`/`_`)。
pub(crate) fn safe_preset_id(id: &str) -> bool {
!id.is_empty()
@@ -25,13 +35,171 @@ pub(crate) fn safe_preset_id(id: &str) -> bool {
/// 读取并校验清单。任何形状问题都返回带 `PET_PRESET_CATALOG_*` 前缀的错误,不做静默兜底。
pub fn read_preset_catalog(app: &AppHandle) -> Result<Vec<PresetPetSpec>, String> {
+ Ok(read_preset_entries(app)?
+ .into_iter()
+ .map(|entry| entry.spec)
+ .collect())
+}
+
+/// 读取清单并标出每个条目的来源;内置在前,登记的在后,与合并顺序一致。
+fn read_preset_entries(app: &AppHandle) -> Result<Vec<PresetPetEntry>, String> {
let manifest = manifest::read(app)
.ok_or_else(|| "PET_PRESET_CATALOG_MISSING: manifest.jsonc was not found".to_string())?;
- let catalog = manifest.pets.built_in;
+ let store = app
+ .store(crate::config::store_dat_file_name())
+ .map_err(|error| format!("PET_REMOTE_STORE_FAILED: {error}"))?;
+ let mut entries: Vec<PresetPetEntry> = manifest
+ .pets
+ .built_in
+ .into_iter()
+ .map(|spec| PresetPetEntry {
+ spec,
+ remote: false,
+ })
+ .collect();
+ entries.extend(
+ remote_catalog(store.get(REMOTE_PET_CATALOG_KEY))?
+ .into_iter()
+ .map(|spec| PresetPetEntry { spec, remote: true }),
+ );
+ let catalog: Vec<PresetPetSpec> = entries.iter().map(|entry| entry.spec.clone()).collect();
+ validate_catalog(&catalog)?;
+ Ok(entries)
+}
+
+fn pet_catalog_lock() -> &'static Mutex<()> {
+ static LOCK: OnceLock<Mutex<()>> = OnceLock::new();
+ LOCK.get_or_init(|| Mutex::new(()))
+}
+
+/// 覆写登记清单;写盘失败时恢复写前的内存值(无此键则删除),避免内存与磁盘分叉。
+fn write_remote_catalog(app: &AppHandle, catalog: Vec<PresetPetSpec>) -> Result<(), String> {
+ let store = app
+ .store(crate::config::store_dat_file_name())
+ .map_err(|error| format!("PET_REMOTE_STORE_FAILED: {error}"))?;
+ let previous = store.get(REMOTE_PET_CATALOG_KEY);
+ store.set(
+ REMOTE_PET_CATALOG_KEY,
+ serde_json::to_value(&catalog)
+ .map_err(|error| format!("PET_REMOTE_CATALOG_INVALID: {error}"))?,
+ );
+ if let Err(error) = store.save() {
+ match previous {
+ Some(previous) => store.set(REMOTE_PET_CATALOG_KEY, previous),
+ None => {
+ store.delete(REMOTE_PET_CATALOG_KEY);
+ }
+ }
+ return Err(format!("PET_REMOTE_STORE_FAILED: {error}"));
+ }
+ Ok(())
+}
+
+fn remote_catalog(value: Option<serde_json::Value>) -> Result<Vec<PresetPetSpec>, String> {
+ let catalog: Vec<PresetPetSpec> = match value {
+ Some(value) => serde_json::from_value(value)
+ .map_err(|error| format!("PET_REMOTE_CATALOG_INVALID: {error}"))?,
+ None => Vec::new(),
+ };
validate_catalog(&catalog)?;
Ok(catalog)
}
+pub(super) fn register_remote_pet(
+ app: &AppHandle,
+ spec: PresetPetSpec,
+) -> Result<PresetPetSpec, String> {
+ let _guard = pet_catalog_lock()
+ .lock()
+ .unwrap_or_else(|error| error.into_inner());
+ let store = app
+ .store(crate::config::store_dat_file_name())
+ .map_err(|error| format!("PET_REMOTE_STORE_FAILED: {error}"))?;
+ let mut registered = remote_catalog(store.get(REMOTE_PET_CATALOG_KEY))?;
+ ensure_new_pet(&read_preset_catalog(app)?, &spec)?;
+ registered.push(spec.clone());
+ write_remote_catalog(app, registered)?;
+ Ok(spec)
+}
+
+/// 反注册用户登记的远端条目;内置条目不在登记清单里,删不到即报错。
+pub(super) fn unregister_remote_pet(app: &AppHandle, id: &str) -> Result<(), String> {
+ let _guard = pet_catalog_lock()
+ .lock()
+ .unwrap_or_else(|error| error.into_inner());
+ let store = app
+ .store(crate::config::store_dat_file_name())
+ .map_err(|error| format!("PET_REMOTE_STORE_FAILED: {error}"))?;
+ let mut registered = remote_catalog(store.get(REMOTE_PET_CATALOG_KEY))?;
+ drop_registered(&mut registered, id)?;
+ write_remote_catalog(app, registered)
+}
+
+pub(super) fn update_remote_pet(
+ app: &AppHandle,
+ spec: PresetPetSpec,
+) -> Result<PresetPetSpec, String> {
+ let _guard = pet_catalog_lock()
+ .lock()
+ .unwrap_or_else(|error| error.into_inner());
+ let store = app
+ .store(crate::config::store_dat_file_name())
+ .map_err(|error| format!("PET_REMOTE_STORE_FAILED: {error}"))?;
+ let mut registered = remote_catalog(store.get(REMOTE_PET_CATALOG_KEY))?;
+ replace_registered(&mut registered, &spec)?;
+ write_remote_catalog(app, registered)?;
+ Ok(spec)
+}
+
+fn replace_registered(catalog: &mut [PresetPetSpec], spec: &PresetPetSpec) -> Result<(), String> {
+ let index = catalog
+ .iter()
+ .position(|item| item.id == spec.id)
+ .ok_or_else(|| format!("PET_NOT_FOUND: preset {} is not registered", spec.id))?;
+ ensure_new_pet(
+ &catalog
+ .iter()
+ .filter(|item| item.id != spec.id)
+ .cloned()
+ .collect::<Vec<_>>(),
+ spec,
+ )?;
+ catalog[index] = spec.clone();
+ Ok(())
+}
+
+fn drop_registered(catalog: &mut Vec<PresetPetSpec>, id: &str) -> Result<(), String> {
+ if !catalog.iter().any(|spec| spec.id == id) {
+ return Err(format!("PET_NOT_FOUND: preset {id} is not registered"));
+ }
+ catalog.retain(|spec| spec.id != id);
+ Ok(())
+}
+
+fn ensure_new_pet(catalog: &[PresetPetSpec], spec: &PresetPetSpec) -> Result<(), String> {
+ validate_catalog(std::slice::from_ref(spec))?;
+ if catalog.iter().any(|item| {
+ item.id == spec.id
+ || item.config == spec.config
+ || match (
+ super::pet::pet_repository_revision(item),
+ super::pet::pet_repository_revision(spec),
+ ) {
+ (Ok((owner, name, _)), Ok((other_owner, other_name, _))) => {
+ owner.eq_ignore_ascii_case(&other_owner)
+ && name.eq_ignore_ascii_case(&other_name)
+ }
+ _ => false,
+ }
+ }) {
+ return Err(format!(
+ "PET_ALREADY_IMPORTED: pet {} or repository is already registered",
+ spec.id
+ ));
+ }
+ Ok(())
+}
+
fn validate_catalog(catalog: &[PresetPetSpec]) -> Result<(), String> {
let mut ids = HashSet::new();
for spec in catalog {
@@ -73,14 +241,133 @@ fn validate_catalog(catalog: &[PresetPetSpec]) -> Result<(), String> {
/// 列出预设宠物清单(前端按当前激活 id 自行取用;条目即 `<Pet>` 的渲染参数)。
#[tauri::command]
-pub fn list_preset_pets(app: AppHandle) -> Result<Vec<PresetPetSpec>, String> {
- read_preset_catalog(&app)
+pub fn list_preset_pets(app: AppHandle) -> Result<Vec<PresetPetEntry>, String> {
+ read_preset_entries(&app)
}
#[cfg(test)]
mod tests {
use super::*;
+ #[test]
+ fn entry_serialization_flattens_the_spec_and_marks_registered_pets() {
+ // 前端 PresetPetItem 直接展开这些字段;`remote` 决定卡片上有没有删除按钮,
+ // 嵌套成 spec 子对象就会静默丢掉这个判定。
+ let spec: PresetPetSpec = serde_json::from_str(
+ r#"{"id":"remote","name":"Remote","config":"https://e/c","uri":{"default":"https://e/w"}}"#,
+ )
+ .unwrap();
+ let value = serde_json::to_value(PresetPetEntry { spec, remote: true }).unwrap();
+ assert_eq!(value["id"], "remote");
+ assert_eq!(value["name"], "Remote");
+ assert_eq!(value["remote"], true);
+ assert!(value.get("spec").is_none());
+ }
+
+ #[test]
+ fn updates_replace_only_registered_entries_and_preserve_original_on_invalid_spec() {
+ let original: PresetPetSpec = serde_json::from_str(
+ r#"{"id":"remote","name":"Old","config":"https://e/old","uri":{"default":"https://e/old/webm"}}"#,
+ ).unwrap();
+ let mut catalog = vec![original.clone()];
+ let mut updated = original.clone();
+ updated.name.clear();
+ assert!(replace_registered(&mut catalog, &updated).is_err());
+ assert_eq!(catalog[0].name, "Old");
+ updated.name = "New".into();
+ updated.id = "builtin".into();
+ assert!(replace_registered(&mut catalog, &updated)
+ .unwrap_err()
+ .starts_with("PET_NOT_FOUND:"));
+ assert_eq!(catalog[0].name, "Old");
+ updated.id = "remote".into();
+ updated.config = "https://e/new".into();
+ assert_eq!(replace_registered(&mut catalog, &updated), Ok(()));
+ assert_eq!(catalog[0].config, "https://e/new");
+ assert_eq!(catalog[0].name, "New");
+ assert_eq!(catalog.len(), 1);
+ }
+
+ #[test]
+ fn unregister_drops_only_registered_ids_and_rejects_built_in_ones() {
+ let spec = |id: &str| -> PresetPetSpec {
+ serde_json::from_str(&format!(
+ r#"{{"id":"{id}","name":"Pet","config":"https://e/c","uri":{{"default":"https://e/w"}}}}"#
+ ))
+ .unwrap()
+ };
+ let mut catalog = vec![spec("remote")];
+ assert_eq!(
+ drop_registered(&mut catalog, "builtin"),
+ Err("PET_NOT_FOUND: preset builtin is not registered".into())
+ );
+ assert_eq!(catalog.len(), 1);
+ assert_eq!(drop_registered(&mut catalog, "remote"), Ok(()));
+ assert!(catalog.is_empty());
+ }
+
+ #[test]
+ fn remote_catalog_roundtrip_preserves_urls_and_rejects_duplicate_id_or_repository() {
+ let spec: PresetPetSpec = serde_json::from_value(serde_json::json!({
+ "id": "remote", "name": "Remote", "kind": "dsh",
+ "config": "https://raw.githubusercontent.com/o/r/HEAD/config.jsonc",
+ "image": "https://raw.githubusercontent.com/o/r/HEAD/preview/preview.gif",
+ "uri": {"default": "https://raw.githubusercontent.com/o/r/HEAD/webm"},
+ "ext": {"default": "webm", "mac": "webm"}
+ }))
+ .unwrap();
+ let value = serde_json::to_value(vec![spec.clone()]).unwrap();
+ let catalog = remote_catalog(Some(value.clone())).unwrap();
+ assert_eq!(serde_json::to_value(&catalog).unwrap(), value);
+ assert_eq!(remote_catalog(None).unwrap().len(), 0);
+ assert!(ensure_new_pet(&catalog, &spec)
+ .unwrap_err()
+ .starts_with("PET_ALREADY_IMPORTED:"));
+ let mut renamed = spec.clone();
+ renamed.id = "renamed".into();
+ assert!(ensure_new_pet(&catalog, &renamed)
+ .unwrap_err()
+ .starts_with("PET_ALREADY_IMPORTED:"));
+ renamed.config = "https://raw.githubusercontent.com/O/R/0123456789abcdef0123456789abcdef01234567/new/config.jsonc".into();
+ assert!(ensure_new_pet(&catalog, &renamed)
+ .unwrap_err()
+ .starts_with("PET_ALREADY_IMPORTED:"));
+ renamed.config = "https://raw.githubusercontent.com/o/other/HEAD/config.jsonc".into();
+ assert_eq!(ensure_new_pet(&catalog, &renamed), Ok(()));
+ assert!(remote_catalog(Some(serde_json::json!({})))
+ .unwrap_err()
+ .starts_with("PET_REMOTE_CATALOG_INVALID:"));
+ }
+
+ #[test]
+ fn remote_catalog_persists_in_an_isolated_store_without_config_content() {
+ let root = tempfile::tempdir().unwrap();
+ let app = tauri::test::mock_builder()
+ .plugin(tauri_plugin_store::Builder::default().build())
+ .build(tauri::test::mock_context(tauri::test::noop_assets()))
+ .unwrap();
+ let path = root.path().join("pets.json");
+ let store = app.store(&path).unwrap();
+ let catalog = serde_json::json!([{
+ "id": "remote", "name": "Remote", "kind": "dsh",
+ "config": "https://raw.githubusercontent.com/o/r/HEAD/config.jsonc",
+ "uri": {"default": "https://raw.githubusercontent.com/o/r/HEAD/webm"}
+ }]);
+ store.set(REMOTE_PET_CATALOG_KEY, catalog.clone());
+ store.save().unwrap();
+ let persisted: serde_json::Value =
+ serde_json::from_slice(&std::fs::read(path).unwrap()).unwrap();
+ assert_eq!(persisted[REMOTE_PET_CATALOG_KEY], catalog);
+ assert_eq!(
+ remote_catalog(Some(persisted[REMOTE_PET_CATALOG_KEY].clone())).unwrap()[0].id,
+ "remote"
+ );
+ assert!(persisted[REMOTE_PET_CATALOG_KEY][0]
+ .get("motions")
+ .is_none());
+ assert_eq!(std::fs::read_dir(root.path()).unwrap().count(), 1);
+ }
+
fn shipped_catalog() -> Vec<PresetPetSpec> {
manifest::read_at(
&std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("resources/manifest.jsonc"),
diff --git a/src-tauri/src/config/manifest.rs b/src-tauri/src/config/manifest.rs
index d70ec304..5a6c84c5 100644
--- a/src-tauri/src/config/manifest.rs
+++ b/src-tauri/src/config/manifest.rs
@@ -572,7 +572,7 @@ fn join_token(root: &Path, rest: &str) -> PathBuf {
root.join(rest.replace('/', std::path::MAIN_SEPARATOR_STR))
}
-fn strip_jsonc(raw: &str) -> String {
+pub(crate) fn strip_jsonc(raw: &str) -> String {
let chars: Vec<char> = raw.chars().collect();
let mut out = String::with_capacity(raw.len());
let mut i = 0;
diff --git a/src-tauri/src/desktop/builder.rs b/src-tauri/src/desktop/builder.rs
index 6865298d..e541f1fd 100644
--- a/src-tauri/src/desktop/builder.rs
+++ b/src-tauri/src/desktop/builder.rs
@@ -1627,6 +1627,10 @@ pub fn handler() -> impl Fn(Invoke<Wry>) -> bool + Send + Sync + 'static {
crate::bridge::set_pet_ignore_cursor_events,
crate::bridge::list_pets,
crate::bridge::import_pet,
+ crate::bridge::delete_pet,
+ crate::bridge::import_pet_repository,
+ crate::bridge::check_pet_updates,
+ crate::bridge::update_pet_repository,
crate::bridge::get_pet_asset,
crate::bridge::list_preset_pets,
crate::desktop::pet_mouse::start_pet_mouse_stream,
diff --git a/src-tauri/tauri.conf.json b/src-tauri/tauri.conf.json
index e2a5b0d9..6ecc6b2c 100644
--- a/src-tauri/tauri.conf.json
+++ b/src-tauri/tauri.conf.json
@@ -12,8 +12,9 @@
"app": {
"macOSPrivateApi": true,
"security": {
- "csp": "default-src 'self'; connect-src 'self' ipc: http://ipc.localhost http://127.0.0.1:*; 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 http://127.0.0.1:*; 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:*"
+ "assetProtocol": { "enable": true, "scope": [] },
+ "csp": "default-src 'self'; connect-src 'self' asset: http://asset.localhost https://asset.localhost ipc: http://ipc.localhost http://127.0.0.1:*; img-src 'self' asset: http://asset.localhost data: blob: https://*.githubusercontent.com; media-src 'self' asset: http://asset.localhost https://asset.localhost 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' asset: http://asset.localhost https://asset.localhost ipc: http://ipc.localhost http://localhost:1420 ws://localhost:1421 http://127.0.0.1:*; img-src 'self' asset: http://asset.localhost data: blob: https://*.githubusercontent.com; media-src 'self' asset: http://asset.localhost https://asset.localhost data: blob: https://*.githubusercontent.com; style-src 'self' 'unsafe-inline'; font-src 'self' data:; script-src 'self'; frame-src http://127.0.0.1:*"
}
},
"plugins": {
diff --git a/src/hooks/use-invoke-iframe.ts b/src/hooks/use-invoke-iframe.ts
index 29214479..79481536 100644
--- a/src/hooks/use-invoke-iframe.ts
+++ b/src/hooks/use-invoke-iframe.ts
@@ -53,6 +53,10 @@ const ALLOWED_INVOKE_CMDS = new Set([
'push_pet_session',
'list_pets',
'import_pet',
+ 'delete_pet',
+ 'import_pet_repository',
+ 'check_pet_updates',
+ 'update_pet_repository',
'get_pet_asset',
'list_preset_pets',
'remote_bridge_ping',
diff --git a/src/pet/app.tsx b/src/pet/app.tsx
index 13262f4a..de888f28 100644
--- a/src/pet/app.tsx
+++ b/src/pet/app.tsx
@@ -65,7 +65,7 @@ export function App() {
size={width}
dragging={draggable.dragging}
onFling={onFling}
- cache={true}
+ cache={source.cache}
hidden={!visible}
hitboxRef={hitboxRef}
onHitboxPointerDown={draggable.onPointerDown}
diff --git a/src/pet/hooks/use-pet-source.test.ts b/src/pet/hooks/use-pet-source.test.ts
index b72dc70c..f51a5a0e 100644
--- a/src/pet/hooks/use-pet-source.test.ts
+++ b/src/pet/hooks/use-pet-source.test.ts
@@ -1,10 +1,13 @@
// @vitest-environment jsdom
+import type { DshPetConfig } from 'dsh-pet-component'
+import { clearMocks, mockConvertFileSrc } from '@tauri-apps/api/mocks'
import { act, cleanup, renderHook } from '@testing-library/react'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
-import { usePetSource } from './use-pet-source'
+import { assetSource, usePetSource } from './use-pet-source'
-const invoke = vi.hoisted(() => vi.fn())
-vi.mock('@tauri-apps/api/core', () => ({ invoke }))
+const { invoke, useListen } = vi.hoisted(() => ({ invoke: vi.fn(), useListen: vi.fn() }))
+vi.mock('@/hooks/use-listen', () => ({ useListen }))
+vi.mock('@tauri-apps/api/core', async importOriginal => ({ ...await importOriginal<typeof import('@tauri-apps/api/core')>(), invoke }))
function deferred<T>() {
let resolve!: (value: T) => void
@@ -17,7 +20,7 @@ function deferred<T>() {
}
function asset(id: string) {
- return { id, spritesheet: `data:image/png;base64,${id}`, sprite_version_number: 2, columns: 8, rows: 9 }
+ return { kind: 'codex' as const, id, spritesheet: `data:image/png;base64,${id}`, sprite_version_number: 2, columns: 8, rows: 9 }
}
beforeEach(() => {
@@ -27,9 +30,119 @@ beforeEach(() => {
afterEach(() => {
cleanup()
vi.restoreAllMocks()
+ clearMocks()
+})
+
+describe('local pet asset sources', () => {
+ it.each(['windows', 'macos'] as const)('converts local directories containing Chinese and spaces into %s asset URL templates', (os) => {
+ mockConvertFileSrc(os)
+ const config: DshPetConfig = { animations: { idle: ['待机 呼吸'] } }
+ const source = assetSource({
+ kind: 'dsh',
+ id: 'chat:video',
+ config,
+ uri: { default: 'E:\\宠物 space\\webm', mac: '/宠物 space/mov' },
+ ext: { default: 'webm', mac: 'mov' },
+ size: 260,
+ })
+ const prefix = os === 'windows' ? 'http://asset.localhost/' : 'asset://localhost/'
+ expect(source).toEqual({
+ kind: 'dsh',
+ config,
+ uri: {
+ default: `${prefix}E%3A%5C%E5%AE%A0%E7%89%A9%20space%5Cwebm/{name}.{ext}`,
+ mac: `${prefix}%2F%E5%AE%A0%E7%89%A9%20space%2Fmov/{name}.{ext}`,
+ },
+ ext: { default: 'webm', mac: 'mov' },
+ aspect: 9 / 16,
+ width: 260,
+ cache: false,
+ })
+ expect(source.config).toBe(config)
+ })
+
+ it('preserves default-only local paths and default video width', () => {
+ mockConvertFileSrc('windows')
+ expect(assetSource({ kind: 'dsh', id: 'chat:video', config: {}, uri: { default: 'E:/pets/webm' }, ext: { default: 'webm' } })).toEqual({
+ kind: 'dsh',
+ config: {},
+ uri: { default: 'http://asset.localhost/E%3A%2Fpets%2Fwebm/{name}.{ext}' },
+ ext: { default: 'webm' },
+ aspect: 9 / 16,
+ width: 220,
+ cache: false,
+ })
+ })
+
+ it.each([1, 2, 99])('preserves Codex data URLs and snake_case atlas version %s', (version) => {
+ expect(assetSource({ ...asset('codex:atlas'), sprite_version_number: version })).toEqual({
+ kind: 'codex',
+ config: { spriteVersionNumber: version === 1 ? 1 : 2, columns: 8, rows: 9 },
+ uri: 'data:image/png;base64,codex:atlas',
+ aspect: 208 / 192,
+ width: 220,
+ cache: true,
+ })
+ })
})
describe('pet source requests', () => {
+ it('routes qualified chat video IDs through get_pet_asset without loading presets', async () => {
+ mockConvertFileSrc('windows')
+ const config: DshPetConfig = { motions: { idle: '待机' } }
+ invoke.mockResolvedValue({ kind: 'dsh', id: 'chat:video', config, uri: { default: 'E:/pets/webm' }, ext: { default: 'webm' } })
+ const { result } = renderHook(() => usePetSource('chat:video'))
+ await act(async () => {})
+ expect(invoke).toHaveBeenCalledExactlyOnceWith('get_pet_asset', { id: 'chat:video' })
+ expect(result.current).toEqual({
+ source: {
+ kind: 'dsh',
+ config,
+ uri: { default: 'http://asset.localhost/E%3A%2Fpets%2Fwebm/{name}.{ext}' },
+ ext: { default: 'webm' },
+ aspect: 9 / 16,
+ width: 220,
+ cache: false,
+ },
+ error: null,
+ })
+ })
+
+ it('keeps remote presets cached with their original URL and video geometry', async () => {
+ invoke.mockResolvedValue([{ id: 'preset', name: 'Preset', config: 'https://cdn/config.jsonc', uri: { default: 'https://cdn/webm' } }])
+ const { result } = renderHook(() => usePetSource('preset'))
+ await act(async () => {})
+ expect(invoke).toHaveBeenCalledExactlyOnceWith('list_preset_pets')
+ expect(result.current.source).toEqual({
+ kind: 'dsh',
+ config: 'https://cdn/config.jsonc',
+ uri: { default: 'https://cdn/webm' },
+ ext: undefined,
+ aspect: 9 / 16,
+ width: 220,
+ cache: true,
+ })
+ })
+
+ it('reloads an active preset on catalog updates with new commit URLs but ignores unrelated pets', async () => {
+ const spec = { id: 'pet', name: 'Pet', config: 'https://raw/old/config.jsonc', uri: { default: 'https://raw/old/webm' } }
+ invoke.mockResolvedValueOnce([spec]).mockResolvedValueOnce([{ ...spec, config: 'https://raw/new/config.jsonc', uri: { default: 'https://raw/new/webm' } }])
+ const { result } = renderHook(() => usePetSource('pet'))
+ await act(async () => {})
+ const handler = useListen.mock.calls.at(-1)![1]
+ expect(useListen.mock.calls.at(-1)![0]).toBe('pet://catalog')
+ await act(async () => {
+ handler({ payload: 'other' })
+ })
+ expect(invoke).toHaveBeenCalledTimes(1)
+ await act(async () => {
+ handler({ payload: 'pet' })
+ })
+ expect(invoke.mock.calls).toEqual([['list_preset_pets'], ['list_preset_pets']])
+ expect(result.current.source?.config).toBe('https://raw/new/config.jsonc')
+ expect(result.current.source?.uri).toEqual({ default: 'https://raw/new/webm' })
+ })
+
it.each(['resolve', 'reject'] as const)('preserves the current pet when an older request finishes with %s', async (completion) => {
const old = deferred<ReturnType<typeof asset>>()
invoke.mockImplementation((command, args) => command === 'log_frontend' ? Promise.resolve() : args.id === 'codex:old' ? old.promise : Promise.resolve(asset(args.id)))
diff --git a/src/pet/hooks/use-pet-source.ts b/src/pet/hooks/use-pet-source.ts
index dccd3ad4..a0f06b3c 100644
--- a/src/pet/hooks/use-pet-source.ts
+++ b/src/pet/hooks/use-pet-source.ts
@@ -1,7 +1,8 @@
-import type { CodexPetConfig, PetConfig } from 'dsh-pet-component'
+import type { CodexPetConfig, DshPetConfig, PetConfig } from 'dsh-pet-component'
import { useUnmount, useWatch } from '@reause/core'
-import { invoke } from '@tauri-apps/api/core'
+import { convertFileSrc, invoke } from '@tauri-apps/api/core'
import { useRef, useState } from 'react'
+import { useListen } from '@/hooks/use-listen'
import { PET_CODEX_ASPECT, PET_DSH_ASPECT } from '../constants'
import { reportPetIssue } from '../utils/log'
@@ -29,27 +30,29 @@ interface PresetPetItem {
ext?: { default: string, mac?: string }
}
-/** 导入的 Codex 宠物资源(Rust `get_pet_asset`,精灵图以 data URL 直接渲染)。 */
-interface PetAsset {
+type PetAsset = {
+ kind: 'codex'
id: string
spritesheet: string
sprite_version_number: number
columns: number
rows: number
+} | {
+ kind: 'dsh'
+ id: string
+ config: DshPetConfig
+ uri: { default: string, mac?: string }
+ ext: { default: string, mac?: string }
+ size?: 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 }
+ cache: boolean
/** 画布比例(高 / 宽),窗口尺寸推导用。 */
aspect: number
/** 100% 档位的渲染宽度 px。 */
@@ -75,12 +78,29 @@ function presetSource(item: PresetPetItem): PetSource {
config: item.config,
uri: item.uri,
ext: item.ext,
+ cache: true,
aspect: kind === 'codex' ? PET_CODEX_ASPECT : PET_DSH_ASPECT,
width: item.size ?? 220,
}
}
-function assetSource(asset: PetAsset): PetSource {
+export function assetSource(asset: PetAsset): PetSource {
+ if (asset.kind === 'dsh') {
+ const uri: PetSource['uri'] = {
+ default: `${convertFileSrc(asset.uri.default)}/{name}.{ext}`,
+ }
+ if (asset.uri.mac !== undefined)
+ uri.mac = `${convertFileSrc(asset.uri.mac)}/{name}.{ext}`
+ return {
+ kind: 'dsh',
+ config: asset.config,
+ uri,
+ ext: asset.ext,
+ cache: false,
+ aspect: PET_DSH_ASPECT,
+ width: asset.size ?? 220,
+ }
+ }
const config: CodexPetConfig = {
spriteVersionNumber: asset.sprite_version_number === 1 ? 1 : 2,
columns: asset.columns,
@@ -90,6 +110,7 @@ function assetSource(asset: PetAsset): PetSource {
kind: 'codex',
config,
uri: asset.spritesheet,
+ cache: true,
aspect: PET_CODEX_ASPECT,
width: 220,
}
@@ -113,12 +134,18 @@ export function usePetSource(activePet: string): PetSourceState {
error: string | null
} | null>(null)
+ const [catalogRevision, setCatalogRevision] = useState(0)
+ useListen<string>('pet://catalog', ({ payload }) => {
+ if (payload === activePet)
+ setCatalogRevision(revision => revision + 1)
+ })
+
const requestRef = useRef(0)
useUnmount(() => {
requestRef.current++
})
- useWatch(activePet, (id) => {
+ useWatch([activePet, catalogRevision], ([id]) => {
const request = ++requestRef.current
if (id === '')
return