Skip to content

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

feat(pet): mirror every codex session into one native pet snapshot

hairyf0a044a55e78b
diff --git a/packages/dsh-tauri-pet/src/client/constants/index.ts b/packages/dsh-tauri-pet/src/client/constants/index.ts
index f671579b..ce654bbc 100644
--- a/packages/dsh-tauri-pet/src/client/constants/index.ts
+++ b/packages/dsh-tauri-pet/src/client/constants/index.ts
@@ -23,7 +23,9 @@ 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_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'
export const BUILTIN_PET_NAME = 'Maid DeepSeek Whale'
export const BUILTIN_PET_DESC_ZH = '一只小小的七比蓝头发的鲸鱼女仆Codex宠物,穿着海军蓝裙子,白色褶边,蓝眼睛,侧鳍和鲸鱼尾巴。'
diff --git a/packages/dsh-tauri-pet/src/client/locales/index.ts b/packages/dsh-tauri-pet/src/client/locales/index.ts
index b44dc43c..b52a2b1b 100644
--- a/packages/dsh-tauri-pet/src/client/locales/index.ts
+++ b/packages/dsh-tauri-pet/src/client/locales/index.ts
@@ -13,11 +13,18 @@ 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: '创建',
@@ -27,6 +34,8 @@ const DICT_ZH: Record<LocaleKey, string> = {
importFailed: '导入宠物失败',
listFailed: '读取宠物列表失败',
name: 'Pets',
+ pendingPlanReview: '待审阅方案',
+ pendingQuestion: '待回答',
petDescWhale: BUILTIN_PET_DESC_ZH,
petNameWhale: BUILTIN_PET_NAME,
select: '选择',
@@ -38,15 +47,23 @@ 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',
@@ -56,6 +73,8 @@ 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',
@@ -67,6 +86,7 @@ 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.ts
index fc78a202..2b35697f 100644
--- a/packages/dsh-tauri-pet/src/client/service/activity.ts
+++ b/packages/dsh-tauri-pet/src/client/service/activity.ts
@@ -1,10 +1,25 @@
import type { ClientContext } from 'dsh-tauri/client'
-import type { PetObservable, PetRuntimeContext, PetSessionActivity, PetSessionSnapshot } from '../types'
+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 { activityBubble, mapPetActivity } from '../utils/activity'
-import { setPetActivity } from './pet'
+import {
+ describePending,
+ describeSession,
+ mapPetActivity,
+ phaseActivity,
+ sessionTitle,
+} from '../utils/activity'
+import { createSessionStatus, reduceSessionEvent } from '../utils/session-status'
+import { setPetSessions } from './pet'
function activityLabel(activity: PetSessionActivity): string {
switch (activity) {
@@ -33,62 +48,172 @@ function resolvePendingSource(ctx: ClientContext): PetObservable<ReadonlyMap<str
}
}
-/** Mirror the current Codex session into the native pet status bridge. */
+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])
+}
+
+/**
+ * 从会话事件窗口把新事件回放进归约器。窗口是「完整事件窗口」快照,因此每次
+ * 推送都按序喂入;`reduceSessionEvent` 会按 seq 去重,这里再按 `lastSeq` 提前
+ * 跳过已消费事件,避免长会话反复重放整段窗口(O(n²) → O(n))。
+ */
+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 {
ctx.effect(() => {
const runtime = compat(ctx) as unknown as PetRuntimeContext
const controller = createLifecycleController()
const pendingSource = resolvePendingSource(ctx)
- let currentSessionId: string | undefined
- let currentSnapshot: PetSessionSnapshot | undefined
- let disposeSession: (() => void) | undefined
+ const snapshots = new Map<string, PetSessionSnapshot | undefined>()
+ const reducerStates = new Map<string, SessionStatusRecord>()
+ const disposers = new Map<string, () => void>()
let lastPayload = ''
+ let disposed = false
+ let pushChain: Promise<void> = Promise.resolve()
function push(): void {
const list = runtime.sessions.list.getSnapshot()
- const id = list.current
- const summary = id === undefined ? undefined : list.byId?.[id]
- const pending = id === undefined
- ? undefined
- : pendingSource?.getSnapshot().get(id) ?? summary?.pendingInteraction
- const activity = mapPetActivity(summary, currentSnapshot, pending)
- const bubble = activityBubble(
- activity,
- activityLabel(activity),
- summary?.title ?? summary?.displayTitle,
- )
- const payload = `${activity}\u0000${bubble ?? ''}`
+ 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)
return
lastPayload = payload
- void setPetActivity(activity, bubble).catch((error) => {
- console.error('[dsh-tauri-pet] update pet activity failed:', error)
+ pushChain = pushChain.then(async () => {
+ if (disposed)
+ return
+ try {
+ await setPetSessions(sessions)
+ }
+ catch (error) {
+ console.error('[dsh-tauri-pet] update pet sessions failed:', error)
+ }
})
}
- function syncCurrent(): void {
- const id = runtime.sessions.list.getSnapshot().current
- if (id !== currentSessionId) {
- disposeSession?.()
- disposeSession = undefined
- currentSessionId = id
- const source = id === undefined ? undefined : runtime.sessions.binding?.(id)?.session
- currentSnapshot = source?.getSnapshot()
- if (source !== undefined) {
- disposeSession = source.subscribe(() => {
- currentSnapshot = source.getSnapshot()
- push()
- })
+ /** 为单条会话绑定快照/事件订阅;返回组合卸载函数。 */
+ function bindSession(id: string): void {
+ const source = runtime.sessions.binding?.(id)
+ if (source === undefined)
+ return
+ const disposeList: Array<() => void> = []
+
+ const sessionStore = source.session
+ if (sessionStore !== undefined) {
+ snapshots.set(id, sessionStore.getSnapshot())
+ disposeList.push(sessionStore.subscribe(() => {
+ snapshots.set(id, sessionStore.getSnapshot())
+ push()
+ }))
+ }
+
+ 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()
+ }))
+ }
+
+ disposers.set(
+ id,
+ () => {
+ for (const dispose of disposeList)
+ dispose()
+ },
+ )
+ }
+
+ function syncSessions(): void {
+ const ids = new Set(runtime.sessions.list.getSnapshot().ids)
+ for (const [id, dispose] of disposers) {
+ if (!ids.has(id)) {
+ dispose()
+ disposers.delete(id)
+ snapshots.delete(id)
+ reducerStates.delete(id)
}
}
+ for (const id of ids) {
+ if (disposers.has(id))
+ continue
+ bindSession(id)
+ }
push()
}
- controller.add(runtime.sessions.list.subscribe(syncCurrent))
- if (pendingSource !== undefined)
- controller.add(pendingSource.subscribe(push))
- controller.add(() => disposeSession?.())
- syncCurrent()
+ 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(() => {
+ disposed = true
+ for (const dispose of disposers.values())
+ dispose()
+ disposers.clear()
+ snapshots.clear()
+ reducerStates.clear()
+ })
+ syncSessions()
return () => controller.dispose()
}, PET_ACTIVITY_EFFECT)
}
diff --git a/packages/dsh-tauri-pet/src/client/service/pet.ts b/packages/dsh-tauri-pet/src/client/service/pet.ts
index 35619096..01b5974c 100644
--- a/packages/dsh-tauri-pet/src/client/service/pet.ts
+++ b/packages/dsh-tauri-pet/src/client/service/pet.ts
@@ -1,6 +1,7 @@
-import type { PetActivity, PetAsset, PetListItem, PetSource, PetStatus } from '../types'
+import type { PetActivity, PetAsset, PetListItem, PetSessionStatus, PetSource, PetStatus } from '../types'
import { invokeBridgedTauri } from 'dsh-tauri/client'
import {
+ CMD_GET_BUILTIN_PET_ASSETS,
CMD_GET_PET_ASSET,
CMD_GET_PET_STATUS,
CMD_HIDE_PET,
@@ -9,6 +10,7 @@ import {
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'
@@ -62,3 +64,13 @@ export function importPet(name: string, data: string): Promise<PetListItem> {
export function setPetActivity(activity: PetActivity, bubble?: string): Promise<PetStatus> {
return invokeBridgedTauri<PetStatus>(CMD_SET_PET_ACTIVITY, { activity, bubble })
}
+
+/** 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.ts
index 24f78420..b35237fb 100644
--- a/packages/dsh-tauri-pet/src/client/types/index.ts
+++ b/packages/dsh-tauri-pet/src/client/types/index.ts
@@ -4,12 +4,27 @@ export type PetActivity = 'failed' | 'idle' | 'moving-left' | 'moving-right' | '
/** 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
+}
+
export interface PetStatus {
active_pet: string
activity: PetActivity
bubble?: string | null
enabled: boolean
pet_size?: number | null
+ sessions?: PetSessionStatus[]
visible: boolean
}
@@ -53,8 +68,24 @@ export interface PetObservable<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<{
@@ -98,11 +129,18 @@ export interface ConversationInputLeftProps {
}
export type LocaleKey
- = | 'activityFailed'
+ = | 'activityApproval'
+ | 'activityFailed'
| 'activityIdle'
+ | 'activityLimit'
+ | 'activityPreparing'
+ | 'activityResult'
| 'activityReview'
| 'activityRunning'
+ | 'activityStopped'
+ | 'activityThinking'
| 'activityWaiting'
+ | 'activityWorking'
| 'codex'
| 'collapsePet'
| 'create'
@@ -112,6 +150,8 @@ export type LocaleKey
| 'importFailed'
| 'listFailed'
| 'name'
+ | 'pendingPlanReview'
+ | 'pendingQuestion'
| 'petDescWhale'
| 'petNameWhale'
| 'select'
@@ -123,4 +163,5 @@ 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.ts
index a8a3d554..6409da5b 100644
--- a/packages/dsh-tauri-pet/src/client/utils/activity.test.ts
+++ b/packages/dsh-tauri-pet/src/client/utils/activity.test.ts
@@ -1,13 +1,23 @@
+import type { PetSessionEvent } from '../types'
import { describe, expect, it } from 'vitest'
-import { activityBubble, mapPetActivity } from './activity'
+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, session, undefined)).toBe('running')
- expect(mapPetActivity({ ...summary, running: false }, { ...session, running: false }, undefined)).toBe('review')
+ 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')
})
@@ -26,3 +36,34 @@ describe('activityBubble', () => {
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.ts
index 09f2a3a6..8e04c891 100644
--- a/packages/dsh-tauri-pet/src/client/utils/activity.ts
+++ b/packages/dsh-tauri-pet/src/client/utils/activity.ts
@@ -1,5 +1,7 @@
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(
@@ -18,6 +20,69 @@ export function mapPetActivity(
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
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.ts
new file mode 100644
index 00000000..9a437204
--- /dev/null
+++ b/packages/dsh-tauri-pet/src/client/utils/session-status.test.ts
@@ -0,0 +1,123 @@
+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.ts
new file mode 100644
index 00000000..c61f8c66
--- /dev/null
+++ b/packages/dsh-tauri-pet/src/client/utils/session-status.ts
@@ -0,0 +1,275 @@
+/**
+ * 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)
+}