DeepSeek Harness Tauri 桌面版 | Only 8mb installer, zero environment setup, preset plugins, Windows / macOS / Linux.
feat(pet): serve and play preset pet assets end to end
hairyf4dfb8fc5884b
diff --git a/src-tauri/src/desktop/builder.rs b/src-tauri/src/desktop/builder.rsindex bcafaf7b..27c9d493 100644--- a/src-tauri/src/desktop/builder.rs+++ b/src-tauri/src/desktop/builder.rs@@ -595,8 +595,11 @@ pub fn handler() -> impl Fn(Invoke<Wry>) -> bool + Send + Sync + 'static {crate::bridge::list_pets,crate::bridge::import_pet,crate::bridge::get_pet_asset,- crate::bridge::get_builtin_pet_assets,- crate::bridge::get_builtin_pet_config,+ crate::bridge::preset_pet::get_preset_pet_config,+ crate::bridge::preset_pet::get_preset_pet_assets,+ crate::bridge::list_preset_pets,+ crate::bridge::download_preset_pet,+ crate::bridge::get_preset_download_progress,crate::desktop::pet_mouse::start_pet_mouse_stream,]}@@ -609,7 +612,7 @@ pub fn builder() -> tauri::Builder<tauri::Wry> {let app = context.app_handle().clone();let label = context.webview_label().to_owned();std::thread::spawn(move || {- responder.respond(crate::bridge::builtin_pet_asset_response(&app, &label, request));+ responder.respond(crate::bridge::preset_pet::preset_pet_asset_response(&app, &label, request));});}).setup(|app| {diff --git a/src-tauri/src/desktop/pet.rs b/src-tauri/src/desktop/pet.rsindex 9b3a7027..e81c9d5d 100644--- a/src-tauri/src/desktop/pet.rs+++ b/src-tauri/src/desktop/pet.rs@@ -38,9 +38,7 @@ const PET_WINDOW_BOTTOM_PAD: f64 = 10.0;/// 顶栏 Toast 区的最小窗口宽度(逻辑像素):桌宠较小时仍保证气泡可读,/// 与 pet WebView 的 PET_BUBBLE_MIN_WIDTH 保持一致。const PET_WINDOW_MIN_WIDTH: f64 = 420.0;-/// 内置宠物的 id(与 bridge 的 DEFAULT_ACTIVE_PET_ID 一致);用于判断资源画布比例。-const PET_BUILTIN_ID: &str = "maid-deepseek-whale";-/// 内置 WebM 画布 16:9(高/宽 = 9/16),与 pet WebView 的内置画布比例保持一致。+/// 预设 WebM 画布 16:9(高/宽 = 9/16),与 dsh-pet 协议画布比例保持一致。const PET_BUILTIN_ASPECT: f64 = 9.0 / 16.0;/// 自定义 Codex v2 精灵图默认 8x11 的 192x208 比例;实际比例以前端加载后为准,/// 这里仅作为窗口初始/DPI 尺寸的近似,避免与前端内置画布比例互相打架。@@ -124,9 +122,10 @@ pub fn get_pet_size_percent<R: Runtime>(app: &AppHandle<R>) -> f64 {.clamp(PET_SIZE_MIN_PERCENT, PET_SIZE_MAX_PERCENT)}-/// 当前激活宠物使用的画布比例(高度/宽度):内置 WebM 固定 9/16,自定义精灵图用-/// 208/192 作为窗口初始/DPI 尺寸的近似。真正的自定义比例由前端加载后修正,因此这-/// 里不再把 208/192 硬编码给所有宠物,避免窗口大小的两个来源互相冲突。+/// 当前激活宠物使用的画布比例(高度/宽度):预设 WebM(未限定 id)固定 9/16,+/// 自定义精灵图(chat:/codex: 来源限定 id)用 208/192 作为窗口初始/DPI 尺寸的近似。+/// 真正的自定义比例由前端加载后修正,因此这里不再把 208/192 硬编码给所有宠物,+/// 避免窗口大小的两个来源互相冲突。pub fn pet_window_aspect<R: Runtime>(app: &AppHandle<R>) -> f64 {let setting = crate::config::get_store_dat_setting(app);let active = setting@@ -134,7 +133,8 @@ pub fn pet_window_aspect<R: Runtime>(app: &AppHandle<R>) -> f64 {.as_deref().map(str::trim).filter(|value| !value.is_empty());- if active.map(|value| value == PET_BUILTIN_ID).unwrap_or(true) {+ // 来源限定 id(chat:/codex:)是自定义精灵图;未限定 id(预设宠物)用 WebM 9/16。+ if active.map(|value| !value.contains(':')).unwrap_or(true) {PET_BUILTIN_ASPECT} else {PET_CUSTOM_ASPECT@@ -467,19 +467,20 @@ mod tests {#[test]fn pet_window_aspect_matches_builtin_and_custom() {- // 未设置 / 空白 / 内置 id 都走内置 16:9 比例;来源限定 id 走自定义图集比例。+ // 未设置 / 空白 / 未限定 id(预设 WebM)都走内置 16:9 比例;+ // 来源限定 id(chat:/codex:)走自定义图集比例。// 使用一个真实 AppHandle 才能读设置,这里仅验证比例常量与归一化分支的纯逻辑。assert_eq!(PET_BUILTIN_ASPECT, 9.0 / 16.0);assert_eq!(PET_CUSTOM_ASPECT, 208.0 / 192.0);- assert_eq!(PET_BUILTIN_ID, "maid-deepseek-whale");let is_builtin = |active: Option<&str>| {active.map(str::trim).filter(|v| !v.is_empty())- .map(|v| v == PET_BUILTIN_ID)+ .map(|v| !v.contains(':')).unwrap_or(true)};assert!(is_builtin(None));assert!(is_builtin(Some(" ")));assert!(is_builtin(Some("maid-deepseek-whale")));+ assert!(is_builtin(Some("another-preset")));assert!(!is_builtin(Some("codex:blue_whale")));assert!(!is_builtin(Some("chat:cat")));}diff --git a/src/hooks/use-iframe-invoke.ts b/src/hooks/use-iframe-invoke.tsindex f54b91cc..872dbaea 100644--- a/src/hooks/use-iframe-invoke.ts+++ b/src/hooks/use-iframe-invoke.ts@@ -45,8 +45,9 @@ const ALLOWED_INVOKE_CMDS = new Set(['list_pets','import_pet','get_pet_asset',- 'get_builtin_pet_assets',- 'get_builtin_pet_config',+ 'list_preset_pets',+ 'download_preset_pet',+ 'get_preset_download_progress',])export function useIframeInvoke(iframeRef: RefObject<HTMLIFrameElement | null>): void {diff --git a/src/pet/components/pet.tsx b/src/pet/components/pet.tsxindex 1e4c50f9..de4ca525 100644--- a/src/pet/components/pet.tsx+++ b/src/pet/components/pet.tsx@@ -11,6 +11,7 @@ import {pick,pickCategoryAction,poolEntryToStatus,+ resolvePresetName,rollKind,} from '../pet-config'@@ -51,10 +52,7 @@ const ACTIONS = {'review': { row: 8, frames: 6, duration: 150, lastDuration: 280 },} as const-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@@ -93,25 +91,29 @@ interface Frame {/** 桌宠唯一视觉组件:资源加载、WebM/Codex v2 播放和 Tauri 窗口细节全部封装。 */export function Pet(props: PetProps) {const [rustStatus, setRustStatus] = useState<RustPetStatus>({ enabled: true, visible: true })- const [assets, setAssets] = useState<Record<string, string>>({})const [customAsset, setCustomAsset] = useState<Asset | null>(null)const [customAssetPet, setCustomAssetPet] = useState<string | null>(null)const [spriteAspect, setSpriteAspect] = useState<{ id: string, value: number } | null>(null)const [failed, setFailed] = useState(false)const [override, setOverride] = useState<{ loop: boolean, revision: number, status: PetStatus } | null>(null)const revisionRef = useRef(0)- const [adHoc, setAdHoc] = useState<{ seq: number, status: AdHocStatus } | null>(null)+ const [adHoc, setAdHoc] = useState<{ seq: number, status: string } | null>(null)const adHocRef = useRef(adHoc)adHocRef.current = adHocconst adHocSeqRef = useRef(0)- // 内置配置(dsh-pet assets/config.jsonc 协议):加载失败时回落内置默认池。- const [config, setConfig] = useState<PetConfig | null>(null)+ // 预设宠物资源(config.jsonc + webm manifest):按宠物 id 一起拉取并整体更新,+ // 避免切换宠物时残留上一个宠物的动画池/URL(旧数据在 fetch 完成前不生效)。+ const [petResources, setPetResources] = useState<{+ pet: string+ config: PetConfig | null+ assets: Record<string, string>+ } | null>(null)const [reducedMotion, setReducedMotion] = useState(() => globalThis.matchMedia?.('(prefers-reduced-motion: reduce)').matches ?? false)const videoARef = useRef<HTMLVideoElement | null>(null)const videoBRef = useRef<HTMLVideoElement | null>(null)const frontIdxRef = useRef(0)const [frontIdx, setFrontIdx] = useState(0)- const pendingRef = useRef<null | { anim: Animation, gen: number, once: boolean, revision: number | undefined, seq: number }>(null)+ const pendingRef = useRef<null | { anim: string, gen: number, once: boolean, revision: number | undefined, seq: number }>(null)const genRef = useRef(0)const spriteRef = useRef<HTMLDivElement | null>(null)const overrideRef = useRef(override)@@ -119,14 +121,28 @@ 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 activePet = normalizeActivePet(rustStatus.active_pet)+ // 预设宠物(未限定 id,来自 ~/.dsh/pets 下载产物)走 WebM 协议渲染;+ // 来源限定 id(chat:/codex:)走 Codex v2 精灵图渲染。+ const isPreset = !activePet.includes(':')+ // 预设宠物资源按当前激活宠物生效:切换宠物时旧资源保持到新 fetch 完成,避免闪烁。+ // 统一 memo 成稳定的 config/assets 引用,避免每次渲染产生新对象导致视频 effect 重跑。+ const { config, assets } = useMemo(() => {+ const preset = petResources !== null && petResources.pet === activePet ? petResources : null+ return {+ config: preset?.config ?? null,+ assets: preset?.assets ?? {},+ }+ }, [activePet, petResources])+ // 预设宠物配置驱动动画池:池条目是动画名(webm 文件名主名,如 待机呼吸休闲),+ // 点击/拖拽/待机链按名字从 assets map 取 URL。配置缺失或命令失败时回落与旧+ // 实现一致的默认池(idle/turn/wave),这些名字在 assets 中不存在时自然不播放。const pools = useMemo(() => {const animations = config?.animationsreturn {idlePool: animations?.idle.length ? animations.idle : ['idle'],turnPool: animations?.turn.length ? animations.turn : ['turn'],+ dragPool: animations?.drag.length ? animations.drag : ['drag'],clicksPool: animations?.clicks.length ? animations.clicks : ['wave'],categories: animations?.categories ?? [],weights: config?.animationWeights ?? { idle: 10, turn: 5, move: 5 },@@ -134,18 +150,17 @@ export function Pet(props: PetProps) {}, [config])const { idlePool, turnPool, clicksPool, categories, weights } = pools- const activePet = normalizeActivePet(rustStatus.active_pet)- const isBuiltin = activePet === BUILT_IN_PET_ID- // 内置宠物拖拽中:播放拖拽悬空浮动动画(不区分方向);自定义宠物仍用方向转向。- const dragHold = props.dragging === true && isBuiltin- // 优先级:拖拽浮动动画 > 手势方向 > 一次性回应(点击 waving / 待机 turn) > ref 命令(会话状态)> 默认 idle。+ // 预设宠物拖拽中:播放拖拽悬空浮动动画(不区分方向);自定义宠物仍用方向转向。+ const dragHold = props.dragging === true && isPreset+ // 优先级:拖拽浮动动画 > 手势方向 > 一次性回应(点击/待机链,预设宠物池条目即动画名) > ref 命令(会话状态)> 默认 idle。// 一次性动画在 override 之上但低于手势方向:点击回应可打断会话状态,拖拽方向仍优先。- const activity: Animation = dragHold ? 'dragging' : props.status ?? adHoc?.status ?? override?.status ?? 'idle'+ const activity: Animation | string = dragHold ? 'dragging' : props.status ?? adHoc?.status ?? override?.status ?? 'idle'const size = normalizePetSize(rustStatus.pet_size)const visible = rustStatus.enabled !== false && rustStatus.visible !== falseconst hasCustomAsset = customAsset !== null && customAssetPet === activePet- // 自定义精灵图使用加载后探测到的真实画布比例(帧高/帧宽),未探测到前回落到图集默认比例。- const petAspect = isBuiltin ? 9 / 16 : (spriteAspect?.id === activePet ? spriteAspect.value : 208 / 192)+ // 预设 WebM 画布 16:9(高/宽 = 9/16,与 dsh-pet 协议一致);自定义精灵图用+ // 加载后探测到的真实画布比例(帧高/帧宽),未探测到前回落到图集默认比例。+ const petAspect = isPreset ? 9 / 16 : (spriteAspect?.id === activePet ? spriteAspect.value : 208 / 192)useImperativeHandle(props.ref, () => ({change(options) {@@ -176,22 +191,39 @@ export function Pet(props: PetProps) {if (!disposed)setRustStatus(value)}).catch(() => {})- void invoke<{ assets?: Record<string, string> }>('get_builtin_pet_assets').then((value) => {- 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?.()}}, [])+ // 预设宠物按 activePet 拉取协议配置与媒体 manifest;切换宠物时重载。+ // 已安装预设的 config.jsonc 池条目(待机呼吸休闲 等)即 webm 文件名主名,+ // assets map 的 key 与池条目一一对应,动画链/点击/拖拽直接按名字取 URL。+ useEffect(() => {+ if (isPreset === false)+ return undefined+ let disposed = false+ void Promise.all([+ invoke<PetConfig>('get_preset_pet_config', { id: activePet }).catch((error) => {+ console.warn('[pet] PET_PRESET_CONFIG_LOAD_FAILED:', error)+ return null+ }),+ invoke<{ assets?: Record<string, string> }>('get_preset_pet_assets', { id: activePet }).catch((error) => {+ console.warn('[pet] PET_PRESET_ASSETS_LOAD_FAILED:', error)+ return { assets: {} }+ }),+ ]).then(([config, value]) => {+ if (disposed)+ return+ // 一起提交,避免 config 与 assets 不同步导致短暂按旧池解析。+ setPetResources({ pet: activePet, config, assets: value.assets ?? {} })+ })+ return () => {+ disposed = true+ }+ }, [activePet, isPreset])+useEffect(() => {const query = globalThis.matchMedia?.('(prefers-reduced-motion: reduce)')if (query === undefined)@@ -217,7 +249,7 @@ export function Pet(props: PetProps) {}, [visible])useEffect(() => {- if (isBuiltin)+ if (isPreset)return undefinedlet disposed = falsevoid invoke<Asset>('get_pet_asset', { id: activePet }).then((value) => {@@ -229,7 +261,7 @@ export function Pet(props: PetProps) {return () => {disposed = true}- }, [activePet, isBuiltin])+ }, [activePet, isPreset])// 原生窗口尺寸跟随当前资源真实画布比例缩放(设置页 drag 滑块实时生效),// 避免与 Rust 只按图集默认比例重设窗口导致两处 set_size 打架(issue #308)。@@ -253,24 +285,32 @@ export function Pet(props: PetProps) {// 双 video 缓冲切换(移植 dsh-pet switchTo):新动画先在后台视频加载,// loadeddata 后才交换前台并淡入,旧视频淡出 + pause + 清 onended(拆雷,// 防止后台残留事件掐断前台动画);全程无空窗/黑帧,动画切换不闪跳。- if (isBuiltin === false || videoARef.current === null || videoBRef.current === null)+ // 只用于预设宠物(WebM);自定义宠物走精灵图渲染,不走视频。+ if (isPreset === false || videoARef.current === null || videoBRef.current === null)return undefined- const source = assets[videoKey(activity)] ?? (activity === 'dragging' ? assets.move : undefined)+ // 预设配置池条目 = 动画名 = webm 文件名主名;adHoc 已携带动画名时直接命中,+ // 会话状态(waiting/running/review/failed/bubble)经 PRESET_SESSION_ANIMATIONS+ // 叠加映射到具体动画名(写代码/轻快记录/玩游戏气急败坏…),映射名无资产时+ // resolvePresetName 返回 null → 保持当前动画。+ const name = resolvePresetName(activity, pools, assets)+ if (name === null)+ return undefined+ const source = assets[name]if (source === undefined)return undefinedconst once = !(override?.loop ?? isLoopingAnimation(activity))const revision = override?.revision- // adHoc seq:点击同一动画(waving→waving)时 seq 递增强制重播(对应 dsh-pet 的 seq 重放)。+ // adHoc seq:点击同一动画时 seq 递增强制重播(对应 dsh-pet 的 seq 重放)。const seq = adHoc?.seq ?? 0const pending = pendingRef.current- // 防重:同一动画 + 同一 revision + 同一 seq(未显式重播)不重复加载;+ // 防重:同一动画名 + 同一 revision + 同一 seq(未显式重播)不重复加载;// override/点击每次触发 revision/seq 递增,同动画重播仍会重载并从头播放。- if (pending !== null && pending.anim === activity && pending.once === once+ if (pending !== null && pending.anim === name && pending.once === once&& pending.revision === revision && pending.seq === seq) {return undefined}const gen = ++genRef.current- pendingRef.current = { anim: activity, gen, once, revision, seq }+ pendingRef.current = { anim: name, gen, once, revision, seq }const target = frontIdxRef.current === 0 ? videoBRef.current : videoARef.currenttarget.src = sourcetarget.loop = !once@@ -303,28 +343,30 @@ export function Pet(props: PetProps) {if (pendingRef.current?.gen === gen)pendingRef.current = null}- }, [activity, adHoc?.seq, assets, isBuiltin, override?.loop, override?.revision])+ }, [activity, adHoc?.seq, assets, isPreset, override?.loop, override?.revision, pools])// 点击回应:clickCount 变化(useDrag 判定「500ms 内两次按下且未拖拽 = 双击」后递增)// → 播放一次点击回应动画。adHoc 优先级在会话 override 之上:双击回应可打断会话状态,- // 播完回落原动画(handleEnded)。动画名来自内置 config.jsonc 的 clicks 池(协议);- // 配置缺失/池条目不可播放时回落 waving。+ // 播完回落原动画(handleEnded)。动画名来自预设 config.jsonc 的 clicks 池(协议,+ // 池条目 = 动画名 = webm 文件名主名);配置缺失/池条目不可播放时回落 waving。useEffect(() => {if (props.clickCount === undefined || props.clickCount === prevClickRef.current)return undefinedprevClickRef.current = props.clickCount- const status = toAdHocStatus(pick(clicksPool)) ?? 'waving'+ const entry = pick(clicksPool)+ const status = isPreset ? (entry ?? 'waving') : (toAdHocStatus(entry) ?? 'waving')// 点击回应:以 props 变化驱动一次性动画状态,属于事件联动而非渲染副作用。// eslint-disable-next-line react/set-state-in-effectsetAdHoc({ seq: ++adHocSeqRef.current, status })- }, [props.clickCount, clicksPool])+ }, [clicksPool, isPreset, props.clickCount])- // 待机链(dsh-pet 权重掷骰链):内置宠物长时间持续待机时,以低频+ // 待机链(dsh-pet 权重掷骰链):预设宠物长时间持续待机时,以低频// (IDLE_TURN_DELAY_MIN~MAX 随机间隔)按 config.jsonc 的 animationWeights 掷骰,// 命中 turn/action 才插播一次一次性动画,平时保持循环待机。move 命中时因 DSH// 不自动漫游而保持待机(协议字段保留,行为对齐「移除自动移动」规格)。+ // 池条目即动画名:turn/action 命中的条目直接作为 adHoc.status 交给视频切换层。useEffect(() => {- if (isBuiltin === false || reducedMotion || activity !== 'idle')+ if (isPreset === false || reducedMotion || activity !== 'idle')return undefinedlet timer: number | undefinedfunction scheduleNextRoll() {@@ -332,8 +374,8 @@ export function Pet(props: PetProps) {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') {+ const status = pick(turnPool)+ if (status !== undefined && status !== 'idle') {setAdHoc({ seq: ++adHocSeqRef.current, status })return}@@ -341,9 +383,8 @@ export function Pet(props: PetProps) {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 })+ if (action.name !== undefined && action.name !== 'idle' && action.name !== current) {+ setAdHoc({ seq: ++adHocSeqRef.current, status: action.name })return}}@@ -353,12 +394,12 @@ export function Pet(props: PetProps) {}scheduleNextRoll()return () => window.clearTimeout(timer)- }, [activity, categories, idlePool, isBuiltin, reducedMotion, turnPool, weights])+ }, [activity, categories, idlePool, isPreset, reducedMotion, turnPool, weights])useEffect(() => {const sprite = spriteRef.currentconst asset = customAsset- if (isBuiltin || asset === null || customAssetPet !== activePet || sprite === null)+ if (isPreset || asset === null || customAssetPet !== activePet || sprite === null)return undefinedconst element = spriteconst loadedAsset = asset@@ -380,27 +421,27 @@ export function Pet(props: PetProps) {if (timer !== undefined)window.clearTimeout(timer)}- }, [activity, activePet, adHoc?.seq, customAsset, customAssetPet, isBuiltin, override?.loop, reducedMotion])+ }, [activity, activePet, adHoc?.seq, customAsset, customAssetPet, isPreset, override?.loop, reducedMotion])useEffect(() => {- if (override?.loop !== false || override === null || isBuiltin || !hasCustomAsset)+ if (override?.loop !== false || override === null || isPreset || !hasCustomAsset)return undefinedconst frames = spriteAction(override.status)const duration = (reducedMotion ? [frames[0]] : frames).reduce((total, frame) => total + frame.duration, 0)const timer = window.setTimeout(setOverride, duration, null)return () => window.clearTimeout(timer)- }, [hasCustomAsset, isBuiltin, override, reducedMotion])+ }, [hasCustomAsset, isPreset, override, reducedMotion])// 自定义精灵无 ended 事件:adHoc(点击回应/待机转向)播完按帧时长估算后清掉,- // 让 activity 回落 idle(内置宠物由视频 ended 事件驱动,走 handleEnded)。+ // 让 activity 回落 idle(预设宠物由视频 ended 事件驱动,走 handleEnded)。useEffect(() => {- if (adHoc === null || isBuiltin || !hasCustomAsset)+ if (adHoc === null || isPreset || !hasCustomAsset)return undefinedconst frames = spriteAction(adHoc.status)const duration = (reducedMotion ? [frames[0]] : frames).reduce((total, frame) => total + frame.duration, 0)const timer = window.setTimeout(setAdHoc, duration, null)return () => window.clearTimeout(timer)- }, [adHoc, hasCustomAsset, isBuiltin, reducedMotion])+ }, [adHoc, hasCustomAsset, isPreset, reducedMotion])function handleEnded(event?: Event) {// 只响应前台视频的 ended:被降级的后台视频在切换时已 pause + 清 onended(拆雷),@@ -450,7 +491,7 @@ export function Pet(props: PetProps) {{/* 视频筐本身不响应事件:可交互面收缩到下方 PET_HIT_BOX 命中区(与 dsh-pet.dsh-pet-hit 一致),事件从命中区冒泡到 app.tsx 的 dragRef 壳触发拖拽。 */}<div className="pointer-events-none relative h-[calc(var(--pet-width)*var(--pet-aspect))] w-[var(--pet-width)] select-none">- <If cond={isBuiltin}>+ <If cond={isPreset}>{/* 双 video 缓冲:前台 opacity-100 淡入、后台 opacity-0 淡出,切换经 loadeddata 就绪后交换(见开关 effect),无空窗/黑帧闪跳。视频均 pointer-events-none,避免截获命中区外的点击。 */}@@ -471,7 +512,7 @@ export function Pet(props: PetProps) {onError={() => setFailed(true)}/></If>- <If cond={!isBuiltin && hasCustomAsset}>+ <If cond={!isPreset && hasCustomAsset}><divref={spriteRef}className="pointer-events-none absolute inset-0 bg-contain bg-no-repeat"@@ -509,19 +550,21 @@ function isPetStatus(value: string): value is PetStatus {}/**- * 把内置配置池条目(内置资产键)映射为可播放的一次性回应状态(AdHocStatus)。- * 资产键 'wave' 归一化为播放状态 'waving';拖拽/方向专用状态不参与回应池;- * 其余条目必须是会话状态或 bubble,否则返回 null(调用方回落默认动画)。+ * 把预设配置池条目(动画名,webm 文件名主名)映射为可播放状态:预设宠物条目+ * 直接就是动画名(如 待机呼吸休闲 / 点击回应-开心跃动);兼容旧内置键 'wave'+ * → 'waving' 的归一化。拖拽/方向专用状态不参与回应池;其余必须命中会话状态+ * 或 bubble,否则返回 null(调用方回落默认动画)。*/-function toAdHocStatus(entry: string): AdHocStatus | null {+function toAdHocStatus(entry: string | undefined): string | null {+ if (entry === undefined)+ return nullconst status = poolEntryToStatus(entry)if (status === 'bubble')return statusif (status === 'dragging' || status === 'moving-left' || status === 'moving-right')return null- // isPetStatus 收窄为 PetStatus;拖拽/方向状态已在上方排除,剩余的 PetStatus- // 全部属于 AdHocStatus(= 会话状态 + bubble)。- return isPetStatus(status) ? (status as AdHocStatus) : null+ // 池条目为动画名时直接作为播放状态使用;其余必须是会话状态或 bubble。+ return isPetStatus(status) ? status : (status.length > 0 ? status : null)}function normalizeActivePet(value: string | null | undefined): string {@@ -543,26 +586,14 @@ function isSupportedAsset(value: Asset): boolean {&& value.spritesheet.length > 0}-function isLoopingAnimation(activity: Animation): boolean {+function isLoopingAnimation(activity: Animation | string): boolean {// moving-* 与 dragging 仅存在于原生拖拽期间(手势状态),持续播放直到拖拽结束。return activity === 'idle' || activity === 'running'|| activity === 'moving-left' || activity === 'moving-right'|| activity === 'dragging'}-function videoKey(activity: Animation): VideoKey {- if (activity === 'moving-left' || activity === 'moving-right')- return 'move'- if (activity === 'dragging')- return 'drag'- if (activity === 'waving')- return 'wave'- if (activity === 'bubble')- return 'bubble'- return activity-}--function spriteSequence(activity: Animation, reducedMotion: boolean, loop: boolean): { frames: Frame[], loopStart: number | null } {+function spriteSequence(activity: Animation | string, reducedMotion: boolean, loop: boolean): { frames: Frame[], loopStart: number | null } {const idleFrames = IDLE_DURATIONS.map((duration, column) => ({ column, duration: duration * 6, row: 0 }))const action = spriteAction(activity)if (activity === 'idle')@@ -574,11 +605,11 @@ function spriteSequence(activity: Animation, reducedMotion: boolean, loop: boolereturn { frames: [...action, ...idleFrames], loopStart: action.length }}-function spriteAction(activity: Animation): Frame[] {+function spriteAction(activity: Animation | string): Frame[] {if (activity === 'idle')return IDLE_DURATIONS.map((duration, column) => ({ column, duration, row: 0 }))const mapped = activity === 'turn' ? 'moving-right' : activity === 'bubble' ? 'waving' : activity === 'dragging' ? 'moving-right' : activity- const config = ACTIONS[mapped]+ const config = ACTIONS[mapped as keyof typeof ACTIONS] ?? ACTIONS.wavingreturn Array.from({ length: config.frames }, (_, column) => ({column,duration: column === config.frames - 1 ? config.lastDuration : config.duration,diff --git a/src/pet/main.tsx b/src/pet/main.tsxindex 52aa2cb4..e9928c96 100644--- a/src/pet/main.tsx+++ b/src/pet/main.tsx@@ -6,6 +6,10 @@ import './main.css'const root = document.getElementById('root') as HTMLElementroot.className = 'h-full w-full'+// 禁用桌宠窗口右键菜单:桌宠窗口是装饰性的透明置顶小窗,右键不应弹出+// WebView 默认 context menu(Chromium/WebView2 尊重 contextmenu 的 preventDefault)。+window.addEventListener('contextmenu', event => event.preventDefault(), { capture: true })+ReactDOM.createRoot(root).render(<React.StrictMode><App />diff --git a/src/pet/pet-config.test.ts b/src/pet/pet-config.test.tsindex 7fad6579..933ca3de 100644--- a/src/pet/pet-config.test.ts+++ b/src/pet/pet-config.test.ts@@ -1,11 +1,11 @@import type { PetCategory, PetWeights } from './pet-config'import { describe, expect, it, vi } from 'vitest'import {-pick,pickCategoryAction,pickWeightedCategory,poolEntryToStatus,+ resolvePresetName,rollKind,} from './pet-config'@@ -99,3 +99,55 @@ describe('poolEntryToStatus', () => {expect(poolEntryToStatus('turn')).toBe('turn')})})++describe('resolvePresetName', () => {+ const pools = {+ idlePool: ['待机呼吸休闲'],+ turnPool: ['东张西望'],+ dragPool: ['被鼠标拖拽悬空反馈'],+ clicksPool: ['点击回应-开心跃动', '点击回应-元气挥手'],+ } as const+ const assets: Record<string, string> = {+ '待机呼吸休闲': 'dsh-pet://localhost/maid-deepseek-whale/webm/%E5%BE%85.webm',+ '东张西望': 'dsh-pet://localhost/maid-deepseek-whale/webm/%E4%B8%9C.webm',+ '被鼠标拖拽悬空反馈': 'dsh-pet://localhost/maid-deepseek-whale/webm/%E8%A2%AB.webm',+ '点击回应-开心跃动': 'dsh-pet://localhost/maid-deepseek-whale/webm/%E5%BC%80.webm',+ // DSH 会话状态叠加映射名(与旧内置 maid-*.webm 一一对应)+ '深度思考碎碎念': 'dsh-pet://localhost/maid-deepseek-whale/webm/%E6%B7%B1.webm',+ '写代码': 'dsh-pet://localhost/maid-deepseek-whale/webm/%E5%86%99.webm',+ '轻快记录': 'dsh-pet://localhost/maid-deepseek-whale/webm/%E8%BD%BB.webm',+ '玩游戏气急败坏': 'dsh-pet://localhost/maid-deepseek-whale/webm/%E6%B0%94.webm',+ }++ it('returns the asset name directly when activity is already a playable name', () => {+ expect(resolvePresetName('待机呼吸休闲', pools, assets)).toBe('待机呼吸休闲')+ expect(resolvePresetName('点击回应-开心跃动', pools, assets)).toBe('点击回应-开心跃动')+ })++ it('maps statuses to their protocol pools', () => {+ vi.spyOn(Math, 'random').mockReturnValue(0.0)+ expect(resolvePresetName('idle', pools, assets)).toBe('待机呼吸休闲')+ expect(resolvePresetName('turn', pools, assets)).toBe('东张西望')+ expect(resolvePresetName('dragging', pools, assets)).toBe('被鼠标拖拽悬空反馈')+ expect(resolvePresetName('waving', pools, assets)).toBe('点击回应-开心跃动')+ vi.restoreAllMocks()+ })++ it('maps session statuses to the DSH overlay animation names', () => {+ expect(resolvePresetName('waiting', pools, assets)).toBe('深度思考碎碎念')+ expect(resolvePresetName('running', pools, assets)).toBe('写代码')+ expect(resolvePresetName('review', pools, assets)).toBe('轻快记录')+ expect(resolvePresetName('failed', pools, assets)).toBe('玩游戏气急败坏')+ })++ it('returns null for session statuses whose overlay asset is missing', () => {+ const partial: Record<string, string> = { 待机呼吸休闲: 'x.webm' }+ expect(resolvePresetName('running', pools, partial)).toBeNull()+ expect(resolvePresetName('bubble', pools, partial)).toBeNull()+ })++ it('returns null when the pool entry is not backed by an asset', () => {+ expect(resolvePresetName('idle', { ...pools, idlePool: ['不存在.webm'] }, assets)).toBeNull()+ expect(resolvePresetName('idle', { ...pools, idlePool: [] }, assets)).toBeNull()+ })+})diff --git a/src/pet/pet-config.ts b/src/pet/pet-config.tsindex 584883a8..6e0c34ca 100644--- a/src/pet/pet-config.ts+++ b/src/pet/pet-config.ts@@ -1,12 +1,13 @@/**- * pet-config.ts — 内置桌宠配置(dsh-pet assets/config.jsonc 协议)的纯逻辑层。+ * pet-config.ts — 预设桌宠配置(dsh-pet assets/config.jsonc 协议)的纯逻辑层。*- * 配置由 Rust 从 dsh-tauri-pet 包 assets/config.jsonc 读取、剥注释并校验后经- * `get_builtin_pet_config` 命令返回(字段形状 = 子仓库 dsh-pet assets/config.jsonc- * 协议的受支持子集,动画池条目 = 内置资产键白名单)。本模块只做两件事:+ * 配置由 Rust 从 ~/.dsh/pets/<id>/config.jsonc 读取、剥注释并校验后经+ * `get_preset_pet_config` 命令返回(字段形状 = 子仓库 dsh-pet assets/config.jsonc+ * 协议的受支持子集,动画池条目 = 动画名 = webm 文件名主名)。本模块只做两件事:* 1. 类型收敛:把命令返回值声明成可直接消费的结构;* 2. 权重掷骰:移植 dsh-pet src/shared/pickers.ts 的 rollKind / pickWeightedCategory /- * pickCategoryAction(DSH 无自动漫游,move 档由调用方决定保持待机,不在本模块移动窗口)。+ * pickCategoryAction(DSH 无自动漫游,move 档由调用方决定保持待机,不在本模块移动窗口),+ * 以及按播放状态解析实际动画名(resolvePresetName)。* 无 React / DOM / Tauri 依赖,可独立单测。*/@@ -120,3 +121,58 @@ export function pickCategoryAction(export function poolEntryToStatus(entry: string): string {return entry === 'wave' ? 'waving' : entry}++/**+ * DSH 会话状态 → dsh-pet 动画名(webm 文件名主名)的叠加映射。+ *+ * dsh-pet 协议(config.jsonc)只有 idle/turn/drag/clicks/moves/categories/events 池,+ * 没有 waiting/running/review/failed/bubble 这些 DSH 会话状态的对应池。这些动画文件+ * 在预设资产里真实存在(与旧内置 maid-*.webm 按字节一一对应,见 pet.todo.md 4.0),+ * 由本表把会话状态映射到具体文件名:running 循环写代码、waiting 深度思考碎碎念、+ * review 轻快记录、failed 玩游戏气急败坏、bubble 鲸鱼吐泡泡特效。+ * 资产缺失时 resolvePresetName 仍返回 null(调用方保持当前动画,不做静默兜底)。+ */+export const PRESET_SESSION_ANIMATIONS: Record<string, string> = {+ waiting: '深度思考碎碎念',+ running: '写代码',+ review: '轻快记录',+ failed: '玩游戏气急败坏',+ bubble: '鲸鱼吐泡泡特效',+}++/**+ * 预设宠物:把播放状态解析为实际动画名(webm 文件名主名,如 待机呼吸休闲)。+ * - 活动名本身就是可播放动画名(adHoc 池条目 / 会话状态映射名)时直接命中资产;+ * - 会话状态(waiting/running/review/failed/bubble)经 PRESET_SESSION_ANIMATIONS+ * 叠加映射到具体动画名;映射名没有对应资产时返回 null(保持当前动画);+ * - 状态档(idle/dragging/turn/waving)从对应池等概率抽一个名字。+ */+export function resolvePresetName(+ activity: string,+ pools: {+ idlePool: readonly string[]+ turnPool: readonly string[]+ dragPool: readonly string[]+ clicksPool: readonly string[]+ },+ assets: Record<string, string>,+): string | null {+ if (assets[activity] !== undefined)+ return activity+ const sessionName = PRESET_SESSION_ANIMATIONS[activity]+ if (sessionName !== undefined && assets[sessionName] !== undefined)+ return sessionName+ const pool = activity === 'idle'+ ? pools.idlePool+ : activity === 'dragging'+ ? pools.dragPool+ : activity === 'turn'+ ? pools.turnPool+ : activity === 'waving'+ ? pools.clicksPool+ : null+ if (pool === null || pool.length === 0)+ return null+ const name = pick(pool)+ return assets[name] !== undefined ? name : null+}