DeepSeek Harness Tauri 桌面版 | Only 8mb installer, zero environment setup, preset plugins, Windows / macOS / Linux.
refactor(pet): raw session forwarding with drag webm and hook-based webview
hairyf33539e8a5914
diff --git a/packages/dsh-tauri-pet/assets/maid-drag.webm b/packages/dsh-tauri-pet/assets/maid-drag.webmnew file mode 100644index 00000000..728f04b2Binary files /dev/null and b/packages/dsh-tauri-pet/assets/maid-drag.webm differdiff --git a/packages/dsh-tauri-pet/src/client/constants/index.ts b/packages/dsh-tauri-pet/src/client/constants/index.tsindex ce654bbc..3f3cf34a 100644--- a/packages/dsh-tauri-pet/src/client/constants/index.ts+++ b/packages/dsh-tauri-pet/src/client/constants/index.ts@@ -5,7 +5,6 @@ export const PET_SECTION_ORDER = 230export const PET_STYLES_EFFECT = 'dsh-tauri-pet: styles'export const PET_SECTION_EFFECT = 'dsh-tauri-pet: settings section'export const PET_ICON_PATCH_EFFECT = 'dsh-tauri-pet: sidebar icon patch'-export const PET_ACTIVITY_EFFECT = 'dsh-tauri-pet: session activity'export const PET_PREFILL_EFFECT = 'dsh-tauri-pet: conversation prefill'export const PET_CLIENT_NS = 'dsh-tauri-pet'export const CONVERSATION_INPUT_LEFT_SLOT = 'conversation.input.left'@@ -13,7 +12,6 @@ export const PET_PREFILL_ID = 'dsh-tauri-pet-prefill'export const PET_PREFILL_ORDER = 230export const PET_PREFILL_PRIORITY = 0export const PET_HATCH_PROMPT = '/hatch-dsh-pet 根据你对我的了解,养一只宠物'-export const PET_ACTIVITY_BUBBLE_MAX = 120export const CMD_GET_PET_STATUS = 'get_pet_status'export const CMD_SET_PET_ENABLED = 'set_pet_enabled'export const CMD_SET_ACTIVE_PET = 'set_active_pet'@@ -22,8 +20,7 @@ export const CMD_SHOW_PET = 'show_pet'export const CMD_HIDE_PET = 'hide_pet'export const CMD_LIST_PETS = 'list_pets'export const CMD_IMPORT_PET = 'import_pet'-export const CMD_SET_PET_ACTIVITY = 'set_pet_activity'-export const CMD_SET_PET_SESSIONS = 'set_pet_sessions'+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 BUILTIN_PET_ID = 'maid-deepseek-whale'diff --git a/packages/dsh-tauri-pet/src/client/index.ts b/packages/dsh-tauri-pet/src/client/index.tsindex 51580a5b..3711ebbc 100644--- a/packages/dsh-tauri-pet/src/client/index.ts+++ b/packages/dsh-tauri-pet/src/client/index.ts@@ -18,7 +18,7 @@ import type { ClientContext } from 'dsh-tauri/client'import { PET_CLIENT_PLUGIN, PET_STYLES_EFFECT } from './constants'import { installLocale } from './locales'import { installPetIconPatch, registerPetPrefill, registerPetSection } from './register/pet'-import { installPetActivity } from './service/activity'+import { installPetSessionForwarder } from './service/activity'import { mountPetStyles } from './styles'/** 插件显示名(诊断元数据)。 */@@ -39,5 +39,5 @@ export function apply(ctx: ClientContext): void {registerPetSection(ctx)installPetIconPatch(ctx)registerPetPrefill(ctx)- installPetActivity(ctx)+ installPetSessionForwarder(ctx)}diff --git a/packages/dsh-tauri-pet/src/client/locales/index.ts b/packages/dsh-tauri-pet/src/client/locales/index.tsindex b52a2b1b..e6a20821 100644--- a/packages/dsh-tauri-pet/src/client/locales/index.ts+++ b/packages/dsh-tauri-pet/src/client/locales/index.ts@@ -1,4 +1,4 @@-/** Bilingual copy for the pet settings section and activity bubbles. */+/** Bilingual copy for the pet settings section. */import type { ClientContext } from 'dsh-tauri/client'import type { LocaleKey } from '../types'import { createExternalStore } from 'dsh-tauri/client'@@ -13,18 +13,6 @@ import {export { PET_CLIENT_NS as NS } from '../constants'const DICT_ZH: Record<LocaleKey, string> = {- activityApproval: '需审批',- activityFailed: '失败',- activityIdle: '空闲',- activityLimit: '已达上限',- activityPreparing: '准备中',- activityResult: '整理中',- activityReview: '待审阅',- activityRunning: '运行中',- activityStopped: '已停止',- activityThinking: '思考中',- activityWaiting: '等待中',- activityWorking: '执行中',codex: 'Codex',collapsePet: '收起宠物',create: '创建',@@ -34,8 +22,6 @@ const DICT_ZH: Record<LocaleKey, string> = {importFailed: '导入宠物失败',listFailed: '读取宠物列表失败',name: 'Pets',- pendingPlanReview: '待审阅方案',- pendingQuestion: '待回答',petDescWhale: BUILTIN_PET_DESC_ZH,petNameWhale: BUILTIN_PET_NAME,select: '选择',@@ -47,23 +33,10 @@ const DICT_ZH: Record<LocaleKey, string> = {tabCodexDesc: '从 Codex 或压缩包中导入 Codex 宠物(支持 .zip 文件)',tabInstalledDesc: '宠物会管理对话串,并突出显示需要关注的事项',toggleFailed: '切换桌宠窗口失败',- toolPrefix: '工具',wakePet: '唤醒宠物',}const DICT_EN: Record<LocaleKey, string> = {- activityApproval: 'Needs approval',- activityFailed: 'Failed',- activityIdle: 'Idle',- activityLimit: 'Limit reached',- activityPreparing: 'Preparing',- activityResult: 'Summarizing',- activityReview: 'Review',- activityRunning: 'Running',- activityStopped: 'Stopped',- activityThinking: 'Thinking',- activityWaiting: 'Waiting',- activityWorking: 'Working',codex: 'Codex',collapsePet: 'Collapse pet',create: 'Create',@@ -73,8 +46,6 @@ const DICT_EN: Record<LocaleKey, string> = {importFailed: 'Failed to import pet',listFailed: 'Failed to load pet list',name: 'Pets',- pendingPlanReview: 'Plan review',- pendingQuestion: 'Waiting for answer',petDescWhale: BUILTIN_PET_DESC_EN,petNameWhale: BUILTIN_PET_NAME,select: 'Choose',@@ -86,7 +57,6 @@ const DICT_EN: Record<LocaleKey, string> = {tabCodexDesc: 'Import Codex pets from Codex or archives (.zip files supported)',tabInstalledDesc: 'Pets manage your conversation threads and highlight items that need attention',toggleFailed: 'Failed to toggle the pet window',- toolPrefix: 'Tool',wakePet: 'Wake pet',}diff --git a/packages/dsh-tauri-pet/src/client/service/activity.ts b/packages/dsh-tauri-pet/src/client/service/activity.tsindex 2b35697f..e42e5d7b 100644--- a/packages/dsh-tauri-pet/src/client/service/activity.ts+++ b/packages/dsh-tauri-pet/src/client/service/activity.ts@@ -1,219 +1,109 @@import type { ClientContext } from 'dsh-tauri/client'-import type {- PetObservable,- PetRuntimeContext,- PetSessionActivity,- PetSessionEvent,- PetSessionSnapshot,- PetSessionStatus,-} from '../types'-import type { SessionStatusRecord } from '../utils/session-status'-import { compat, createLifecycleController } from 'dsh-tauri/client'-import { PET_ACTIVITY_EFFECT } from '../constants'-import { text } from '../locales'-import {- describePending,- describeSession,- mapPetActivity,- phaseActivity,- sessionTitle,-} from '../utils/activity'-import { createSessionStatus, reduceSessionEvent } from '../utils/session-status'-import { setPetSessions } from './pet'+import { createLifecycleController } from 'dsh-tauri/client'+import { toTransferable } from '../utils/transferable'+import { pushPetSession } from './pet'-function activityLabel(activity: PetSessionActivity): string {- switch (activity) {- case 'failed':- return text('activityFailed')- case 'review':- return text('activityReview')- case 'running':- return text('activityRunning')- case 'waiting':- return text('activityWaiting')- case 'idle':- default:- return text('activityIdle')- }-}+type SessionAction = 'create' | 'update' | 'remove'-function resolvePendingSource(ctx: ClientContext): PetObservable<ReadonlyMap<string, unknown>> | undefined {- const lookup = ctx as unknown as { get?: (name: string) => unknown }- try {- const service = lookup.get?.('uiSession') as PetRuntimeContext['uiSession'] | undefined- return service?.pendingInteractions+interface RawSessionBinding {+ sessionId: string+ session: {+ getSnapshot: () => unknown+ subscribe: (listener: () => void) => () => void}- catch {- return undefined- }-}--function pendingKindOf(value: unknown): string | undefined {- if (value && typeof value === 'object')- return typeof (value as { kind?: unknown }).kind === 'string' ? (value as { kind: string }).kind : undefined- return typeof value === 'string' ? value : undefined}-function resolveText(key: string): string {- return text(key as Parameters<typeof text>[0])+interface RawSessions {+ list: {+ getSnapshot: () => {+ byId?: Record<string, Record<string, unknown>>+ ids: readonly string[]+ }+ subscribe: (listener: () => void) => () => void+ }+ binding: (id: string) => RawSessionBinding | undefined}/**- * 从会话事件窗口把新事件回放进归约器。窗口是「完整事件窗口」快照,因此每次- * 推送都按序喂入;`reduceSessionEvent` 会按 seq 去重,这里再按 `lastSeq` 提前- * 跳过已消费事件,避免长会话反复重放整段窗口(O(n²) → O(n))。+ * 将 DSH 会话原始快照按生命周期推送给桌宠窗口,不生成宠物专用 projection。*/-function replayEventWindow(record: SessionStatusRecord, window: { entries?: PetSessionEvent[] }): void {- const entries = Array.isArray(window.entries) ? window.entries : []- for (const event of entries) {- const seq = Number(event?.seq ?? 0)- if (Number.isFinite(seq) && seq <= record.lastSeq)- continue- reduceSessionEvent(record, event)- }-}--/** Mirror every known Codex session into one native snapshot; the pet owns visual arbitration. */-export function installPetActivity(ctx: ClientContext): void {+export function installPetSessionForwarder(ctx: ClientContext): void {ctx.effect(() => {- const runtime = compat(ctx) as unknown as PetRuntimeContextconst controller = createLifecycleController()- const pendingSource = resolvePendingSource(ctx)- const snapshots = new Map<string, PetSessionSnapshot | undefined>()- const reducerStates = new Map<string, SessionStatusRecord>()const disposers = new Map<string, () => void>()- let lastPayload = ''+ const known = new Set<string>()let disposed = false- let pushChain: Promise<void> = Promise.resolve()-- function push(): void {- const list = runtime.sessions.list.getSnapshot()- const sessions: PetSessionStatus[] = []- for (const id of list.ids) {- const summary = list.byId?.[id]- const snapshot = snapshots.get(id)- const pending = pendingSource?.getSnapshot().get(id) ?? summary?.pendingInteraction- const record = reducerStates.get(id)-- let activity: PetSessionActivity- if (pending !== undefined)- activity = 'waiting'- else if (record !== undefined && record.phase !== 'idle' && record.phase !== 'stopped')- activity = phaseActivity(record)- else- activity = mapPetActivity(summary, snapshot, pending)-- // 会话真正空闲(未运行、未完成、无报错、无待决策)时不弹 Toast。- if (activity === 'idle')- continue- const title = sessionTitle(summary?.title ?? summary?.displayTitle, activityLabel(activity))- let description: string- if (pending !== undefined)- description = describePending(pendingKindOf(pending), resolveText)- else if (record !== undefined && record.phase !== 'idle')- description = describeSession(record, resolveText)- else- description = resolveText('activityRunning')-- sessions.push({ id, activity, bubble: title, description })- }- sessions.sort((left, right) => {- const current = runtime.sessions.list.getSnapshot().current- if (left.id === current)- return -1- if (right.id === current)- return 1- return left.id.localeCompare(right.id)- })- const payload = JSON.stringify(sessions)- if (payload === lastPayload)+ function emit(action: SessionAction, session: Record<string, unknown>): void {+ if (disposed)return- lastPayload = payload- pushChain = pushChain.then(async () => {- if (disposed)- return- try {- await setPetSessions(sessions)- }- catch (error) {- console.error('[dsh-tauri-pet] update pet sessions failed:', error)- }+ const payload = toTransferable(session) as Record<string, unknown>+ void pushPetSession(action, payload).catch((error) => {+ if (!disposed)+ console.error(`[dsh-tauri-pet] session ${action} push failed:`, error)})}- /** 为单条会话绑定快照/事件订阅;返回组合卸载函数。 */- function bindSession(id: string): void {- const source = runtime.sessions.binding?.(id)- if (source === undefined)- return- const disposeList: Array<() => void> = []+ const sessions = ctx.sessions as unknown as RawSessions- const sessionStore = source.session- if (sessionStore !== undefined) {- snapshots.set(id, sessionStore.getSnapshot())- disposeList.push(sessionStore.subscribe(() => {- snapshots.set(id, sessionStore.getSnapshot())- push()- }))- }+ function snapshotOf(id: string, binding: RawSessionBinding): Record<string, unknown> {+ const list = sessions.list.getSnapshot()+ const summary = list.byId?.[id]+ const snapshot = binding.session.getSnapshot()+ const value = snapshot && typeof snapshot === 'object'+ ? snapshot as Record<string, unknown>+ : { value: snapshot }+ return { id: binding.sessionId, ...(summary ?? {}), ...value }+ }- const eventSource = source.eventSource- if (eventSource !== undefined) {- const record = createSessionStatus()- reducerStates.set(id, record)- replayEventWindow(record, eventSource.getSnapshot())- disposeList.push(eventSource.subscribe(() => {- replayEventWindow(record, eventSource.getSnapshot())- push()- }))+ function bind(id: string, action: SessionAction): void {+ const binding = sessions.binding(id)+ if (binding === undefined) {+ emit(action, { id })+ return}-- disposers.set(- id,- () => {- for (const dispose of disposeList)- dispose()- },- )+ emit(action, snapshotOf(id, binding))+ disposers.set(id, binding.session.subscribe(() => emit('update', snapshotOf(id, binding))))}- function syncSessions(): void {- const ids = new Set(runtime.sessions.list.getSnapshot().ids)- for (const [id, dispose] of disposers) {+ function sync(): void {+ const list = sessions.list.getSnapshot()+ const ids = new Set(list.ids)+ for (const id of known) {if (!ids.has(id)) {- dispose()+ disposers.get(id)?.()disposers.delete(id)- snapshots.delete(id)- reducerStates.delete(id)+ emit('remove', { id })}}for (const id of ids) {- if (disposers.has(id))+ const binding = sessions.binding(id)+ if (binding === undefined) {+ if (!known.has(id))+ bind(id, 'create')continue- bindSession(id)+ }+ if (disposers.has(id))+ emit('update', snapshotOf(id, binding))+ else+ bind(id, known.has(id) ? 'update' : 'create')}- push()+ known.clear()+ for (const id of ids)+ known.add(id)}- controller.add(runtime.sessions.list.subscribe(syncSessions))- if (pendingSource !== undefined) {- controller.add(pendingSource.subscribe(() => {- syncSessions()- push()- }))- }- const bindingRetryTimer = globalThis.setInterval(syncSessions, 250)- controller.add(() => globalThis.clearInterval(bindingRetryTimer))+ controller.add(sessions.list.subscribe(sync))+ const retryTimer = globalThis.setInterval(sync, 250)+ controller.add(() => globalThis.clearInterval(retryTimer))controller.add(() => {disposed = truefor (const dispose of disposers.values())dispose()disposers.clear()- snapshots.clear()- reducerStates.clear()+ known.clear()})- syncSessions()+ sync()return () => controller.dispose()- }, PET_ACTIVITY_EFFECT)+ }, 'dsh-tauri-pet: raw session events')}diff --git a/packages/dsh-tauri-pet/src/client/service/pet.ts b/packages/dsh-tauri-pet/src/client/service/pet.tsindex 01b5974c..83d3ac66 100644--- a/packages/dsh-tauri-pet/src/client/service/pet.ts+++ b/packages/dsh-tauri-pet/src/client/service/pet.ts@@ -1,4 +1,4 @@-import type { PetActivity, PetAsset, PetListItem, PetSessionStatus, PetSource, PetStatus } from '../types'+import type { PetAsset, PetListItem, PetSource, PetStatus } from '../types'import { invokeBridgedTauri } from 'dsh-tauri/client'import {CMD_GET_BUILTIN_PET_ASSETS,@@ -7,70 +7,57 @@ import {CMD_HIDE_PET,CMD_IMPORT_PET,CMD_LIST_PETS,+ CMD_PUSH_PET_SESSION,CMD_SET_ACTIVE_PET,- CMD_SET_PET_ACTIVITY,CMD_SET_PET_ENABLED,- CMD_SET_PET_SESSIONS,CMD_SET_PET_SIZE,CMD_SHOW_PET,} from '../constants'-/** Query the complete persistent and transient pet state. */export function fetchPetStatus(): Promise<PetStatus> {return invokeBridgedTauri<PetStatus>(CMD_GET_PET_STATUS)}-/** Persistently enable or disable the pet capability. */export function setPetEnabled(enabled: boolean): Promise<PetStatus> {return invokeBridgedTauri<PetStatus>(CMD_SET_PET_ENABLED, { enabled })}-/** Persist the selected pet package id. */export function setActivePet(id: string): Promise<PetStatus> {return invokeBridgedTauri<PetStatus>(CMD_SET_ACTIVE_PET, { id })}-/** Persist the pet scale percentage. */export function setPetSize(size: number): Promise<PetStatus> {return invokeBridgedTauri<PetStatus>(CMD_SET_PET_SIZE, { size })}-/** Restore a previously enabled pet window. */export function showPet(): Promise<PetStatus> {return invokeBridgedTauri<PetStatus>(CMD_SHOW_PET)}-/** Hide the window without disabling the persisted pet capability. */export function hidePet(): Promise<PetStatus> {return invokeBridgedTauri<PetStatus>(CMD_HIDE_PET)}-/** List imported Codex pet archives. */export function fetchPetList(source: PetSource): Promise<PetListItem[]> {return invokeBridgedTauri<PetListItem[]>(CMD_LIST_PETS, { source })}-/** Resolve the selected Chat/Codex spritesheet directly from its owner directory. */export function fetchPetAsset(id: string): Promise<PetAsset> {return invokeBridgedTauri<PetAsset>(CMD_GET_PET_ASSET, { id })}-/** Import one Codex-compatible zip archive. */export function importPet(name: string, data: string): Promise<PetListItem> {return invokeBridgedTauri<PetListItem>(CMD_IMPORT_PET, { name, data })}-/** Push the current session-derived animation and optional speech bubble. */-export function setPetActivity(activity: PetActivity, bubble?: string): Promise<PetStatus> {- return invokeBridgedTauri<PetStatus>(CMD_SET_PET_ACTIVITY, { activity, bubble })+/** Forward one untouched DSH session snapshot to the pet webview. */+export function pushPetSession(+ action: 'create' | 'update' | 'remove',+ session: Record<string, unknown>,+): Promise<void> {+ return invokeBridgedTauri<void>(CMD_PUSH_PET_SESSION, { action, session })}-/** Push the complete session snapshot; the pet window derives one visual state and per-session Toasts. */-export function setPetSessions(sessions: PetSessionStatus[]): Promise<PetStatus> {- return invokeBridgedTauri<PetStatus>(CMD_SET_PET_SESSIONS, { sessions })-}--/** Load built-in media through the Rust runtime resource boundary. */export function fetchBuiltinPetAssets(): Promise<{ assets: Record<string, string> }> {return invokeBridgedTauri<{ assets: Record<string, string> }>(CMD_GET_BUILTIN_PET_ASSETS)}diff --git a/packages/dsh-tauri-pet/src/client/types/index.ts b/packages/dsh-tauri-pet/src/client/types/index.tsindex b35237fb..bfdeedb6 100644--- a/packages/dsh-tauri-pet/src/client/types/index.ts+++ b/packages/dsh-tauri-pet/src/client/types/index.ts@@ -1,30 +1,8 @@-/** Shared client types for the pet settings, bridge, and session activity. */-export type PetActivity = 'failed' | 'idle' | 'moving-left' | 'moving-right' | 'review' | 'running' | 'turn' | 'waiting' | 'waving'--/** Session states selected by the activity adapter before native animation details. */-export type PetSessionActivity = Extract<PetActivity, 'failed' | 'idle' | 'review' | 'running' | 'waiting'>--/**- * Single session projection pushed to the pet window.- *- * - `bubble` — 固定标题(会话名/展示名),创建 toast 时写入,之后不随状态变化。- * - `description` — 实时描述(思考 / 工具 + 工具名 / 需决策 / 待审阅 / 失败…),- * 每次状态推进都更新,驱动 toast 的 description 槽原地刷新。- */-export interface PetSessionStatus {- activity: PetSessionActivity- bubble?: string | null- description?: string | null- id: string-}-+/** Shared client types for pet settings and raw session forwarding. */export interface PetStatus {active_pet: string- activity: PetActivity- bubble?: string | nullenabled: booleanpet_size?: number | null- sessions?: PetSessionStatus[]visible: boolean}@@ -46,56 +24,6 @@ export interface PetAsset {spritesheet: string}-export interface PetSessionSummary {- completed?: boolean- displayTitle?: string- id: string- pendingInteraction?: unknown- running?: boolean- title?: string-}--export interface PetSessionSnapshot {- awaitingFirstTurn?: boolean- lastAgentError?: string | null- pendingSubmissions?: readonly unknown[]- queue?: readonly unknown[]- running?: boolean-}--export interface PetObservable<T> {- getSnapshot: () => T- subscribe: (listener: () => void) => () => void-}--/** A single session event that can fall through the session event window. */-export interface PetSessionEvent {- data?: Record<string, unknown>- seq?: number- type?: string-}--/** Session event window snapshot exposed by `eventSource.getSnapshot()`. */-export interface PetSessionEventWindow {- change?: { kind?: string, entries?: PetSessionEvent[] }- entries?: PetSessionEvent[]- hasMore?: boolean- revision?: number-}--export interface PetSessionsRuntime {- binding?: (id: string) => {- eventSource?: PetObservable<PetSessionEventWindow>- session?: PetObservable<PetSessionSnapshot>- } | undefined- list: PetObservable<{- byId?: Record<string, PetSessionSummary>- current?: string- ids: string[]- }>- open?: (id: string) => void-}-export interface WorkspaceItem {id?: stringsessionIds?: readonly string[]@@ -103,16 +31,23 @@ export interface WorkspaceItem {}export interface PetRuntimeContext {- sessions: PetSessionsRuntime- uiSession?: {- pendingInteractions?: PetObservable<ReadonlyMap<string, unknown>>+ sessions: {+ list: {+ getSnapshot: () => {+ current?: string+ ids: readonly string[]+ }+ }+ open?: (id: string) => void}workspaces: {connectWorkspace?: (id: string) => Promise<string>- list: PetObservable<{- items?: WorkspaceItem[]- recentWorkspaceId?: string- }>+ list: {+ getSnapshot: () => {+ items?: WorkspaceItem[]+ recentWorkspaceId?: string+ }+ }}}@@ -129,19 +64,7 @@ export interface ConversationInputLeftProps {}export type LocaleKey- = | 'activityApproval'- | 'activityFailed'- | 'activityIdle'- | 'activityLimit'- | 'activityPreparing'- | 'activityResult'- | 'activityReview'- | 'activityRunning'- | 'activityStopped'- | 'activityThinking'- | 'activityWaiting'- | 'activityWorking'- | 'codex'+ = | 'codex'| 'collapsePet'| 'create'| 'createFailed'@@ -150,8 +73,7 @@ export type LocaleKey| 'importFailed'| 'listFailed'| 'name'- | 'pendingPlanReview'- | 'pendingQuestion'+| 'petDescWhale'| 'petNameWhale'| 'select'@@ -163,5 +85,4 @@ export type LocaleKey| 'tabCodexDesc'| 'tabInstalledDesc'| 'toggleFailed'- | 'toolPrefix'| 'wakePet'diff --git a/packages/dsh-tauri-pet/src/client/utils/activity.test.ts b/packages/dsh-tauri-pet/src/client/utils/activity.test.tsdeleted file mode 100644index 6409da5b..00000000--- a/packages/dsh-tauri-pet/src/client/utils/activity.test.ts+++ /dev/null@@ -1,69 +0,0 @@-import type { PetSessionEvent } from '../types'-import { describe, expect, it } from 'vitest'-import { activityBubble, describePending, describeSession, mapPetActivity, sessionTitle } from './activity'-import { createSessionStatus, reduceSessionEvent } from './session-status'--function event(type: string, data: Record<string, unknown> = {}, seq = 1): PetSessionEvent {- return { type, data, seq }-}--const text = (key: string) => key--describe('mapPetActivity', () => {- it('follows the Codex reference state precedence', () => {- const summary = { id: 'session', running: true, completed: true }- const session = { running: true, lastAgentError: 'boom' }- expect(mapPetActivity(summary, session, { kind: 'question' })).toBe('waiting')- expect(mapPetActivity({ ...summary, completed: false }, { ...session, lastAgentError: 'boom' }, undefined)).toBe('running')- expect(mapPetActivity({ ...summary, completed: false }, { ...session, lastAgentError: null }, undefined)).toBe('running')- expect(mapPetActivity({ ...summary, completed: false }, { ...session, lastAgentError: null }, { kind: 'question' })).toBe('waiting')- expect(mapPetActivity({ ...summary, running: false }, { ...session, running: false, lastAgentError: null }, undefined)).toBe('review')- expect(mapPetActivity({ id: 'session' }, { running: false, lastAgentError: 'boom' }, undefined)).toBe('failed')- expect(mapPetActivity({ id: 'session' }, { running: false, lastAgentError: null }, undefined)).toBe('idle')- })-})--describe('activityBubble', () => {- it('includes context for non-idle states and clears idle bubbles', () => {- expect(activityBubble('running', 'Running', 'Fix tests')).toBe('Running: Fix tests')- expect(activityBubble('waiting', 'Waiting')).toBe('Waiting')- expect(activityBubble('idle', 'Idle', 'Done')).toBeUndefined()- })-- it('truncates long Unicode titles to the bridge-safe bubble limit', () => {- const bubble = activityBubble('running', '运行中', '鲸'.repeat(200))- expect(Array.from(bubble ?? '')).toHaveLength(120)- expect(bubble?.startsWith('运行中: ')).toBe(true)- })-})--describe('sessionTitle', () => {- it('uses the session title and falls back to the label', () => {- expect(sessionTitle('Fix tests', 'Running')).toBe('Fix tests')- expect(sessionTitle(' ', 'Running')).toBe('Running')- expect(sessionTitle(undefined, 'Waiting')).toBe('Waiting')- })-})--describe('describeSession', () => {- it('maps each phase to its copy', () => {- const run = (type: string, data: Record<string, unknown> = {}, seq = 1) =>- reduceSessionEvent(createSessionStatus(), event(type, data, seq))-- expect(describeSession(run('turn/start'), text)).toBe('activityPreparing')- expect(describeSession(run('tool/call', { name: 'Pwsh', callId: 'c1' }, 10), text)).toBe('activityWorking · toolPrefix Pwsh')- expect(describeSession(run('tool/result', { callId: 'c1' }, 11), text)).toBe('activityResult')- expect(describeSession(run('approval/asked', { id: 'a1' }, 12), text)).toBe('activityApproval')- expect(describeSession(run('turn/end', { reason: { kind: 'completed' } }, 13), text)).toBe('activityReview')- })-})--describe('describePending', () => {- it('maps decision kinds to copy', () => {- expect(describePending('approval', text)).toBe('activityApproval')- expect(describePending('plan-review', text)).toBe('pendingPlanReview')- expect(describePending('question', text)).toBe('pendingQuestion')- expect(describePending('user-question', text)).toBe('activityWaiting')- expect(describePending(undefined, text)).toBe('activityWaiting')- })-})diff --git a/packages/dsh-tauri-pet/src/client/utils/activity.ts b/packages/dsh-tauri-pet/src/client/utils/activity.tsdeleted file mode 100644index 8e04c891..00000000--- a/packages/dsh-tauri-pet/src/client/utils/activity.ts+++ /dev/null@@ -1,91 +0,0 @@-import type { PetSessionActivity, PetSessionSnapshot, PetSessionSummary } from '../types'-import type { SessionStatusRecord } from './session-status'-import { PET_ACTIVITY_BUBBLE_MAX } from '../constants'-import { phaseToActivity } from './session-status'--/** Map the Codex reference precedence to the desktop animation protocol. */-export function mapPetActivity(- summary: PetSessionSummary | undefined,- session: PetSessionSnapshot | undefined,- pendingInteraction: unknown,-): PetSessionActivity {- if (pendingInteraction !== undefined)- return 'waiting'- if (summary?.running === true || session?.running === true)- return 'running'- if (summary?.completed === true)- return 'review'- if (session?.lastAgentError !== null && session?.lastAgentError !== undefined)- return 'failed'- return 'idle'-}--/** 会话固定标题:优先展示名/标题,缺省回落动作文案,保证 toast title 非空。 */-export function sessionTitle(title: string | undefined, label: string): string {- const normalized = (title ?? '').trim()- return normalized || label-}--/** 由归约 phase 推导到 pet 动作(供 push 使用,与 phaseToActivity 对齐)。 */-export function phaseActivity(record: SessionStatusRecord): PetSessionActivity {- return phaseToActivity(record.phase)-}--/**- * 把一条归约记录转成实时描述文案;`text` 由调用方提供(便于单测),- * 映射表逐点对齐 dsh-dafeiyu 各阶段 → 文案。- */-export function describeSession(- record: SessionStatusRecord,- text: (key: string, params?: Record<string, string>) => string,-): string {- switch (record.phase) {- case 'preparing':- return text('activityPreparing')- case 'thinking':- return text('activityThinking')- case 'result':- return text('activityResult')- case 'working':- return record.toolName- ? `${text('activityWorking')} · ${text('toolPrefix')} ${record.toolName}`- : text('activityWorking')- case 'waiting':- return describePending(record.pendingKind, text)- case 'review':- return text('activityReview')- case 'failed':- return text('activityFailed')- case 'stopped':- return text('activityStopped')- case 'idle':- default:- return text('activityIdle')- }-}--/** 等待决策的类型 → 描述(对齐 dsh-dafeiyu 的 approval / user-question 与 uiSession 的 kind)。 */-export function describePending(- pendingKind: string | undefined,- text: (key: string, params?: Record<string, string>) => string,-): string {- switch (pendingKind) {- case 'approval':- return text('activityApproval')- case 'plan-review':- return text('pendingPlanReview')- case 'question':- return text('pendingQuestion')- case 'user-question':- return text('activityWaiting')- default:- return text('activityWaiting')- }-}--export function activityBubble(activity: PetSessionActivity, label: string, title?: string): string | undefined {- if (activity === 'idle')- return undefined- const message = title ? `${label}: ${title}` : label- return Array.from(message).slice(0, PET_ACTIVITY_BUBBLE_MAX).join('')-}diff --git a/packages/dsh-tauri-pet/src/client/utils/session-status.test.ts b/packages/dsh-tauri-pet/src/client/utils/session-status.test.tsdeleted file mode 100644index 9a437204..00000000--- a/packages/dsh-tauri-pet/src/client/utils/session-status.test.ts+++ /dev/null@@ -1,123 +0,0 @@-import type { PetSessionEvent } from '../types'-import { describe, expect, it } from 'vitest'-import {- createSessionStatus,- isUserQuestionTool,- phaseToActivity,- reduceSessionEvent,- toolCallIdOf,-} from './session-status'--function event(type: string, data: Record<string, unknown> = {}, seq = 1): PetSessionEvent {- return { type, data, seq }-}--describe('phaseToActivity', () => {- it('maps thinking/working to running, waiting to waiting, etc.', () => {- expect(phaseToActivity('preparing')).toBe('running')- expect(phaseToActivity('thinking')).toBe('running')- expect(phaseToActivity('working')).toBe('running')- expect(phaseToActivity('waiting')).toBe('waiting')- expect(phaseToActivity('review')).toBe('review')- expect(phaseToActivity('failed')).toBe('failed')- expect(phaseToActivity('idle')).toBe('idle')- expect(phaseToActivity('stopped')).toBe('idle')- })-})--describe('reduceSessionEvent', () => {- it('turn/start prepares the turn', () => {- const state = reduceSessionEvent(createSessionStatus(), event('turn/start', {}, 1))- expect(state.phase).toBe('preparing')- expect(state.turnActive).toBe(true)- expect(state.activity).toBe('running')- })-- it('tool/call enters working with the tool name', () => {- let state = reduceSessionEvent(createSessionStatus(), event('turn/start', {}, 1))- state = reduceSessionEvent(state, event('tool/call', { name: 'Pwsh', callId: 'c1' }, 2))- expect(state.phase).toBe('working')- expect(state.toolName).toBe('Pwsh')- expect(state.activity).toBe('running')- })-- it('tool/result resumes to result (整理) when no tools remain open', () => {- let state = reduceSessionEvent(createSessionStatus(), event('turn/start', {}, 1))- state = reduceSessionEvent(state, event('tool/call', { name: 'Pwsh', callId: 'c1' }, 2))- state = reduceSessionEvent(state, event('tool/result', { callId: 'c1' }, 3))- expect(state.phase).toBe('result')- expect(state.toolName).toBeUndefined()- })-- it('user-question tool enters waiting', () => {- let state = reduceSessionEvent(createSessionStatus(), event('turn/start', {}, 1))- state = reduceSessionEvent(state, event('tool/call', { name: 'ask_user_question', callId: 'q1' }, 2))- expect(state.phase).toBe('waiting')- expect(state.activity).toBe('waiting')- })-- it('approval/asked enters waiting with approval kind', () => {- let state = reduceSessionEvent(createSessionStatus(), event('turn/start', {}, 1))- state = reduceSessionEvent(state, event('approval/asked', { id: 'a1', toolName: 'node' }, 2))- expect(state.phase).toBe('waiting')- expect(state.pendingKind).toBe('approval')- expect(state.activity).toBe('waiting')- })-- it('turn/end completed settles to review', () => {- let state = reduceSessionEvent(createSessionStatus(), event('turn/start', {}, 1))- state = reduceSessionEvent(state, event('turn/end', { reason: { kind: 'completed' } }, 2))- expect(state.phase).toBe('review')- expect(state.activity).toBe('review')- })-- it('turn/end blocked stays waiting, aborted stops, other reason fails', () => {- let state = reduceSessionEvent(createSessionStatus(), event('turn/start', {}, 1))- state = reduceSessionEvent(state, event('turn/end', { reason: { kind: 'blocked' } }, 2))- expect(state.phase).toBe('waiting')-- state = reduceSessionEvent(createSessionStatus(), event('turn/start', {}, 1))- state = reduceSessionEvent(state, event('turn/end', { reason: { kind: 'aborted' } }, 2))- expect(state.phase).toBe('stopped')-- state = reduceSessionEvent(createSessionStatus(), event('turn/start', {}, 1))- state = reduceSessionEvent(state, event('turn/end', { reason: { kind: 'max-tokens' } }, 2))- expect(state.phase).toBe('failed')- })-- it('replaying an already-consumed seq is a no-op', () => {- let state = reduceSessionEvent(createSessionStatus(), event('turn/start', {}, 1))- state = reduceSessionEvent(state, event('tool/call', { name: 'Pwsh', callId: 'c1' }, 2))- const after = reduceSessionEvent(state, event('tool/call', { name: 'Pwsh', callId: 'c1' }, 2))- expect(after).toBe(state)- })-- it('a held turn does not flicker to idle between tool calls', () => {- // 两次 tool/call 之间有 tool/result,但 turn 尚未 end,应保持 running。- let state = reduceSessionEvent(createSessionStatus(), event('turn/start', {}, 1))- state = reduceSessionEvent(state, event('tool/call', { name: 'read', callId: 'c1' }, 2))- state = reduceSessionEvent(state, event('tool/result', { callId: 'c1' }, 3))- expect(state.activity).toBe('running')- expect(state.phase).toBe('result')- })-})--describe('toolCallIdOf', () => {- it('reads callId from message.source.callId, then message.toolCallId, then data.callId', () => {- expect(toolCallIdOf(event('tool/call', { message: { source: { callId: 'x' } } }))).toBe('x')- expect(toolCallIdOf(event('tool/call', { message: { toolCallId: 'y' } }))).toBe('y')- expect(toolCallIdOf(event('tool/call', { callId: 'z' }))).toBe('z')- expect(toolCallIdOf(event('tool/call', {}), 'fb')).toBe('fb')- })-})--describe('isUserQuestionTool', () => {- it('flags only true question/approval tools', () => {- expect(isUserQuestionTool('ask_user_question')).toBe(true)- expect(isUserQuestionTool('exit_plan_mode')).toBe(true)- expect(isUserQuestionTool('request_user_input')).toBe(true)- expect(isUserQuestionTool('code_review')).toBe(false)- expect(isUserQuestionTool('allowlist_files')).toBe(false)- expect(isUserQuestionTool('search')).toBe(false)- })-})diff --git a/packages/dsh-tauri-pet/src/client/utils/session-status.ts b/packages/dsh-tauri-pet/src/client/utils/session-status.tsdeleted file mode 100644index c61f8c66..00000000--- a/packages/dsh-tauri-pet/src/client/utils/session-status.ts+++ /dev/null@@ -1,275 +0,0 @@-/**- * session-status.ts — 从 DSH 会话事件推导「会话进行态」的纯归约器。- *- * 逻辑逐点对齐 dsh-dafeiyu 的 companion-reducer.js:- * 会话事件(turn/start、tool/call、tool/result、approval/asked、turn/end…)- * 顺序喂入 `reduceSessionEvent`,得到当前会话的 phase(准备/思考/工具/等待/- * 审阅/失败/空闲)+ toolName + pendingKind。只要会话在处理中,phase 不可能- * 在两次工具调用之间回落成 idle,从而避免 Toast 闪烁(issue #308 bug 2)。- *- * 纯函数设计:不依赖 React / 运行时,可直接单测状态转换。每次调用返回传入- * 记录(就地推进),seq 去重保证窗口重复回放不会重复计。- */--import type { PetSessionActivity, PetSessionEvent } from '../types'--/** 会话进行态(驱动 toast 描述 + pet 动作),沿用 dsh-dafeiyu 的阶段粒度。 */-export type SessionPhase- = 'preparing'- | 'thinking'- | 'working'- | 'result'- | 'waiting'- | 'review'- | 'failed'- | 'stopped'- | 'idle'--/** 归约后的一条会话状态记录。 */-export interface SessionStatusRecord {- activity: PetSessionActivity- phase: SessionPhase- pendingKind?: 'approval' | 'plan-review' | 'question' | 'user-question'- task?: string- toolName?: string- turnActive: boolean- /** 尚未结束的工具调用:callId -> toolName。 */- openTools: Map<string, string>- /** seq 递增去重:防止同一段窗口重复回放同一事件。 */- lastSeq: number- updatedAt: number-}--/** 事件里取 toolCallId 的优先级;取自 dsh-dafeiyu toolCallIdOf。 */-export function toolCallIdOf(event: PetSessionEvent, fallback = ''): string {- const message = event.data?.message as {- content?: unknown- source?: { callId?: unknown }- toolCallId?: unknown- callId?: unknown- } | undefined- const content = Array.isArray(message?.content)- ? (message?.content as Array<{ toolCallId?: unknown }>).find(item => item?.toolCallId)?.toolCallId- : undefined- return String(- message?.source?.callId- ?? content- ?? message?.toolCallId- ?? message?.callId- ?? event.data?.callId- ?? fallback,- )-}--/** 判断某个工具名是否属于「向用户提问 / 等待决策」语义;取自 dsh-dafeiyu isUserQuestionTool。 */-export function isUserQuestionTool(name: string): boolean {- const value = String(name || '').toLowerCase()- const tokens = value.split(/[^a-z0-9]+/u).filter(Boolean)-- const asks = new Set(['ask', 'asking', 'request', 'requests', 'requesting', 'require', 'requires', 'prompt', 'needs', 'need', 'seek', 'seeks', 'get', 'gets'])- const filler = new Set(['for', 'from', 'the', 'a', 'an'])- const userWords = new Set(['user', 'human', 'me'])- const nouns = new Set(['question', 'questions', 'input', 'answer', 'answers', 'decision', 'decisions', 'confirmation', 'approval', 'permission', 'authorization', 'authorisation', 'consent', 'clarify', 'clarification', 'help'])-- const hasUserNoun = tokens.some((token, index) =>- userWords.has(token) && nouns.has(tokens[index + 1] ?? ''),- )- const hasNounFromUser = tokens.some((token, index) =>- nouns.has(token) && tokens[index + 1] === 'from' && userWords.has(tokens[index + 2] ?? ''),- )- const hasAsk = tokens.some((token, index) => {- if (!asks.has(token))- return false- let cursor = index + 1- while (cursor < tokens.length && (filler.has(tokens[cursor]) || userWords.has(tokens[cursor]))) {- if (userWords.has(tokens[cursor])) {- const next = tokens[cursor + 1]- return !next || nouns.has(next)- }- cursor += 1- }- return cursor < tokens.length && nouns.has(tokens[cursor])- })- const strong = tokens.some(token =>- token === 'authorize' || token === 'authorise' || token === 'consent',- )- const submitsPlanForApproval = tokens.some((token, index) =>- token === 'exit' && tokens[index + 1] === 'plan' && tokens[index + 2] === 'mode',- )- return hasUserNoun || hasNounFromUser || hasAsk || strong || submitsPlanForApproval-}--/** phase → pet 动画 activity;对齐 dsh-dafeiyu 的选择与仓库既有协议。 */-export function phaseToActivity(phase: SessionPhase): PetSessionActivity {- switch (phase) {- case 'waiting':- return 'waiting'- case 'review':- return 'review'- case 'failed':- return 'failed'- case 'idle':- case 'stopped':- return 'idle'- default:- return 'running'- }-}--/** 新建一条空闲基线记录。 */-export function createSessionStatus(): SessionStatusRecord {- return {- activity: 'idle',- phase: 'idle',- turnActive: false,- openTools: new Map(),- lastSeq: -1,- updatedAt: 0,- }-}--function nextState(state: SessionStatusRecord, patch: Partial<SessionStatusRecord>): SessionStatusRecord {- return Object.assign(state, patch, { updatedAt: state.updatedAt + 1 }) as SessionStatusRecord-}--/**- * 把一条会话事件归约进记录。事件可能来自 eventSource 窗口(含历史),因此- * 先按 seq 去重:`seq <= lastSeq` 的事件视为已消费,直接跳过。- * @returns 变更后的记录;若事件无影响或已被消费,返回原记录引用。- */-export function reduceSessionEvent(state: SessionStatusRecord, event: PetSessionEvent): SessionStatusRecord {- if (!event || typeof event.type !== 'string')- return state- const seq = Number(event.seq ?? 0)- if (Number.isFinite(seq) && seq <= state.lastSeq)- return state- if (Number.isFinite(seq))- state.lastSeq = seq-- const tools = state.openTools- const patch: Partial<SessionStatusRecord> = {}- const phase = state.phase-- switch (event.type) {- case 'turn/start':- patch.turnActive = true- patch.task = undefined- patch.pendingKind = undefined- tools.clear()- patch.activity = 'running'- patch.phase = 'preparing'- break-- case 'step/start':- case 'assistant/chunk':- case 'assistant/message':- if (!state.turnActive || tools.size > 0)- return state- if (phase === 'thinking')- return state- patch.activity = 'running'- patch.phase = 'thinking'- break-- case 'tool/call': {- const callId = toolCallIdOf(event, `seq-${String(event.seq ?? 'unknown')}`)- const name = String(event.data?.name ?? (event.data?.message as { name?: string } | undefined)?.name ?? 'tool')- tools.set(callId, name)- if (isUserQuestionTool(name)) {- patch.activity = 'waiting'- patch.phase = 'waiting'- patch.toolName = name- patch.pendingKind = 'user-question'- }- else {- patch.activity = 'running'- patch.phase = 'working'- patch.toolName = name- patch.pendingKind = undefined- }- break- }-- case 'tool/result': {- const callId = toolCallIdOf(event)- if (callId)- tools.delete(callId)- if (tools.size > 0) {- patch.activity = 'running'- patch.phase = 'working'- patch.toolName = tools.values().next().value- }- else {- patch.activity = 'running'- patch.phase = 'result'- patch.toolName = undefined- }- break- }-- case 'approval/asked':- patch.activity = 'waiting'- patch.phase = 'waiting'- patch.toolName = String(event.data?.toolName ?? 'approval')- patch.pendingKind = 'approval'- break-- case 'approval/decided':- case 'user/message': {- const callId = state.pendingKind === 'user-question'- ? event.data?.callId- : event.data?.id- if (callId)- tools.delete(String(callId))- if (tools.size > 0) {- patch.activity = 'running'- patch.phase = 'working'- patch.toolName = tools.values().next().value- }- else {- patch.activity = 'running'- patch.phase = 'result'- patch.toolName = undefined- }- patch.pendingKind = undefined- break- }-- case 'todo/write': {- const todos = Array.isArray(event.data?.todos) ? event.data.todos : []- const current = todos.find(todo => todo?.status === 'in_progress')- ?? todos.find(todo => todo?.status === 'pending')- patch.task = current?.content ? String(current.content) : state.task- break- }-- case 'turn/end': {- patch.turnActive = false- tools.clear()- patch.toolName = undefined- const kind = String((event.data?.reason as { kind?: string } | undefined)?.kind ?? 'completed')- if (kind === 'blocked') {- patch.activity = 'waiting'- patch.phase = 'waiting'- }- else if (kind === 'aborted') {- patch.activity = 'idle'- patch.phase = 'stopped'- }- else if (kind !== 'completed') {- patch.activity = 'failed'- patch.phase = 'failed'- }- else {- patch.activity = 'review'- patch.phase = 'review'- }- break- }-- default:- return state- }-- return nextState(state, patch)-}diff --git a/packages/dsh-tauri-pet/src/client/utils/transferable.test.ts b/packages/dsh-tauri-pet/src/client/utils/transferable.test.tsnew file mode 100644index 00000000..397d7df9--- /dev/null+++ b/packages/dsh-tauri-pet/src/client/utils/transferable.test.ts@@ -0,0 +1,65 @@+import { describe, expect, it } from 'vitest'+import { toTransferable } from './transferable'++describe('toTransferable', () => {+ it('剥离函数、符号、bigint 与 undefined,保留纯 JSON 数据', () => {+ expect(toTransferable({+ id: 's1',+ status: 'running',+ apply: () => undefined,+ count: 0n,+ hidden: undefined,+ [Symbol('tag')]: 'never-kept',+ })).toEqual({ id: 's1', status: 'running' })+ })++ it('递归收敛嵌套数组并过滤不可传输项', () => {+ expect(toTransferable({+ pending: ['a', () => undefined, null, 3, undefined],+ })).toEqual({ pending: ['a', null, 3] })+ })++ it('打破循环引用而不是无限递归', () => {+ const root: Record<string, unknown> = { id: 's1' }+ const child: Record<string, unknown> = { parent: root }+ root.child = child+ const cleaned = toTransferable(root) as Record<string, unknown>+ expect(cleaned.id).toBe('s1')+ expect(cleaned.child).toEqual({})+ })++ it('共享引用各自保留而非互相抹除', () => {+ const shared = { marker: 'x' }+ const cleaned = toTransferable({ a: shared, b: shared })+ expect(cleaned).toEqual({ a: { marker: 'x' }, b: { marker: 'x' } })+ })++ it('date 转 ISO 字符串,Map 转普通对象,Set 转数组', () => {+ const cleaned = toTransferable({+ when: new Date('2024-01-02T03:04:05.000Z'),+ map: new Map([['k', 'v']]),+ set: new Set([1, 2]),+ })+ expect(cleaned).toEqual({+ when: '2024-01-02T03:04:05.000Z',+ map: { k: 'v' },+ set: [1, 2],+ })+ })++ it('class 实例与宿主对象被丢弃(postMessage 无法结构化克隆)', () => {+ class SessionRecord {+ constructor(readonly title: string) {}+ }+ expect(toTransferable({ record: new SessionRecord('t'), ok: true }))+ .toEqual({ ok: true })+ })++ it('原始值与空值原样通过', () => {+ expect(toTransferable('s')).toBe('s')+ expect(toTransferable(7)).toBe(7)+ expect(toTransferable(true)).toBe(true)+ expect(toTransferable(null)).toBeNull()+ expect(toTransferable(undefined)).toBeUndefined()+ })+})diff --git a/packages/dsh-tauri-pet/src/client/utils/transferable.ts b/packages/dsh-tauri-pet/src/client/utils/transferable.tsnew file mode 100644index 00000000..2822fc7b--- /dev/null+++ b/packages/dsh-tauri-pet/src/client/utils/transferable.ts@@ -0,0 +1,57 @@+/**+ * 把会话快照递归收敛为可跨窗口传输的纯 JSON 数据,供 postMessage / Tauri invoke+ * 序列化:剔除函数/符号/bigint/undefined 与 class 实例(postMessage 结构化克隆+ * 会抛 DataCloneError,Rust 侧也要求 serde_json 可序列化),seen 集合打破循环引用。+ */+export function toTransferable(value: unknown, seen: WeakSet<object> = new WeakSet()): unknown {+ if (value === null || value === undefined)+ return value+ const type = typeof value+ if (type === 'function' || type === 'symbol' || type === 'bigint')+ return undefined+ if (type !== 'object')+ return value+ if (seen.has(value))+ return undefined+ seen.add(value)+ if (Array.isArray(value)) {+ const result = value+ .map(item => toTransferable(item, seen))+ .filter(item => item !== undefined)+ seen.delete(value)+ return result+ }+ if (value instanceof Date)+ return value.toISOString()+ if (value instanceof Map) {+ const result: Record<string, unknown> = {}+ for (const [key, item] of value) {+ const cleanKey = toTransferable(key, seen)+ const cleanItem = toTransferable(item, seen)+ if (typeof cleanKey === 'string' && cleanItem !== undefined)+ result[cleanKey] = cleanItem+ }+ seen.delete(value)+ return result+ }+ if (value instanceof Set) {+ const result = [...value]+ .map(item => toTransferable(item, seen))+ .filter(item => item !== undefined)+ seen.delete(value)+ return result+ }+ const proto = Object.getPrototypeOf(value)+ if (proto !== Object.prototype && proto !== null) {+ seen.delete(value)+ return undefined+ }+ const result: Record<string, unknown> = {}+ for (const key of Object.keys(value)) {+ const cleanItem = toTransferable((value as Record<string, unknown>)[key], seen)+ if (cleanItem !== undefined)+ result[key] = cleanItem+ }+ seen.delete(value)+ return result+}diff --git a/src-tauri/src/bridge/pet.rs b/src-tauri/src/bridge/pet.rsindex 426fade2..fa0caab0 100644--- a/src-tauri/src/bridge/pet.rs+++ b/src-tauri/src/bridge/pet.rs@@ -7,14 +7,14 @@//! 错误遵循仓库约定:`Result<_, String>`,Err 以大写协议前缀开头(如//! `PET_SIZE_OUT_OF_RANGE:`)。//!-//! 实时性:一切会改变状态(开关/选择/大小)的命令都通过 `pet://status` 事件-//! 把最新 PetStatus 推给 pet 窗口——设置页拖动条拖动中实时调整宠物大小就是-//! 走这条通道;pet 窗口的 get_pet_status 轮询仅作兜底。+//! 实时性:一切会改变设置状态(开关/选择/大小)的命令都通过 `pet://status`+//! 事件把最新设置推给 pet 窗口;会话 CRUD 则通过独立的 `session:*` 事件直接转发。use crate::config;use crate::desktop::pet as pet_window;use base64::{engine::general_purpose::STANDARD, Engine};use serde::{Deserialize, Serialize};+use serde_json::Value;use std::collections::HashSet;use std::fs;use std::io::{Cursor, Read, Seek, SeekFrom, Write};@@ -33,10 +33,6 @@ pub const PET_SIZE_MAX: f64 = pet_window::PET_SIZE_MAX_PERCENT;/// 缺省选择对外统一呈现的精确内置宠物 id。pub const DEFAULT_ACTIVE_PET_ID: &str = "maid-deepseek-whale";-/// 气泡文本最大字符数,限制跨 WebView 事件负载并避免异常大气泡遮挡屏幕。-pub const PET_BUBBLE_MAX_CHARS: usize = 280;-/// 会话实时描述最大字符数(思考/工具/需决策…),同气泡上限,防止事件负载膨胀。-pub const PET_DESCRIPTION_MAX_CHARS: usize = 280;/// 导入桌宠资源包的压缩大小上限(32 MiB)。const PET_PACKAGE_MAX_BYTES: usize = 32 * 1024 * 1024;/// 防止 zip 炸弹的条目数与解压后总大小上限。@@ -51,7 +47,7 @@ const PET_SPRITE_VERSION: u8 = 2;const PET_SPRITE_COLUMNS: u8 = 8;const PET_SPRITE_ROWS: u8 = 11;-/// 状态变化推送给 pet 窗口的事件名(实时同步大小/选择/动作;轮询兜底)。+/// 设置变化推送给 pet 窗口的事件名;会话生命周期使用 `session:*` 事件。pub const PET_STATUS_EVENT: &str = "pet://status";#[cfg(target_os = "windows")]@@ -65,6 +61,7 @@ const BUILTIN_ASSET_NAMES: &[(&str, &str)] = &[("idle", "maid-idle.webm"),("turn", "maid-turn.webm"),("move", "maid-move.webm"),+ ("drag", "maid-drag.webm"),("wave", "maid-wave.webm"),("waiting", "maid-waiting.webm"),("running", "maid-running.webm"),@@ -79,72 +76,15 @@ pub struct BuiltinPetAssets {pub assets: std::collections::BTreeMap<String, String>,}-/// 桌宠动作白名单;连字符命名与视频资源和插件协议保持一致。-#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]-#[serde(rename_all = "kebab-case")]-pub enum PetActivity {- #[default]- Idle,- Turn,- MovingLeft,- MovingRight,- Waving,- Waiting,- Running,- Review,- Failed,-}--impl PetActivity {- /// 将 iframe 传入的不可信字符串严格收敛到动作白名单。- fn parse(value: &str) -> Option<Self> {- match value {- "idle" => Some(Self::Idle),- "turn" => Some(Self::Turn),- "moving-left" => Some(Self::MovingLeft),- "moving-right" => Some(Self::MovingRight),- "waving" => Some(Self::Waving),- "waiting" => Some(Self::Waiting),- "running" => Some(Self::Running),- "review" => Some(Self::Review),- "failed" => Some(Self::Failed),- _ => None,- }- }-- fn is_session_activity(self) -> bool {- matches!(self, Self::Idle | Self::Waiting | Self::Running | Self::Review | Self::Failed)- }-}--/// 只驻留当前进程的可见性与动作;重启后恢复显示、idle 且无气泡。+/// 只驻留当前进程的可见性;会话动作和 Toast 完全由 pet WebView 管理。#[derive(Debug, Clone)]struct PetTransientState {visible: bool,- activity: PetActivity,- bubble: Option<String>,- sessions: Vec<PetSessionStatus>,-}--#[derive(Debug, Clone, Serialize, Deserialize)]-pub struct PetSessionStatus {- pub id: String,- pub activity: PetActivity,- /// 固定标题(会话名),toast title 与桌宠气泡共用。- pub bubble: Option<String>,- /// 实时描述(思考 / 工具 + 工具名 / 需决策…),toast description 原地刷新。- #[serde(default)]- pub description: Option<String>,}impl Default for PetTransientState {fn default() -> Self {- Self {- visible: true,- activity: PetActivity::default(),- bubble: None,- sessions: Vec::new(),- }+ Self { visible: true }}}@@ -164,12 +104,6 @@ pub struct PetStatus {pub active_pet: String,/// 宠物大小百分比(50–200,100 = 精灵图原始尺寸);None = 未设置(默认 100)。pub pet_size: Option<f64>,- /// 当前瞬态动作。- pub activity: PetActivity,- /// 当前瞬态气泡;None 表示不展示。- pub bubble: Option<String>,- #[serde(default)]- pub sessions: Vec<PetSessionStatus>,}/// 文件系统宠物的数据来源。@@ -247,37 +181,6 @@ fn normalize_active_pet(active_pet: Option<&str>) -> String {}}-/// 校验并归一化一段可选文本:纯空白视为清空,其余保留原始排版,超长报错。-fn normalize_optional_text(- value: Option<String>,- max_chars: usize,- too_long_prefix: &str,-) -> Result<Option<String>, String> {- let value = value.and_then(|text| {- if text.trim().is_empty() {- None- } else {- Some(text)- }- });- if value.as_deref().map(|text| text.chars().count()).unwrap_or(0) > max_chars {- return Err(format!(- "{too_long_prefix}: text must not exceed {max_chars} characters"- ));- }- Ok(value)-}--/// 校验并归一化气泡:纯空白视为清空,其余保留原始排版。-fn normalize_bubble(bubble: Option<String>) -> Result<Option<String>, String> {- normalize_optional_text(bubble, PET_BUBBLE_MAX_CHARS, "PET_BUBBLE_TOO_LONG:")-}--/// 校验并归一化实时描述:规则同气泡,但错误前缀区分(PET_DESCRIPTION_TOO_LONG:)。-fn normalize_description(description: Option<String>) -> Result<Option<String>, String> {- normalize_optional_text(description, PET_DESCRIPTION_MAX_CHARS, "PET_DESCRIPTION_TOO_LONG:")-}-/// 将持久设置和进程内瞬态状态合并为唯一的对外状态。fn status_from_setting(setting: &config::Setting) -> PetStatus {let transient = transient_state()@@ -289,9 +192,6 @@ fn status_from_setting(setting: &config::Setting) -> PetStatus {visible: setting.pet_enabled && transient.visible,active_pet: normalize_active_pet(setting.active_pet.as_deref()),pet_size: setting.pet_size,- activity: transient.activity,- bubble: transient.bubble,- sessions: transient.sessions,}}@@ -359,82 +259,42 @@ pub fn set_pet_size(app: AppHandle, size: f64) -> Result<PetStatus, String> {Ok(status)}-/// 更新瞬态动作与气泡;动作严格校验白名单,空气泡归一化为 None。-#[tauri::command]-pub fn set_pet_activity(- app: AppHandle,- activity: String,- bubble: Option<String>,-) -> Result<PetStatus, String> {- let activity = PetActivity::parse(activity.trim()).ok_or_else(|| {- "PET_ACTIVITY_INVALID: activity must be idle/turn/moving-left/moving-right/waving/waiting/running/review/failed".to_string()- })?;- let bubble = normalize_bubble(bubble)?;- {- let mut transient = transient_state()- .lock()- .unwrap_or_else(|error| error.into_inner());- transient.activity = activity;- transient.bubble = bubble;- transient.sessions.clear();- }- let status = status_from_setting(&config::get_store_dat_setting(&app));- emit_pet_status(&app, &status);- Ok(status)-}--/// 更新完整会话快照。会话气泡是事件语义的输入,重复快照不会由 Rust 追加队列;-/// pet WebView 按稳定 session id 精确创建/关闭 Toast。+/// 将 DSH 会话原始数据推送到独立桌宠 WebView,不在桌面端构造宠物专用结构。#[tauri::command]-pub fn set_pet_sessions(+pub fn push_pet_session(app: AppHandle,- sessions: Vec<PetSessionStatus>,-) -> Result<PetStatus, String> {- if sessions.len() > 128 {- return Err("PET_SESSIONS_TOO_MANY: sessions must not exceed 128 entries".to_string());- }- let mut seen = HashSet::new();- let mut normalized = Vec::with_capacity(sessions.len());- for mut session in sessions {- session.id = session.id.trim().to_string();- if session.id.is_empty() || session.id.len() > 256 || !seen.insert(session.id.clone()) {- return Err("PET_SESSION_ID_INVALID: session ids must be unique, non-empty, and at most 256 bytes".to_string());- }- if !session.activity.is_session_activity() {- return Err("PET_SESSION_ACTIVITY_INVALID: session activity must be idle/waiting/running/review/failed".to_string());- }- session.bubble = normalize_bubble(session.bubble)?;- session.description = normalize_description(session.description)?;- normalized.push(session);- }- let selected = normalized- .iter()- .enumerate()- .max_by_key(|(index, session)| {- let rank = match session.activity {- PetActivity::Failed => 5,- PetActivity::Review => 4,- PetActivity::Running => 3,- PetActivity::Waiting => 2,- PetActivity::Idle => 0,- _ => unreachable!("session activity was validated above"),- };- (rank, std::cmp::Reverse(*index))- })- .map(|(_, session)| session)- .cloned();- {- let mut transient = transient_state().lock().unwrap_or_else(|error| error.into_inner());- transient.sessions = normalized;- transient.activity = selected.as_ref().map(|session| session.activity).unwrap_or(PetActivity::Idle);- transient.bubble = selected.and_then(|session| session.bubble);- }- let status = status_from_setting(&config::get_store_dat_setting(&app));- emit_pet_status(&app, &status);- Ok(status)+ action: String,+ session: Value,+) -> Result<(), String> {+ let action = action.trim();+ if !matches!(action, "create" | "update" | "remove") {+ return Err("PET_SESSION_ACTION_INVALID: action must be create/update/remove".to_string());+ }+ let id = session+ .get("id")+ .or_else(|| session.get("sessionId"))+ .and_then(Value::as_str)+ .filter(|value| !value.is_empty())+ .map(str::to_owned)+ .ok_or_else(|| "PET_SESSION_ID_INVALID: raw session must include id".to_string())?;+ let event = match action {+ "create" => "session:create",+ "update" => "session:update",+ "remove" => "session:remove",+ _ => unreachable!("session action was validated above"),+ };+ app.emit_to(+ pet_window::PET_WINDOW_LABEL,+ event,+ session,+ )+ .map_err(|error| format!("PET_SESSION_PUSH_FAILED: failed to emit session {id}: {error}"))}/// 按物理像素增量移动桌宠窗口,限制在可见显示器并保存最终位置。+///+/// 缩放(`pet://status` 收到新 pet_size)后由 pet WebView 调用 `move_pet_window(0, 0)`+/// 把放大后的窗口夹回可见屏幕,避免右侧/底部被推出屏幕。#[tauri::command]pub fn move_pet_window(app: AppHandle, delta_x: i32, delta_y: i32) -> Result<(), String> {pet_window::move_pet_window(&app, delta_x, delta_y)@@ -1281,59 +1141,6 @@ mod tests {}}- #[test]- fn pet_activity_accepts_only_protocol_whitelist() {- for activity in [- "idle",- "turn",- "moving-left",- "moving-right",- "waving",- "waiting",- "running",- "review",- "failed",- ] {- assert!(PetActivity::parse(activity).is_some(), "应接受 {activity}");- }- for activity in ["move", "MovingLeft", "idle ", "success", ""] {- assert!(- PetActivity::parse(activity).is_none(),- "不应接受 {activity}"- );- }- }-- #[test]- fn pet_activity_serializes_with_kebab_case() {- assert_eq!(- serde_json::to_string(&PetActivity::MovingLeft).unwrap(),- "\"moving-left\""- );- assert_eq!(- serde_json::to_string(&PetActivity::MovingRight).unwrap(),- "\"moving-right\""- );- }-- #[test]- fn bubble_validation_counts_unicode_characters() {- assert_eq!(normalize_bubble(Some(" ".to_string())).unwrap(), None);- let max = "鲸".repeat(PET_BUBBLE_MAX_CHARS);- assert_eq!(normalize_bubble(Some(max.clone())).unwrap(), Some(max));- let error = normalize_bubble(Some("鲸".repeat(PET_BUBBLE_MAX_CHARS + 1))).unwrap_err();- assert!(error.starts_with("PET_BUBBLE_TOO_LONG:"));- }-- #[test]- fn description_validation_counts_unicode_and_prefixes_error() {- assert_eq!(normalize_description(Some(" ".to_string())).unwrap(), None);- let max = "思".repeat(PET_DESCRIPTION_MAX_CHARS);- assert_eq!(normalize_description(Some(max.clone())).unwrap(), Some(max));- let error = normalize_description(Some("思".repeat(PET_DESCRIPTION_MAX_CHARS + 1))).unwrap_err();- assert!(error.starts_with("PET_DESCRIPTION_TOO_LONG:"));- }-#[test]fn status_never_reports_visible_when_disabled() {let setting = config::Setting {diff --git a/src-tauri/src/desktop/builder.rs b/src-tauri/src/desktop/builder.rsindex 2d169f0b..6fcb57f2 100644--- a/src-tauri/src/desktop/builder.rs+++ b/src-tauri/src/desktop/builder.rs@@ -587,8 +587,7 @@ pub fn handler() -> impl Fn(Invoke<Wry>) -> bool + Send + Sync + 'static {crate::bridge::set_pet_enabled,crate::bridge::set_active_pet,crate::bridge::set_pet_size,- crate::bridge::set_pet_activity,- crate::bridge::set_pet_sessions,+ crate::bridge::push_pet_session,crate::bridge::move_pet_window,crate::bridge::show_pet,crate::bridge::hide_pet,diff --git a/src-tauri/src/desktop/pet.rs b/src-tauri/src/desktop/pet.rsindex 5b1acb88..9b3a7027 100644--- a/src-tauri/src/desktop/pet.rs+++ b/src-tauri/src/desktop/pet.rs@@ -35,6 +35,9 @@ pub const PET_SPRITE_BASE_WIDTH: f64 = 220.0;const PET_WINDOW_PAD_X: f64 = 32.0;const PET_WINDOW_TOP_PAD: f64 = 72.0;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 的内置画布比例保持一致。@@ -142,7 +145,7 @@ pub fn pet_window_aspect<R: Runtime>(app: &AppHandle<R>) -> f64 {pub fn pet_window_logical_size(percent: f64, aspect: f64) -> (f64, f64) {let scale = percent / 100.0;(- (PET_SPRITE_BASE_WIDTH * scale) + PET_WINDOW_PAD_X,+ ((PET_SPRITE_BASE_WIDTH * scale) + PET_WINDOW_PAD_X).max(PET_WINDOW_MIN_WIDTH),(PET_SPRITE_BASE_WIDTH * aspect * scale) + PET_WINDOW_TOP_PAD + PET_WINDOW_BOTTOM_PAD,)}@@ -450,7 +453,11 @@ mod tests {for percent in [50.0, 100.0, 200.0] {let (width, height) = pet_window_logical_size(percent, PET_CUSTOM_ASPECT);let scale = percent / 100.0;- assert_eq!(width, PET_SPRITE_BASE_WIDTH * scale + PET_WINDOW_PAD_X);+ // 大比例时窗口跟随宠物宽度,小比例时兜底到 Toast 区最小宽度。+ assert_eq!(+ width,+ (PET_SPRITE_BASE_WIDTH * scale + PET_WINDOW_PAD_X).max(PET_WINDOW_MIN_WIDTH)+ );assert_eq!(height, PET_SPRITE_BASE_WIDTH * PET_CUSTOM_ASPECT * scale + 82.0);}// 内置鲸鱼为 16:9 画布,窗口高度远小于 8x11 图集,避免窗口过高产生大片透明区。diff --git a/src/components/toast-provider.tsx b/src/components/toast-provider.tsxindex 6abcac81..4fef4e15 100644--- a/src/components/toast-provider.tsx+++ b/src/components/toast-provider.tsx@@ -1,5 +1,8 @@import type { ReactNode } from 'react'+import type { ToastUpdateEvent } from '@/utils/toast'+import { useEventBus } from '@hairy/react-lib'import { Toast } from '@heroui/react'+import { useState } from 'react'import { If } from 'react-if-lite'import { placements, activeQueues } from '@/utils/toast'@@ -13,6 +16,18 @@ interface ToastProviderProps {* 自定义渲染分支,仍复用这里的 queues 与 src/utils/toast.ts API。*/export function ToastProvider(props: ToastProviderProps) {+ const [updates, setUpdates] = useState(() => new Map<string, ToastUpdateEvent['options']>())++ useEventBus<ToastUpdateEvent>('toast.update').on((event) => {+ if (event === undefined || typeof event.key !== 'string')+ return+ setUpdates((current) => {+ const next = new Map(current)+ next.set(event.key, { ...(current.get(event.key) ?? {}), ...event.options })+ return next+ })+ })+return (<>{placements.map(placement => (@@ -23,7 +38,7 @@ export function ToastProvider(props: ToastProviderProps) {>{props.hideCloseButton? ({ toast: item }) => {- const content = item.content+ const content = { ...item.content, ...updates.get(item.key) }return (<Toast toast={item} variant={content?.variant}><Toast.Content>diff --git a/src/hooks/use-iframe-invoke.ts b/src/hooks/use-iframe-invoke.tsindex 66b69f9b..5b08c53b 100644--- a/src/hooks/use-iframe-invoke.ts+++ b/src/hooks/use-iframe-invoke.ts@@ -39,9 +39,7 @@ const ALLOWED_INVOKE_CMDS = new Set(['set_pet_enabled','set_active_pet','set_pet_size',- 'set_pet_activity',- 'set_pet_sessions',- 'move_pet_window',+ 'push_pet_session','show_pet','hide_pet','list_pets',diff --git a/src/pet/app.tsx b/src/pet/app.tsxnew file mode 100644index 00000000..1b668843--- /dev/null+++ b/src/pet/app.tsx@@ -0,0 +1,53 @@+import type { DragDirection } from './hooks/use-drag'+import type { PetHandle, PetStatus } from './hooks/use-pet'+import { useWatch } from '@hairy/react-lib'+import { useRef } from 'react'+import { ToastProvider } from '@/components/toast-provider'+import { Pet } from './components/pet'+import { useBubble } from './hooks/use-bubble'+import { useDrag } from './hooks/use-drag'+import { usePet } from './hooks/use-pet'++/** 拖拽方向 → 动画状态:桌面宠物在原生拖拽期间播放对应的移动动画。 */+const DRAW_STATUS: Record<DragDirection, PetStatus> = {+ left: 'moving-left',+ right: 'moving-right',+}++/** 桌宠窗口的唯一组合入口:只把会话状态映射到公开的 Pet 命令面。 */+export function App() {+ const petRef = useRef<PetHandle>(null)+ const pet = usePet(petRef)+ const bubble = useBubble()+ const dragRef = useRef<HTMLDivElement>(null)+ const { clickCount, direction, dragging } = useDrag(dragRef)+ const drawStatus = direction === undefined ? undefined : DRAW_STATUS[direction]++ useWatch(+ [bubble.status, pet],+ () => {+ if (bubble.status === undefined)+ return pet.clear()+ pet.change({+ loop: bubble.status === 'running',+ status: bubble.status,+ })+ },+ )++ return (+ <ToastProvider hideCloseButton>+ {/* pointer-events-none:原生拖拽面只在宠物本体(pet 内层 pointer-events-auto)上生效,+ 透明空白区点击保持惰性(事件经宠物节点冒泡到 dragRef 触发拖拽)。+ 点击回应不依赖 DOM click/dblclick:Windows 原生拖拽会吞掉 pointerup,+ 事件不合成——由 useDrag 按「两次按下间隔 < 500ms 且未拖拽」判定双击并用+ clickCount 上报;单击/拖拽结束均不触发。 */}+ <div+ ref={dragRef}+ className="pointer-events-none h-full w-full touch-none select-none"+ >+ <Pet status={drawStatus} dragging={dragging} clickCount={clickCount} ref={petRef} />+ </div>+ </ToastProvider>+ )+}diff --git a/src/pet/arbiter.test.ts b/src/pet/arbiter.test.tsdeleted file mode 100644index 647a859f..00000000--- a/src/pet/arbiter.test.ts+++ /dev/null@@ -1,47 +0,0 @@-import { describe, expect, it } from 'vitest'-import { dragFacing, isCurrentPetGeneration, resolvePetActivity } from './arbiter'--describe('resolvePetActivity', () => {- it('lets dragging override every session state while actively dragging', () => {- for (const sessionActivity of ['idle', 'waiting', 'running', 'review', 'failed'] as const) {- expect(resolvePetActivity({ sessionActivity, draggingActivity: 'moving-right', interactionActivity: null })).toBe('moving-right')- }- })-- it('restores the non-idle session state once dragging stops', () => {- for (const sessionActivity of ['waiting', 'running', 'review', 'failed'] as const) {- expect(resolvePetActivity({ sessionActivity, draggingActivity: null, interactionActivity: null })).toBe(sessionActivity)- }- })-- it('keeps a non-idle session above a local interaction', () => {- expect(resolvePetActivity({ sessionActivity: 'waiting', draggingActivity: null, interactionActivity: 'waving' })).toBe('waiting')- })-- it('falls back to interaction then idle only while session is idle and not dragging', () => {- expect(resolvePetActivity({ sessionActivity: 'idle', draggingActivity: 'moving-left', interactionActivity: 'waving' })).toBe('moving-left')- expect(resolvePetActivity({ sessionActivity: 'idle', draggingActivity: null, interactionActivity: 'waving' })).toBe('waving')- expect(resolvePetActivity({ sessionActivity: 'idle', draggingActivity: null, interactionActivity: null })).toBe('idle')- })-})--describe('dragFacing', () => {- it('uses adjacent physical x positions', () => {- expect(dragFacing(100, 90, 'right')).toBe('left')- expect(dragFacing(100, 110, 'left')).toBe('right')- expect(dragFacing(100, 100, 'left')).toBe('left')- })-- it('keeps current direction when displacement is below jitter threshold', () => {- expect(dragFacing(100, 102, 'right', 4)).toBe('right')- expect(dragFacing(100, 98, 'left', 4)).toBe('left')- expect(dragFacing(100, 105, 'left', 4)).toBe('right')- })-})--describe('isCurrentPetGeneration', () => {- it('rejects stale completion callbacks', () => {- expect(isCurrentPetGeneration(2, 1)).toBe(false)- expect(isCurrentPetGeneration(2, 2)).toBe(true)- })-})diff --git a/src/pet/arbiter.ts b/src/pet/arbiter.tsdeleted file mode 100644index 521ecf78..00000000--- a/src/pet/arbiter.ts+++ /dev/null@@ -1,38 +0,0 @@-import type { PetActivity, PetAnimation, PetFacing } from './state'--export interface PetArbitrationInput {- sessionActivity: PetActivity- interactionActivity: PetAnimation | null- draggingActivity: Extract<PetActivity, 'moving-left' | 'moving-right'> | null-}--/**- * 统一桌宠动作优先级:拖动动画只在「正在拖动」期间覆盖会话状态;- * 拖动一旦结束 draggingActivity 变回 null,随后按 session → interaction → idle 回落,- * 从而在 waiting/running/review/failed 之后仍恢复原会话动画,绝不硬编码 idle。- * 会话状态依旧压过一次性交互(wave/bubble/turn),避免低优先级回调覆盖工作状态。- */-export function resolvePetActivity(input: PetArbitrationInput): PetAnimation {- if (input.draggingActivity !== null)- return input.draggingActivity- if (input.sessionActivity !== 'idle')- return input.sessionActivity- return input.interactionActivity ?? 'idle'-}--/** 一次性交互只在仍处于相同 generation 时允许提交完成。 */-export function isCurrentPetGeneration(current: number, expected: number): boolean {- return current === expected-}--/**- * 拖动方向由相邻物理窗口位置决定;当两次位置的位移小于 jitter 时保持当前方向,- * 避免光标/窗口微小抖动让 facing 反复横跳。- */-export function dragFacing(previousX: number, nextX: number, current: PetFacing, jitter = 0): PetFacing {- if (nextX === previousX)- return current- if (Math.abs(nextX - previousX) < jitter)- return current- return nextX < previousX ? 'left' : 'right'-}diff --git a/src/pet/components/pet.tsx b/src/pet/components/pet.tsxnew file mode 100644index 00000000..02ccfdd0--- /dev/null+++ b/src/pet/components/pet.tsx@@ -0,0 +1,477 @@+import type { CSSProperties, Ref, SyntheticEvent } from 'react'+import type { PetHandle, PetStatus } from '../hooks/use-pet'+import { invoke } from '@tauri-apps/api/core'+import { listen } from '@tauri-apps/api/event'+import { getCurrentWindow, LogicalSize } from '@tauri-apps/api/window'+import { useEffect, useImperativeHandle, useRef, useState } from 'react'+import { If } from 'react-if-lite'+import { PET_STATUSES } from '../hooks/use-pet'++const BUILT_IN_PET_ID = 'maid-deepseek-whale'+const PET_BASE_WIDTH = 220+const PET_DEFAULT_SIZE_PERCENT = 100+const PET_SIZE_MIN_PERCENT = 50+const PET_SIZE_MAX_PERCENT = 200+/** 透明窗口右侧留白(逻辑像素),与 Rust pet_window_logical_size 的 PAD 常量一致。 */+const PET_WINDOW_PAD_X = 32+/** 顶部 Toast 区 + 底部留白(逻辑像素),与 Rust 的 TOP_PAD + BOTTOM_PAD 一致。 */+const PET_WINDOW_PAD_Y = 82+/** 顶栏 Toast 区的最小窗口宽度(逻辑像素),与 Rust pet_window_logical_size 的 MIN_WIDTH 一致。 */+const PET_BUBBLE_MIN_WIDTH = 420+const IDLE_DURATIONS = [280, 110, 110, 140, 140, 320] as const+/**+ * 待机转向插播间隔下限/上限(ms):平时以循环待机动画为主(参考 dsh-pet+ * animationWeights idle:10 / turn:5 的权重语义——turn 是播完掷骰链里的低频事件),+ * 只有长时间持续待机才偶尔插播一次转身,避免高频切换的观感。+ */+const IDLE_TURN_DELAY_MIN = 25000+const IDLE_TURN_DELAY_MAX = 50000+const ACTIONS = {+ 'moving-right': { row: 1, frames: 8, duration: 120, lastDuration: 220 },+ 'moving-left': { row: 2, frames: 8, duration: 120, lastDuration: 220 },+ 'waving': { row: 3, frames: 4, duration: 140, lastDuration: 280 },+ 'failed': { row: 5, frames: 8, duration: 140, lastDuration: 240 },+ 'waiting': { row: 6, frames: 6, duration: 150, lastDuration: 260 },+ 'running': { row: 7, frames: 6, duration: 120, lastDuration: 220 },+ 'review': { row: 8, frames: 6, duration: 150, lastDuration: 280 },+} as const++type VideoKey = 'idle' | 'turn' | 'move' | 'drag' | 'wave' | 'waiting' | 'running' | 'review' | 'failed' | 'bubble'+type Animation = PetStatus | 'bubble' | 'dragging'++interface Asset {+ columns: number+ id: string+ rows: number+ sprite_version_number: number+ spritesheet: string+}++interface RustPetStatus {+ active_pet?: string | null+ enabled?: boolean+ pet_size?: number | null+ visible?: boolean | null+}++export interface PetProps {+ ref?: Ref<PetHandle | null>+ status?: PetStatus+ /** 原生拖拽会话进行中;内置宠物据此播放拖拽浮动动画(忽略方向)。 */+ dragging?: boolean+ /**+ * 点击计次(useDrag 判定「按下-松开且窗口未达拖拽阈值 = 点击」后递增);+ * 变化时播放一次点击回应动画(waving)。不依赖 DOM click/dblclick 合成。+ */+ clickCount?: number+}++interface Frame {+ column: number+ duration: number+ row: number+}++/** 桌宠唯一视觉组件:资源加载、WebM/Codex v2 播放和 Tauri 窗口细节全部封装。 */+export function Pet(props: PetProps) {+ const [rustStatus, setRustStatus] = useState<RustPetStatus>({ enabled: true, visible: true })+ const [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: 'turn' | 'waving' } | null>(null)+ const adHocRef = useRef(adHoc)+ adHocRef.current = adHoc+ const adHocSeqRef = useRef(0)+ 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 genRef = useRef(0)+ const spriteRef = useRef<HTMLDivElement | null>(null)+ const overrideRef = useRef(override)+ overrideRef.current = override+ const prevClickRef = useRef(0)+ const handleEndedRef = useRef<(event?: Event) => void>(() => {})++ const activePet = normalizeActivePet(rustStatus.active_pet)+ const isBuiltin = activePet === BUILT_IN_PET_ID+ // 内置宠物拖拽中:播放拖拽悬空浮动动画(不区分方向);自定义宠物仍用方向转向。+ const dragHold = props.dragging === true && isBuiltin+ // 优先级:拖拽浮动动画 > 手势方向 > 一次性回应(点击 waving / 待机 turn) > ref 命令(会话状态)> 默认 idle。+ // 一次性动画在 override 之上但低于手势方向:点击回应可打断会话状态,拖拽方向仍优先。+ const activity: Animation = dragHold ? 'dragging' : props.status ?? adHoc?.status ?? override?.status ?? 'idle'+ const size = normalizePetSize(rustStatus.pet_size)+ const visible = rustStatus.enabled !== false && rustStatus.visible !== false+ const hasCustomAsset = customAsset !== null && customAssetPet === activePet+ // 自定义精灵图使用加载后探测到的真实画布比例(帧高/帧宽),未探测到前回落到图集默认比例。+ const petAspect = isBuiltin ? 9 / 16 : (spriteAspect?.id === activePet ? spriteAspect.value : 208 / 192)++ useImperativeHandle(props.ref, () => ({+ change(options) {+ if (isPetStatus(options.status))+ setOverride({ loop: options.loop === true, revision: ++revisionRef.current, status: options.status })+ },+ clear() {+ setOverride(null)+ },+ get status() {+ return props.status ?? overrideRef.current?.status ?? 'idle'+ },+ }), [props.status])++ useEffect(() => {+ let disposed = false+ let unlisten: (() => void) | undefined+ void listen<RustPetStatus>('pet://status', (event) => {+ if (!disposed)+ setRustStatus(event.payload)+ }).then((dispose) => {+ if (disposed)+ dispose()+ else+ unlisten = dispose+ }).catch(() => {})+ void invoke<RustPetStatus>('get_pet_status').then((value) => {+ if (!disposed)+ setRustStatus(value)+ }).catch(() => {})+ void invoke<{ assets?: Record<string, string> }>('get_builtin_pet_assets').then((value) => {+ if (!disposed)+ setAssets(value.assets ?? {})+ }).catch(() => {})+ return () => {+ disposed = true+ unlisten?.()+ }+ }, [])++ useEffect(() => {+ const query = globalThis.matchMedia?.('(prefers-reduced-motion: reduce)')+ if (query === undefined)+ return undefined+ function updateMotion() {+ setReducedMotion(query.matches)+ }+ query.addEventListener('change', updateMotion)+ return () => query.removeEventListener('change', updateMotion)+ }, [])++ useEffect(() => {+ if (isBuiltin)+ return undefined+ let disposed = false+ void invoke<Asset>('get_pet_asset', { id: activePet }).then((value) => {+ if (!disposed && isSupportedAsset(value)) {+ setCustomAsset(value)+ setCustomAssetPet(activePet)+ }+ }).catch(() => {})+ return () => {+ disposed = true+ }+ }, [activePet, isBuiltin])++ // 原生窗口尺寸跟随当前资源真实画布比例缩放(设置页 drag 滑块实时生效),+ // 避免与 Rust 只按图集默认比例重设窗口导致两处 set_size 打架(issue #308)。+ useEffect(() => {+ if (!visible)+ return undefined+ const appWindow = getCurrentWindow()+ // 气泡常驻窗口右侧留白之上,窗口宽度兜底到气泡可读宽度;宠物锚定右侧,+ // 加宽窗口只向左扩展透明区,宠物在屏幕上的位置保持不变。+ const width = Math.max((PET_BASE_WIDTH * size) / 100 + PET_WINDOW_PAD_X, PET_BUBBLE_MIN_WIDTH)+ const height = (PET_BASE_WIDTH * size) / 100 * petAspect + PET_WINDOW_PAD_Y+ void appWindow.setSize(new LogicalSize(width, height)).then(() => {+ // 放大后把窗口夹回可见显示器,避免右侧/底部被推出屏幕。+ void invoke<void>('move_pet_window', { deltaX: 0, deltaY: 0 }).catch(() => {})+ }).catch((error) => {+ console.warn('[pet] PET_WINDOW_RESIZE_FAILED:', error)+ })+ }, [petAspect, size, visible])++ useEffect(() => {+ // 双 video 缓冲切换(移植 dsh-pet switchTo):新动画先在后台视频加载,+ // loadeddata 后才交换前台并淡入,旧视频淡出 + pause + 清 onended(拆雷,+ // 防止后台残留事件掐断前台动画);全程无空窗/黑帧,动画切换不闪跳。+ if (isBuiltin === false || videoARef.current === null || videoBRef.current === null)+ return undefined+ const source = assets[videoKey(activity)] ?? (activity === 'dragging' ? assets.move : undefined)+ if (source === undefined)+ return undefined+ const once = !(override?.loop ?? isLoopingAnimation(activity))+ const revision = override?.revision+ // adHoc seq:点击同一动画(waving→waving)时 seq 递增强制重播(对应 dsh-pet 的 seq 重放)。+ const seq = adHoc?.seq ?? 0+ const pending = pendingRef.current+ // 防重:同一动画 + 同一 revision + 同一 seq(未显式重播)不重复加载;+ // override/点击每次触发 revision/seq 递增,同动画重播仍会重载并从头播放。+ if (pending !== null && pending.anim === activity && pending.once === once+ && pending.revision === revision && pending.seq === seq) {+ return undefined+ }+ const gen = ++genRef.current+ pendingRef.current = { anim: activity, gen, once, revision, seq }+ const target = frontIdxRef.current === 0 ? videoBRef.current : videoARef.current+ target.src = source+ target.loop = !once+ target.onended = once ? event => handleEndedRef.current(event) : null+ target.load()+ const onReady = () => {+ target.removeEventListener('loadeddata', onReady)+ if (pendingRef.current?.gen !== gen)+ return // 已被更新的切换取代+ const old = frontIdxRef.current === 0 ? videoARef.current : videoBRef.current+ if (old !== null && old !== target) {+ old.onended = null // 拆雷:后台残留 onended 会掐断前台动画+ old.pause()+ }+ frontIdxRef.current = frontIdxRef.current === 0 ? 1 : 0+ // 交换前台发生在 loadeddata 事件回调(或视频已就绪的立即分支):属于响应加载完成,+ // 而非渲染副作用;规则无法区分事件回调与 effect 同步阶段,忽略。+ // eslint-disable-next-line react/set-state-in-effect+ setFrontIdx(frontIdxRef.current)+ pendingRef.current = null+ void target.play().catch(() => setFailed(true))+ }+ target.addEventListener('loadeddata', onReady)+ if (target.readyState >= 2)+ onReady()+ return () => {+ target.removeEventListener('loadeddata', onReady)+ // 若本次加载尚未完成(StrictMode 双挂载 / 依赖变化提前清理),清掉 pending,+ // 让下一次 effect 重新发起加载,避免「监听器已移除但 pending 仍在」的死锁。+ if (pendingRef.current?.gen === gen)+ pendingRef.current = null+ }+ }, [activity, adHoc?.seq, assets, isBuiltin, override?.loop, override?.revision])++ // 点击回应:clickCount 变化(useDrag 判定「500ms 内两次按下且未拖拽 = 双击」后递增)+ // → 播放一次 waving。adHoc 优先级在会话 override 之上:双击回应可打断会话状态,+ // 播完回落原动画(handleEnded)。+ useEffect(() => {+ if (props.clickCount === undefined || props.clickCount === prevClickRef.current)+ return undefined+ prevClickRef.current = props.clickCount+ // 点击回应:以 props 变化驱动一次性动画状态,属于事件联动而非渲染副作用。+ // eslint-disable-next-line react/set-state-in-effect+ setAdHoc({ seq: ++adHocSeqRef.current, status: 'waving' })+ }, [props.clickCount])++ // 待机转向链(参考 dsh-pet 的权重掷骰链):内置宠物长时间持续待机时,+ // 才以低频(IDLE_TURN_DELAY_MIN~MAX 随机)插播一次转身动画,平时保持循环待机。+ 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' })+ return () => window.clearTimeout(timer)+ }, [activity, isBuiltin, reducedMotion])++ useEffect(() => {+ const sprite = spriteRef.current+ const asset = customAsset+ if (isBuiltin || asset === null || customAssetPet !== activePet || sprite === null)+ return undefined+ const element = sprite+ const loadedAsset = asset+ const sequence = spriteSequence(activity, reducedMotion, override?.loop ?? isLoopingAnimation(activity))+ let index = 0+ let timer: number | undefined+ function paint() {+ const frame = sequence.frames[index]+ element.style.backgroundPosition = framePosition(frame, loadedAsset.columns, loadedAsset.rows)+ if (sequence.frames.length > 1) {+ timer = window.setTimeout(() => {+ index = index + 1 >= sequence.frames.length ? (sequence.loopStart ?? index) : index + 1+ paint()+ }, frame.duration)+ }+ }+ paint()+ return () => {+ if (timer !== undefined)+ window.clearTimeout(timer)+ }+ }, [activity, activePet, adHoc?.seq, customAsset, customAssetPet, isBuiltin, override?.loop, reducedMotion])++ useEffect(() => {+ if (override?.loop !== false || override === null || isBuiltin || !hasCustomAsset)+ return undefined+ const frames = spriteAction(override.status)+ const duration = (reducedMotion ? [frames[0]] : frames).reduce((total, frame) => total + frame.duration, 0)+ const timer = window.setTimeout(setOverride, duration, null)+ return () => window.clearTimeout(timer)+ }, [hasCustomAsset, isBuiltin, override, reducedMotion])++ // 自定义精灵无 ended 事件:adHoc(点击回应/待机转向)播完按帧时长估算后清掉,+ // 让 activity 回落 idle(内置宠物由视频 ended 事件驱动,走 handleEnded)。+ useEffect(() => {+ if (adHoc === null || isBuiltin || !hasCustomAsset)+ return undefined+ const frames = spriteAction(adHoc.status)+ const duration = (reducedMotion ? [frames[0]] : frames).reduce((total, frame) => total + frame.duration, 0)+ const timer = window.setTimeout(setAdHoc, duration, null)+ return () => window.clearTimeout(timer)+ }, [adHoc, hasCustomAsset, isBuiltin, reducedMotion])++ function handleEnded(event?: Event) {+ // 只响应前台视频的 ended:被降级的后台视频在切换时已 pause + 清 onended(拆雷),+ // 不会触发;双保险再校验一次事件来源是否为当前前台视频。+ const source = event?.currentTarget as HTMLVideoElement | undefined+ const front = frontIdxRef.current === 0 ? videoARef.current : videoBRef.current+ if (source !== undefined && source !== front)+ return+ // 一次性动画播完:优先清 adHoc(点击回应 waving / 待机转向 turn),+ // 否则清非 loop 的 override 命令(bubble 会话动画播完回 idle)。+ if (adHocRef.current !== null) {+ setAdHoc(null)+ return+ }+ if (overrideRef.current?.loop !== true)+ setOverride(null)+ }+ handleEndedRef.current = handleEnded++ function handleSpriteLoaded(event: SyntheticEvent<HTMLImageElement>) {+ const image = event.currentTarget+ if (customAsset !== null) {+ const frameWidth = image.naturalWidth / customAsset.columns+ const frameHeight = image.naturalHeight / customAsset.rows+ if (frameWidth > 0 && frameHeight > 0)+ setSpriteAspect({ id: customAsset.id, value: frameHeight / frameWidth })+ }+ setFailed(false)+ }++ const style = {+ '--pet-width': `${PET_BASE_WIDTH * size / 100}px`,+ '--pet-aspect': String(petAspect),+ } as CSSProperties++ return (+ <If cond={visible}>+ <main className="pointer-events-none fixed inset-0 flex items-end justify-center overflow-visible" style={style}>+ <div className="pointer-events-auto relative h-[calc(var(--pet-width)*var(--pet-aspect))] w-[var(--pet-width)] select-none">+ <If cond={isBuiltin}>+ {/* 双 video 缓冲:前台 opacity-100 淡入、后台 opacity-0 淡出,+ 切换经 loadeddata 就绪后交换(见开关 effect),无空窗/黑帧闪跳。 */}+ <video+ ref={videoARef}+ className={`absolute inset-0 h-full w-full object-contain transition-opacity duration-200 ${frontIdx === 0 ? 'opacity-100' : 'opacity-0'}`}+ muted+ playsInline+ preload="auto"+ onError={() => setFailed(true)}+ />+ <video+ ref={videoBRef}+ className={`absolute inset-0 h-full w-full object-contain transition-opacity duration-200 ${frontIdx === 1 ? 'opacity-100' : 'opacity-0'}`}+ muted+ playsInline+ preload="auto"+ onError={() => setFailed(true)}+ />+ </If>+ <If cond={!isBuiltin && hasCustomAsset}>+ <div+ ref={spriteRef}+ className="absolute inset-0 bg-contain bg-no-repeat"+ style={{+ backgroundImage: customAsset ? `url(${customAsset.spritesheet})` : undefined,+ backgroundSize: customAsset ? `${customAsset.columns * 100}% ${customAsset.rows * 100}%` : undefined,+ }}+ />+ {/* 探测精灵图真实像素尺寸,换算成帧比例供窗口缩放使用;0×0 不可见。 */}+ <img+ className="pointer-events-none absolute h-0 w-0 opacity-0"+ src={customAsset?.spritesheet}+ alt=""+ draggable={false}+ onError={() => setFailed(true)}+ onLoad={handleSpriteLoaded}+ />+ </If>+ <If cond={failed && assets.fallback !== undefined}>+ <img className="absolute inset-0 h-full w-full object-contain" src={assets.fallback} alt="" draggable={false} />+ </If>+ </div>+ </main>+ </If>+ )+}++function isPetStatus(value: string): value is PetStatus {+ return (PET_STATUSES as readonly string[]).includes(value)+}++function normalizeActivePet(value: string | null | undefined): string {+ const normalized = value?.trim()+ return normalized || BUILT_IN_PET_ID+}++function normalizePetSize(value: number | null | undefined): number {+ if (typeof value !== 'number' || !Number.isFinite(value))+ return PET_DEFAULT_SIZE_PERCENT+ return Math.min(PET_SIZE_MAX_PERCENT, Math.max(PET_SIZE_MIN_PERCENT, value))+}++function isSupportedAsset(value: Asset): boolean {+ return value.sprite_version_number === 2+ && value.columns === 8+ && value.rows === 11+ && typeof value.spritesheet === 'string'+ && value.spritesheet.length > 0+}++function isLoopingAnimation(activity: Animation): 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 } {+ const idleFrames = IDLE_DURATIONS.map((duration, column) => ({ column, duration: duration * 6, row: 0 }))+ const action = spriteAction(activity)+ if (activity === 'idle')+ return reducedMotion ? { frames: [idleFrames[0]], loopStart: 0 } : { frames: idleFrames, loopStart: 0 }+ if (reducedMotion)+ return { frames: [action[0]], loopStart: loop ? 0 : null }+ if (loop)+ return { frames: action, loopStart: 0 }+ return { frames: [...action, ...idleFrames], loopStart: action.length }+}++function spriteAction(activity: Animation): 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]+ return Array.from({ length: config.frames }, (_, column) => ({+ column,+ duration: column === config.frames - 1 ? config.lastDuration : config.duration,+ row: config.row,+ }))+}++function framePosition(frame: Frame, columns: number, rows: number): string {+ return `${frame.column * 100 / Math.max(1, columns - 1)}% ${frame.row * 100 / Math.max(1, rows - 1)}%`+}diff --git a/src/pet/drag-machine.test.ts b/src/pet/drag-machine.test.tsdeleted file mode 100644index 8dede913..00000000--- a/src/pet/drag-machine.test.ts+++ /dev/null@@ -1,64 +0,0 @@-import { describe, expect, it } from 'vitest'-import {- beginDrag,- createDragMachine,- dragSample,- hasDragged,- isDragActive,-} from './drag-machine'--describe('drag machine lifecycle', () => {- it('starts from idle and enters starting on begin', () => {- expect(createDragMachine().phase).toBe('idle')- const started = beginDrag('left')- expect(started.phase).toBe('starting')- expect(started.facing).toBe('left')- expect(started.anchorX).toBeNull()- })-- it('reports active only while starting or dragging', () => {- const idle = createDragMachine()- expect(isDragActive(idle)).toBe(false)- const started = beginDrag('left')- expect(isDragActive(started)).toBe(true)- const dragged = dragSample(started, 90)- expect(isDragActive(dragged)).toBe(true)- })-})--describe('dragSample direction', () => {- it('records anchor on first sample without changing direction', () => {- const started = beginDrag('left')- const first = dragSample(started, 100)- expect(first.phase).toBe('starting')- expect(first.anchorX).toBe(100)- expect(first.facing).toBe('left')- })-- it('ignores sub-threshold jitter and keeps direction', () => {- let machine = beginDrag('left')- machine = dragSample(machine, 100)- machine = dragSample(machine, 101)- expect(machine.phase).toBe('starting')- expect(machine.facing).toBe('left')- expect(machine.anchorX).toBe(100)- })-- it('commits direction once displacement crosses threshold', () => {- let machine = beginDrag('left')- machine = dragSample(machine, 100)- machine = dragSample(machine, 120)- expect(machine.phase).toBe('dragging')- expect(machine.facing).toBe('right')- expect(hasDragged(machine)).toBe(true)- })-- it('switches direction on a large reverse move', () => {- let machine = beginDrag('left')- machine = dragSample(machine, 100)- machine = dragSample(machine, 140)- expect(machine.facing).toBe('right')- machine = dragSample(machine, 80)- expect(machine.facing).toBe('left')- })-})diff --git a/src/pet/drag-machine.ts b/src/pet/drag-machine.tsdeleted file mode 100644index 950e5b7e..00000000--- a/src/pet/drag-machine.ts+++ /dev/null@@ -1,70 +0,0 @@-// 桌宠拖动状态机的纯逻辑:用窗口物理位置增量决定方向,与 WebView 指针事件解耦。--import type { PetFacing } from './state'-import { dragFacing } from './arbiter'--/**- * 拖动生命周期:idle(无拖动)→ starting(已按下、等待窗口真正移动)- * → dragging(窗口已越过抖动阈值,方向动画应播放)→ ending(松开、待复位)。- */-export type DragPhase = 'idle' | 'starting' | 'dragging' | 'ending'--// 方向判定阈值:窗口每次位移小于该物理像素数时不改变方向,避免 facing 闪烁。-export const DRAG_JITTER_PX = 4-// 原生拖动期间 onMoved/指针事件可能不稳定,按下后以该间隔轮询窗口物理位置作为兜底。-export const DRAG_SAMPLE_INTERVAL_MS = 40--export interface DragMachine {- phase: DragPhase- facing: PetFacing- /** 上一次已提交方向的窗口 X 坐标;用于累计抖动,避免慢速拖动因单次增量过小而不更新。 */- anchorX: number | null-}--export function createDragMachine(): DragMachine {- return { phase: 'idle', facing: 'left', anchorX: null }-}--/** 按下时进入 starting;朝向保留当前值,方向待窗口真正移动后再定。 */-export function beginDrag(facing: PetFacing): DragMachine {- return { phase: 'starting', facing, anchorX: null }-}--/**- * 窗口物理位置采样:从 anchorX 起累计位移,越过抖动阈值才提交方向并进入 dragging。- * 未越过阈值时保留当前方向且不更新 anchorX,从而让慢速连续拖动也能在累计后正确转向。- */-export function dragSample(current: DragMachine, x: number): DragMachine {- if (current.phase !== 'starting' && current.phase !== 'dragging')- return current- if (current.anchorX === null)- return { ...current, anchorX: x }- const delta = x - current.anchorX- if (Math.abs(delta) < DRAG_JITTER_PX)- return current- return {- phase: 'dragging',- facing: dragFacing(current.anchorX, x, current.facing, DRAG_JITTER_PX),- anchorX: x,- }-}--/** 松开/取消:进入 ending,表示一次拖动(或点击)交互已结束。 */-export function endDrag(current: DragMachine): DragMachine {- return { ...current, phase: 'ending' }-}--/** 复位到初始空闲态。 */-export function resetDrag(): DragMachine {- return createDragMachine()-}--/** 是否处于「启动中或拖动中」(onMoved/轮询 应当继续采样)。 */-export function isDragActive(machine: DragMachine): boolean {- return machine.phase === 'starting' || machine.phase === 'dragging'-}--/** 是否已经真实越过阈值拖动(区分拖拽与点击)。 */-export function hasDragged(machine: DragMachine): boolean {- return machine.phase === 'dragging'-}diff --git a/src/pet/hooks/use-bubble.ts b/src/pet/hooks/use-bubble.tsnew file mode 100644index 00000000..a0b56b22--- /dev/null+++ b/src/pet/hooks/use-bubble.ts@@ -0,0 +1,257 @@+import type { PetStatus } from './use-pet'+import { listen } from '@tauri-apps/api/event'+import { useEffect, useState } from 'react'+import { toast } from '@/utils/toast'++export interface BubbleSession {+ [key: string]: unknown+ id: string+}++export interface BubbleHandle {+ readonly status: PetStatus | undefined+}++type SessionAction = 'create' | 'remove' | 'update'++/** 气泡标题 / 正文的最大字符数,超长截断省略,避免失败堆栈等长文本撑爆窗口。 */+const TITLE_MAX_LENGTH = 40+const DESCRIPTION_MAX_LENGTH = 120+/** 终态气泡自动隐藏时长(毫秒):失败展示 4s、待审阅 2.5s(对齐参考实现的完成脉冲)。实时状态(running / waiting)常驻,由后续会话事件更新内容。 */+const FAILED_BUBBLE_TIMEOUT = 4000+const REVIEW_BUBBLE_TIMEOUT = 2500++/** 桌宠窗口的会话气泡:DSH 发送原始会话快照,本 hook 私有管理会话→toast key 映射,仅暴露聚合宠物状态。 */+export function useBubble(): BubbleHandle {+ const [status, setStatus] = useState<PetStatus | undefined>(undefined)++ useEffect(() => {+ const sessions = new Map<string, BubbleSession>()+ const toastKeys = new Map<string, string>()+ const hideTimers = new Map<string, number>()+ const previousStatus = new Map<string, PetStatus | undefined>()+ /** 已自动隐藏的终态会话:保持隐藏直到状态离开终态,避免插件心跳重发 update 反复重建气泡。 */+ const dismissed = new Set<string>()+ let disposed = false++ function apply(payload: unknown, action: SessionAction): void {+ const session = rawSession(payload)+ if (session === undefined)+ return++ if (action === 'remove') {+ sessions.delete(session.id)+ previousStatus.delete(session.id)+ dismissed.delete(session.id)+ clearHideTimer(session.id)+ closeToast(session.id)+ }+ else {+ sessions.set(session.id, session)+ syncToast(session)+ }++ if (!disposed)+ setStatus(statusOf(sessions))+ }++ function syncToast(session: BubbleSession): void {+ const current = sessionStatus(session)+ const previous = previousStatus.get(session.id)+ previousStatus.set(session.id, current)+ const key = toastKeys.get(session.id)+ if (current === undefined) {+ if (key !== undefined)+ closeToast(session.id)+ return+ }++ const terminal = isTerminalStatus(current)+ // 状态离开终态后允许重建气泡。+ if (!terminal)+ dismissed.delete(session.id)++ const content = toastContent(session)+ if (key === undefined) {+ if (dismissed.has(session.id))+ return+ let createdKey = ''+ createdKey = toast(content.title, {+ description: content.description,+ placement: 'top end',+ variant: content.variant,+ timeout: 0,+ onClose: () => {+ if (toastKeys.get(session.id) === createdKey) {+ toastKeys.delete(session.id)+ clearHideTimer(session.id)+ }+ },+ })+ toastKeys.set(session.id, createdKey)+ }+ else {+ toast.update(key, content)+ }+ // 只在状态跃迁到终态时启动隐藏计时,心跳更新重置场景下不会反复延后。+ if (previous !== current && terminal)+ scheduleHide(session.id, current)+ }++ function scheduleHide(id: string, current: PetStatus): void {+ clearHideTimer(id)+ const timeout = current === 'failed'+ ? FAILED_BUBBLE_TIMEOUT+ : current === 'review'+ ? REVIEW_BUBBLE_TIMEOUT+ : undefined+ const key = toastKeys.get(id)+ if (timeout === undefined || key === undefined)+ return+ const timer = window.setTimeout(() => {+ if (toastKeys.get(id) !== key)+ return+ dismissed.add(id)+ closeToast(id)+ }, timeout)+ hideTimers.set(id, timer)+ }++ function clearHideTimer(id: string): void {+ const timer = hideTimers.get(id)+ if (timer !== undefined) {+ window.clearTimeout(timer)+ hideTimers.delete(id)+ }+ }++ function closeToast(id: string): void {+ clearHideTimer(id)+ const key = toastKeys.get(id)+ if (key === undefined)+ return+ toast.close(key)+ toastKeys.delete(id)+ }++ let unlisteners: Array<() => void> = []+ void Promise.all([+ listen('session:create', event => apply(event.payload, 'create')),+ listen('session:update', event => apply(event.payload, 'update')),+ listen('session:remove', event => apply(event.payload, 'remove')),+ ]).then((listeners) => {+ if (disposed) {+ for (const unlisten of listeners)+ unlisten()+ }+ else {+ unlisteners = listeners+ }+ }).catch(() => {})++ return () => {+ disposed = true+ for (const unlisten of unlisteners)+ unlisten()+ for (const timer of hideTimers.values())+ window.clearTimeout(timer)+ hideTimers.clear()+ for (const key of toastKeys.values())+ toast.close(key)+ toastKeys.clear()+ }+ }, [])++ return { status }+}++function rawSession(payload: unknown): BubbleSession | undefined {+ if (!payload || typeof payload !== 'object')+ return undefined+ const value = payload as Record<string, unknown>+ const session = value.session && typeof value.session === 'object'+ ? value.session as Record<string, unknown>+ : value+ const id = session.id ?? session.sessionId+ if (typeof id !== 'string' || id.length === 0)+ return undefined+ return { ...session, id }+}++function toastContent(session: BubbleSession): {+ title: string+ description: string+ variant: 'accent' | 'danger' | 'default'+} {+ const status = sessionStatus(session)+ const title = truncate(firstText(session.title, session.displayTitle, session.name, session.id), TITLE_MAX_LENGTH)+ const description = truncate(firstText(+ session.description,+ session.message,+ session.lastAgentError ? `失败:${String(session.lastAgentError)}` : undefined,+ statusLabel(status),+ ), DESCRIPTION_MAX_LENGTH)+ return {+ title,+ description,+ variant: status === 'failed' ? 'danger' : 'default',+ }+}++function truncate(text: string, maxLength: number): string {+ if (text.length <= maxLength)+ return text+ return `${text.slice(0, maxLength).trimEnd()}…`+}++function firstText(...values: unknown[]): string {+ for (const value of values) {+ if (typeof value === 'string' && value.trim().length > 0)+ return value.trim()+ }+ return '会话'+}++function statusLabel(status: PetStatus | undefined): string {+ switch (status) {+ case 'failed': return '失败'+ case 'review': return '待审阅'+ case 'waiting': return '等待中'+ case 'running': return '思考中'+ default: return '空闲'+ }+}++function statusOf(sessions: ReadonlyMap<string, BubbleSession>): PetStatus | undefined {+ const statuses = [...sessions.values()].map(sessionStatus)+ return statuses.find(value => value === 'failed')+ ?? statuses.find(value => value === 'waiting')+ ?? statuses.find(value => value === 'review')+ ?? statuses.find(value => value === 'running')+ ?? undefined+}++function isTerminalStatus(status: PetStatus): boolean {+ return status === 'failed' || status === 'review'+}++function hasPendingInteraction(value: unknown): boolean {+ return value !== undefined && value !== null && value !== false+}++function hasPendingItems(value: unknown): boolean {+ return Array.isArray(value) ? value.length > 0 : value !== undefined && value !== null+}++function sessionStatus(session: BubbleSession): PetStatus | undefined {+ const value = session.status ?? session.activity ?? session.phase+ if (value === 'failed' || value === 'error' || session.lastAgentError)+ return 'failed'+ if (value === 'review' || value === 'reviewing' || value === 'plan-review')+ return 'review'+ if (value === 'waiting' || value === 'pending' || value === 'blocked' || hasPendingInteraction(session.pendingInteraction) || hasPendingItems(session.pending))+ return 'waiting'+ if (value === 'running' || value === 'working' || value === 'thinking' || session.running === true)+ return 'running'+ return undefined+}diff --git a/src/pet/hooks/use-drag.ts b/src/pet/hooks/use-drag.tsnew file mode 100644index 00000000..dd23d4e4--- /dev/null+++ b/src/pet/hooks/use-drag.ts@@ -0,0 +1,216 @@+import type { RefObject } from 'react'+import { getCurrentWindow } from '@tauri-apps/api/window'+import { useEffect, useRef, useState } from 'react'++/** 拖拽的水平方向。 */+export type DragDirection = 'left' | 'right'++export interface UseDragResult {+ /** 原生拖拽会话进行中(按下后开始,结束/超时后为 false)。 */+ dragging: boolean+ /** 当前拖拽方向;未拖拽、位移不足或拖拽停顿时为 undefined。 */+ direction: DragDirection | undefined+ /**+ * 双击计次(两次按下间隔 < DOUBLE_CLICK_MS 且期间未进入拖拽):驱动点击回应动画+ * (waving)。不依赖 DOM click/dblclick 事件合成——Windows 原生拖拽会吞掉+ * pointerup,click/dblclick 永远不触发;改用 pointerdown 时间戳判定双击,+ * 三条平台路径全部可靠。+ */+ clickCount: number+}++/** 判定方向的水平位移阈值(物理像素),滤除拖拽起始时刻的抖动/初始跳变。 */+const DRAG_DIRECTION_THRESHOLD = 3+/**+ * 判定「真正开始拖拽」的累计位移阈值(物理像素),对应 dsh-pet 的 DRAG_THRESHOLD+ * (shared/constants.ts:10,逻辑像素 5):按下后累计位移未达阈值不算拖拽——+ * 单击、双击不进入拖拽、不播放拖动动画(点击回应由双击判定驱动)。+ * 位移按 X/Y 双轴累计(Math.hypot):垂直拖拽 X 位移可能很小,但不能因此+ * 把拖拽误判为点击。方向采样仍然基于逐次 dx,位移基准独立于方向采样基准。+ */+const DRAG_START_THRESHOLD = 8+/** 双击判定窗口(ms):两次 pointerdown 间隔小于该值且期间未拖拽,视为双击。 */+const DOUBLE_CLICK_MS = 500+/**+ * 方向停摆阈值:超过此时长没有新的窗口 Moved 事件,方向归零(宠物回到+ * idle/会话动画)。拖拽中短暂停顿(重新抓握)后继续移动会重新产生方向。+ */+const DRAG_DIRECTION_IDLE_TIMEOUT = 350+/**+ * 拖拽会话硬结束阈值:超过此时长没有 Moved 事件即认为原生拖拽已结束。+ * Windows 拖拽结束时 webview 收不到 pointerup(按钮事件被系统模态循环吞掉),+ * 只能靠 Moved 事件流停歇判结束;该阈值同时允许拖拽中较长的停顿后继续。+ */+const DRAG_SESSION_TIMEOUT = 1500++/**+ * 桌宠窗口拖拽 Hook:用 Tauri 原生窗口拖动移动桌宠,并借用窗口 Moved 事件+ * 采样位移方向(原生拖拽期间 webview 收不到 pointermove),供上层切换+ * moving-left / moving-right 动画。+ *+ * 生命周期不依赖 `startDragging()` 的 Promise 时机:+ * - tao 0.35(Windows)用 `PostMessageW(WM_NCLBUTTONDOWN, HTCAPTION)` 发起+ * 原生拖拽后立即返回,Promise 瞬间 resolve —— 它不代表拖拽结束,不能+ * 在 await 后清理拖拽态;+ * - 因此「拖拽进行中」= 按下后 Moved 事件持续到来。「结束」由两级停歇判断:+ * 方向停摆(DRAG_DIRECTION_IDLE_TIMEOUT)只清方向,会话仍存活,停顿后+ * 继续移动方向会恢复;会话硬超时(DRAG_SESSION_TIMEOUT)才真正结束整场+ * 拖拽;pointerup / pointercancel 作兜底。+ */+export function useDrag(dragRef: RefObject<HTMLElement | null>): UseDragResult {+ const draggingRef = useRef(false)+ const engagedRef = useRef(false)+ const moveXRef = useRef<number | undefined>(undefined)+ const moveStartXRef = useRef<number | undefined>(undefined)+ const moveStartYRef = useRef<number | undefined>(undefined)+ const lastDownRef = useRef<number | undefined>(undefined)+ const directionTimerRef = useRef<number | undefined>(undefined)+ const sessionTimerRef = useRef<number | undefined>(undefined)+ const [dragging, setDragging] = useState(false)+ const [direction, setDirection] = useState<DragDirection | undefined>(undefined)+ const [clickCount, setClickCount] = useState(0)++ useEffect(() => {+ const element = dragRef.current+ if (element === null)+ return undefined+ const appWindow = getCurrentWindow()+ let disposed = false+ let unlisten: (() => void) | undefined++ function clearTimer(ref: { current: number | undefined }): void {+ if (ref.current !== undefined) {+ window.clearTimeout(ref.current)+ ref.current = undefined+ }+ }++ /** 暂停移动:方向与位移基准归零,但拖拽会话保持存活。 */+ function parkDirection(): void {+ moveXRef.current = undefined+ setDirection(undefined)+ }++ function endDrag(): void {+ clearTimer(directionTimerRef)+ clearTimer(sessionTimerRef)+ draggingRef.current = false+ engagedRef.current = false+ setDragging(false)+ moveXRef.current = undefined+ moveStartXRef.current = undefined+ moveStartYRef.current = undefined+ setDirection(undefined)+ }++ /** 新的位移说明拖拽仍在进行:重置两级停歇计时。 */+ function armTimers(): void {+ clearTimer(directionTimerRef)+ clearTimer(sessionTimerRef)+ // 计时器句柄存 ref、由 cleanup 经 clearTimer 统一清理;规则无法追踪 ref 间接清理。+ // eslint-disable-next-line react/web-api-no-leaked-timeout+ directionTimerRef.current = window.setTimeout(parkDirection, DRAG_DIRECTION_IDLE_TIMEOUT)+ // eslint-disable-next-line react/web-api-no-leaked-timeout+ sessionTimerRef.current = window.setTimeout(endDrag, DRAG_SESSION_TIMEOUT)+ }++ async function handlePointerDown(event: PointerEvent): Promise<void> {+ if (event.button !== 0)+ return+ // 双击判定(必须先于 endDrag 读取 engagedRef:它反映「自上次按下以来是否拖拽过」)。+ // 不依赖 DOM dblclick:Windows 原生拖拽的模态循环会吞掉第一次 pointerup,+ // click/dblclick 事件无法合成;这里直接用两次 pointerdown 的间隔 + 未拖拽+ // 判定双击,跨平台可靠。单击/拖拽结束均不会计次(上次会话拖拽过则不算双击)。+ const now = performance.now()+ const isDoubleClick = lastDownRef.current !== undefined+ && now - lastDownRef.current < DOUBLE_CLICK_MS+ && engagedRef.current === false+ lastDownRef.current = now+ // 不调用 preventDefault:取消 pointerdown 会抑制兼容鼠标事件(click/dblclick),+ // 文本选择/触屏滚动已由 CSS(select-none/touch-none)防护。+ // 先清理残留状态(快速连续拖拽时上一轮的空闲计时可能还没到)。+ endDrag()+ draggingRef.current = true+ engagedRef.current = false+ // 参考 dsh-pet:按下仅记录会话,不立即进入拖拽动画(点击不播放拖动浮动),+ // 位移超过 DRAG_START_THRESHOLD 后 onMoved 才把 dragging 置 true。+ setDragging(false)+ moveXRef.current = undefined+ moveStartXRef.current = undefined+ moveStartYRef.current = undefined+ setDirection(undefined)+ if (isDoubleClick)+ setClickCount(count => count + 1)+ void appWindow.startDragging().catch(() => {})+ }++ function handlePointerUp(): void {+ // Windows 原生拖拽结束时 webview 收不到 pointerup(按钮事件被系统模态循环+ // 吞掉),会话由 DRAG_SESSION_TIMEOUT 超时兜底结束。+ endDrag()+ }++ element.addEventListener('pointerdown', handlePointerDown)+ element.addEventListener('pointerup', handlePointerUp)+ element.addEventListener('pointercancel', handlePointerUp)++ void appWindow.onMoved((event) => {+ // 只依赖共享 ref 判断拖拽态:startDragging 的 resolve 时机(平台差异)+ // 与 effect 重建(StrictMode)都不应影响方向采样。+ if (!draggingRef.current)+ return+ armTimers()+ const x = event.payload.x+ const y = event.payload.y+ if (moveStartXRef.current === undefined || moveStartYRef.current === undefined) {+ // 首个 Moved 事件作为位移基准:吞掉 startDragging 可能带来的初始跳变,+ // 以及暂停与恢复之间的坐标不连续。方向采样同样以它起步。+ moveStartXRef.current = x+ moveStartYRef.current = y+ moveXRef.current = x+ return+ }+ if (!engagedRef.current) {+ // 未达拖拽阈值:单击/双击/轻微抖动不算拖拽,不采样方向(基准保持不动)。+ // 位移按 X/Y 双轴累计:垂直拖拽 X 位移较小,不能因此误判为点击。+ if (Math.hypot(x - moveStartXRef.current, y - moveStartYRef.current) < DRAG_START_THRESHOLD)+ return+ engagedRef.current = true+ setDragging(true)+ }+ if (moveXRef.current === undefined) {+ // 停顿(parkDirection)后恢复移动:重新建立方向采样基准。+ moveXRef.current = x+ return+ }+ const dx = x - moveXRef.current+ moveXRef.current = x+ if (Math.abs(dx) >= DRAG_DIRECTION_THRESHOLD)+ setDirection(dx > 0 ? 'right' : 'left')+ }).then((dispose) => {+ if (disposed)+ dispose()+ else+ unlisten = dispose+ }).catch(() => {})++ return () => {+ disposed = true+ unlisten?.()+ element.removeEventListener('pointerdown', handlePointerDown)+ element.removeEventListener('pointerup', handlePointerUp)+ element.removeEventListener('pointercancel', handlePointerUp)+ clearTimer(directionTimerRef)+ clearTimer(sessionTimerRef)+ draggingRef.current = false+ engagedRef.current = false+ setDragging(false)+ moveXRef.current = undefined+ moveStartXRef.current = undefined+ moveStartYRef.current = undefined+ setDirection(undefined)+ }+ }, [dragRef])++ return { dragging, direction, clickCount }+}diff --git a/src/pet/hooks/use-pet.ts b/src/pet/hooks/use-pet.tsnew file mode 100644index 00000000..da0d46fa--- /dev/null+++ b/src/pet/hooks/use-pet.ts@@ -0,0 +1,49 @@+import type { RefObject } from 'react'+import { useRef } from 'react'++export const PET_STATUSES = [+ 'idle',+ 'turn',+ 'moving-left',+ 'moving-right',+ 'waving',+ 'waiting',+ 'running',+ 'review',+ 'failed',+] as const++export type PetStatus = (typeof PET_STATUSES)[number]++export interface PetChangeOptions {+ loop?: boolean+ status: PetStatus+}++export interface PetHandle {+ change: (options: PetChangeOptions) => void+ clear: () => void+ readonly status: PetStatus+}++/**+ * 提供桌宠的命令面。组件内部通过同一个 ref 暴露真正的播放器,调用方不接触+ * 资源、Codex 精灵图或动画结束事件;ref 命令优先于 status 属性。+ */+export function usePet(petRef?: RefObject<PetHandle | null>): PetHandle {+ const handleRef = useRef<PetHandle | null>(null)+ if (handleRef.current === null) {+ handleRef.current = {+ change(options) {+ petRef?.current?.change(options)+ },+ clear() {+ petRef?.current?.clear()+ },+ get status() {+ return petRef?.current?.status ?? 'idle'+ },+ }+ }+ return handleRef.current+}diff --git a/src/pet/main.css b/src/pet/main.cssnew file mode 100644index 00000000..f13cac92--- /dev/null+++ b/src/pet/main.css@@ -0,0 +1,17 @@+@import "tailwindcss";++@config "../../tailwind.config.js";+@import "@heroui/styles";++@layer base {+ html,+ body,+ #root {+ min-height: 100%;+ background: transparent;+ }++ body {+ overflow: hidden;+ }+}diff --git a/src/pet/main.tsx b/src/pet/main.tsxindex bdda6620..52aa2cb4 100644--- a/src/pet/main.tsx+++ b/src/pet/main.tsx@@ -1,17 +1,13 @@import React from 'react'import ReactDOM from 'react-dom/client'-import { ToastProvider } from '@/components/toast-provider'-import { PetWindow } from './pet'-import './pet.css'+import { App } from './app'+import './main.css'const root = document.getElementById('root') as HTMLElement-root.style.width = '100%'-root.style.height = '100%'+root.className = 'h-full w-full'ReactDOM.createRoot(root).render(<React.StrictMode>- <ToastProvider hideCloseButton>- <PetWindow />- </ToastProvider>+ <App /></React.StrictMode>,)diff --git a/src/pet/pet.css b/src/pet/pet.cssdeleted file mode 100644index 1d187c8d..00000000--- a/src/pet/pet.css+++ /dev/null@@ -1,182 +0,0 @@-@import "@heroui/styles";--/* 桌宠窗口保持全透明,只有视频、降级图与气泡参与绘制。 */-html,-body,-#root {- width: 100%;- height: 100%;- margin: 0;- padding: 0;- overflow: hidden;- background: transparent;-}--html,-body {- color-scheme: light;- font-family: ui-rounded, 'SF Pro Rounded', 'Segoe UI', 'PingFang SC', 'Microsoft YaHei', sans-serif;- -webkit-user-select: none;- user-select: none;-}--/* 舞台只负责把宠物固定在透明窗口底部,不制造任何不透明底色。 */-.pet-stage {- position: relative;- display: flex;- width: 100%;- height: 100%;- align-items: flex-end;- justify-content: center;- pointer-events: none;-}--.pet-stage[data-visible='false'] {- display: none;-}--/* --pet-width 由 pet_size 百分比计算;视频始终保持 dsh-pet 的 16:9 画布。 */-.pet-anchor {- position: relative;- width: var(--pet-width);- height: calc(var(--pet-width) * var(--pet-aspect));- margin-bottom: 0;- pointer-events: auto;-}--.pet-hit-area {- position: absolute;- inset: 0;- z-index: 1;- overflow: visible;- cursor: grab;- touch-action: none;-}--.pet-hit-area:active {- cursor: grabbing;-}--.pet-video,-.pet-sprite,-.pet-fallback {- position: absolute;- inset: 0;- display: block;- width: 100%;- height: 100%;- object-fit: contain;- object-position: center bottom;- pointer-events: none;- transform: scaleX(var(--pet-facing));- transform-origin: center bottom;- filter: drop-shadow(0 6px 8px rgb(0 0 0 / 22%));-}--.pet-sprite {- background-repeat: no-repeat;-}--/* 透明探针只读取自定义精灵图原始尺寸,不参与绘制或交互。 */-.pet-sprite-probe {- position: absolute;- width: 0;- height: 0;- opacity: 0;- pointer-events: none;-}--.pet-fallback {- z-index: 2;-}-/* HeroUI Toast 区域仅占用固定 120px 顶部留白,绝不进入宠物画面。 */-.pet-toast-region {- position: absolute;- left: 50%;- bottom: calc(100% + 8px);- z-index: 3;- display: flex;- box-sizing: border-box;- width: min(calc(var(--pet-width) * 0.92), calc(100vw - 12px));- height: 112px;- margin: 0;- padding: 0;- align-items: flex-end;- justify-content: center;- overflow: visible;- outline: none;- pointer-events: none;- transform: translateX(-50%);-}--.pet-toast {- position: relative;- display: flex;- box-sizing: border-box;- width: 100%;- max-height: 100%;- padding: clamp(5px, calc(7px * var(--pet-scale)), 14px)- clamp(8px, calc(10px * var(--pet-scale)), 20px);- border: 1px solid rgb(255 255 255 / 78%);- border-radius: clamp(10px, calc(12px * var(--pet-scale)), 24px);- background: rgb(255 255 255 / 94%);- box-shadow: 0 5px 18px rgb(14 31 53 / 18%), 0 1px 3px rgb(14 31 53 / 10%);- color: #263247;- pointer-events: none;- transform-origin: 50% 100%;- animation: pet-toast-enter 180ms ease-out both;-}--.pet-toast::after {- position: absolute;- left: 50%;- bottom: -4px;- width: 10px;- height: 10px;- background: rgb(255 255 255 / 94%);- content: '';- transform: translateX(-50%) rotate(45deg);-}--.pet-toast-content {- display: block;- width: 100%;- max-height: 100%;- overflow: hidden;-}--.pet-toast-title {- display: block;- margin: 0;- color: inherit;- font-size: clamp(11px, calc(12px * var(--pet-scale)), 16px);- font-weight: 600;- line-height: 1.4;- overflow-wrap: anywhere;- text-align: center;- white-space: normal;-}--@keyframes pet-toast-enter {- from {- opacity: 0;- transform: translateY(5px) scale(0.96);- }-- to {- opacity: 1;- transform: translateY(0) scale(1);- }-}--/* 降低动态效果时取消 Toast 过渡;视频仍保留状态首帧与系统状态可辨识性。 */-@media (prefers-reduced-motion: reduce) {- .pet-toast {- animation: none;- }-}--/* 常驻 9 个内置视频仅激活项可见;隐藏项保留解码状态与暂停帧,切换即时无闪帧。 */-.pet-video[data-active='false'] {- visibility: hidden;-}diff --git a/src/pet/pet.tsx b/src/pet/pet.tsxdeleted file mode 100644index 64e5fea1..00000000--- a/src/pet/pet.tsx+++ /dev/null@@ -1,765 +0,0 @@-import type { CSSProperties, PointerEvent as ReactPointerEvent } from 'react'-import type { DragMachine, DragPhase } from './drag-machine'-import type {- PetActivity,- PetAnimation,- PetFacing,-} from './state'-import { invoke } from '@tauri-apps/api/core'-import { listen } from '@tauri-apps/api/event'-import { cursorPosition, getCurrentWindow, LogicalSize } from '@tauri-apps/api/window'-import { useEffect, useRef, useState } from 'react'-import { If } from 'react-if-lite'-import { toast } from '@/utils/toast'-import { resolvePetActivity } from './arbiter'-import {- beginDrag,- createDragMachine,- DRAG_SAMPLE_INTERVAL_MS,- dragSample,- endDrag,- hasDragged,- isDragActive,- resetDrag,-} from './drag-machine'-import { SessionBubble } from './session-bubble'-import { sessionBubbleDescription, sessionBubbleStore, sessionBubbleTitle } from './session-bubbles'-import {- getPetVisual,- getSpriteFramePosition,- getSpriteSequence,- normalizePetActivity,-} from './state'-import { useEvent } from 'react-use'--interface PetStatus {- enabled: boolean- visible?: boolean | null- active_pet?: string | null- pet_size?: number | null- activity?: unknown- bubble?: unknown- sessions?: Array<{ id: string, activity?: unknown, bubble?: unknown, description?: unknown }>-}--interface PetAsset {- columns: number- id: string- rows: number- sprite_version_number: number- spritesheet: string-}--interface DragState {- active: boolean- nativeStarted: boolean- pointerId: number- requestId: number-}--interface Copy {- petLabel: string-}--const BUILT_IN_PET_ID = 'maid-deepseek-whale'-const PET_DEFAULT_SIZE_PERCENT = 100-const PET_BASE_WIDTH = 220-const PET_STATUS_EVENT = 'pet://status'-const CLICK_DELAY_MS = 220--const COPY: Record<'en' | 'zh', Copy> = {- en: {- petLabel: 'DeepSeek Harness desktop pet',- },- zh: {- petLabel: 'DeepSeek Harness 桌宠',- },-}--type BuiltinAssetKey = 'idle' | 'turn' | 'move' | 'wave' | 'waiting' | 'running' | 'review' | 'failed' | 'bubble' | 'fallback'--/** 常驻预加载的 9 个内置视频键;fallback 走 <img> 降级路径,不占视频槽位。 */-type VideoKey = Exclude<BuiltinAssetKey, 'fallback'>-const VIDEO_KEYS: VideoKey[] = ['idle', 'turn', 'move', 'wave', 'waiting', 'running', 'review', 'failed', 'bubble']-/** 一次性动画结束后回到动作起点;循环动画暂停后原位续播。 */-const ONCE_KEYS = new Set<VideoKey>(['turn', 'wave', 'bubble'])--/** 独立透明桌宠窗口:事件驱动状态、内置视频、自定义精灵图与无积压拖拽。 */-export function PetWindow() {- const [status, setStatus] = useState<PetStatus>({ enabled: false })- const [builtinAssets, setBuiltinAssets] = useState<Record<string, string>>({})- const [sessionActivity, setSessionActivity] = useState<PetActivity>('idle')- const [localActivity, setLocalActivity] = useState<PetAnimation | null>(null)- const [facing, setFacing] = useState<PetFacing>('left')- const [failedPet, setFailedPet] = useState<string | null>(null)- const [builtinAssetFailed, setBuiltinAssetFailed] = useState(false)- const [fallbackFailed, setFallbackFailed] = useState(false)- const [customAsset, setCustomAsset] = useState<PetAsset | null>(null)- const [spriteAspect, setSpriteAspect] = useState<{ id: string, value: number } | null>(null)- const [reducedMotion, setReducedMotion] = useState(() => window.matchMedia('(prefers-reduced-motion: reduce)').matches)- const [dragPhase, setDragPhase] = useState<DragPhase>('idle')- const clickTimerRef = useRef<number | null>(null)- const activeVideoKeyRef = useRef<VideoKey | null>(null)- const videoElementsRef = useRef<Record<VideoKey, HTMLVideoElement | null>>({ idle: null, turn: null, move: null, wave: null, waiting: null, running: null, review: null, failed: null, bubble: null })- const spriteRef = useRef<HTMLDivElement | null>(null)- const dragRef = useRef<DragState>({ active: false, nativeStarted: false, pointerId: -1, requestId: 0 })- const dragMachineRef = useRef<DragMachine>(createDragMachine())- const dragRequestRef = useRef(0)- const sessionToastKeysRef = useRef(new Map<string, string>())- const sessionActivityRef = useRef<PetActivity>('idle')- sessionActivityRef.current = sessionActivity- // 拖动动画由 dragPhase(phase==='dragging')+ facing 直接驱动;- // 不再从 ref 在渲染期读取,避免 facing/localActivity 不变时不重渲染导致动画不播(root cause #3)。- const draggingActivity = dragPhase === 'dragging'- ? (facing === 'left' ? 'moving-left' : 'moving-right')- : null- const activity = resolvePetActivity({- sessionActivity,- draggingActivity,- interactionActivity: localActivity,- })- const isWorkLocked = sessionActivity === 'waiting' || sessionActivity === 'running'- const visual = getPetVisual(activity, facing)- const whaleFallbackUrl = builtinAssetUrl('fallback', builtinAssets)- const activePet = normalizeActivePet(status.active_pet)- const usesCustomSprite = activePet !== BUILT_IN_PET_ID- const visibleCustomAsset = customAsset?.id === activePet ? customAsset : null- const mediaFailed = failedPet === activePet || builtinAssetFailed- // 内置媒体池是否就绪:src 由 Rust 固定白名单映射,idle 到位即按 9 个常驻视频渲染。- const videoPoolReady = !usesCustomSprite && !builtinAssetFailed && builtinAssets.idle !== undefined- const activeVideoKey = assetKeyForVisual(visual.asset)- const petSizePercent = normalizePetSize(status.pet_size)- const copy = getCopy()- const isVisible = status.enabled && status.visible !== false- const petAspect = usesCustomSprite- ? (spriteAspect?.id === activePet ? spriteAspect.value : 208 / 192)- : 9 / 16- const petStyle = {- '--pet-width': `${(PET_BASE_WIDTH * petSizePercent) / 100}px`,- '--pet-scale': String(petSizePercent / 100),- '--pet-facing': usesCustomSprite || visual.facing === 'left' ? '1' : '-1',- '--pet-aspect': usesCustomSprite && spriteAspect?.id === activePet ? spriteAspect.value : (usesCustomSprite ? 208 / 192 : 9 / 16),- } as CSSProperties-- // 内置媒体清单由 Rust 固定白名单生成,避免前端注入插件目录路径。- useEffect(() => {- let cancelled = false- void invoke<{ assets?: Record<string, string> }>('get_builtin_pet_assets').then((value) => {- if (!cancelled && value.assets)- setBuiltinAssets(value.assets)- if (!cancelled && !value.assets?.idle)- setBuiltinAssetFailed(true)- }).catch((error) => {- setBuiltinAssetFailed(true)- console.error('[pet] PET_BUILTIN_ASSET_LOAD_FAILED:', error)- })- return () => {- cancelled = true- }- }, [])-- // 初次读取一次持久化状态,随后完全依赖 pet://status 事件,不再轮询。- useEffect(() => {- let cancelled = false- let dispose: (() => void) | undefined-- function applyStatus(nextStatus: PetStatus) {- if (cancelled)- return- setStatus(nextStatus)- syncSessionToasts(nextStatus)- if (!nextStatus.enabled || nextStatus.visible === false)- toast.clear()- const nextActivity = normalizePetActivity(nextStatus.activity)- setSessionActivity(nextActivity)- if (nextActivity !== 'idle') {- clearClickTimer()- setLocalActivity(null)- }- }-- void (async () => {- try {- const unlisten = await listen<PetStatus>(PET_STATUS_EVENT, (event) => {- applyStatus(event.payload)- })- if (cancelled)- unlisten()- else- dispose = unlisten- const initial = await invoke<PetStatus>('get_pet_status')- applyStatus(initial)- }- catch (error) {- console.error('[pet] PET_STATUS_CHANNEL_FAILED:', error)- }- })()-- return () => {- cancelled = true- dispose?.()- clearSessionToasts()- }- // 仅在窗口首次挂载时建立事件通道;气泡函数通过 ref 定时器管理自身生命周期。- }, [])-- // active_pet 使用来源限定 id;只有内置默认宠物继续走 WebM 状态机。- useEffect(() => {- let cancelled = false- if (!usesCustomSprite)- return undefined-- void invoke<PetAsset>('get_pet_asset', { id: activePet }).then((asset) => {- if (cancelled)- return- if (!isSupportedAsset(asset))- throw new Error('PET_ASSET_INVALID: expected Codex v2 8x11 spritesheet')- setFailedPet(null)- setCustomAsset(asset)- }).catch((error) => {- if (!cancelled) {- setFailedPet(activePet)- console.error('[pet] get_pet_asset failed:', error)- }- })-- return () => {- cancelled = true- }- }, [activePet, usesCustomSprite])-- // 精灵图逐帧计时与参考实现一致,动作三轮后安全进入慢速 idle。- useEffect(() => {- const sprite = spriteRef.current- if (!usesCustomSprite || visibleCustomAsset === null || sprite === null)- return undefined- const spriteElement = sprite- const asset = visibleCustomAsset- const sequence = getSpriteSequence(activity, facing, reducedMotion)- let index = 0- let timer: number | undefined-- function paint() {- const current = sequence.frames[index]- spriteElement.style.backgroundPosition = getSpriteFramePosition(current, asset.columns, asset.rows)- spriteElement.dataset.petFrame = String(index)- if (sequence.frames.length === 1)- return- timer = window.setTimeout(() => {- const next = index + 1- index = next >= sequence.frames.length ? (sequence.loopStart ?? index) : next- paint()- }, current.duration)- }-- paint()- return () => {- if (timer !== undefined)- window.clearTimeout(timer)- }- }, [activity, facing, reducedMotion, usesCustomSprite, visibleCustomAsset])-- // 一次性交互在精灵图中完整播放三轮后回到会话状态;turn 同时切换朝向。- useEffect(() => {- if (!usesCustomSprite || localActivity === null)- return undefined- const sequence = getSpriteSequence(localActivity, facing, reducedMotion)- const actionLength = sequence.loopStart ?? sequence.frames.length- const duration = sequence.frames.slice(0, actionLength).reduce((total, frame) => total + frame.duration, 0)- const timer = window.setTimeout(() => {- if (localActivity === 'turn')- setFacing(current => current === 'left' ? 'right' : 'left')- setLocalActivity(null)- }, duration)- return () => window.clearTimeout(timer)- }, [facing, localActivity, reducedMotion, usesCustomSprite])-- // 拖动方向完全由窗口物理位置驱动(outerPosition 增量),与 WebView 指针事件无关。- // 主来源 appWindow.onMoved;Windows 系统模态拖动期间该事件可能被吞掉,故按下后另起一个- // 固定间隔轮询 outerPosition 的兜底,二者都喂给 dragSample 状态机。- // dragPhase 驱动此 effect 建立/拆除兜底轮询;采样函数内联以规避 react-hooks 依赖提示。- useEffect(() => {- const appWindow = getCurrentWindow()- let cancelled = false- let disposeMoved: (() => void) | undefined-- function applyDragSample(x: number) {- const machine = dragMachineRef.current- const next = dragSample(machine, x)-- if (next === machine)- return-- dragMachineRef.current = next- if (next.phase !== machine.phase)- setDragPhase(next.phase)- if (next.facing !== machine.facing)- setFacing(next.facing)- }-- void appWindow.onMoved((event) => {- if (!cancelled)- applyDragSample(event.payload.x)- }).then((unlisten) => {- if (cancelled)- unlisten()- else- disposeMoved = unlisten- }).catch(() => {})-- let timer: number | null = null- if (isDragActive(dragMachineRef.current)) {- timer = window.setInterval(() => {- void appWindow.outerPosition().then((position) => {- if (!cancelled)- applyDragSample(position.x)- }).catch(() => {})- }, DRAG_SAMPLE_INTERVAL_MS)- }-- return () => {- cancelled = true- disposeMoved?.()- if (timer !== null)- window.clearInterval(timer)- }- }, [dragPhase])-- // 原生窗口尺寸跟随实际资源宽高;透明顶部只为 Toast 保留,不扩大宠物拖拽区。- // 由前端按当前资源真实画布比例设置,避免与 Rust(只按图集默认比例)重复 set_size 打架。- useEffect(() => {- if (!status.enabled)- return- const appWindow = getCurrentWindow()- const width = (PET_BASE_WIDTH * petSizePercent) / 100 + 32- const height = (PET_BASE_WIDTH * petSizePercent) / 100 * petAspect + 82- void appWindow.setSize(new LogicalSize(width, height)).then(() => {- // 放大后把窗口夹回可见显示器,避免右侧/底部被推出屏幕;复用 Rust 的夹取逻辑。- void invoke('move_pet_window', { deltaX: 0, deltaY: 0 }).catch(() => {})- }).catch((error) => {- console.warn('[pet] PET_WINDOW_RESIZE_FAILED:', error)- })- }, [petAspect, petSizePercent, status.enabled])-- // 透明窗口仍覆盖一个矩形;只有资源本身与 Toast 的真实 DOM 区域接收鼠标。- // 使用全局物理光标坐标轮询,可在 setIgnoreCursorEvents(true) 后重新恢复可点击状态。- useEffect(() => {- const appWindow = getCurrentWindow()- let cancelled = false- let lastIgnore: boolean | undefined-- async function updateCursorMode() {- if (cancelled || !status.enabled || status.visible === false)- return- try {- const [cursor, origin, scale] = await Promise.all([- cursorPosition(),- appWindow.innerPosition(),- appWindow.scaleFactor(),- ])- const anchor = document.querySelector<HTMLElement>('.pet-anchor')?.getBoundingClientRect()- const toastRegions = [...document.querySelectorAll<HTMLElement>('[data-slot="toast-region"]')]- const contains = (rect: DOMRect | undefined) => rect !== undefined- && cursor.x >= origin.x + rect.left * scale- && cursor.x <= origin.x + rect.right * scale- && cursor.y >= origin.y + rect.top * scale- && cursor.y <= origin.y + rect.bottom * scale- const interactive = contains(anchor) || toastRegions.some(region => contains(region.getBoundingClientRect()))- const ignore = !interactive- if (ignore !== lastIgnore) {- lastIgnore = ignore- await appWindow.setIgnoreCursorEvents(ignore)- }- }- catch {- // 窗口销毁或系统暂时无法读取光标位置时不改变当前命中模式。- }- }-- void updateCursorMode()- const timer = window.setInterval(() => {- void updateCursorMode()- }, 50)- return () => {- cancelled = true- window.clearInterval(timer)- void appWindow.setIgnoreCursorEvents(false).catch(() => {})- }- }, [status.enabled, status.visible])-- // 跟随操作系统的降低动态效果偏好,自定义精灵图冻结在对应动作首帧。- useEffect(() => {- const query = window.matchMedia('(prefers-reduced-motion: reduce)')- function applyPreference() {- setReducedMotion(query.matches)- }- query.addEventListener('change', applyPreference)- return () => query.removeEventListener('change', applyPreference)- }, [])-- // 常驻 9 个内置视频只激活一个:切出时暂停(一次性动画停回首帧),切入时回零后播放,- // 其余视频保持预载与解码状态,不再重建 <video>,避免动作切换闪帧(issue #308)。- useEffect(() => {- if (!videoPoolReady)- return undefined- const elements = videoElementsRef.current- const next = activeVideoKey- const el = elements[next]- if (!el || !el.src)- return undefined- const previous = activeVideoKeyRef.current- if (previous !== null && previous !== next) {- const oldPaused = elements[previous]- if (oldPaused) {- oldPaused.pause()- if (ONCE_KEYS.has(previous))- oldPaused.currentTime = 0- }- }- activeVideoKeyRef.current = next- // 激活的媒体真正开始播放时清除失败标记;后台视频的 playing 事件被守卫忽略,不误清。- const handlePlaying = () => {- if (activeVideoKeyRef.current === next)- setFailedPet(null)- }- el.addEventListener('playing', handlePlaying)- // 一次性动画每次进入都从动作起点开始;无元数据时跳过(新建视频首帧本就是 0)。- if (ONCE_KEYS.has(next) && el.readyState >= 1)- el.currentTime = 0- el.play().catch(() => {})- return () => {- el.removeEventListener('playing', handlePlaying)- const current = activeVideoKeyRef.current- activeVideoKeyRef.current = null- if (current === null)- return- const leaving = elements[current]- if (leaving) {- leaving.pause()- if (ONCE_KEYS.has(current))- leaving.currentTime = 0- }- }- }, [activeVideoKey, isVisible, videoPoolReady])-- // 点击任务在卸载时回收;会话 Toast 与宠物共用当前 WebView 的 queue。- useEffect(() => {- return () => {- clearClickTimer()- clearSessionToasts()- toast.clear()- }- }, [])-- function syncSessionToasts(nextStatus: PetStatus) {- const keys = sessionToastKeysRef.current- const sessions = nextStatus.enabled && nextStatus.visible !== false ? (nextStatus.sessions ?? []) : []- const active = new Map<string, { description: string, title: string }>()- for (const session of sessions) {- if (typeof session.id !== 'string' || session.id.length === 0)- continue- if (session.activity === 'idle')- continue- // 会话标题固定、描述实时:标题在创建 toast 时写入,描述随每次推送刷新。- active.set(session.id, { description: sessionBubbleDescription(session), title: sessionBubbleTitle(session) })- sessionBubbleStore.set(session.id, sessionBubbleDescription(session))- }- for (const [id, key] of keys) {- if (!active.has(id)) {- toast.close(key)- keys.delete(id)- sessionBubbleStore.delete(id)- }- }- for (const [id, presentation] of active) {- const key = keys.get(id)- if (key === undefined) {- // 会话 Toast 必须常驻至会话结束:显式 timeout 0(HeroUI 持久 Toast 哨兵)。- const created = toast(presentation.title, {- placement: 'top',- timeout: 0,- description: <SessionBubble sessionId={id} />,- onClose: () => {- if (keys.get(id) === created) {- keys.delete(id)- sessionBubbleStore.delete(id)- }- },- })- keys.set(id, created)- }- }- }-- function clearSessionToasts() {- const keys = sessionToastKeysRef.current- for (const key of keys.values())- toast.close(key)- for (const id of keys.keys())- sessionBubbleStore.delete(id)- keys.clear()- }-- function clearClickTimer() {- if (clickTimerRef.current !== null) {- window.clearTimeout(clickTimerRef.current)- clickTimerRef.current = null- }- }-- function handleAnimationEnded(key: VideoKey) {- // 抢占守卫:播放期间已切走的旧视频,其 ended 回调不再生效。- if (key !== activeVideoKeyRef.current)- return- if (key === 'turn')- setFacing(current => (current === 'left' ? 'right' : 'left'))- if (localActivity !== null) {- setLocalActivity(null)- return- }- if (key === 'turn' || key === 'wave')- setSessionActivity('idle')- }-- function handleVideoError(key: VideoKey) {- if (key === activeVideoKeyRef.current)- setFailedPet(activePet)- }-- function handleSpriteError() {- setFailedPet(activePet)- }-- function handleMediaLoaded(key: VideoKey) {- if (key === activeVideoKeyRef.current)- setFailedPet(null)- }-- function handleSpriteLoaded(event: React.SyntheticEvent<HTMLImageElement>) {- const image = event.currentTarget- if (visibleCustomAsset !== null) {- const frameWidth = image.naturalWidth / visibleCustomAsset.columns- const frameHeight = image.naturalHeight / visibleCustomAsset.rows- if (frameWidth > 0 && frameHeight > 0)- setSpriteAspect({ id: visibleCustomAsset.id, value: frameHeight / frameWidth })- }- setFailedPet(null)- }-- function handlePointerDown(event: ReactPointerEvent<HTMLDivElement>) {- if (event.button !== 0)- return- const requestId = dragRequestRef.current + 1- dragRequestRef.current = requestId- dragRef.current = {- active: true,- nativeStarted: true,- pointerId: event.pointerId,- requestId,- }- dragMachineRef.current = beginDrag(facing)- setDragPhase(dragMachineRef.current.phase)- // 交给操作系统追踪窗口。Windows 原生拖拽会正确处理跨显示器 DPI 切换,- // 方向改由窗口物理位置增量驱动,不再把不同坐标系的 PointerEvent 增量换算成窗口像素。- void performNativeDrag(requestId)- }-- function handlePointerUp(event: ReactPointerEvent<HTMLDivElement>) {- console.log('----')- const drag = dragRef.current- if (!drag.active || drag.pointerId !== event.pointerId)- return- // startDragging 的 Promise 在系统结束拖拽后负责区分点击与实际移动。- if (!drag.nativeStarted)- finishPetInteraction(false)- }-- function handlePointerCancel(event: ReactPointerEvent<HTMLDivElement>) {- const drag = dragRef.current- if (drag.pointerId !== event.pointerId)- return- // 取消视为一次拖动结束:先进入 ending,再复位且不触发挥手。- dragMachineRef.current = endDrag(dragMachineRef.current)- setDragPhase('ending')- finishPetInteraction(true)- }-- function handleDoubleClick() {- dragRequestRef.current += 1- dragRef.current.active = false- dragMachineRef.current = resetDrag()- setDragPhase('idle')- clearClickTimer()- if (isWorkLocked || sessionActivity === 'review' || sessionActivity === 'failed')- return- setLocalActivity('bubble')- }- async function performNativeDrag(requestId: number) {- const appWindow = getCurrentWindow()- const originPromise = appWindow.outerPosition()- try {- const nativeDrag = appWindow.startDragging()- const origin = await originPromise- await nativeDrag- const position = await appWindow.outerPosition()- if (dragRequestRef.current !== requestId)- return- const moved = position.x !== origin.x || position.y !== origin.y- || hasDragged(dragMachineRef.current)- finishPetInteraction(moved)- }- catch (error) {- if (dragRequestRef.current === requestId)- finishPetInteraction(false)- console.warn('[pet] native drag failed:', error)- }- }-- function finishPetInteraction(moved: boolean) {- const drag = dragRef.current- drag.active = false- drag.nativeStarted = false- // 结束拖动:复位状态机到 idle,并停掉此前的方向覆盖;- // 会话活动从不在此处改写成 idle,交给 resolvePetActivity 按 dragging→session→交互 回落。- dragMachineRef.current = resetDrag()- setDragPhase('idle')- if (moved) {- setLocalActivity(null)- return- }- clearClickTimer()- clickTimerRef.current = window.setTimeout(() => {- clickTimerRef.current = null- if (isWorkLocked || sessionActivityRef.current === 'review' || sessionActivityRef.current === 'failed')- return- // 无状态单击只播放挥手动画,不再弹 Toast。- setLocalActivity('waving')- }, CLICK_DELAY_MS)- }-- return (- <main className="pet-stage" data-visible={isVisible}>- <If cond={isVisible}>- <div className="pet-anchor" style={petStyle} data-sprite={usesCustomSprite}>- <div- className="pet-hit-area"- aria-label={copy.petLabel}- data-activity={activity}- data-active-pet={activePet}- onDoubleClick={handleDoubleClick}- onPointerCancel={handlePointerCancel}- onPointerDown={handlePointerDown}- onPointerUp={handlePointerUp}- role="img"- >- <If cond={videoPoolReady}>- {VIDEO_KEYS.map(key => (- <video- key={key}- ref={(el) => {- videoElementsRef.current[key] = el- }}- className="pet-video"- data-active={activeVideoKey === key}- data-facing={visual.facing}- loop={!ONCE_KEYS.has(key)}- muted- onEnded={() => handleAnimationEnded(key)}- onError={() => handleVideoError(key)}- onLoadedData={() => handleMediaLoaded(key)}- playsInline- preload="auto"- src={builtinAssetUrl(key, builtinAssets)}- />- ))}- </If>- <If cond={usesCustomSprite && visibleCustomAsset !== null}>- <div- ref={spriteRef}- className="pet-sprite"- data-facing={facing}- style={{- backgroundImage: visibleCustomAsset ? `url(${visibleCustomAsset.spritesheet})` : undefined,- backgroundPosition: visibleCustomAsset- ? getSpriteFramePosition(getSpriteSequence(activity, facing, reducedMotion).frames[0], visibleCustomAsset.columns, visibleCustomAsset.rows)- : undefined,- backgroundSize: visibleCustomAsset ? `${visibleCustomAsset.columns * 100}% ${visibleCustomAsset.rows * 100}%` : undefined,- }}- />- <img- className="pet-sprite-probe"- src={visibleCustomAsset?.spritesheet}- alt=""- draggable={false}- onError={handleSpriteError}- onLoad={handleSpriteLoaded}- />- </If>- <If cond={mediaFailed}>- <If cond={whaleFallbackUrl !== undefined && !fallbackFailed}>- <img- className="pet-fallback"- src={whaleFallbackUrl}- alt=""- draggable={false}- onError={() => setFallbackFailed(true)}- />- </If>- <If cond={whaleFallbackUrl === undefined || fallbackFailed}>- <span className="pet-media-error" role="status">PET_BUILTIN_ASSET_UNAVAILABLE</span>- </If>- </If>- </div>- </div>- </If>- </main>- )-}--function builtinAssetUrl(key: BuiltinAssetKey, assets: Record<string, string>): string | undefined {- return assets[key]-}--function assetKeyForVisual(asset: string): VideoKey {- if (asset === 'maid-turn.webm')- return 'turn'- if (asset === 'maid-move.webm')- return 'move'- if (asset === 'maid-wave.webm')- return 'wave'- if (asset === 'maid-waiting.webm')- return 'waiting'- if (asset === 'maid-running.webm')- return 'running'- if (asset === 'maid-review.webm')- return 'review'- if (asset === 'maid-failed.webm')- return 'failed'- if (asset === 'maid-bubble.webm')- return 'bubble'- return 'idle'-}--function isSupportedAsset(value: PetAsset): boolean {- return value.sprite_version_number === 2- && value.columns === 8- && value.rows === 11- && typeof value.spritesheet === 'string'- && value.spritesheet.length > 0-}--function normalizeActivePet(value: string | null | undefined): string {- const normalized = value?.trim()- return normalized || BUILT_IN_PET_ID-}--function normalizePetSize(value: number | null | undefined): number {- if (typeof value !== 'number' || !Number.isFinite(value))- return PET_DEFAULT_SIZE_PERCENT- return Math.min(200, Math.max(50, value))-}--function getCopy(): Copy {- const language = document.documentElement.lang || navigator.language- return language.toLowerCase().startsWith('zh') ? COPY.zh : COPY.en-}diff --git a/src/pet/session-bubble.tsx b/src/pet/session-bubble.tsxdeleted file mode 100644index 44424628..00000000--- a/src/pet/session-bubble.tsx+++ /dev/null@@ -1,16 +0,0 @@-import { useSyncExternalStore } from 'react'-import { sessionBubbleStore } from './session-bubbles'--/**- * 会话 Toast 实时描述宿主:作为 toast 的 description 元素在 add 时传入一次,- * 通过订阅 store 的版本号在描述变化时原地重渲染,保持实例稳定;- * 标题由调用方以固定字符串写入 content.title,不随状态变化。- */-export function SessionBubble({ sessionId }: { sessionId: string }) {- const version = useSyncExternalStore(- sessionBubbleStore.subscribe,- sessionBubbleStore.getSnapshot,- )- void version- return sessionBubbleStore.get(sessionId) ?? ''-}diff --git a/src/pet/session-bubbles.test.ts b/src/pet/session-bubbles.test.tsdeleted file mode 100644index 6399721f..00000000--- a/src/pet/session-bubbles.test.ts+++ /dev/null@@ -1,62 +0,0 @@-import { describe, expect, it } from 'vitest'-import { createSessionBubbleStore, sessionBubbleDescription, sessionBubbleTitle } from './session-bubbles'--describe('sessionBubbleTitle', () => {- it('uses trimmed bubble title when present', () => {- expect(sessionBubbleTitle({ activity: 'running', bubble: ' Fix tests ' })).toBe('Fix tests')- })-- it('falls back to activity when bubble missing', () => {- expect(sessionBubbleTitle({ activity: 'review' })).toBe('review')- })-- it('falls back to working when unknown activity', () => {- expect(sessionBubbleTitle({ bubble: '' })).toBe('working')- })-})--describe('sessionBubbleDescription', () => {- it('uses the live description field', () => {- expect(sessionBubbleDescription({ activity: 'running', description: '正在思考…' })).toBe('正在思考…')- })-- it('falls back to the title when description missing', () => {- expect(sessionBubbleDescription({ activity: 'waiting', bubble: '会话A' })).toBe('会话A')- })-- it('extracts description from object bubble', () => {- expect(sessionBubbleDescription({ activity: 'running', description: { text: '工具 Pwsh' } })).toBe('工具 Pwsh')- })-})--describe('sessionBubbleStore', () => {- it('keeps snapshot stable unless a value changes', () => {- const store = createSessionBubbleStore()- const before = store.getSnapshot()- expect(store.get('a')).toBeUndefined()- store.set('a', '思考中')- expect(store.get('a')).toBe('思考中')- expect(store.getSnapshot()).toBe(before + 1)- store.set('a', '思考中')- expect(store.getSnapshot()).toBe(before + 1)- store.delete('a')- expect(store.get('a')).toBeUndefined()- expect(store.getSnapshot()).toBe(before + 2)- })-- it('notifies listeners only on actual changes', () => {- const store = createSessionBubbleStore()- let notified = 0- const unsubscribe = store.subscribe(() => {- notified += 1- })- store.set('s1', 'a')- store.set('s1', 'a')- store.set('s1', 'b')- store.delete('s1')- store.delete('s1')- unsubscribe()- store.set('s2', 'c')- expect(notified).toBe(3)- })-})diff --git a/src/pet/session-bubbles.ts b/src/pet/session-bubbles.tsdeleted file mode 100644index 23e0486d..00000000--- a/src/pet/session-bubbles.ts+++ /dev/null@@ -1,88 +0,0 @@-/**- * session-bubbles.ts — 会话 Toast 的描述 store 与标题/描述纯函数。- *- * 会话 Toast 采用「固定标题 + 实时描述」语义(issue #308 bug 3):- * - create:会话首次进入进行态时 `toast()` 一次,title 传固定字符串,description- * 传一个订阅本 store 的 React 元素(见 session-bubble.tsx),此后绝不更换实例;- * - update:会话描述变化时仅更新 store,React 元素订阅到版本变化后原地重渲染- * 描述文本,队列层不产生 add/close 反复操作,避免闪烁;- * - remove:会话离开进行态时由调用方 `toast.close(key)`,并删除 store 条目。- * 单条推送:每个会话独立一份描述与实例,多条会话互不合并。- */--export interface SessionBubbleInput {- activity?: unknown- bubble?: unknown- description?: unknown-}--export interface SessionBubbleStore {- get: (id: string) => string | undefined- set: (id: string, description: string) => void- delete: (id: string) => void- subscribe: (listener: () => void) => () => void- getSnapshot: () => number-}--export function createSessionBubbleStore(): SessionBubbleStore {- const descriptions = new Map<string, string>()- const listeners = new Set<() => void>()- let version = 0-- function emit() {- version += 1- for (const listener of [...listeners])- listener()- }-- return {- get(id) {- return descriptions.get(id)- },- set(id, description) {- if (descriptions.get(id) === description)- return- descriptions.set(id, description)- emit()- },- delete(id) {- if (!descriptions.has(id))- return- descriptions.delete(id)- emit()- },- subscribe(listener) {- listeners.add(listener)- return () => {- listeners.delete(listener)- }- },- getSnapshot() {- return version- },- }-}--/** 全局单例:pet WebView 内所有会话 Toast 共享同一份描述状态。 */-export const sessionBubbleStore = createSessionBubbleStore()--export function normalizeToastMessage(value: unknown): string {- if (typeof value === 'string')- return value.trim()- if (value && typeof value === 'object' && 'text' in value && typeof value.text === 'string')- return value.text.trim()- return ''-}--/** 会话固定标题:优先气泡(会话名),缺省回落动作名。 */-export function sessionBubbleTitle(session: SessionBubbleInput): string {- const state = typeof session.activity === 'string' && session.activity !== 'idle'- ? session.activity- : 'working'- return normalizeToastMessage(session.bubble) || state-}--/** 会话实时描述:优先描述字段,缺省回落标题。 */-export function sessionBubbleDescription(session: SessionBubbleInput): string {- return normalizeToastMessage(session.description) || sessionBubbleTitle(session)-}diff --git a/src/pet/state.test.ts b/src/pet/state.test.tsdeleted file mode 100644index 1cf00a04..00000000--- a/src/pet/state.test.ts+++ /dev/null@@ -1,60 +0,0 @@-import { describe, expect, it } from 'vitest'-import {- getPetVisual,- getSpriteFramePosition,- getSpriteSequence,- normalizePetActivity,-} from './state'--describe('normalizePetActivity', () => {- it('保留协议内状态并把未知值收敛为空闲', () => {- expect(normalizePetActivity('running')).toBe('running')- expect(normalizePetActivity('moving-right')).toBe('moving-right')- expect(normalizePetActivity('unknown')).toBe('idle')- expect(normalizePetActivity(null)).toBe('idle')- })-})--describe('getPetVisual', () => {- it('将移动状态映射到共享素材和对应朝向', () => {- expect(getPetVisual('moving-left', 'right')).toEqual({- asset: 'maid-move.webm',- loop: true,- facing: 'left',- })- expect(getPetVisual('moving-right', 'left')).toEqual({- asset: 'maid-move.webm',- loop: true,- facing: 'right',- })- })-- it('仅让一次性动作停止循环', () => {- expect(getPetVisual('turn', 'left').loop).toBe(false)- expect(getPetVisual('waving', 'left').loop).toBe(false)- expect(getPetVisual('bubble', 'left').loop).toBe(false)- expect(getPetVisual('waiting', 'left').loop).toBe(true)- expect(getPetVisual('running', 'left').loop).toBe(true)- })-})--describe('getSpriteSequence', () => {- it('按 v2 行号映射动作并在三轮后进入慢速 idle', () => {- const sequence = getSpriteSequence('running', 'left', false)- expect(sequence.frames).toHaveLength(24)- expect(sequence.loopStart).toBe(18)- expect(sequence.frames[0]).toEqual({ column: 0, duration: 120, row: 7 })- expect(sequence.frames[17]).toEqual({ column: 5, duration: 220, row: 7 })- expect(sequence.frames[18]).toEqual({ column: 0, duration: 1_680, row: 0 })- })-- it('左右移动使用独立行且降低动态效果时只保留首帧', () => {- expect(getSpriteSequence('moving-right', 'left', true).frames[0].row).toBe(1)- expect(getSpriteSequence('moving-left', 'right', true).frames[0].row).toBe(2)- expect(getSpriteSequence('bubble', 'left', true).frames[0].row).toBe(3)- })-- it('将 8x11 网格帧换算为百分比坐标', () => {- expect(getSpriteFramePosition({ column: 7, duration: 120, row: 10 }, 8, 11)).toBe('100% 100%')- })-})diff --git a/src/pet/state.ts b/src/pet/state.tsdeleted file mode 100644index ebd44c87..00000000--- a/src/pet/state.ts+++ /dev/null@@ -1,145 +0,0 @@-// 桌宠状态机的纯逻辑:集中维护状态、素材与循环方式,便于独立测试。--export const PET_ACTIVITIES = [- 'idle',- 'turn',- 'moving-left',- 'moving-right',- 'waving',- 'waiting',- 'running',- 'review',- 'failed',-] as const--export type PetActivity = (typeof PET_ACTIVITIES)[number]-export type PetFacing = 'left' | 'right'-export type PetAnimation = PetActivity | 'bubble'-export type PetAssetName- = | 'maid-idle.webm'- | 'maid-turn.webm'- | 'maid-move.webm'- | 'maid-wave.webm'- | 'maid-waiting.webm'- | 'maid-running.webm'- | 'maid-review.webm'- | 'maid-failed.webm'- | 'maid-bubble.webm'--export interface PetVisual {- asset: PetAssetName- facing: PetFacing- loop: boolean-}--export interface SpriteFrame {- column: number- duration: number- row: number-}--export interface SpriteSequence {- frames: SpriteFrame[]- loopStart: number | null-}--const PET_ACTIVITY_SET = new Set<string>(PET_ACTIVITIES)-const SPRITE_ACTION_REPEATS = 3-const SPRITE_IDLE_DURATIONS = [280, 110, 110, 140, 140, 320] as const-const SPRITE_IDLE_SLOWDOWN = 6-const SPRITE_ANIMATIONS: Record<Exclude<PetAnimation, 'idle' | 'turn' | 'bubble'>, {- duration: number- frames: number- lastDuration: number- row: number-}> = {- 'moving-right': { row: 1, frames: 8, duration: 120, lastDuration: 220 },- 'moving-left': { row: 2, frames: 8, duration: 120, lastDuration: 220 },- 'waving': { row: 3, frames: 4, duration: 140, lastDuration: 280 },- 'failed': { row: 5, frames: 8, duration: 140, lastDuration: 240 },- 'waiting': { row: 6, frames: 6, duration: 150, lastDuration: 260 },- 'running': { row: 7, frames: 6, duration: 120, lastDuration: 220 },- 'review': { row: 8, frames: 6, duration: 150, lastDuration: 280 },-}--/** 把事件中的未知活动收敛到可验证的桌宠状态。 */-export function normalizePetActivity(value: unknown): PetActivity {- if (typeof value === 'string' && PET_ACTIVITY_SET.has(value))- return value as PetActivity- return 'idle'-}--/** 根据活动给出唯一素材、循环方式与朝向。 */-export function getPetVisual(activity: PetAnimation, currentFacing: PetFacing): PetVisual {- switch (activity) {- case 'turn':- return { asset: 'maid-turn.webm', loop: false, facing: currentFacing }- case 'moving-left':- return { asset: 'maid-move.webm', loop: true, facing: 'left' }- case 'moving-right':- return { asset: 'maid-move.webm', loop: true, facing: 'right' }- case 'waving':- return { asset: 'maid-wave.webm', loop: false, facing: currentFacing }- case 'waiting':- return { asset: 'maid-waiting.webm', loop: true, facing: currentFacing }- case 'running':- return { asset: 'maid-running.webm', loop: true, facing: currentFacing }- case 'review':- return { asset: 'maid-review.webm', loop: true, facing: currentFacing }- case 'failed':- return { asset: 'maid-failed.webm', loop: true, facing: currentFacing }- case 'bubble':- return { asset: 'maid-bubble.webm', loop: false, facing: currentFacing }- case 'idle':- default:- return { asset: 'maid-idle.webm', loop: true, facing: currentFacing }- }-}--/** 构造 Codex v2 精灵图序列:动作重复三次后进入慢速 idle 循环。 */-export function getSpriteSequence(- activity: PetAnimation,- facing: PetFacing,- reducedMotion: boolean,-): SpriteSequence {- const idleFrames = SPRITE_IDLE_DURATIONS.map((duration, column) => ({- column,- duration: duration * SPRITE_IDLE_SLOWDOWN,- row: 0,- }))- const action = getSpriteAction(activity, facing)- if (reducedMotion)- return { frames: [action[0]], loopStart: null }- if (activity === 'idle')- return { frames: idleFrames, loopStart: 0 }-- const repeated: SpriteFrame[] = []- for (let repeat = 0; repeat < SPRITE_ACTION_REPEATS; repeat += 1)- repeated.push(...action)- return { frames: [...repeated, ...idleFrames], loopStart: repeated.length }-}--/** 将逻辑帧换算成 CSS 精灵图百分比坐标。 */-export function getSpriteFramePosition(frame: SpriteFrame, columns: number, rows: number): string {- const lastColumn = Math.max(1, columns - 1)- const lastRow = Math.max(1, rows - 1)- return `${frame.column * 100 / lastColumn}% ${frame.row * 100 / lastRow}%`-}--function getSpriteAction(activity: PetAnimation, facing: PetFacing): SpriteFrame[] {- if (activity === 'idle') {- return SPRITE_IDLE_DURATIONS.map((duration, column) => ({ column, duration, row: 0 }))- }-- const mappedActivity = activity === 'turn'- ? (facing === 'left' ? 'moving-right' : 'moving-left')- : activity === 'bubble'- ? 'waving'- : activity- const animation = SPRITE_ANIMATIONS[mappedActivity]- return Array.from({ length: animation.frames }, (_, column) => ({- column,- duration: column === animation.frames - 1 ? animation.lastDuration : animation.duration,- row: animation.row,- }))-}diff --git a/src/utils/toast.ts b/src/utils/toast.tsindex efedb4ca..670fb1a0 100644--- a/src/utils/toast.ts+++ b/src/utils/toast.ts@@ -1,10 +1,17 @@import type { ToastContentValue } from '@heroui/react/toast'import type { ToastVariants } from '@heroui/styles'import type { ReactNode } from 'react'+import { emitter } from '@hairy/react-lib'import { ToastQueue } from '@heroui/react'/** toast() 可选项:库内未暴露的 HeroUIToastOptions(toast-queue 收敛的 content + 超时回调),这里用公开的 ToastContentValue 组合 */export type ToastOptions = Partial<ToastContentValue & { timeout?: number, onClose?: () => void }> & { placement?: Placement }+export type ToastUpdateOptions = Partial<ToastContentValue>++export interface ToastUpdateEvent {+ key: string+ options: ToastUpdateOptions+}export type Placement = NonNullable<ToastVariants['placement']>export const placements = [@@ -28,33 +35,52 @@ export const activeQueues = navigator.platform.toLowerCase().includes('linux')? linuxQueues: queues+const toastContents = new Map<string, ToastContentValue>()const placementsKeys = new Map<string, Placement>()-export function toast(- message: string | ReactNode,- options?: ToastOptions,-) {- // 默认右下角;个别调用方需要其他位置时显式传 placement- const { placement = 'bottom end', timeout, onClose, ...rest } = options || {}- const key = activeQueues[placement].add(- { title: message, ...rest },- { timeout, onClose },- )- placementsKeys.set(key, placement)- return key-}--function close(key: string) {- const placement = placementsKeys.get(key)- placementsKeys.delete(key)- if (placement)- activeQueues[placement].close(key)-}+/**+ * 统一 toast API:直接调用创建,toast.update/close/clear 通过 key 管理。+ * update 触发 emitter 'toast.update',由 ToastProvider 经 useEventBus 消费后+ * 原地更新对应 queue 的 content(HeroUI ToastQueue 没有 update 方法)。+ */+export const toast = Object.assign(+ (message: string | ReactNode, options?: ToastOptions) => {+ // 默认右下角;个别调用方需要其他位置时显式传 placement+ const { placement = 'bottom end', timeout, onClose, ...rest } = options || {}+ let key = ''+ const content = { title: message, ...rest }+ key = activeQueues[placement].add(content, {+ timeout,+ onClose: () => {+ toastContents.delete(key)+ placementsKeys.delete(key)+ onClose?.()+ },+ })+ toastContents.set(key, content)+ placementsKeys.set(key, placement)+ return key+ },+ {+ update(key: string, options: ToastUpdateOptions): void {+ if (!placementsKeys.has(key))+ return+ toastContents.set(key, { ...(toastContents.get(key) ?? {}), ...options })+ emitter.emit('toast.update', { key, options })+ },-function clear() {- placementsKeys.clear()- placements.forEach(p => activeQueues[p].clear())-}+ close(key: string): void {+ const placement = placementsKeys.get(key)+ if (placement)+ activeQueues[placement].close(key)+ else+ toastContents.delete(key)+ },-toast.close = close-toast.clear = clear+ clear(): void {+ toastContents.clear()+ placementsKeys.clear()+ placements.forEach(p => activeQueues[p].clear())+ },+ },+)diff --git a/tailwind.config.js b/tailwind.config.jsindex 2ee63eb9..a6a1d320 100644--- a/tailwind.config.js+++ b/tailwind.config.js@@ -1,6 +1,6 @@/** @type {import("tailwindcss").Config} */export default {- content: ['./index.html', './src/**/*.{js,ts,jsx,tsx}'],+ content: ['./index.html', './pet.html', './src/**/*.{js,ts,jsx,tsx}'],theme: {extend: {colors: {