DeepSeek Harness Tauri 桌面版 | Only 8mb installer, zero environment setup, preset plugins, Windows / macOS / Linux.
feat(pet): delegate bubbles to dsh-pet-component v0.2.1
hairyf59eca09e4ecb
diff --git a/packages/dsh-tauri-pet/docs/sync-log.md b/packages/dsh-tauri-pet/docs/sync-log.mdindex 0f4f8650..1a366398 100644--- a/packages/dsh-tauri-pet/docs/sync-log.md+++ b/packages/dsh-tauri-pet/docs/sync-log.md@@ -21,6 +21,42 @@## 同步记录+### 2026 —— dsh-pet-component v0.2.1:气泡托管给组件(宿主只调 `pet.bubble`)++不是上游同步,而是渲染层依赖升级(`dsh-pet-component@^0.1.1` → `^0.2.1`),+记录在此以便核对气泡与动作的命令面。v0.2.1 只有两个修复(拖动接管时作废未播完的+一次性命令 `7c91d0d`、气泡度量下界抬到参考实现的固定值 `7ca0c3f`),+`dist/index.d.mts` 与 0.2.0 逐字节相同(sha256 `FFC04031…`),宿主侧无需改动。++- **气泡完全托管**:原三层拆分(`utils/bubble.ts` 文案 + `utils/bubble-tracker.ts` 603 行的+ 「会话 → HeroUI toast 状态机」+ `hooks/use-bubble.ts` 订阅)收敛为+ `src/pet/hooks/use-bubble-tracker.ts`(React 壳)+ `.constants.ts`(文案库)++ `.helpers.ts`(纯函数)。宿主只把会话快照收敛成动作档位与标题/正文/加载态,经+ `useControllablePet(petRef).bubble({ id, title, description, loading, motion })` 下发。+ 叠加、原地更新、定时收起(终态 failed/error 4000、review 2500、success 3000 —— 与旧常量同值)、+ 多会话动作优先级聚合(`BUBBLE_MOTION_PRIORITY`,与旧 `STATUS_PRIORITY` 同表)全在组件内。+ 宿主的 `statusOf` / `STATUS_COALESCE_MS` 合并窗口 / `failedUntil` 终态脉冲 / `scheduleHide` /+ `dismissed` / 沉淀计时全部删除;桌宠窗口不再挂 `<ToastProvider custom>`。+- **动作随气泡走**:常驻气泡(`timeout: 0`)驱动声明式 `motion` prop;限时气泡(终态)由组件用+ 命令面播一次,气泡收起不再掐断动画 —— 旧实现为绕开「成功动画被 3s 收起打断」而设的+ `TERMINAL_PULSE_TTL(10000)` 因此整体删除。`app.tsx` 的 `motion` prop 只剩拖动方向。+- **行为差异**:子代理会话此前「不弹 toast、但状态仍参与动作聚合」,v0.2.0 没有气泡就没有动作+ 载体,故子代理现在既不弹气泡也不驱动动作(父会话在子代理运行期间本身有常驻气泡,观感不变)。+ 另新增 `flush()`:`pet.bubble` 在 `<Pet>` 挂载前静默丢弃事件,宠物资源就绪后重放一次补齐。+- **碎碎念不接入**:不传 `onMuttering` 即完全无副作用(组件内 `onMuttering === undefined` 直接 return)。+- **唤醒锁入口随重构搬家**:桌宠窗口的 `useWakeLock()/useWatch/ release()` 抽成+ `src/pet/hooks/use-wakelock-release.ts`,`test/wake-lock.test.ts` 的 `WAKE_LOCK_ENTRIES`+ 改指向该文件(issue #469 的不变量本身不变)。+- 校验:`pnpm exec vite build`(`pet.html` 入口 65 KB)、`pnpm exec vitest run`(53 files / 456 tests)、+ `pnpm exec eslint src/pet src/ui/pet test/wake-lock.test.ts vitest.config.ts --max-warnings=0`;+ `pnpm typecheck` 在 `src/` 无错(`packages/dsh-tauri-worktree` 的 `Cannot find module 'dsh-tauri'`+ 一批是 worktree 未构建插件类型的既有问题,与本次改动无关)。+- **遗留(未在本次处理)**:`src/components/toast-provider.tsx` 的 `custom` 分支已无调用方,但删除它+ 与「主窗口 toast 是否真的渲染」耦合 —— 该文件给主窗口传的是 `children = null`,而+ `@heroui/react` 的 `ToastProvider` 只在 `children === undefined` 时回落到+ `getDefaultChildren`(HeroUI `dist/components/toast/toast.js:398`),`null` 会原样渲染成空。+ 即 `7171082c` 引入 `custom` 时可能顺带关掉了主窗口的 toast 内容,需独立核实后再一并清理。+### 2026 —— 预设宠物改为 dsh-pet-component 直连远端(移除下载/解压链路)不是上游同步,而是渲染层换实现导致预设获取方式的整体变化,记录在此以便后续核对素材来源与命令面。diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex dc4fe43f..1c7e5076 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -181,8 +181,8 @@ catalogs:specifier: ^5.101.4version: 5.101.4dsh-pet-component:- specifier: ^0.1.1- version: 0.1.1+ specifier: ^0.2.1+ version: 0.2.1i18next:specifier: ^26.3.6version: 26.3.6@@ -342,7 +342,7 @@ importers:version: 2.4.4dsh-pet-component:specifier: catalog:runtime- version: 0.1.1([email protected])([email protected])+ version: 0.2.1([email protected])([email protected])i18next:specifier: catalog:runtimeversion: 26.3.6([email protected])@@ -2482,11 +2482,6 @@ packages:peerDependencies:react: ^16.8.0 || ^17.0.0-rc.1 || ^18.0.0 || ^19.0.0-rc.1- '@reause/[email protected]':- resolution: {integrity: sha512-NkEzEvYyFpWND8H2yQ3e3iikifUqhMObdLXe1xNiGbfcZLDsExljt5SF/cCEgx9V4S/HLeNpcPnQU/yL7Y8Czw==}- peerDependencies:- react: '>=18'-'@reause/[email protected]':resolution: {integrity: sha512-dw3p7M/Muz3QPDRlg6suaiGdHa2GLXzTzZBXG6P9M64B96r4e9pZ+8dw3hgLci1GyiM7Ht+GEpYF68cG+W+YFw==}peerDependencies:@@ -3622,8 +3617,8 @@ packages:resolution: {integrity: sha512-nI4U3TottKAcAD9LLud4Cb7b2QztQMUEfHbvhTH09bqXTxnSie8WnjPALV/WMCrJZ6UV/qHJ6L03OqO3LcdYZw==}engines: {node: '>=12'}- resolution: {integrity: sha512-M2bDCPP3Nva2acdFgu1c8BD5UZ9v0rUfTVrUm7yhSDWUSsn+x1dLtgbU//65JiDHUwh9+r5HdRal0rIJZGyIWg==}+ resolution: {integrity: sha512-rJwYiHOb8eFzi+XUGIVZ2tASnUPs4l1gVwtO1JFsyzTdlH1+dTxBWAAcRmeZtBuH4Q4I1jOWgc3Y7VGpuoqfPQ==}peerDependencies:react: ^19.0.0@@ -6918,11 +6913,6 @@ snapshots:dependencies:react: 19.2.8- '@reause/[email protected]([email protected])':- dependencies:- '@reause/shared': 0.1.4([email protected])- react: 19.2.8-'@reause/[email protected]([email protected])':dependencies:'@reause/shared': 0.1.7([email protected])@@ -7881,9 +7871,10 @@ snapshots:dependencies:- '@reause/core': 0.1.4([email protected])+ '@gravity-ui/icons': 2.21.0([email protected])+ '@reause/core': 0.1.7([email protected])css-render: 0.15.14idb-keyval: 6.3.0diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yamlindex 14bbfd94..3282245c 100644--- a/pnpm-workspace.yaml+++ b/pnpm-workspace.yaml@@ -9,6 +9,7 @@ inject-workspace-packages: trueminimumReleaseAgeExclude:- '@reause/[email protected]'- '@reause/[email protected]'shellEmulator: truetrustPolicy: no-downgrade@@ -84,7 +85,7 @@ catalogs:'@overlastic/react': ^0.9.0'@reause/core': ^0.1.7'@tanstack/react-query': ^5.101.4- dsh-pet-component: ^0.1.1+ dsh-pet-component: ^0.2.1i18next: ^26.3.6react: ^19.2.8react-dom: ^19.2.8diff --git a/src/pet/app.tsx b/src/pet/app.tsxindex f09f00ea..144de178 100644--- a/src/pet/app.tsx+++ b/src/pet/app.tsx@@ -1,84 +1,79 @@import type { PetRef, PetRenderMotion } from 'dsh-pet-component'-import { useEventListener, useWakeLock, useWatch } from '@reause/core'-import { Pet } from 'dsh-pet-component'+import { useEventListener } from '@reause/core'+import { Pet, useControllablePet } from 'dsh-pet-component'import { useRef } from 'react'import { If } from 'react-if-lite'-import { ToastProvider } from '@/components/toast-provider'import { useOmitIgnoreCursorEvents } from '@/hooks/use-omit-ignore-cursor-events'import { useWindowDraggable } from '@/hooks/use-window-draggable'import { Hint } from '@/ui/pet/hint'import { PET_BASE_WIDTH, PET_DSH_ASPECT } from './constants'-import { useBubble } from './hooks/use-bubble'+import { useBubbleTracker } from './hooks/use-bubble-tracker'import { usePetSource } from './hooks/use-pet-source'import { normalizeSizePercent, usePetStatus } from './hooks/use-pet-status'import { usePetWindowSize } from './hooks/use-pet-window'+import { useWakelockRelease } from './hooks/use-wakelock-release'/*** 桌宠窗口的唯一组合入口。** 三条输入各管一段,互不越界:* - 设置状态(`usePetStatus`)→ 选哪个宠物、多大、是否可见;- * - 会话气泡(`useBubble`)→ 聚合出的动作档位;+ * - 会话气泡(`useBubbleTracker`)→ 经 `pet.bubble(...)` 下发,**动作随气泡走**;* - 手势(`useWindowDraggable`)→ 拖动期间的方向动作。*- * 动作全部经 `pet.motion(...)` / `pet.clear()` 下发到 `<Pet>` 的命令面(优先级高于- * 声明式 `motion` prop),渲染细节(动画池解析、双视频缓冲、雪碧图、缓存、双击回应)- * 由 `dsh-pet-component` 接管。+ * v0.2.0 起气泡完全由 `dsh-pet-component` 托管(叠加、原地更新、定时收起、多会话动作+ * 优先级),渲染细节(动画池解析、双视频缓冲、雪碧图、缓存、双击回应)同样如此:+ * 宿主只把 `motion` prop 留给拖动方向,会话档位随各自的气泡走。*/export function App() {const petRef = useRef<PetRef>(null)+ const pet = useControllablePet(petRef)const status = usePetStatus()// issue #469:桌宠动画是常驻播放的 <video>,Chromium 会因此持有 Video Wake Lock// 让系统无法息屏;本窗口没有常亮的正当需求,唤醒锁一旦生效就立刻释放。- const wakelock = useWakeLock()- useWatch(wakelock.isActive, () => {- void wakelock.release()- }, { immediate: true })-- const activePet = status?.active_pet ?? ''- const { source, error } = usePetSource(activePet)+ const activedPet = status?.active_pet ?? ''+ const { source, error } = usePetSource(activedPet)const hitboxRef = useRef<HTMLDivElement>(null)- const bubble = useBubble()- const { dragging, direction } = useWindowDraggable()+ const draggable = useWindowDraggable()const visible = status === null || (status.enabled !== false && status.visible !== false)const width = (source?.width ?? PET_BASE_WIDTH) * normalizeSizePercent(status?.pet_size) / 100++ useBubbleTracker(pet, source)usePetWindowSize(width, source?.aspect ?? PET_DSH_ASPECT, visible)useOmitIgnoreCursorEvents(hitboxRef)- // 桌宠窗口是装饰性的透明置顶小窗:右键不应弹出 WebView 默认 context menu。- useEventListener('contextmenu', (event: Event) => event.preventDefault())+ useEventListener('contextmenu', event => event.preventDefault())+ useWakelockRelease()// 手势优先于会话档位:拖动期间按方向播走路动画(dsh-pet 渲染器内部强制走 drag 池,- // 会忽略这里的方向,由组件保证);拖动结束或方向停摆后自动回落到会话档位。- const motion: PetRenderMotion | undefined = dragging- ? (direction === undefined ? undefined : `moving-${direction}`)- : bubble.motion+ // 会忽略这里的方向,由组件保证);拖动结束即回落 `undefined`,交给气泡聚合出的档位。+ const motion: PetRenderMotion | undefined = draggable.dragging+ ? (draggable.direction === undefined ? undefined : `moving-${draggable.direction}`)+ : undefinedreturn (- <ToastProvider custom>- {/* 外层只负责铺满透明窗口并让宠物锚定底部居中;窗口内可交互面只有命中箱,- 其余区域由 useOmitIgnoreCursorEvents 按命中箱矩形整体穿透。 */}- <main className={`pointer-events-none fixed inset-0 flex items-end justify-center ${visible ? '' : 'invisible'}`}>- {source && (- <Pet- ref={petRef}- kind={source.kind}- config={source.config}- uri={source.uri}- ext={source.ext}- motion={motion}- size={width}- dragging={dragging}- cache={true}- hidden={!visible}- hitboxRef={hitboxRef}- />- )}- {/* 选中了宠物但资源解析不出来(导入的宠物被删除、清单里没有该 id):必须给出- 可见提示 —— 透明窗口里「空」与「在加载」观感相同,静默留空等于让用户以为坏了。 */}- <If cond={error !== null} then={<Hint petId={activePet} />} />- </main>- </ToastProvider>+ // 外层只负责铺满透明窗口并让宠物锚定底部居中;窗口内可交互面只有命中箱,+ // 其余区域由 useOmitIgnoreCursorEvents 按命中箱矩形整体穿透。+ <main className={`pointer-events-none fixed inset-0 flex items-end justify-center ${visible ? '' : 'invisible'}`}>+ {source && (+ <Pet+ ref={petRef}+ kind={source.kind}+ config={source.config}+ uri={source.uri}+ ext={source.ext}+ motion={motion}+ size={width}+ dragging={draggable.dragging}+ cache={true}+ hidden={!visible}+ hitboxRef={hitboxRef}+ />+ )}+ {/* 选中了宠物但资源解析不出来(导入的宠物被删除、清单里没有该 id):必须给出+ 可见提示 —— 透明窗口里「空」与「在加载」观感相同,静默留空等于让用户以为坏了。 */}+ <If cond={error !== null} then={<Hint petId={activedPet} />} />+ </main>)}diff --git a/src/pet/hooks/use-bubble-tracker.constants.ts b/src/pet/hooks/use-bubble-tracker.constants.tsnew file mode 100644index 00000000..066c9d95--- /dev/null+++ b/src/pet/hooks/use-bubble-tracker.constants.ts@@ -0,0 +1,99 @@+import type { Motion } from 'dsh-pet-component'++/** 桌宠窗口无 i18n 基础设施,就地按窗口语言取单语文案。 */+export const IS_ZH = (typeof document !== 'undefined' ? document.documentElement.lang || navigator.language : 'zh-CN')+ .toLowerCase()+ .startsWith('zh')++/** 语言二选一助手,降低代码冗余 */+export const pickLang = <T>(zh: T, en: T): T => (IS_ZH ? zh : en)++/** 会话标题兜底文案 */+export const UNTITLED_SESSION_TITLE = pickLang('新会话', 'New session')++/** 会话标题前缀 */+export const SESSION_LABELS = {+ subagent: pickLang('子代理', 'Subagent'),+ waitApproval: pickLang('需授权', 'Needs approval'),+ waitChoice: pickLang('需选择', 'Needs your input'),+} as const++/** 气泡文案库(按组多备选句) */+export const STATUS_COPY: Record<string, readonly string[]> = {+ thinking: pickLang(['正在分析', '思考中', '整理结果中'], ['Analyzing information', 'Thinking', 'Organizing results']),+ working: pickLang(['正在处理任务', '步骤正在进行中', '系统运行中'], ['Processing task', 'Step in progress', 'System is working']),+ result: pickLang(['正在整理结果', '步骤已完成,准备下一步', '正在确认后续操作'], ['Organizing results', 'Step completed, preparing for next step', 'Confirming next action']),+ waiting: pickLang(['等待确认', '需提供后续指令', '请决策下一步操作'], ['Awaiting your confirmation', 'Requires your input', 'Please decide on the next step']),+ approval: pickLang(['等待审批', '需授权确认', '敏感操作确认授权'], ['Awaiting your approval', 'Authorization required', 'Please confirm and authorize this action']),+ success: pickLang(['任务已完成', '本阶段任务已完成', '流程执行成功'], ['Task completed successfully', 'Current phase completed', 'Execution succeeded']),+ running: pickLang(['任务运行中', '当前步骤正在处理'], ['Task is running', 'Current step is processing']),+ review: pickLang(['正在汇总变更', '变更已就绪,等待审阅'], ['Consolidating', 'Ready for your review']),+ failed: pickLang(['步骤执行失败', '操作执行过程中发生异常'], ['Step execution failed', 'An error occurred during operation']),+ error: pickLang(['任务发生错误', '出现异常,请进行排查', '流程未能成功'], ['Task encountered an error', 'Exception detected, please check', 'Process failed to complete']),+ stopped: pickLang(['任务已终止', '任务已在此处暂停'], ['Task terminated', 'Task paused at this stage']),+} as const++/** 工具活动分类文案 */+export const ACTIVITY_COPY: Record<string, readonly string[]> = {+ searching: pickLang(['正在检索', '正在项目中进行全面搜索', '正在调阅相关文件'], ['Searching', 'Searching across the project', 'Checking related files']),+ editing: pickLang(['正在修改', '正在写入变更内容', '正在调整代码实现'], ['Editing', 'Applying changes', 'Adjusting implementation']),+ testing: pickLang(['正在检验', '正在运行测试集进行确认', '正在验证变更有效性'], ['Verifying', 'Running test suites', 'Verifying changes']),+ commanding: pickLang(['正在执行', '正在启动项目服务', '正在监控指令执行状态'], ['Executing', 'Starting project services', 'Monitoring command execution']),+} as const++/** 状态与动画分类集合 */+export const DONE_BUBBLE_TIMEOUT = 3000+export const TERMINAL_MOTIONS = new Set<Motion>(['failed', 'review', 'error', 'success'])+export const WORK_STATUSES = new Set(['thinking', 'working', 'result', 'waiting', 'success', 'error'])+export const ACTIVE_MOTIONS = new Set<Motion>(['running', 'thinking', 'working', 'result'])++export const TOOL_LABELS: Record<string, string> = {+ pwsh: 'Pwsh',+ bash: 'Bash',+ grep: 'Grep',+ glob: 'Glob',+ read: '读取',+ read_image: '看图',+ write: '写入',+ edit: '编辑',+ str_replace_editor: '编辑',+ web_search: '搜索',+ web_fetch: '抓取',+ think: '思考',+ skill: '技能',+}++export const TOOL_ARG_KEYS: Record<string, readonly string[]> = {+ pwsh: ['command'],+ bash: ['command'],+ grep: ['pattern'],+ glob: ['pattern'],+ read: ['file_path', 'path'],+ read_image: ['file_path', 'path'],+ write: ['file_path', 'path'],+ edit: ['file_path', 'path'],+ str_replace_editor: ['file_path', 'path'],+ web_search: ['queries', 'query'],+ web_fetch: ['url'],+ think: ['thought'],+ skill: ['name'],+}++export const TOOL_PATTERNS: Array<[RegExp, string]> = [+ [/search|grep|find|glob|web|read|fetch|open/, 'searching'],+ [/write|edit|patch|replace|create|move|delete/, 'editing'],+ [/test|check|lint|build|verify/, 'testing'],+ [/shell|bash|exec|command|terminal|powershell|pwsh/, 'commanding'],+]++export const STATUS_TEXT_MAP: Record<string, string> = {+ think: pickLang('思考中', 'Thinking'),+ thinking: pickLang('思考中', 'Thinking'),+ working: pickLang('处理中', 'Working'),+ result: pickLang('整理中', 'Organizing'),+ waiting: pickLang('等待中', 'Waiting'),+ review: pickLang('待审阅', 'Review'),+ failed: pickLang('失败', 'Failed'),+ error: pickLang('出错', 'Error'),+ success: pickLang('已完成', 'Done'),+}diff --git a/src/pet/hooks/use-bubble-tracker.helpers.ts b/src/pet/hooks/use-bubble-tracker.helpers.tsnew file mode 100644index 00000000..9a928047--- /dev/null+++ b/src/pet/hooks/use-bubble-tracker.helpers.ts@@ -0,0 +1,200 @@+import type { Motion } from 'dsh-pet-component'+import {+ ACTIVE_MOTIONS,+ ACTIVITY_COPY,+ pickLang,+ SESSION_LABELS,+ STATUS_COPY,+ STATUS_TEXT_MAP,+ TOOL_ARG_KEYS,+ TOOL_LABELS,+ TOOL_PATTERNS,+ UNTITLED_SESSION_TITLE,+ WORK_STATUSES,+} from './use-bubble-tracker.constants'++export interface SessionTitleSource {+ [key: string]: unknown+ title?: unknown+ displayTitle?: unknown+ name?: unknown+ phase?: unknown+ origin?: unknown+}++export interface BubbleSession {+ [key: string]: unknown+ id: string+}++/** seed → 稳定非负整数 */+export function seedNumber(seed: string | number | undefined): number {+ const value = String(seed ?? '')+ const numeric = Number(value)+ if (Number.isFinite(numeric))+ return Math.abs(Math.trunc(numeric))+ return [...value].reduce((total, char) => total + (char.codePointAt(0) ?? 0), 0)+}++function selectCopy(variants: readonly string[], seed?: string | number): string {+ return variants[seedNumber(seed) % variants.length] ?? variants[0]+}++export function statusCopy(group: string, seed?: string | number): string {+ return selectCopy(STATUS_COPY[group] ?? STATUS_COPY.working, seed)+}++export function activityCopy(activity: string, seed?: string | number): string {+ return selectCopy(ACTIVITY_COPY[activity] ?? STATUS_COPY.working, seed)+}++export function taskCopy(task: string | undefined): string | undefined {+ const value = String(task ?? '').trim().replace(/[。!?.!?]+$/u, '')+ if (!value)+ return undefined+ if (/^(?:正在|继续)/u.test(value))+ return value+ if (/^(?:准备|检查|验证|修改|修复|测试|构建|整理|分析|梳理|查找|搜索|读取|实现)/u.test(value))+ return `正在${value}`+ return `正在处理「${value}」`+}++export function toolActivityGroup(tool: string | undefined): string {+ const value = String(tool || '').toLowerCase()+ return TOOL_PATTERNS.find(([pattern]) => pattern.test(value))?.[1] ?? 'working'+}++export function sessionTitle(session: SessionTitleSource): string {+ const base = [session.title, session.displayTitle, session.name]+ .find((v): v is string => typeof v === 'string' && v.trim().length > 0)+ ?.trim() ?? UNTITLED_SESSION_TITLE++ if (session.phase === 'approval')+ return `${SESSION_LABELS.waitApproval} · ${base}`+ if (session.phase === 'user-question' || session.phase === 'blocked')+ return `${SESSION_LABELS.waitChoice} · ${base}`+ if (session.origin === 'subagent')+ return `${SESSION_LABELS.subagent} · ${base}`+ return base+}++export function rawSession(payload: unknown): BubbleSession | undefined {+ if (!payload || typeof payload !== 'object')+ return undefined+ const record = payload as Record<string, unknown>+ const session = (record.session && typeof record.session === 'object' ? record.session : record) as Record<string, unknown>+ const id = session.id ?? session.sessionId+ return typeof id === 'string' && id.length > 0 ? { ...session, id } : undefined+}++export function sessionMotion(session: BubbleSession): Motion | undefined {+ const work = session.workStatus as string+ if (WORK_STATUSES.has(work))+ return work as Motion++ const value = session.status ?? session.activity ?? session.phase+ const agentError = session.lastAgentError++ if (session.running !== true && (value === 'failed' || value === 'error' || (Boolean(agentError) && agentError !== 'aborted'))) {+ return 'failed'+ }+ if (value === 'review' || value === 'reviewing' || value === 'plan-review')+ return 'review'++ const hasPending = Array.isArray(session.pending) ? session.pending.length > 0 : Boolean(session.pending)+ if (value === 'waiting' || value === 'pending' || value === 'blocked' || Boolean(session.pendingInteraction) || hasPending) {+ return 'waiting'+ }+ if (value === 'running' || value === 'working' || value === 'thinking' || session.running === true) {+ return 'running'+ }++ return undefined+}++function sanitizeText(str: string): string {+ return str.replace(/\s+/g, ' ').trim()+}++function toolArgDetail(tool: string, args: unknown): string | undefined {+ if (typeof args !== 'string' || !args)+ return undefined+ try {+ const record = JSON.parse(args)+ if (!record || typeof record !== 'object' || Array.isArray(record))+ return undefined++ const keys = TOOL_ARG_KEYS[tool] ?? ['file_path', 'path']+ for (const key of keys) {+ const val = record[key]+ if (typeof val === 'string' && val.trim())+ return sanitizeText(val)+ if (Array.isArray(val)) {+ const first = val.find(item => typeof item === 'string' && item.trim())+ if (first)+ return sanitizeText(first)+ }+ }+ }+ catch {+ /* 忽略非合法 JSON */+ }+ return undefined+}++export function getLiveActivity(session: BubbleSession, motion: Motion): string | undefined {+ if (!ACTIVE_MOTIONS.has(motion) || !session.liveActivity || typeof session.liveActivity !== 'object') {+ return undefined+ }+ const { kind, text, name, args } = session.liveActivity as Record<string, unknown>++ if (kind === 'reasoning' && typeof text === 'string' && text.trim()) {+ return pickLang(`思考 · ${sanitizeText(text)}`, `Thought · ${sanitizeText(text)}`)+ }+ if (kind === 'tool' && typeof name === 'string' && name) {+ const tool = name.toLowerCase()+ const label = TOOL_LABELS[tool]+ if (!label)+ return pickLang(`工具调用 · ${name}`, `Tool · ${name}`)+ const detail = toolArgDetail(tool, args)+ return detail ? `${label} · ${detail}` : label+ }+ return undefined+}++export function bubbleContent(session: BubbleSession, motion: Motion) {+ const isSub = session.origin === 'subagent'+ const title = sessionTitle(session)+ const seed = session.id++ const statusText = STATUS_TEXT_MAP[motion]+ ?? (motion === 'running'+ ? (isSub ? pickLang('运行中', 'Running') : pickLang('思考中', 'Thinking'))+ : pickLang('空闲', 'Idle'))++ const fallbackCopy = motion === 'waiting'+ ? statusCopy(session.phase === 'approval' ? 'approval' : 'waiting', seed)+ : motion === 'working'+ ? statusCopy(toolActivityGroup(String((session.liveActivity as Record<string, unknown> | undefined)?.name ?? '')), seed)+ : statusCopy(motion, seed)++ const candidates = [+ session.lastAgentError ? pickLang(`失败:${String(session.lastAgentError)}`, `Failed: ${String(session.lastAgentError)}`) : undefined,+ taskCopy(session.task as string | undefined),+ getLiveActivity(session, motion),+ fallbackCopy,+ session.description,+ session.message,+ statusText,+ ]++ const description = candidates+ .find((item): item is string => typeof item === 'string' && item.trim().length > 0)+ ?.trim() ?? pickLang('会话', 'Session')++ return {+ title,+ description,+ loading: ACTIVE_MOTIONS.has(motion),+ }+}diff --git a/src/pet/utils/bubble.test.ts b/src/pet/hooks/use-bubble-tracker.test.tssimilarity index 50%rename from src/pet/utils/bubble.test.tsrename to src/pet/hooks/use-bubble-tracker.test.tsindex 2e6cf696..54e315de 100644--- a/src/pet/utils/bubble.test.ts+++ b/src/pet/hooks/use-bubble-tracker.test.ts@@ -1,11 +1,22 @@/**- * bubble-copy.test.ts — 桌宠气泡文案纯函数(对齐 dsh-dafeiyu src/status-copy.js)单测。+ * use-bubble-tracker.test.ts — 桌宠气泡层单测(文案纯函数 + 会话快照 → pet.bubble 映射)。*- * 覆盖:seed 稳定选句(同 seed 恒定、不同 seed 可换句)、分组回落、工具活动分类- * 文案、taskCopy 句式(对齐 dsh-dafeiyu:正在/继续、动作动词、默认处理「…」)。+ * 气泡自身的叠加、原地更新、定时收起与多会话动作聚合由 `dsh-pet-component` 负责,+ * 这里锁两件事:文案选句(同 seed 恒定、分组回落、任务句式)与宿主侧剩下的契约+ * (档位推导、子代理静默、终态只下发一次、挂载前被丢弃的气泡能靠 flush 补齐)。*/+import type { PetBubbleHandle, PetBubbleOptions } from 'dsh-pet-component'import { describe, expect, it } from 'vitest'-import { activityCopy, seedNumber, sessionTitle, statusCopy, taskCopy, toolActivityGroup, UNTITLED_SESSION_TITLE } from './bubble'+import { createBubbleTracker } from './use-bubble-tracker'+import { UNTITLED_SESSION_TITLE } from './use-bubble-tracker.constants'+import {+ activityCopy,+ seedNumber,+ sessionTitle,+ statusCopy,+ taskCopy,+ toolActivityGroup,+} from './use-bubble-tracker.helpers'describe('seedNumber', () => {it('numeric strings resolve to the absolute truncated integer', () => {@@ -133,3 +144,122 @@ describe('sessionTitle', () => {expect(sessionTitle({ origin: 'subagent' })).toContain(UNTITLED_SESSION_TITLE)})})++type Call+ = | { type: 'show', options: PetBubbleOptions }+ | { type: 'close', id: string | undefined }+ | { type: 'clear' }++/** 假命令面:`mounted` 控制 `pet.bubble` 返回 key 还是空串(组件未挂载)。 */+function createFakeBubble(initiallyMounted = true) {+ const calls: Call[] = []+ const state = { mounted: initiallyMounted }+ const bubble = ((options: PetBubbleOptions) => {+ calls.push({ type: 'show', options })+ return state.mounted ? options.id ?? `auto-${calls.length}` : ''+ }) as PetBubbleHandle+ bubble.close = (id?: string) => {+ calls.push({ type: 'close', id })+ }+ bubble.clear = () => {+ calls.push({ type: 'clear' })+ }+ return { bubble, calls, state }+}++function shows(calls: Call[]): PetBubbleOptions[] {+ return calls.filter(call => call.type === 'show').map(call => call.options)+}++describe('createBubbleTracker', () => {+ it('maps a session snapshot to a bubble carrying its own motion', () => {+ const { bubble, calls } = createFakeBubble()+ createBubbleTracker(bubble).apply({ id: 's1', title: '会话一', workStatus: 'working', task: '修复登录' }, 'create')++ expect(shows(calls)).toEqual([+ { id: 's1', title: '会话一', description: '正在修复登录', loading: true, motion: 'working' },+ ])+ })++ it('prefers the fine-grained workStatus over the coarse status', () => {+ const { bubble, calls } = createFakeBubble()+ const tracker = createBubbleTracker(bubble)+ tracker.apply({ id: 's1', status: 'running', workStatus: 'waiting' }, 'update')++ expect(shows(calls)[0]?.motion).toBe('waiting')+ expect(shows(calls)[0]?.loading).toBe(false)+ })++ it('keeps every subagent session silent', () => {+ const { bubble, calls } = createFakeBubble()+ const tracker = createBubbleTracker(bubble)+ tracker.apply({ id: 'a1', origin: 'subagent', title: '子代理', workStatus: 'working' }, 'create')+ tracker.apply({ id: 'a1', origin: 'subagent', title: '子代理', workStatus: 'result' }, 'update')++ expect(calls).toEqual([])+ })++ it('closes the bubble when the session is removed or falls back to no motion', () => {+ const { bubble, calls } = createFakeBubble()+ const tracker = createBubbleTracker(bubble)+ tracker.apply({ id: 's1', workStatus: 'thinking' }, 'create')+ tracker.apply({ id: 's1' }, 'update')+ tracker.apply({ id: 's2', workStatus: 'thinking' }, 'create')+ tracker.apply({ id: 's2' }, 'remove')++ expect(calls.filter(call => call.type === 'close')).toEqual([+ { type: 'close', id: 's1' },+ { type: 'close', id: 's2' },+ ])+ })++ it('shows a terminal motion only once until the session leaves it', () => {+ const { bubble, calls } = createFakeBubble()+ const tracker = createBubbleTracker(bubble)+ tracker.apply({ id: 's1', workStatus: 'success' }, 'update')+ tracker.apply({ id: 's1', workStatus: 'success' }, 'update')+ expect(shows(calls)).toHaveLength(1)++ tracker.apply({ id: 's1', workStatus: 'thinking' }, 'update')+ tracker.apply({ id: 's1', workStatus: 'success' }, 'update')+ expect(shows(calls)).toHaveLength(3)+ })++ it('flushes bubbles dropped while <Pet> was not mounted', () => {+ const { bubble, calls, state } = createFakeBubble(false)+ const tracker = createBubbleTracker(bubble)+ tracker.apply({ id: 's1', workStatus: 'success' }, 'create')+ expect(shows(calls)).toHaveLength(1)++ state.mounted = true+ tracker.flush()+ expect(shows(calls)).toHaveLength(2)+ expect(shows(calls)[1]?.motion).toBe('success')+ })++ it('appends a one-shot done bubble when a running turn ends without a work status', () => {+ const { bubble, calls } = createFakeBubble()+ const tracker = createBubbleTracker(bubble)+ tracker.apply({ id: 's1', title: '会话一', status: 'running' }, 'create')+ tracker.apply({ id: 's1', title: '会话一' }, 'update')++ expect(shows(calls).at(-1)).toEqual({+ id: 's1:done',+ title: '会话一',+ description: '已完成',+ variant: 'success',+ timeout: 3000,+ })+ })++ it('drops host state and clears the component bubbles on dispose', () => {+ const { bubble, calls } = createFakeBubble()+ const tracker = createBubbleTracker(bubble)+ tracker.apply({ id: 's1', workStatus: 'working' }, 'create')+ tracker.dispose()+ tracker.flush()++ expect(calls.at(-1)).toEqual({ type: 'clear' })+ expect(shows(calls)).toHaveLength(1)+ })+})diff --git a/src/pet/hooks/use-bubble-tracker.ts b/src/pet/hooks/use-bubble-tracker.tsnew file mode 100644index 00000000..47d908b8--- /dev/null+++ b/src/pet/hooks/use-bubble-tracker.ts@@ -0,0 +1,130 @@+import type { Motion, PetBubbleHandle, PetRef } from 'dsh-pet-component'+import type { BubbleSession } from './use-bubble-tracker.helpers'+import type { PetSource } from './use-pet-source'+import { useUnmount, useWatch } from '@reause/core'+import { useRef } from 'react'+import { useListen } from '@/hooks/use-listen'+import {+ DONE_BUBBLE_TIMEOUT,+ pickLang,+ TERMINAL_MOTIONS,+} from './use-bubble-tracker.constants'+import {+ bubbleContent,++ rawSession,+ sessionMotion,+ sessionTitle,+} from './use-bubble-tracker.helpers'++type SessionAction = 'create' | 'remove' | 'update'++export interface BubbleTracker {+ apply: (payload: unknown, action: SessionAction) => void+ flush: () => void+ dispose: () => void+}++/** 订阅会话事件驱动桌宠气泡的 React Hook */+export function useBubbleTracker(pet: PetRef, source?: PetSource | null) {+ const trackerRef = useRef<BubbleTracker | null>(null)+ trackerRef.current ??= createBubbleTracker(pet.bubble)+ const tracker = trackerRef.current++ useWatch(source !== null, (ready) => {+ if (ready)+ tracker.flush()+ }, { immediate: true })++ useListen('session:create', event => tracker.apply(event.payload, 'create'))+ useListen('session:update', event => tracker.apply(event.payload, 'update'))+ useListen('session:remove', event => tracker.apply(event.payload, 'remove'))+ useUnmount(() => tracker.dispose())+}++/** 创建会话气泡桥状态机 */+export function createBubbleTracker(bubble: PetBubbleHandle): BubbleTracker {+ const sessions = new Map<string, BubbleSession>()+ const previousMotion = new Map<string, Motion | undefined>()+ const terminalShown = new Set<string>()++ const forget = (id: string) => {+ sessions.delete(id)+ previousMotion.delete(id)+ terminalShown.delete(id)+ }++ const sync = (session: BubbleSession) => {+ const { id } = session+ const motion = sessionMotion(session)+ const previous = previousMotion.get(id)++ if (motion === undefined) {+ forget(id)+ bubble.close(id)+ if (previous === 'running') {+ bubble({+ id: `${id}:done`,+ title: sessionTitle(session).trim(),+ description: pickLang('已完成', 'Done'),+ variant: 'success',+ timeout: DONE_BUBBLE_TIMEOUT,+ })+ }+ return+ }++ if (TERMINAL_MOTIONS.has(motion)) {+ if (terminalShown.has(id))+ return+ }+ else {+ terminalShown.delete(id)+ }++ previousMotion.set(id, motion)+ const content = bubbleContent(session, motion)+ const key = bubble({+ id,+ title: content.title,+ description: content.description,+ loading: content.loading,+ motion,+ })++ if (key !== '' && TERMINAL_MOTIONS.has(motion)) {+ terminalShown.add(id)+ }+ }++ return {+ apply(payload, action) {+ const session = rawSession(payload)+ if (!session)+ return++ const { id } = session+ if (action === 'remove' || session.origin === 'subagent') {+ if (action === 'remove' || sessions.has(id)) {+ forget(id)+ bubble.close(id)+ }+ return+ }++ sessions.set(id, session)+ sync(session)+ },++ flush() {+ for (const session of [...sessions.values()]) sync(session)+ },++ dispose() {+ sessions.clear()+ previousMotion.clear()+ terminalShown.clear()+ bubble.clear()+ },+ }+}diff --git a/src/pet/hooks/use-bubble.ts b/src/pet/hooks/use-bubble.tsdeleted file mode 100644index 378bb522..00000000--- a/src/pet/hooks/use-bubble.ts+++ /dev/null@@ -1,39 +0,0 @@-import type { Motion } from 'dsh-pet-component'-import type { BubbleTracker } from '../utils/bubble-tracker'-import { useUnmount } from '@reause/core'-import { useRef, useState } from 'react'-import { useListen } from '@/hooks/use-listen'-import { createBubbleTracker } from '../utils/bubble-tracker'--export type { BubbleSession } from '../utils/bubble-tracker'--export interface BubbleHandle {- /**- * 多会话聚合出的动作档位(`dsh-pet-component` 的 14 个 Motion 之一);- * `undefined` = 无会话需要展示(调用方 `pet.clear()` 回落待机)。- */- readonly motion: Motion | undefined-}--/**- * 桌宠窗口的会话气泡:只做两件事——- * 1. 用 `useListen` 订阅 DSH 推来的三个会话事件,把载荷喂给状态机;- * 2. 卸载时释放状态机里的定时器与 toast。- *- * 会话 → toast 映射、聚合优先级、合并窗口、沉淀与脉冲 TTL 等全部逻辑在- * `pet/utils/bubble-tracker.ts`(不依赖 React,可单独推理)。- */-export function useBubble(): BubbleHandle {- const [motion, setMotion] = useState<Motion | undefined>(undefined)- // 每个 hook 实例一台状态机:ref 惰性创建,StrictMode 的重复渲染不会重建- const trackerRef = useRef<BubbleTracker | null>(null)- trackerRef.current ??= createBubbleTracker(setMotion)- const tracker = trackerRef.current-- useListen('session:create', event => tracker.apply(event.payload, 'create'))- useListen('session:update', event => tracker.apply(event.payload, 'update'))- useListen('session:remove', event => tracker.apply(event.payload, 'remove'))- useUnmount(() => tracker.dispose())-- return { motion }-}diff --git a/src/pet/hooks/use-wakelock-release.ts b/src/pet/hooks/use-wakelock-release.tsnew file mode 100644index 00000000..9d6d69d9--- /dev/null+++ b/src/pet/hooks/use-wakelock-release.ts@@ -0,0 +1,8 @@+import { useWakeLock, useWatch } from '@reause/core'++export function useWakelockRelease(): void {+ const wakelock = useWakeLock()+ useWatch(wakelock.isActive, () => {+ void wakelock.release()+ }, { immediate: true })+}diff --git a/src/pet/utils/bubble-tracker.ts b/src/pet/utils/bubble-tracker.tsdeleted file mode 100644index a34b489f..00000000--- a/src/pet/utils/bubble-tracker.ts+++ /dev/null@@ -1,603 +0,0 @@-import type { ToastContentValue } from '@heroui/react'-import type { Motion } from 'dsh-pet-component'-import { toast } from '@/utils/toast'-import { IS_ZH, sessionTitle, statusCopy, taskCopy, toolActivityGroup } from './bubble'--/**- * 会话气泡状态机(桌宠窗口专用,**不依赖 React**)。- *- * DSH 把每个会话的原始快照经 `session:create|update|remove` 事件推给桌宠窗口;- * 这里把这些快照收敛成:- * - 一张「会话 → toast」映射(创建/原地更新/定时收起);- * - 一个多会话聚合出的动作档位(`Motion`),经 `onMotion` 回吐给 React 层。- *- * 之所以从 `use-bubble.ts` 里抽出来:原实现把状态容器与三个 `listen` 一起塞进- * 一个 500 行的 `useEffect`,既无法单测,也让「订阅」这件事被埋没。现在:- * - React 侧只负责 `useListen` ×3 与 `useUnmount` 释放;- * - 本文件是纯逻辑(除 `toast` 这一外部副作用),可单独推理/测试。- */--export interface BubbleSession {- [key: string]: unknown- id: string-}--type SessionAction = 'create' | 'remove' | 'update'--export interface BubbleTracker {- /** 喂入一个会话事件载荷(原始快照或 `{ session }` 包装)。 */- apply: (payload: unknown, action: SessionAction) => void- /** 释放所有定时器与 toast;可在 StrictMode 的双挂载间重复调用。 */- dispose: () => void-}--const FAILED_BUBBLE_TIMEOUT = 4000-const REVIEW_BUBBLE_TIMEOUT = 2500-const SUCCESS_TOAST_TIMEOUT = 3000-const FAILED_PULSE_TTL = 1800-/**- * 终态档(success/error)聚合保持时长:对齐 dsh-pet 的 BUBBLE_DURATION_MS=10000- * (终态动画播一次 + 10s 收气泡)语义。不得复用 SUCCESS_TOAST_TIMEOUT(3s)——成功- * 终态动画(如 雀跃庆祝)实际播放时长超过 3s 时,聚合状态提前回落会让 app.tsx 的- * useWatch 调 pet.clear() 掐断未播完的动画(用户报告:成功动画没播完就换回待机)。- * 动画播完由视频 ended(handleEnded → 清 override)自然回落,toast 收起仍走- * scheduleHide 的独立 3s(SUCCESS_TOAST_TIMEOUT),二者互不影响。- */-const TERMINAL_PULSE_TTL = 10000-/** 会话完成/变空闲后保留的时长:超过即从会话表沉淀,防止 durable subagent 等永不发 remove 的会话无界积累。 */-const IDLE_SESSION_RETENTION = 5000-/**- * 聚合状态下发合并窗口(ms):突发到达的多会话状态变更只取窗内「最新」值下发一次。- * 多会话并行时每个 session:update 事件都走 updateAgg,若每档都立即 setStatus,- * app.tsx 的 useWatch 会对逐个差异档位调用 pet.change 重载动画——工作档位- * (thinking 20 / result 25 / working 30)交错抖动会让桌宠动画被频繁切回/重放。- * 统一合并:窗内只刷新 pendingAgg,到期一次性下发最新聚合态,中间档位全部丢弃。- */-const STATUS_COALESCE_MS = 100--/** 工具名 → toast 展示标签(沿用既有风格:英文工具名大写 / 中文动词)。 */-const TOOL_LABELS: Record<string, string> = {- pwsh: 'Pwsh',- bash: 'Bash',- grep: 'Grep',- glob: 'Glob',- read: '读取',- read_image: '看图',- write: '写入',- edit: '编辑',- str_replace_editor: '编辑',- web_search: '搜索',- web_fetch: '抓取',- think: '思考',- skill: '技能',-}--/** 工具名 → 从 args(JSON 字符串)提取展示明细的键,按优先级取第一个非空值。 */-const TOOL_ARG_KEYS: Record<string, readonly string[]> = {- pwsh: ['command'],- bash: ['command'],- grep: ['pattern'],- glob: ['pattern'],- read: ['file_path', 'path'],- read_image: ['file_path', 'path'],- write: ['file_path', 'path'],- edit: ['file_path', 'path'],- str_replace_editor: ['file_path', 'path'],- web_search: ['queries', 'query'],- web_fetch: ['url'],- think: ['thought'],- skill: ['name'],-}--/** 状态优先级映射,数值越大优先级越高(对齐 dsh-dafeiyu statePriority:等待>错误>工作>思考>空闲)。 */-const STATUS_PRIORITY: Record<string, number> = {- 'waiting': 60,- 'error': 50,- 'failed': 45,- 'review': 40,- 'working': 30,- 'result': 25,- 'thinking': 20,- 'running': 12,- 'success': 10,- 'idle': 0,- 'turn': 0,- 'moving-left': 0,- 'moving-right': 0,- 'waving': 0,-}--/** 细分工作档位(host reducer workStatus 输出):与 `dsh-pet-component` 的动作名同名。 */-const WORK_STATUSES = ['thinking', 'working', 'result', 'waiting', 'success', 'error'] as const--type WorkStatus = (typeof WORK_STATUSES)[number]--/** 统一解析原始会话对象 */-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 : value) as Record<string, unknown>- const id = session.id ?? session.sessionId- return typeof id === 'string' && id.length > 0 ? { ...session, id } : undefined-}--/** 提取单个会话的状态(细分档优先,忽略底层恢复逻辑)。 */-function sessionStatus(session: BubbleSession, ignoreError = false): Motion | undefined {- // 细分工作档位(host reducer 权威):thinking/working/result/waiting/success/error- const work = session.workStatus as unknown- if (WORK_STATUSES.includes(work as WorkStatus)) {- // error/success 是终态档;pulse 过期(ignoreError)后回落底层推导,不残留失败/成功视觉。- if (ignoreError && (work === 'error' || work === 'success'))- return undefined- return work as Motion- }-- const value = session.status ?? session.activity ?? session.phase-- // 终态错误判定只在回合已结束(running !== true)时生效:工具级失败/旧快照的- // lastAgentError 若与 running=true 并存,说明回合仍在跑(agent 捕获错误继续),- // 此时绝不判 failed 收起气泡(用户报告:会话还在跑 toast 却消失了)。- // lastAgentError==='aborted' 是旧版插件宿主(未重新部署 dist 的安装)把手动取消误记为- // 错误的兜底豁免:取消是用户主动中断而非失败,不弹「失败:aborted」。新版宿主已不再下发该值。- const agentError = session.lastAgentError- if (!ignoreError && session.running !== true && (value === 'failed' || value === 'error' || (Boolean(agentError) && agentError !== 'aborted'))) {- return 'failed'- }- if (value === 'review' || value === 'reviewing' || value === 'plan-review') {- return 'review'- }-- const hasInteraction = Boolean(session.pendingInteraction)- const hasPending = Array.isArray(session.pending) ? session.pending.length > 0 : Boolean(session.pending)-- if (value === 'waiting' || value === 'pending' || value === 'blocked' || hasInteraction || hasPending) {- return 'waiting'- }-- if (value === 'running' || value === 'working' || value === 'thinking' || session.running === true) {- return 'running'- }-- return undefined-}--/** 计算聚合最高优先级状态(零额外堆内存分配) */-function statusOf(- sessions: ReadonlyMap<string, BubbleSession>,- failedUntil: ReadonlyMap<string, number>,- now: number,-): Motion | undefined {- let highestStatus: Motion | undefined- let maxPriority = 0-- for (const session of sessions.values()) {- let status = sessionStatus(session)- if (status === 'failed' || status === 'error' || status === 'success') {- const deadline = failedUntil.get(session.id)- if (deadline === undefined || now >= deadline) {- status = sessionStatus(session, true) // 底层恢复状态- }- }-- if (status) {- const priority = STATUS_PRIORITY[status] ?? 0- if (priority > maxPriority) {- maxPriority = priority- highestStatus = status- if (maxPriority === STATUS_PRIORITY.waiting)- break // 'waiting' 为最高优先级,提前终止遍历- }- }- }- return highestStatus-}--/** 格式化空白字符 */-function sanitizeText(str: string): string {- return str.replace(/\s+/g, ' ').trim()-}--/** 从工具 args(JSON 字符串)按优先级提取展示明细;解析失败或无匹配键时返回 undefined。 */-function toolArgDetail(tool: string, args: unknown): string | undefined {- if (typeof args !== 'string' || !args)- return undefined-- let parsed: unknown- try {- parsed = JSON.parse(args)- }- catch {- return undefined- }- if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed))- return undefined-- const record = parsed as Record<string, unknown>- for (const key of TOOL_ARG_KEYS[tool] ?? ['file_path', 'path']) {- const value = record[key]- if (typeof value === 'string' && value.trim()) {- return sanitizeText(value)- }- if (Array.isArray(value)) {- const first = value.find(item => typeof item === 'string' && item.trim())- if (typeof first === 'string' && first.trim()) {- return sanitizeText(first)- }- }- }- return undefined-}--/** 生成 Toast 渲染数据(对齐 dsh-dafeiyu:优先失败详情 → 任务文案 → 工具/思考活动 → 档位状态文案)。 */-function toastContent(session: BubbleSession, status: Motion) {- const getFirstString = (...items: unknown[]): string | undefined => {- for (const item of items) {- if (typeof item === 'string' && item.trim().length > 0) {- return item.trim()- }- }- return undefined- }-- const getLiveActivity = (): string | undefined => {- if (status !== 'running' && status !== 'thinking' && status !== 'working' && status !== 'result') {- return undefined- }- if (!session.liveActivity || typeof session.liveActivity !== 'object') {- return undefined- }-- const { kind, text, name, args } = session.liveActivity as Record<string, unknown>-- if (kind === 'reasoning' && typeof text === 'string' && text.trim()) {- return IS_ZH ? `思考 · ${sanitizeText(text)}` : `Thought · ${sanitizeText(text)}`- }-- if (kind === 'tool' && typeof name === 'string' && name) {- const tool = name.toLowerCase()- const label = TOOL_LABELS[tool]- if (!label)- return IS_ZH ? `工具调用 · ${name}` : `Tool · ${name}`-- const detail = toolArgDetail(tool, args)- return detail ? `${label} · ${detail}` : label- }-- return undefined- }-- const isSub = session.origin === 'subagent'- const title = sessionTitle(session)- // 会话稳定 seed(同会话同档位文案恒定,跨档位切换自然换句;对齐 dsh-dafeiyu statusCopy(seed))。- const seed = session.id- const statusTextMap: Record<string, string> = {- 'think': IS_ZH ? '思考中' : 'Thinking',- 'thinking': IS_ZH ? '思考中' : 'Thinking',- 'working': IS_ZH ? '处理中' : 'Working',- 'result': IS_ZH ? '整理中' : 'Organizing',- 'waiting': IS_ZH ? '等待中' : 'Waiting',- 'running': isSub ? (IS_ZH ? '运行中' : 'Running') : (IS_ZH ? '思考中' : 'Thinking'),- 'review': IS_ZH ? '待审阅' : 'Review',- 'failed': IS_ZH ? '失败' : 'Failed',- 'error': IS_ZH ? '出错' : 'Error',- 'success': IS_ZH ? '已完成' : 'Done',- 'idle': IS_ZH ? '空闲' : 'Idle',- 'turn': IS_ZH ? '空闲' : 'Idle',- 'moving-left': IS_ZH ? '空闲' : 'Idle',- 'moving-right': IS_ZH ? '空闲' : 'Idle',- 'waving': IS_ZH ? '空闲' : 'Idle',- }-- const statusText = statusTextMap[status] ?? (IS_ZH ? '空闲' : 'Idle')- // 档位状态文案:waiting 分 approval/user-question 两档,working 按工具活动分类选句。- const fallbackCopy = status === 'waiting'- ? (session.phase === 'approval' ? statusCopy('approval', seed) : statusCopy('waiting', seed))- : status === 'working'- ? statusCopy(toolActivityGroup(String((session.liveActivity as Record<string, unknown> | undefined)?.name ?? '')), seed)- : statusCopy(status, seed)- const description = getFirstString(- session.lastAgentError ? (IS_ZH ? `失败:${String(session.lastAgentError)}` : `Failed: ${String(session.lastAgentError)}`) : undefined,- taskCopy(session.task as string | undefined), // todo 任务文案:正在处理「xxx」- getLiveActivity(), // 工具/思考活动详情(保留既有实用信息)- fallbackCopy, // 档位状态文案(dsh-dafeiyu statusCopy)- session.description,- session.message,- statusText,- ) ?? (IS_ZH ? '会话' : 'Session')-- const variant = status === 'waiting' || status === 'review'- ? 'warning'- : status === 'failed' || status === 'error'- ? 'danger'- : status === 'success'- ? 'success'- : 'default'-- return {- title,- description,- // 工作中平凡态显示 spinner(running/细分工作档位);等待/终态档不显示 loading。- isLoading: status === 'running' || status === 'thinking' || status === 'working' || status === 'result',- variant,- }-}--/**- * 创建一台会话气泡状态机。- *- * @param onMotion 聚合档位变化时的回调(React 侧传 `setState`)- */-export function createBubbleTracker(onMotion: (motion: Motion | undefined) => void): BubbleTracker {- // 状态容器(随实例生灭;React 侧只在卸载时 dispose,StrictMode 双挂载可安全重复调用)- const sessions = new Map<string, BubbleSession>()- const toastKeys = new Map<string, string>()- const hideTimers = new Map<string, number>()- const previousStatus = new Map<string, Motion | undefined>()- const failedUntil = new Map<string, number>()- const pulseTimers = new Map<string, number>()- const consumedFailed = new Set<string>()- const dismissed = new Set<string>()- const pruneTimers = new Map<string, number>()-- let lastAgg: Motion | undefined- /** 合并窗口内最新计算出的聚合态(未下发前持续被更新,窗口到期统一下发)。 */- let pendingAgg: Motion | undefined- /** pendingAgg 是否有待下发的变更(区分「待下发 undefined 态」与「无变更」)。 */- let hasPendingAgg = false- let aggFlushTimer: number | undefined-- /** 合并窗口到期:把窗口内「最新」聚合态下发(中间态已丢弃,只发最终值)。 */- const flushPendingAgg = () => {- aggFlushTimer = undefined- if (!hasPendingAgg)- return- hasPendingAgg = false- const next = pendingAgg- if (next !== lastAgg) {- lastAgg = next- onMotion(next)- }- }-- const updateAgg = () => {- const next = statusOf(sessions, failedUntil, Date.now())- if (next === lastAgg && !hasPendingAgg)- return- // 始终只处理「最新」的会话状态变更:突发(多会话交错或单会话档位连跳)内- // 每次 updateAgg 都刷新 pendingAgg 并重置合并窗口(trailing 窗口),- // lastAgg 保持已下发的值——窗口只收敛到最终聚合态再一次性下发,- // 中间档位(thinking/result/working 交错)全部丢弃,避免逐个触发- // app.tsx 的 pet.change 让动画被反复切回/重载(多会话频繁切回动画的根因)。- hasPendingAgg = true- pendingAgg = next- if (aggFlushTimer !== undefined)- window.clearTimeout(aggFlushTimer)- aggFlushTimer = window.setTimeout(flushPendingAgg, STATUS_COALESCE_MS)- }-- const clearTimer = (map: Map<string, number>, id: string) => {- const timer = map.get(id)- if (timer !== undefined) {- window.clearTimeout(timer)- map.delete(id)- }- }-- const closeToast = (id: string) => {- clearTimer(hideTimers, id)- const key = toastKeys.get(id)- if (key !== undefined) {- toast.close(key)- toastKeys.delete(id)- }- }-- /** 清除指定会话的所有关联缓存及定时器 */- const removeSessionData = (id: string) => {- sessions.delete(id)- previousStatus.delete(id)- dismissed.delete(id)- failedUntil.delete(id)- consumedFailed.delete(id)- clearTimer(pulseTimers, id)- clearTimer(hideTimers, id)- clearTimer(pruneTimers, id)- closeToast(id)- }-- /** 沉淀清除:超过保留时间后彻底清理空闲会话 */- const pruneSession = (id: string) => {- const session = sessions.get(id)- if (!session)- return- // 活跃档(think/work/result/waiting/running/review)不沉淀;- // 终态档(workStatus success/error)翻开底层:底层空闲(回合完成且无错误残留)才可沉淀。- const status = sessionStatus(session)- const bottom = sessionStatus(session, true)- if (bottom !== undefined)- return- if (status !== undefined && status !== 'success' && status !== 'error')- return-- removeSessionData(id)- updateAgg()- }-- const armPrune = (id: string) => {- clearTimer(pruneTimers, id)- const timer = window.setTimeout(() => {- pruneTimers.delete(id)- pruneSession(id)- }, IDLE_SESSION_RETENTION)- pruneTimers.set(id, timer)- }-- const scheduleHide = (id: string, current: Motion) => {- clearTimer(hideTimers, id)- const timeout = current === 'failed' || current === 'error'- ? FAILED_BUBBLE_TIMEOUT- : current === 'review'- ? REVIEW_BUBBLE_TIMEOUT- : current === 'success'- ? SUCCESS_TOAST_TIMEOUT- : undefined- const key = toastKeys.get(id)- if (timeout === undefined || key === undefined)- return-- const timer = window.setTimeout(() => {- if (toastKeys.get(id) === key) {- dismissed.add(id)- closeToast(id)- }- }, timeout)- hideTimers.set(id, timer)- }-- const trackFailedPulse = (session: BubbleSession) => {- const current = sessionStatus(session)- const previous = previousStatus.get(session.id)-- if (current === 'failed' || current === 'error' || current === 'success') {- if (previous === current || consumedFailed.has(session.id))- return-- // 终态档脉冲窗口:failed 短 TTL 恢复底层状态;success/error 为终态档,- // 保持 TERMINAL_PULSE_TTL(对齐 dsh-pet 10s 收气泡),等动画完整播完再回落空闲。- const ttl = current === 'success' || current === 'error' ? TERMINAL_PULSE_TTL : FAILED_PULSE_TTL- const deadline = Date.now() + ttl- failedUntil.set(session.id, deadline)- clearTimer(pulseTimers, session.id)-- const timer = window.setTimeout(() => {- if (failedUntil.get(session.id) !== deadline)- return- failedUntil.delete(session.id)- clearTimer(pulseTimers, session.id)- consumedFailed.add(session.id)- updateAgg()- }, ttl)-- pulseTimers.set(session.id, timer)- }- else {- failedUntil.delete(session.id)- clearTimer(pulseTimers, session.id)- consumedFailed.delete(session.id)- }- }-- const syncToast = (session: BubbleSession) => {- const current = sessionStatus(session)- const previous = previousStatus.get(session.id)- previousStatus.set(session.id, current)- const key = toastKeys.get(session.id)-- // 子代理会话整体静默:状态仍参与聚合与沉淀(previousStatus/armPrune 照常),- // 但不创建/更新/关闭任何 toast——子代理任务多且切换频繁,活跃追踪 toast 会- // 不断弹出/更新,属于视觉噪音(此前只抑制了「已完成」toast,活跃 toast 仍会弹)。- if (session.origin === 'subagent') {- if (key !== undefined) {- closeToast(session.id)- }- if (current === undefined && previous !== undefined) {- armPrune(session.id)- }- return- }-- if (current === undefined) {- if (key !== undefined)- closeToast(session.id)-- // 子代理静默关闭:不弹「已完成」成功 toast- if (previous === 'running' && session.origin !== 'subagent') {- toast(sessionTitle(session).trim(), {- description: '已完成',- placement: 'top end',- variant: 'success',- timeout: SUCCESS_TOAST_TIMEOUT,- })- }- if (previous !== undefined)- armPrune(session.id)- return- }-- clearTimer(pruneTimers, session.id)- // 终态档(播完即收):failed/error 失败、review 待审阅、success 完成。- const isTerminal = current === 'failed' || current === 'review' || current === 'error' || current === 'success'- if (!isTerminal) {- dismissed.delete(session.id)- }-- const content = toastContent(session, current)- if (key === undefined) {- if (dismissed.has(session.id) || previous === current)- return-- let createdKey = ''- createdKey = toast(content.title, {- isLoading: content.isLoading,- description: content.description,- placement: 'top end',- variant: content.variant as 'warning' | 'danger' | 'default' | 'success',- timeout: 0,- onClose: () => {- if (toastKeys.get(session.id) === createdKey) {- toastKeys.delete(session.id)- clearTimer(hideTimers, session.id)- }- },- })- toastKeys.set(session.id, createdKey)- }- else {- toast.update(key, content as ToastContentValue)- }-- if (previous !== current && isTerminal) {- scheduleHide(session.id, current)- }- }-- function apply(payload: unknown, action: SessionAction): void {- const session = rawSession(payload)- if (!session)- return-- if (action === 'remove') {- removeSessionData(session.id)- }- else {- sessions.set(session.id, session)- trackFailedPulse(session)- syncToast(session)- }-- updateAgg()- }-- function dispose(): void {- // 统一清理所有 Map 定时器与 Toast(幂等;StrictMode 的「挂载→释放→再挂载」下- // 第二次释放是空操作,追踪器本身仍可继续接收事件)。- const clearAllTimers = (map: Map<string, number>) => {- map.forEach(timer => window.clearTimeout(timer))- map.clear()- }- clearAllTimers(hideTimers)- clearAllTimers(pulseTimers)- clearAllTimers(pruneTimers)- if (aggFlushTimer !== undefined) {- window.clearTimeout(aggFlushTimer)- aggFlushTimer = undefined- }- hasPendingAgg = false-- toastKeys.forEach(key => toast.close(key))- toastKeys.clear()- }-- return { apply, dispose }-}diff --git a/src/pet/utils/bubble.ts b/src/pet/utils/bubble.tsdeleted file mode 100644index ea5b6a42..00000000--- a/src/pet/utils/bubble.ts+++ /dev/null@@ -1,164 +0,0 @@-/**- * bubble-copy.ts — 桌宠会话气泡文案的纯逻辑层(对齐 dsh-dafeiyu src/status-copy.js)。- *- * 分组文案(thinking/working/result/waiting/approval/success/error/…)+ seed 稳定选句、- * 工具活动分类文案(activityCopy)、todo 任务文案(taskCopy)都是纯函数,无 React/DOM- * 依赖,可独立单测。use-bubble.ts 只负责把会话状态喂进来取一句展示。- * 桌宠窗口无 i18n 基础设施:按窗口语言(IS_ZH)就地取中/英文案。- */--/** 桌宠窗口无 i18n 基础设施,就地按窗口语言取单语文案(与 pet.tsx 保留文案一致)。 */-export const IS_ZH = (typeof document !== 'undefined' ? document.documentElement.lang || navigator.language : 'zh-CN')- .toLowerCase()- .startsWith('zh')--/**- * 气泡文案库(对齐 dsh-dafeiyu src/status-copy.js 分组 + seed 稳定选句)。- * 各组多备选句:statusCopy 按会话稳定 seed 选一句,避免同一会话反复切换文案。- */-const STATUS_COPY: Record<string, readonly string[]> = {- thinking: IS_ZH- ? ['正在分析', '思考中', '整理结果中']- : ['Analyzing information', 'Thinking', 'Organizing results'],- working: IS_ZH- ? ['正在处理任务', '步骤正在进行中', '系统运行中']- : ['Processing task', 'Step in progress', 'System is working'],- result: IS_ZH- ? ['正在整理结果', '步骤已完成,准备下一步', '正在确认后续操作']- : ['Organizing results', 'Step completed, preparing for next step', 'Confirming next action'],- waiting: IS_ZH- ? ['等待确认', '需提供后续指令', '请决策下一步操作']- : ['Awaiting your confirmation', 'Requires your input', 'Please decide on the next step'],- approval: IS_ZH- ? ['等待审批', '需授权确认', '敏感操作确认授权']- : ['Awaiting your approval', 'Authorization required', 'Please confirm and authorize this action'],- success: IS_ZH- ? ['任务已完成', '本阶段任务已完成', '流程执行成功']- : ['Task completed successfully', 'Current phase completed', 'Execution succeeded'],- running: IS_ZH- ? ['任务运行中', '当前步骤正在处理']- : ['Task is running', 'Current step is processing'],- review: IS_ZH- ? ['正在汇总变更', '变更已就绪,等待审阅']- : ['Consolidating', 'Ready for your review'],- failed: IS_ZH- ? ['步骤执行失败', '操作执行过程中发生异常']- : ['Step execution failed', 'An error occurred during operation'],- error: IS_ZH- ? ['任务发生错误', '出现异常,请进行排查', '流程未能成功']- : ['Task encountered an error', 'Exception detected, please check', 'Process failed to complete'],- stopped: IS_ZH- ? ['任务已终止', '任务已在此处暂停']- : ['Task terminated', 'Task paused at this stage'],-} as const--/** 工具活动分类 → 文案(对齐 dsh-dafeiyu activityCopy:按工具分类选句)。 */-const ACTIVITY_COPY: Record<string, readonly string[]> = {- searching: IS_ZH- ? ['正在检索', '正在项目中进行全面搜索', '正在调阅相关文件']- : ['Searching', 'Searching across the project', 'Checking related files'],- editing: IS_ZH- ? ['正在修改', '正在写入变更内容', '正在调整代码实现']- : ['Editing', 'Applying changes', 'Adjusting implementation'],- testing: IS_ZH- ? ['正在检验', '正在运行测试集进行确认', '正在验证变更有效性']- : ['Verifying', 'Running test suites', 'Verifying changes'],- commanding: IS_ZH- ? ['正在执行', '正在启动项目服务', '正在监控指令执行状态']- : ['Executing', 'Starting project services', 'Monitoring command execution'],-} as const--/** seed → 稳定非负整数(数值取整数部分,否则按字符码点求和;对齐 dsh-dafeiyu seedNumber)。 */-export function seedNumber(seed: string | number | undefined): number {- const value = String(seed ?? '')- const numeric = Number(value)- if (Number.isFinite(numeric))- return Math.abs(Math.trunc(numeric))- return [...value].reduce((total, character) => total + (character.codePointAt(0) ?? 0), 0)-}--/** 按组取一句稳定文案(选句随 seed 变化但同一 seed 恒定)。 */-export function statusCopy(group: string, seed?: string | number): string {- const variants = STATUS_COPY[group] ?? STATUS_COPY.working- return variants[seedNumber(seed) % variants.length] ?? variants[0]-}--/** 工具活动分类文案(dsh-dafeiyu activityCopy 的对齐实现);无分类回落 working 通用文案。 */-export function activityCopy(activity: string, seed?: string | number): string {- const variants = ACTIVITY_COPY[activity] ?? STATUS_COPY.working- return variants[seedNumber(seed) % variants.length] ?? variants[0]-}--/**- * 任务文本 → 气泡文案(对齐 dsh-dafeiyu taskCopy 的句式,但**不带句末语气词**:- * 「正在/继续」开头 → 原文;动作动词开头 → 正在+原文;否则 正在处理「原文」)。- * 上游 dsh-dafeiyu 每句都以「呢」收尾,本仓库按用户反馈去掉该语气词。- */-export function taskCopy(task: string | undefined): string | undefined {- const value = String(task ?? '').trim().replace(/[。!?.!?]+$/u, '')- if (!value)- return undefined- if (/^(?:正在|继续)/u.test(value))- return value- if (/^(?:准备|检查|验证|修改|修复|测试|构建|整理|分析|梳理|查找|搜索|读取|实现)/u.test(value))- return `正在${value}`- return `正在处理「${value}」`-}--/** 工具名 → 活动分类(对齐 dsh-dafeiyu toolActivity 正则 + DSH 实际工具名 pwsh;供 working 档无 liveActivity 时选文案)。 */-export function toolActivityGroup(tool: string | undefined): string {- const value = String(tool || '').toLowerCase()- if (/search|grep|find|glob|web|read|fetch|open/.test(value))- return 'searching'- if (/write|edit|patch|replace|create|move|delete/.test(value))- return 'editing'- if (/test|check|lint|build|verify/.test(value))- return 'testing'- if (/shell|bash|exec|command|terminal|powershell|pwsh/.test(value))- return 'commanding'- return 'working'-}--/** 会话标题兜底文案:标题还没生成(或首条提示尚未出标题)时不要暴露内部 session id。 */-export const UNTITLED_SESSION_TITLE = IS_ZH ? '新会话' : 'New session'--/** 会话标题前缀(等待/子代理等需要用户注意的态)。 */-const SESSION_LABELS = {- subagent: IS_ZH ? '子代理' : 'Subagent',- waitApproval: IS_ZH ? '需授权' : 'Needs approval',- waitChoice: IS_ZH ? '需选择' : 'Needs your input',-} as const--/**- * 标题展示只读这些字段:标题与身份来自宿主投影,phase/origin 决定前缀。- * 带索引签名是为了直接吃完整展示态(`use-bubble` 的会话对象),多余字段一律忽略。- */-export interface SessionTitleSource {- [key: string]: unknown- title?: unknown- displayTitle?: unknown- name?: unknown- phase?: unknown- origin?: unknown-}--/**- * 会话标题(含等待/子代理前缀)。- *- * 标题缺失时回落到 {@link UNTITLED_SESSION_TITLE}(「新会话」),**绝不回落到 `session.id`**:- * 会话 id 是内部标识,标题还没生成时它会以 `session-xxxx-xxxx…` 形态漏进气泡标题。- */-export function sessionTitle(session: SessionTitleSource): string {- const base = [session.title, session.displayTitle, session.name]- .find((value): value is string => typeof value === 'string' && value.trim().length > 0)- ?.trim()- ?? UNTITLED_SESSION_TITLE-- if (session.phase === 'approval')- return `${SESSION_LABELS.waitApproval} · ${base}`- if (session.phase === 'user-question' || session.phase === 'blocked')- return `${SESSION_LABELS.waitChoice} · ${base}`- if (session.origin === 'subagent')- return `${SESSION_LABELS.subagent} · ${base}`- return base-}diff --git a/src/ui/pet/hint.tsx b/src/ui/pet/hint.tsxindex 2ecfb638..9f8f0f7d 100644--- a/src/ui/pet/hint.tsx+++ b/src/ui/pet/hint.tsx@@ -1,10 +1,10 @@-import { IS_ZH } from '@/pet/utils/bubble'+import { IS_ZH } from '@/pet/hooks/use-bubble-tracker.constants'/*** hint.tsx — 桌宠窗口里唯一会出现的文字提示。** 桌宠窗口是透明置顶小窗,**没有任何其它 UI 或 i18n 基础设施**(气泡文案同样就地取- * 单语),所以这里按窗口语言(`pet/utils/bubble` 的 `IS_ZH`,与气泡文案同源)就近给出+ * 单语),所以这里按窗口语言(`pet/hooks/use-bubble-tracker` 的 `IS_ZH`,与气泡文案同源)就近给出* 单句提示。静默留空是不行的:用户看到的是「宠物加载不出来」,既不知道原因也不知道去哪修。*/diff --git a/test/wake-lock.test.ts b/test/wake-lock.test.tsindex 50e6e84f..d3a47d19 100644--- a/test/wake-lock.test.ts+++ b/test/wake-lock.test.ts@@ -11,10 +11,11 @@ import { describe, expect, it } from 'vitest'** 原先的 `navigator.wakeLock.request` 猴补丁(`utils/disable-wake-lock.ts`)已删除,* 这里把「两个窗口入口都释放唤醒锁」的不变量锁在源码层面:任一入口漏掉即失败。+ * 桌宠窗口侧已抽成 `pet/hooks/use-wakelock-release.ts`,断言跟着搬家。*/const WAKE_LOCK_ENTRIES = ['../src/layout/index.tsx',- '../src/pet/app.tsx',+ '../src/pet/hooks/use-wakelock-release.ts',]describe('wake lock contract', () => {diff --git a/vitest.config.ts b/vitest.config.tsindex 7631982e..74548401 100644--- a/vitest.config.ts+++ b/vitest.config.ts@@ -32,6 +32,8 @@ export default defineConfig({'test/patch-layer.test.ts',// issue #539:旧版 WebKit 缺全局 Iterator 导致插件加载失败,壳层兼容垫片回归。'test/compat-iterator.test.ts',+ // v0.2.0:气泡托管给 dsh-pet-component,宿主侧只剩「会话快照 → pet.bubble」的映射。+ 'src/pet/hooks/use-bubble-tracker.test.ts',],maxWorkers: 4,testTimeout: 30_000,