DeepSeek Harness Tauri 桌面版 | Only 8mb installer, zero environment setup, preset plugins, Windows / macOS / Linux.
feat(pet): support dsh-pet assets/config.jsonc protocol in dsh-tauri-pet
hairyfb5b51ce818c2
diff --git a/docs/plugins/pet.todo.md b/docs/plugins/pet.todo.mdindex 15d59d40..99f63d15 100644--- a/docs/plugins/pet.todo.md+++ b/docs/plugins/pet.todo.md@@ -153,6 +153,31 @@ BongoCat 是窗口行为基准,不是完整交互基准。它在 mousedown 立## 4. 当前实现检查点+### 4.0 最近完成(feat/pet-reapply,config.jsonc 协议支持)++- 内置协议配置文件已落地:`packages/dsh-tauri-pet/assets/config.jsonc`,结构对齐+ 子仓库 `source/dsh-pet/dsh-pet/assets/config.jsonc`(animations / animationWeights /+ pets / physics / eventsRefreshSec),动画池条目引用内置资产键白名单+ (`BUILTIN_ASSET_NAMES` 的 key),由 `package.json#files: assets` 随插件部署。+- Rust 新增 `get_builtin_pet_config` 命令:从已部署的 `dsh-tauri-pet/assets/config.jsonc`+ 限量读取(256 KiB),`strip_jsonc` 剥注释(字符串字面量内不误剥),`serde_json` 解析,+ `validate_builtin_pet_config` 校验协议形状(pets/animations 各池/moves/categories/events/+ animationWeights),所有池条目必须命中内置资产键白名单,错误统一+ `PET_BUILTIN_CONFIG_INVALID:` 前缀,不做静默兜底;已注册进 builder 命令表与+ iframe invoke 白名单,插件客户端 `fetchBuiltinPetConfig()` 可调用。+- pet WebView:新增纯函数模块 `src/pet/pet-config.ts`(rollKind / pick /+ pickWeightedCategory / pickCategoryAction / poolEntryToStatus,移植 dsh-pet+ src/shared/pickers.ts)并配 9 条单测;`src/pet/components/pet.tsx` 启动加载配置,+ 待机链按协议权重掷骰(move 命中因 DSH 无自动漫游保持待机),点击回应改从 clicks 池+ 抽取,池条目经 `toAdHocStatus` 归一化(wave→waving)且拒绝拖拽/方向专用状态。+- 验证:`pnpm typecheck`、`pnpm --filter dsh-tauri-pet typecheck/build`、+ `eslint src/pet packages/dsh-tauri-pet/src/client --max-warnings=0` 零 warning、+ `vitest run src/pet/pet-config.test.ts` 9/9、`cargo check --lib`、+ `cargo test bridge::pet::tests --lib` 14/14、`pnpm build` 全部通过。+ 完整 `pnpm test -- --run` 仅 3 条失败,全部来自 `test/plugin-resource-closure.test.ts`+ (读取 `src-tauri/resources/node_modules` 部署产物,fresh worktree 不含该生成目录,+ 源 checkout 下通过,与本次改动无关)。+### 4.1 已完成并应保留- 三个参考仓库已加入 `source/*` 子模块。diff --git a/packages/dsh-tauri-pet/README.md b/packages/dsh-tauri-pet/README.mdindex 42095a64..412e33b8 100644--- a/packages/dsh-tauri-pet/README.md+++ b/packages/dsh-tauri-pet/README.md@@ -35,6 +35,8 @@ Chat 宠物安装在 `${DSH_HOME:-$HOME/.dsh}/pets`,Codex 宠物安装在| `set_pet_size` | 持久化 50–200% 的大小 || `list_pets` | 按 `source` 列出 Chat 或 Codex 宠物 || `get_pet_asset` | 获取指定宠物的完整 8×11 spritesheet data URL |+| `get_builtin_pet_assets` | 返回内置媒体(WebM/GIF)的 URL manifest |+| `get_builtin_pet_config` | 返回内置协议配置(`assets/config.jsonc`,dsh-pet 协议子集) || `import_pet` | 导入 Codex `.zip` 资源包 || `set_pet_activity` | 更新 `idle`、`turn`、`moving-left`、`moving-right`、`waving`、`waiting`、`running`、`review` 或 `failed` |diff --git a/packages/dsh-tauri-pet/assets/config.jsonc b/packages/dsh-tauri-pet/assets/config.jsoncnew file mode 100644index 00000000..c9ee06d4--- /dev/null+++ b/packages/dsh-tauri-pet/assets/config.jsonc@@ -0,0 +1,91 @@+// dsh-tauri-pet 内置桌宠配置(JSONC:允许 // 与 /* */ 注释)。+// 协议对齐子仓库 source/dsh-pet/dsh-pet/assets/config.jsonc(animations /+// animationWeights / pets / physics / eventsRefreshSec / events),唯一差异:+// 动画池条目引用的是 dsh-tauri-pet 内置资产键(src-tauri/src/bridge/pet.rs 的+// BUILTIN_ASSET_NAMES:idle / turn / move / drag / wave / waiting / running /+// review / failed / bubble / fallback),而不是任意 webm 文件名——运行时资产由+// Rust 从内置插件目录白名单加载,池里写了不存在的键会在加载层显式报错。+{+ // ===================== 宠物列表(内置宠物唯一来源) =====================+ // id = BUILTIN_PET_ID(maid-deepseek-whale);size 为舞台宽度(px),+ // 高度自动 = size × 9/16。DSH 桌宠为独立透明置顶窗口,display 固定 desktop。+ "pets": [+ {+ "name": "Maid DeepSeek Whale",+ "id": "maid-deepseek-whale",+ "size": 220,+ "balanceEnabled": false,+ "whisperEnabled": false,+ "display": "desktop",+ "position": {+ "corner": "bottom-right",+ "marginX": 24,+ "marginY": 16+ }+ }+ ],++ // ===================== 动作动画池配置 =====================+ // 与 dsh-pet 协议同构;每项是内置资产键数组(见上方说明),+ // 数组可放多个同档动画,运行时等概率抽取(当前内置资产每档只有 1 个)。+ "animations": {+ // 待机动画池(循环播放)+ "idle": ["idle"],+ // 转向动画池(播完翻转朝向的一次性动画)+ "turn": ["turn"],+ // 拖拽动画池(被无形抓起悬空的姿势)+ "drag": ["drag"],+ // 点击回应动画池(点按宠物时随机抽 1 个)+ "clicks": ["wave"],+ // 移动动画池:default 为通用参数,actions 可覆盖部分参数+ // (DSH 已移除自动漫游,move 权重仅保留协议字段,运行时不再主动移动窗口)+ "moves": {+ "default": { "minDist": 60, "maxDist": 240, "margin": 20, "leadSec": 2, "tailSec": 2 },+ "actions": [+ { "name": "move" }+ ]+ },+ // 随机动作分类池:weight 为该分类出现权重;抽中 action 时按权重选分类,+ // 再从分类 actions 中等概率抽一个播放一次。+ "categories": [+ {+ "id": "小动作",+ "weight": 80,+ "actions": ["wave", "bubble", "turn"]+ }+ ],+ // 事件动画:不进随机链,只由代码显式触发(DSH 当前保留协议字段,+ // 会话状态动画由 session:* 事件直接驱动,不使用 events 池)。+ "events": {+ "balance": ["bubble"],+ "whisper": ["bubble"]+ }+ },++ // ===================== 事件触发周期(协议保留字段) =====================+ "eventsRefreshSec": {+ "balance": 1800,+ "whisper": 300+ },++ // ===================== 动画链顶层权重 =====================+ // idle/turn/move 权重之和 + 上面各分类 weight 合计 = 100。+ // 当前:10 + 5 + 5 + 80 = 100。抽中 move 时因 DSH 无自动漫游而保持待机。+ "animationWeights": {+ "idle": 10,+ "turn": 5,+ "move": 5+ },++ // ===================== 宠物物理(协议保留字段) =====================+ // DSH 桌宠使用系统原生窗口拖拽(startDragging),不使用抛掷物理;+ // 字段保留与 dsh-pet 默认值一致,便于未来对齐交互。+ "physics": {+ "gravity": 1400,+ "restitution": 0.78,+ "groundFriction": 2.5,+ "ceilingBounce": true,+ "throwPower": 1.0,+ "petCollision": false+ }+}diff --git a/packages/dsh-tauri-pet/src/client/constants/index.ts b/packages/dsh-tauri-pet/src/client/constants/index.tsindex 3f3cf34a..0ae94957 100644--- a/packages/dsh-tauri-pet/src/client/constants/index.ts+++ b/packages/dsh-tauri-pet/src/client/constants/index.ts@@ -23,6 +23,7 @@ export const CMD_IMPORT_PET = 'import_pet'export const CMD_PUSH_PET_SESSION = 'push_pet_session'export const CMD_GET_PET_ASSET = 'get_pet_asset'export const CMD_GET_BUILTIN_PET_ASSETS = 'get_builtin_pet_assets'+export const CMD_GET_BUILTIN_PET_CONFIG = 'get_builtin_pet_config'export const BUILTIN_PET_ID = 'maid-deepseek-whale'export const BUILTIN_PET_NAME = 'Maid DeepSeek Whale'export const BUILTIN_PET_DESC_ZH = '一只小小的七比蓝头发的鲸鱼女仆Codex宠物,穿着海军蓝裙子,白色褶边,蓝眼睛,侧鳍和鲸鱼尾巴。'diff --git a/packages/dsh-tauri-pet/src/client/service/pet.ts b/packages/dsh-tauri-pet/src/client/service/pet.tsindex 83d3ac66..2663fb50 100644--- a/packages/dsh-tauri-pet/src/client/service/pet.ts+++ b/packages/dsh-tauri-pet/src/client/service/pet.ts@@ -1,7 +1,8 @@-import type { PetAsset, PetListItem, PetSource, PetStatus } from '../types'+import type { PetAsset, PetConfig, PetListItem, PetSource, PetStatus } from '../types'import { invokeBridgedTauri } from 'dsh-tauri/client'import {CMD_GET_BUILTIN_PET_ASSETS,+ CMD_GET_BUILTIN_PET_CONFIG,CMD_GET_PET_ASSET,CMD_GET_PET_STATUS,CMD_HIDE_PET,@@ -61,3 +62,8 @@ export function pushPetSession(export function fetchBuiltinPetAssets(): Promise<{ assets: Record<string, string> }> {return invokeBridgedTauri<{ assets: Record<string, string> }>(CMD_GET_BUILTIN_PET_ASSETS)}++/** 内置协议配置(dsh-pet assets/config.jsonc 协议子集):动画池/权重/宠物定义。 */+export function fetchBuiltinPetConfig(): Promise<PetConfig> {+ return invokeBridgedTauri<PetConfig>(CMD_GET_BUILTIN_PET_CONFIG)+}diff --git a/packages/dsh-tauri-pet/src/client/types/index.ts b/packages/dsh-tauri-pet/src/client/types/index.tsindex bfdeedb6..82e5f744 100644--- a/packages/dsh-tauri-pet/src/client/types/index.ts+++ b/packages/dsh-tauri-pet/src/client/types/index.ts@@ -24,6 +24,26 @@ export interface PetAsset {spritesheet: string}+/** 内置协议配置(dsh-pet assets/config.jsonc 协议子集),由 Rust 校验后返回。 */+export interface PetConfig {+ pets: { id: string, name?: string, size?: number }[]+ animations: {+ idle: string[]+ turn: string[]+ drag: string[]+ clicks: string[]+ moves: {+ default: Record<string, number>+ actions: { name: string, params?: Record<string, number> }[]+ }+ categories: { id: string, weight: number, noMirror?: boolean, actions: string[] }[]+ events?: Record<string, string[]>+ }+ animationWeights: { idle: number, turn: number, move: number }+ physics?: Record<string, unknown>+ eventsRefreshSec?: Record<string, number>+}+export interface WorkspaceItem {id?: stringsessionIds?: readonly string[]diff --git a/src-tauri/src/bridge/pet.rs b/src-tauri/src/bridge/pet.rsindex fa0caab0..669a522f 100644--- a/src-tauri/src/bridge/pet.rs+++ b/src-tauri/src/bridge/pet.rs@@ -50,6 +50,13 @@ const PET_SPRITE_ROWS: u8 = 11;/// 设置变化推送给 pet 窗口的事件名;会话生命周期使用 `session:*` 事件。pub const PET_STATUS_EVENT: &str = "pet://status";+/// 内置宠物协议配置文件(JSONC):dsh-tauri-pet 包 assets/config.jsonc,+/// 结构对齐子仓库 dsh-pet 的 assets/config.jsonc(animations / animationWeights /+/// pets / physics / eventsRefreshSec)。只读、白名单限定,运行时按需解析。+const BUILTIN_CONFIG_FILE: &str = "config.jsonc";+/// 内置配置的最大体积(与清单同一档位的受限读取上限)。+const PET_CONFIG_MAX_BYTES: u64 = 256 * 1024;+#[cfg(target_os = "windows")]const BUILTIN_ASSET_ORIGIN: &str = "http://dsh-pet.localhost";#[cfg(not(target_os = "windows"))]@@ -710,6 +717,242 @@ pub fn get_builtin_pet_assets() -> BuiltinPetAssets {BuiltinPetAssets { assets }}+/// 剥除 JSONC 注释(行注释 // 与块注释 /* */),保留字符串字面量原样。+/// 与子仓库 dsh-pet host 的 stripJsonc 语义一致(不逐字复制正则,避免 URL+/// 里的 // 被误剥)。+fn strip_jsonc(src: &str) -> String {+ let bytes: Vec<char> = src.chars().collect();+ let mut out = String::with_capacity(src.len());+ let mut index = 0;+ let mut in_string = false;+ let mut escaped = false;+ while index < bytes.len() {+ let c = bytes[index];+ if in_string {+ out.push(c);+ if escaped {+ escaped = false;+ } else if c == '\\' {+ escaped = true;+ } else if c == '"' {+ in_string = false;+ }+ index += 1;+ continue;+ }+ match c {+ '"' => {+ in_string = true;+ out.push(c);+ index += 1;+ }+ '/' if index + 1 < bytes.len() && bytes[index + 1] == '/' => {+ index += 2;+ while index < bytes.len() && bytes[index] != '\n' {+ index += 1;+ }+ }+ '/' if index + 1 < bytes.len() && bytes[index + 1] == '*' => {+ index += 2;+ let mut closed = false;+ while index + 1 < bytes.len() {+ if bytes[index] == '*' && bytes[index + 1] == '/' {+ index += 2;+ closed = true;+ break;+ }+ index += 1;+ }+ if !closed {+ break;+ }+ }+ _ => {+ out.push(c);+ index += 1;+ }+ }+ }+ out+}++/// 统一内置配置校验错误前缀;detail 可以是 &str 或 String。+fn config_invalid(detail: impl Into<String>) -> String {+ format!("PET_BUILTIN_CONFIG_INVALID: {}", detail.into())+}++/// 校验内置 config.jsonc 的协议形状(子仓库 dsh-pet assets/config.jsonc 协议子集):+/// - 顶层必须含 pets(非空数组,每个有非空 id)与 animations / animationWeights;+/// - animations 必须含 idle/turn/drag/clicks 字符串池、moves(default 对象 ++/// actions 数组)、categories(id/weight/actions)、可选 events;+/// - 所有池条目(idle/turn/drag/clicks、moves.actions[].name、categories[].actions、+/// events.*)必须命中内置资产键白名单(BUILTIN_ASSET_NAMES 的 key);+/// - animationWeights 的 idle/turn/move 必须是非负数字。+/// 任一不符返回带 PET_BUILTIN_CONFIG_INVALID 前缀的错误,不做静默兜底。+fn validate_builtin_pet_config(value: &Value) -> Result<(), String> {+ let invalid = config_invalid;+ let root = value+ .as_object()+ .ok_or_else(|| invalid("config root must be an object".to_string()))?;++ let pets = root+ .get("pets")+ .and_then(Value::as_array)+ .ok_or_else(|| invalid("pets must be a non-empty array".to_string()))?;+ if pets.is_empty() {+ return Err(invalid("pets must contain at least one pet".to_string()));+ }+ for pet in pets {+ let id = pet+ .get("id")+ .and_then(Value::as_str)+ .map(str::trim)+ .filter(|id| !id.is_empty())+ .ok_or_else(|| invalid("each pet must have a non-empty string id".to_string()))?;+ validate_manifest_id(id).map_err(|_| invalid("pet id is not a safe manifest id".to_string()))?;+ }++ let animations = root+ .get("animations")+ .and_then(Value::as_object)+ .ok_or_else(|| invalid("animations must be an object".to_string()))?;+ for pool in ["idle", "turn", "drag", "clicks"] {+ let entries = animations+ .get(pool)+ .and_then(Value::as_array)+ .ok_or_else(|| invalid(format!("animations.{pool} must be an array")))?;+ validate_pool_entries(entries, pool)?;+ }++ let moves = animations+ .get("moves")+ .and_then(Value::as_object)+ .ok_or_else(|| invalid("animations.moves must be an object".to_string()))?;+ if !moves.contains_key("default") || moves.get("default").and_then(Value::as_object).is_none() {+ return Err(invalid("animations.moves.default must be an object".to_string()));+ }+ let move_actions = moves+ .get("actions")+ .and_then(Value::as_array)+ .ok_or_else(|| invalid("animations.moves.actions must be an array".to_string()))?;+ for action in move_actions {+ let name = action+ .get("name")+ .and_then(Value::as_str)+ .map(str::trim)+ .filter(|name| !name.is_empty())+ .ok_or_else(|| invalid("each moves action must have a non-empty name".to_string()))?;+ if !builtin_asset_key_known(name) {+ return Err(invalid(format!(+ "moves action '{name}' is not a built-in asset key"+ )));+ }+ }++ let categories = animations+ .get("categories")+ .and_then(Value::as_array)+ .ok_or_else(|| invalid("animations.categories must be an array".to_string()))?;+ for category in categories {+ let id = category+ .get("id")+ .and_then(Value::as_str)+ .map(str::trim)+ .filter(|id| !id.is_empty())+ .ok_or_else(|| invalid("each category must have a non-empty id".to_string()))?;+ let _ = id;+ let weight = category+ .get("weight")+ .and_then(Value::as_f64)+ .ok_or_else(|| invalid("each category must have a numeric weight".to_string()))?;+ if !weight.is_finite() || weight < 0.0 {+ return Err(invalid("category weight must be a non-negative number".to_string()));+ }+ let actions = category+ .get("actions")+ .and_then(Value::as_array)+ .ok_or_else(|| invalid("each category must have an actions array".to_string()))?;+ validate_pool_entries(actions, "categories.actions")?;+ }++ if let Some(events) = animations.get("events") {+ let events = events+ .as_object()+ .ok_or_else(|| invalid("animations.events must be an object".to_string()))?;+ for (event, pool) in events {+ let pool = pool+ .as_array()+ .ok_or_else(|| invalid(format!("animations.events.{event} must be an array")))?;+ validate_pool_entries(pool, &format!("events.{event}"))?;+ }+ }++ let weights = root+ .get("animationWeights")+ .and_then(Value::as_object)+ .ok_or_else(|| invalid("animationWeights must be an object".to_string()))?;+ for key in ["idle", "turn", "move"] {+ let weight = weights+ .get(key)+ .and_then(Value::as_f64)+ .ok_or_else(|| invalid(format!("animationWeights.{key} must be a number")))?;+ if !weight.is_finite() || weight < 0.0 {+ return Err(invalid(format!(+ "animationWeights.{key} must be a non-negative number"+ )));+ }+ }+ Ok(())+}++/// 池条目必须是内置资产键白名单内的非空字符串;空池(无动画可用)也允许,+/// 由运行时回落默认动画,但写了未知键必须显式报错。+fn validate_pool_entries(entries: &[Value], pool: &str) -> Result<(), String> {+ let invalid = config_invalid;+ for entry in entries {+ let name = entry+ .as_str()+ .map(str::trim)+ .filter(|name| !name.is_empty())+ .ok_or_else(|| invalid(format!("{pool} entries must be non-empty strings")))?;+ if !builtin_asset_key_known(name) {+ return Err(invalid(format!(+ "{pool} entry '{name}' is not a built-in asset key"+ )));+ }+ }+ Ok(())+}++fn builtin_asset_key_known(name: &str) -> bool {+ BUILTIN_ASSET_NAMES.iter().any(|(key, _)| *key == name)+}++/// 读取并解析内置 dsh-tauri-pet/assets/config.jsonc(JSONC 协议),返回校验后的 JSON。+/// 与媒体同一资源边界:固定文件名 + 白名单目录 + 限量读取 + 显式错误前缀。+#[tauri::command]+pub fn get_builtin_pet_config(app: AppHandle) -> Result<Value, String> {+ let path = resolve_builtin_asset_path(&app, BUILTIN_CONFIG_FILE).map_err(|error| {+ error.replacen(+ "PET_BUILTIN_ASSET_",+ "PET_BUILTIN_CONFIG_",+ 1,+ )+ })?;+ let bytes = read_bounded_file(+ &path,+ PET_CONFIG_MAX_BYTES,+ "PET_BUILTIN_CONFIG_READ_FAILED",+ )?;+ let text = std::str::from_utf8(&bytes)+ .map_err(|error| format!("PET_BUILTIN_CONFIG_INVALID: config is not UTF-8: {error}"))?;+ let json = strip_jsonc(text);+ let value: Value = serde_json::from_str(&json)+ .map_err(|error| format!("PET_BUILTIN_CONFIG_INVALID: invalid JSON: {error}"))?;+ validate_builtin_pet_config(&value)?;+ Ok(value)+}+/// 为 dsh-pet 自定义协议读取固定白名单资源;调用方已在 builder 中限制为 pet WebView。pub fn builtin_pet_asset_response(app: &AppHandle,@@ -1321,4 +1564,106 @@ mod tests {assert!(error.starts_with("PET_PATH_INVALID:"));assert!(!directory.0.exists(), "完整校验失败前不得创建 staging");}++ #[test]+ fn strip_jsonc_removes_line_and_block_comments_only_outside_strings() {+ let src = r#"{+ // 行注释+ "idle": ["idle"], /* 块注释 */ "turn": ["turn"],+ "url": "https://example.com/a//b", // 行尾注释+ "s": "/* not a comment */"+}"#;+ let stripped = strip_jsonc(src);+ assert!(!stripped.contains("行注释"));+ assert!(!stripped.contains("块注释"));+ assert!(!stripped.contains("行尾注释"));+ assert!(stripped.contains("\"https://example.com/a//b\""));+ assert!(stripped.contains("\"/* not a comment */\""));+ let parsed: serde_json::Value = serde_json::from_str(&stripped).expect("valid JSON");+ assert_eq!(parsed["idle"][0], "idle");+ assert_eq!(parsed["turn"][0], "turn");+ }++ #[test]+ fn builtin_config_accepts_protocol_shaped_document() {+ let value: Value = serde_json::from_str(+ r#"{+ "pets": [{ "id": "maid-deepseek-whale", "name": "Maid", "size": 220 }],+ "animations": {+ "idle": ["idle"],+ "turn": ["turn"],+ "drag": ["drag"],+ "clicks": ["wave"],+ "moves": { "default": { "minDist": 60 }, "actions": [{ "name": "move" }] },+ "categories": [+ { "id": "小动作", "weight": 80, "actions": ["wave", "bubble", "turn"] }+ ],+ "events": { "balance": ["bubble"] }+ },+ "animationWeights": { "idle": 10, "turn": 5, "move": 5 },+ "physics": { "gravity": 1400 }+}"#,+ )+ .unwrap();+ assert!(validate_builtin_pet_config(&value).is_ok());+ }++ #[test]+ fn builtin_config_rejects_unknown_asset_keys_and_bad_shape() {+ let unknown_pool: Value = serde_json::from_str(+ r#"{+ "pets": [{ "id": "maid-deepseek-whale" }],+ "animations": {+ "idle": ["not-a-key"],+ "turn": ["turn"],+ "drag": ["drag"],+ "clicks": ["wave"],+ "moves": { "default": {}, "actions": [] },+ "categories": []+ },+ "animationWeights": { "idle": 1, "turn": 1, "move": 1 }+}"#,+ )+ .unwrap();+ let error = validate_builtin_pet_config(&unknown_pool).unwrap_err();+ assert!(error.starts_with("PET_BUILTIN_CONFIG_INVALID:"));+ assert!(error.contains("not-a-key"));++ let missing_pets: Value = serde_json::from_str(+ r#"{+ "animations": {+ "idle": ["idle"],+ "turn": ["turn"],+ "drag": ["drag"],+ "clicks": ["wave"],+ "moves": { "default": {}, "actions": [] },+ "categories": []+ },+ "animationWeights": { "idle": 1, "turn": 1, "move": 1 }+}"#,+ )+ .unwrap();+ assert!(validate_builtin_pet_config(&missing_pets)+ .unwrap_err()+ .starts_with("PET_BUILTIN_CONFIG_INVALID:"));++ let bad_weights: Value = serde_json::from_str(+ r#"{+ "pets": [{ "id": "maid-deepseek-whale" }],+ "animations": {+ "idle": ["idle"],+ "turn": ["turn"],+ "drag": ["drag"],+ "clicks": ["wave"],+ "moves": { "default": {}, "actions": [] },+ "categories": []+ },+ "animationWeights": { "idle": -1, "turn": 1, "move": 1 }+}"#,+ )+ .unwrap();+ assert!(validate_builtin_pet_config(&bad_weights)+ .unwrap_err()+ .starts_with("PET_BUILTIN_CONFIG_INVALID:"));+ }}diff --git a/src-tauri/src/desktop/builder.rs b/src-tauri/src/desktop/builder.rsindex 0948d20c..fa7c4069 100644--- a/src-tauri/src/desktop/builder.rs+++ b/src-tauri/src/desktop/builder.rs@@ -595,6 +595,7 @@ pub fn handler() -> impl Fn(Invoke<Wry>) -> bool + Send + Sync + 'static {crate::bridge::import_pet,crate::bridge::get_pet_asset,crate::bridge::get_builtin_pet_assets,+ crate::bridge::get_builtin_pet_config,crate::desktop::pet_mouse::start_pet_mouse_stream,]}diff --git a/src/hooks/use-iframe-invoke.ts b/src/hooks/use-iframe-invoke.tsindex 5b08c53b..f54b91cc 100644--- a/src/hooks/use-iframe-invoke.ts+++ b/src/hooks/use-iframe-invoke.ts@@ -46,6 +46,7 @@ const ALLOWED_INVOKE_CMDS = new Set(['import_pet','get_pet_asset','get_builtin_pet_assets',+ 'get_builtin_pet_config',])export function useIframeInvoke(iframeRef: RefObject<HTMLIFrameElement | null>): void {diff --git a/src/pet/components/pet.tsx b/src/pet/components/pet.tsxindex 186340ab..7cacf1f1 100644--- a/src/pet/components/pet.tsx+++ b/src/pet/components/pet.tsx@@ -1,11 +1,18 @@import type { CSSProperties, Ref, RefObject, SyntheticEvent } from 'react'import type { PetHandle, PetStatus } from '../hooks/use-pet'+import type { PetConfig } from '../pet-config'import { invoke } from '@tauri-apps/api/core'import { listen } from '@tauri-apps/api/event'import { getCurrentWindow, LogicalSize } from '@tauri-apps/api/window'-import { useEffect, useImperativeHandle, useRef, useState } from 'react'+import { useEffect, useImperativeHandle, useMemo, useRef, useState } from 'react'import { If } from 'react-if-lite'import { PET_STATUSES } from '../hooks/use-pet'+import {+ pick,+ pickCategoryAction,+ poolEntryToStatus,+ rollKind,+} from '../pet-config'const BUILT_IN_PET_ID = 'maid-deepseek-whale'const PET_BASE_WIDTH = 220@@ -20,9 +27,11 @@ const PET_WINDOW_PAD_Y = 82const PET_BUBBLE_MIN_WIDTH = 420const IDLE_DURATIONS = [280, 110, 110, 140, 140, 320] as const/**- * 待机转向插播间隔下限/上限(ms):平时以循环待机动画为主(参考 dsh-pet- * animationWeights idle:10 / turn:5 的权重语义——turn 是播完掷骰链里的低频事件),+ * 待机转向插播间隔下限/上限(ms):平时以循环待机动画为主,参考 dsh-pet+ * animationWeights idle:10 / turn:5 的权重语义——turn 是播完掷骰链里的低频事件,* 只有长时间持续待机才偶尔插播一次转身,避免高频切换的观感。+ * 当内置 config.jsonc 可用时,实际掷骰改由协议权重(rollKind)驱动,这两个+ * 常量仅作为「每次掷骰的间隔」使用。*/const IDLE_TURN_DELAY_MIN = 25000const IDLE_TURN_DELAY_MAX = 50000@@ -44,6 +53,8 @@ const ACTIONS = {type VideoKey = 'idle' | 'turn' | 'move' | 'drag' | 'wave' | 'waiting' | 'running' | 'review' | 'failed' | 'bubble'type Animation = PetStatus | 'bubble' | 'dragging'+/** 一次性回应(点击/待机链)可用的播放状态:会话状态 + bubble,排除拖拽专用。 */+type AdHocStatus = Exclude<Animation, 'dragging' | 'moving-left' | 'moving-right'>interface Asset {columns: number@@ -89,10 +100,12 @@ export function Pet(props: PetProps) {const [failed, setFailed] = useState(false)const [override, setOverride] = useState<{ loop: boolean, revision: number, status: PetStatus } | null>(null)const revisionRef = useRef(0)- const [adHoc, setAdHoc] = useState<{ seq: number, status: 'turn' | 'waving' } | null>(null)+ const [adHoc, setAdHoc] = useState<{ seq: number, status: AdHocStatus } | null>(null)const adHocRef = useRef(adHoc)adHocRef.current = adHocconst adHocSeqRef = useRef(0)+ // 内置配置(dsh-pet assets/config.jsonc 协议):加载失败时回落内置默认池。+ const [config, setConfig] = useState<PetConfig | null>(null)const [reducedMotion, setReducedMotion] = useState(() => globalThis.matchMedia?.('(prefers-reduced-motion: reduce)').matches ?? false)const videoARef = useRef<HTMLVideoElement | null>(null)const videoBRef = useRef<HTMLVideoElement | null>(null)@@ -106,6 +119,21 @@ export function Pet(props: PetProps) {const prevClickRef = useRef(0)const handleEndedRef = useRef<(event?: Event) => void>(() => {})+ // 内置配置驱动动画池:池条目是内置资产键(idle/turn/move/drag/wave/waiting/running/+ // review/failed/bubble/fallback),经 poolEntryToStatus 映射为播放状态。配置缺失+ // 或命令失败时回落与旧实现一致的默认池(idle/turn/wave)。+ const pools = useMemo(() => {+ const animations = config?.animations+ return {+ idlePool: animations?.idle.length ? animations.idle : ['idle'],+ turnPool: animations?.turn.length ? animations.turn : ['turn'],+ clicksPool: animations?.clicks.length ? animations.clicks : ['wave'],+ categories: animations?.categories ?? [],+ weights: config?.animationWeights ?? { idle: 10, turn: 5, move: 5 },+ }+ }, [config])+ const { idlePool, turnPool, clicksPool, categories, weights } = pools+const activePet = normalizeActivePet(rustStatus.active_pet)const isBuiltin = activePet === BUILT_IN_PET_ID// 内置宠物拖拽中:播放拖拽悬空浮动动画(不区分方向);自定义宠物仍用方向转向。@@ -152,6 +180,12 @@ export function Pet(props: PetProps) {if (!disposed)setAssets(value.assets ?? {})}).catch(() => {})+ void invoke<PetConfig>('get_builtin_pet_config').then((value) => {+ if (!disposed)+ setConfig(value)+ }).catch((error) => {+ console.warn('[pet] PET_BUILTIN_CONFIG_LOAD_FAILED:', error)+ })return () => {disposed = trueunlisten?.()@@ -259,26 +293,54 @@ export function Pet(props: PetProps) {}, [activity, adHoc?.seq, assets, isBuiltin, override?.loop, override?.revision])// 点击回应:clickCount 变化(useDrag 判定「500ms 内两次按下且未拖拽 = 双击」后递增)- // → 播放一次 waving。adHoc 优先级在会话 override 之上:双击回应可打断会话状态,- // 播完回落原动画(handleEnded)。+ // → 播放一次点击回应动画。adHoc 优先级在会话 override 之上:双击回应可打断会话状态,+ // 播完回落原动画(handleEnded)。动画名来自内置 config.jsonc 的 clicks 池(协议);+ // 配置缺失/池条目不可播放时回落 waving。useEffect(() => {if (props.clickCount === undefined || props.clickCount === prevClickRef.current)return undefinedprevClickRef.current = props.clickCount+ const status = toAdHocStatus(pick(clicksPool)) ?? 'waving'// 点击回应:以 props 变化驱动一次性动画状态,属于事件联动而非渲染副作用。// eslint-disable-next-line react/set-state-in-effect- setAdHoc({ seq: ++adHocSeqRef.current, status: 'waving' })- }, [props.clickCount])+ setAdHoc({ seq: ++adHocSeqRef.current, status })+ }, [props.clickCount, clicksPool])- // 待机转向链(参考 dsh-pet 的权重掷骰链):内置宠物长时间持续待机时,- // 才以低频(IDLE_TURN_DELAY_MIN~MAX 随机)插播一次转身动画,平时保持循环待机。+ // 待机链(dsh-pet 权重掷骰链):内置宠物长时间持续待机时,以低频+ // (IDLE_TURN_DELAY_MIN~MAX 随机间隔)按 config.jsonc 的 animationWeights 掷骰,+ // 命中 turn/action 才插播一次一次性动画,平时保持循环待机。move 命中时因 DSH+ // 不自动漫游而保持待机(协议字段保留,行为对齐「移除自动移动」规格)。useEffect(() => {if (isBuiltin === false || reducedMotion || activity !== 'idle')return undefined- const delay = IDLE_TURN_DELAY_MIN + Math.random() * (IDLE_TURN_DELAY_MAX - IDLE_TURN_DELAY_MIN)- const timer = window.setTimeout(setAdHoc, delay, { seq: ++adHocSeqRef.current, status: 'turn' })+ let timer: number | undefined+ function scheduleNextRoll() {+ const delay = IDLE_TURN_DELAY_MIN + Math.random() * (IDLE_TURN_DELAY_MAX - IDLE_TURN_DELAY_MIN)+ timer = window.setTimeout(() => {+ const kind = rollKind(Math.random(), weights)+ if (kind === 'turn' && turnPool.length > 0) {+ const status = toAdHocStatus(pick(turnPool))+ if (status !== null && status !== 'idle') {+ setAdHoc({ seq: ++adHocSeqRef.current, status })+ return+ }+ }+ if (kind === 'action' && categories.length > 0) {+ const current = adHocRef.current?.status ?? 'idle'+ const action = pickCategoryAction(categories, idlePool, 'left', current)+ const status = toAdHocStatus(action.name)+ if (status !== null && status !== 'idle' && action.name !== current) {+ setAdHoc({ seq: ++adHocSeqRef.current, status })+ return+ }+ }+ // idle / move(不自动漫游)/ 不可播放条目:继续待机并等待下一次掷骰。+ scheduleNextRoll()+ }, delay)+ }+ scheduleNextRoll()return () => window.clearTimeout(timer)- }, [activity, isBuiltin, reducedMotion])+ }, [activity, categories, idlePool, isBuiltin, reducedMotion, turnPool, weights])useEffect(() => {const sprite = spriteRef.current@@ -426,6 +488,22 @@ function isPetStatus(value: string): value is PetStatus {return (PET_STATUSES as readonly string[]).includes(value)}+/**+ * 把内置配置池条目(内置资产键)映射为可播放的一次性回应状态(AdHocStatus)。+ * 资产键 'wave' 归一化为播放状态 'waving';拖拽/方向专用状态不参与回应池;+ * 其余条目必须是会话状态或 bubble,否则返回 null(调用方回落默认动画)。+ */+function toAdHocStatus(entry: string): AdHocStatus | null {+ const status = poolEntryToStatus(entry)+ if (status === 'bubble')+ return status+ if (status === 'dragging' || status === 'moving-left' || status === 'moving-right')+ return null+ // isPetStatus 收窄为 PetStatus;拖拽/方向状态已在上方排除,剩余的 PetStatus+ // 全部属于 AdHocStatus(= 会话状态 + bubble)。+ return isPetStatus(status) ? (status as AdHocStatus) : null+}+function normalizeActivePet(value: string | null | undefined): string {const normalized = value?.trim()return normalized || BUILT_IN_PET_IDdiff --git a/src/pet/hooks/use-bubble.ts b/src/pet/hooks/use-bubble.tsindex 18ef7a8e..90adaf02 100644--- a/src/pet/hooks/use-bubble.ts+++ b/src/pet/hooks/use-bubble.ts@@ -20,9 +20,11 @@ const DESCRIPTION_MAX_LENGTH = 120/** 终态气泡自动隐藏时长(毫秒):失败展示 4s、待审阅 2.5s(对齐参考实现的完成脉冲)。实时状态(running / waiting)常驻,由后续会话事件更新内容。 */const FAILED_BUBBLE_TIMEOUT = 4000const REVIEW_BUBBLE_TIMEOUT = 2500-/** 失败动画脉冲时长(毫秒):对齐参考实现 companion-reducer 的工具失败脉冲 ttlMs=1800。+/**+ * 失败动画脉冲时长(毫秒):对齐参考实现 companion-reducer 的工具失败脉冲 ttlMs=1800。* 失败只作为瞬态脉冲展示一次,到期自动恢复到底层会话状态,避免 DSH 快照上粘性的- * lastAgentError 经插件 250ms 心跳重发后永久占用 'failed'、阻塞其他会话的动画切换。 */+ * lastAgentError 经插件 250ms 心跳重发后永久占用 'failed'、阻塞其他会话的动画切换。+ */const FAILED_PULSE_TTL = 1800/** 桌宠窗口的会话气泡:DSH 发送原始会话快照,本 hook 私有管理会话→toast key 映射,仅暴露聚合宠物状态。 */diff --git a/src/pet/pet-config.test.ts b/src/pet/pet-config.test.tsnew file mode 100644index 00000000..7fad6579--- /dev/null+++ b/src/pet/pet-config.test.ts@@ -0,0 +1,101 @@+import type { PetCategory, PetWeights } from './pet-config'+import { describe, expect, it, vi } from 'vitest'+import {++ pick,+ pickCategoryAction,+ pickWeightedCategory,+ poolEntryToStatus,+ rollKind,+} from './pet-config'++const WEIGHTS: PetWeights = { idle: 10, turn: 5, move: 5 }++describe('rollKind', () => {+ it('maps roll ranges to idle/turn/move/action by weights', () => {+ expect(rollKind(0.0, WEIGHTS)).toBe('idle')+ expect(rollKind(0.0999, WEIGHTS)).toBe('idle')+ expect(rollKind(0.10, WEIGHTS)).toBe('turn')+ expect(rollKind(0.1499, WEIGHTS)).toBe('turn')+ expect(rollKind(0.15, WEIGHTS)).toBe('move')+ expect(rollKind(0.1999, WEIGHTS)).toBe('move')+ // topEnd = (10+5+5)/100 = 0.20,剩余 0.20~1.00 全归 action+ expect(rollKind(0.20, WEIGHTS)).toBe('action')+ expect(rollKind(0.9999, WEIGHTS)).toBe('action')+ })++ it('treats zero-sum weights as always-action', () => {+ expect(rollKind(0.0, { idle: 0, turn: 0, move: 0 })).toBe('action')+ expect(rollKind(0.9, { idle: 0, turn: 0, move: 0 })).toBe('action')+ })+})++describe('pickWeightedCategory', () => {+ const categories: PetCategory[] = [+ { id: '小动作', weight: 20, actions: ['wave', 'bubble'] },+ { id: '玩耍', weight: 20, actions: ['turn'] },+ { id: '文字', weight: 10, noMirror: true, actions: ['waiting'] },+ ]++ it('excludes noMirror categories while facing right', () => {+ vi.spyOn(Math, 'random').mockReturnValue(0.95)+ const left = pickWeightedCategory(categories, 'left')+ const right = pickWeightedCategory(categories, 'right')+ // facing=right 时 noMirror 分类被排除,抽取结果只剩前两个分类+ expect(['小动作', '玩耍', '文字']).toContain(left?.id)+ expect(['小动作', '玩耍']).toContain(right?.id)+ expect(right?.id).not.toBe('文字')+ vi.restoreAllMocks()+ })++ it('skips categories without actions and returns null for empty pools', () => {+ expect(pickWeightedCategory([], 'left')).toBeNull()+ expect(pickWeightedCategory([{ id: '空', weight: 1, actions: [] }], 'left')).toBeNull()+ })+})++describe('pickCategoryAction', () => {+ it('picks an action from a weighted category', () => {+ vi.spyOn(Math, 'random').mockReturnValue(0.0)+ const result = pickCategoryAction(+ [{ id: '小动作', weight: 1, actions: ['wave', 'bubble'] }],+ ['idle'],+ 'left',+ 'idle',+ )+ expect(result.id).toBe('小动作')+ expect(result.name).toBe('wave')+ vi.restoreAllMocks()+ })++ it('falls back to the idle pool when no category is available', () => {+ vi.spyOn(Math, 'random').mockReturnValue(0.5)+ const result = pickCategoryAction([], ['idle', 'turn'], 'left', 'idle')+ expect(result.id).toBe('FALLBACK')+ expect(['idle', 'turn']).toContain(result.name)+ vi.restoreAllMocks()+ })+})++describe('pick', () => {+ it('picks from a pool and avoids the excluded entry when possible', () => {+ vi.spyOn(Math, 'random').mockReturnValue(0.0)+ expect(pick(['a', 'b'], 'a')).toBe('b')+ vi.restoreAllMocks()+ })++ it('falls back to the original pool when exclusion empties it', () => {+ vi.spyOn(Math, 'random').mockReturnValue(0.0)+ expect(pick(['a'], 'a')).toBe('a')+ vi.restoreAllMocks()+ })+})++describe('poolEntryToStatus', () => {+ it('normalizes the wave asset key to the waving status', () => {+ expect(poolEntryToStatus('wave')).toBe('waving')+ expect(poolEntryToStatus('idle')).toBe('idle')+ expect(poolEntryToStatus('bubble')).toBe('bubble')+ expect(poolEntryToStatus('turn')).toBe('turn')+ })+})diff --git a/src/pet/pet-config.ts b/src/pet/pet-config.tsnew file mode 100644index 00000000..584883a8--- /dev/null+++ b/src/pet/pet-config.ts@@ -0,0 +1,122 @@+/**+ * pet-config.ts — 内置桌宠配置(dsh-pet assets/config.jsonc 协议)的纯逻辑层。+ *+ * 配置由 Rust 从 dsh-tauri-pet 包 assets/config.jsonc 读取、剥注释并校验后经+ * `get_builtin_pet_config` 命令返回(字段形状 = 子仓库 dsh-pet assets/config.jsonc+ * 协议的受支持子集,动画池条目 = 内置资产键白名单)。本模块只做两件事:+ * 1. 类型收敛:把命令返回值声明成可直接消费的结构;+ * 2. 权重掷骰:移植 dsh-pet src/shared/pickers.ts 的 rollKind / pickWeightedCategory /+ * pickCategoryAction(DSH 无自动漫游,move 档由调用方决定保持待机,不在本模块移动窗口)。+ * 无 React / DOM / Tauri 依赖,可独立单测。+ */++/** 动画链掷骰结果类别。 */+export type PetRollKind = 'idle' | 'turn' | 'move' | 'action'++/** 动画链顶层权重(idle/turn/move,协议字段 animationWeights)。 */+export interface PetWeights {+ idle: number+ turn: number+ move: number+}++/** 随机动作分类(带文字、镜像会颠倒的池带 noMirror)。 */+export interface PetCategory {+ id: string+ weight: number+ noMirror?: boolean+ actions: string[]+}++/** 移动池(DSH 不自动移动窗口,仅保留协议字段供未来对齐)。 */+export interface PetMovesConfig {+ default: Record<string, number>+ actions: { name: string, params?: Record<string, number> }[]+}++/** config.jsonc 的 animations 段(协议子集)。 */+export interface PetAnimationsConfig {+ idle: string[]+ turn: string[]+ drag: string[]+ clicks: string[]+ moves: PetMovesConfig+ categories: PetCategory[]+ events?: Record<string, string[]>+}++/** config.jsonc 全集(受支持子集;pets/physics/eventsRefreshSec 由 Rust 校验)。 */+export interface PetConfig {+ pets: { id: string, name?: string, size?: number }[]+ animations: PetAnimationsConfig+ animationWeights: PetWeights+ physics?: Record<string, unknown>+ eventsRefreshSec?: Record<string, number>+}++/** 从字符串池等概率抽一个;exclude 排除某个名字(避免连续重复)。 */+export function pick<T>(pool: readonly T[], exclude?: T): T {+ const entries = exclude === undefined ? pool : pool.filter(item => item !== exclude)+ // 排除后池空(单元素池 + 排除自己):退回原池抽——宁可重复,也不要返回 undefined+ const source = entries.length > 0 ? entries : pool+ return source[Math.floor(Math.random() * source.length)] ?? source[0]+}++/**+ * 按权重掷骰:roll ∈ [0,1) → 下一个动画类别(纯函数,可单测)。+ * topEnd = (idle+turn+move)/100:三档权重占比之和,剩余概率归入 'action'。+ */+export function rollKind(roll: number, weights: PetWeights): PetRollKind {+ const total = weights.idle + weights.turn + weights.move+ if (total <= 0)+ return 'action'+ const topEnd = total / 100+ if (roll < weights.idle / 100)+ return 'idle'+ if (roll < (weights.idle + weights.turn) / 100)+ return 'turn'+ if (roll < topEnd)+ return 'move'+ return 'action'+}++/**+ * 按权重在分类池中选一个分类;noMirror 分类在镜像(facing=right)时被排除,+ * 剩余权重自动归一化。分类池为空时返回 null。+ */+export function pickWeightedCategory(categories: PetCategory[], facing: 'left' | 'right'): PetCategory | null {+ const cats = categories.filter(category => category.actions.length > 0)+ if (cats.length === 0)+ return null+ const filtered = cats.filter(category => !(category.noMirror === true && facing === 'right'))+ const eligible = filtered.length > 0 ? filtered : cats+ const totalWeight = eligible.reduce((sum, category) => sum + Math.max(0, category.weight), 0) || 1+ let target = Math.random() * totalWeight+ for (const category of eligible) {+ target -= Math.max(0, category.weight)+ if (target <= 0)+ return category+ }+ return eligible[eligible.length - 1]+}++/** 从分类池选一个动作;无可用分类时回退 idle 池(返回 {id, name},纯函数)。 */+export function pickCategoryAction(+ categories: PetCategory[],+ idlePool: readonly string[],+ facing: 'left' | 'right',+ current: string,+): { id: string, name: string } {+ const category = pickWeightedCategory(categories, facing)+ if (category === null)+ return { id: 'FALLBACK', name: pick(idlePool, current) }+ return { id: category.id, name: pick(category.actions, current) }+}++/**+ * 把动画池条目(内置资产键)映射为播放状态:唯一需要归一化的是点击/分类池里的+ * 'wave'(资产键)→ 'waving'(播放状态);其余键与播放状态同名。+ */+export function poolEntryToStatus(entry: string): string {+ return entry === 'wave' ? 'waving' : entry+}