Skip to content

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

fix: 会话归档时静默移除通知与 Pet 状态 (#1149)

Hairye049a59bb809
diff --git a/packages/dsh-tauri-notification/src/client/register/notify.test.ts b/packages/dsh-tauri-notification/src/client/register/notify.test.ts
index 9ff3497c..8d304e37 100644
--- a/packages/dsh-tauri-notification/src/client/register/notify.test.ts
+++ b/packages/dsh-tauri-notification/src/client/register/notify.test.ts
@@ -27,6 +27,7 @@ function snapshotSource<T>(initial: T): SnapshotSource<T> {
const mocks = vi.hoisted(() => ({
showNativeNotification: vi.fn(),
+ playSound: vi.fn(),
turnEndedByUser: vi.fn(async () => false),
adapter: undefined as unknown,
settings: { turnComplete: 'background', approval: true, question: true, sound: 'default', customSound: null },
@@ -64,7 +65,7 @@ vi.mock('dsh-tauri/client', () => ({
vi.mock('../store', () => ({ notificationSettings: { $state: mocks.settings } }))
vi.mock('../service/native', () => ({ showNativeNotification: mocks.showNativeNotification }))
vi.mock('../service/turn-end', () => ({ turnEndedByUser: mocks.turnEndedByUser }))
-vi.mock('../service/sound', () => ({ createSoundPlayer: () => ({ play: vi.fn(), dispose: vi.fn() }) }))
+vi.mock('../service/sound', () => ({ createSoundPlayer: () => ({ play: mocks.playSound, dispose: vi.fn() }) }))
vi.mock('../service/sound-assets', () => ({ requestBuiltinSounds: vi.fn() }))
function summary(id: string, overrides: Partial<SessionSummaryFace> = {}): SessionSummaryFace {
@@ -88,16 +89,17 @@ const APPROVAL_PENDING: PendingInteractionFace = {
interface Harness {
list: SnapshotSource<SessionListStateFace>
sessionStatus: SnapshotSource<ReadonlyMap<string, SessionStatusFace>>
+ workspaces: SnapshotSource<{ archivedSessionIds: readonly string[] }>
}
/** 注册通知运行时,并返回可发布快照的两个数据源。 */
-function startNotify(initialList: SessionListStateFace, initialStatuses: ReadonlyMap<string, SessionStatusFace>): Harness {
+function startNotify(initialList: SessionListStateFace, initialStatuses: ReadonlyMap<string, SessionStatusFace>, archiveAware = true): Harness {
const list = snapshotSource(initialList)
const sessionStatus = snapshotSource(initialStatuses)
- mocks.adapter = {
- sessionList: () => ({ current: undefined }),
- openSession: () => ({ status: 'opened' }),
- }
+ const workspaces = snapshotSource<{ archivedSessionIds: readonly string[] }>({ archivedSessionIds: [] })
+ mocks.adapter = archiveAware
+ ? { has: (capability: string) => capability === 'workspaces.list', workspaces: { list: workspaces }, sessionList: () => ({ current: undefined }), openSession: () => ({ status: 'opened' }) }
+ : { has: () => false, sessionList: () => ({ current: undefined }), openSession: () => ({ status: 'opened' }) }
notifyFeature.call({
get: (name: string) => {
if (name === 'sessions')
@@ -107,12 +109,13 @@ function startNotify(initialList: SessionListStateFace, initialStatuses: Readonl
return undefined
},
})
- return { list, sessionStatus }
+ return { list, sessionStatus, workspaces }
}
describe('notification notify runtime', () => {
beforeEach(() => {
vi.useFakeTimers()
+ mocks.turnEndedByUser.mockReset().mockResolvedValue(false)
})
afterEach(() => {
@@ -121,6 +124,92 @@ describe('notification notify runtime', () => {
vi.useRealTimers()
})
+ it('进行中会话归档后忽略完成与待处理交互且不播放声音', async () => {
+ const { sessionStatus, workspaces } = startNotify(
+ { ids: ['main'], byId: { main: summary('main', { running: true }) } },
+ new Map([['main', status(true)]]),
+ )
+ workspaces.publish({ archivedSessionIds: ['main'] })
+ sessionStatus.publish(new Map([['main', status(false, { ...APPROVAL_PENDING, sessionId: 'main' })]]))
+ await vi.advanceTimersByTimeAsync(1000)
+
+ expect(mocks.turnEndedByUser).not.toHaveBeenCalled()
+ expect(mocks.showNativeNotification).not.toHaveBeenCalled()
+ expect(mocks.playSound).not.toHaveBeenCalled()
+ })
+
+ it('归档变化单独到达即撤销完成和授权的 settle 定时器', async () => {
+ const { sessionStatus, workspaces } = startNotify(
+ { ids: ['main'], byId: { main: summary('main', { running: true }) } },
+ new Map([['main', status(true)]]),
+ )
+ sessionStatus.publish(new Map([['main', status(false, { ...APPROVAL_PENDING, sessionId: 'main' })]]))
+ expect(vi.getTimerCount()).toBe(2)
+ workspaces.publish({ archivedSessionIds: ['main'] })
+
+ expect(vi.getTimerCount()).toBe(0)
+ await vi.advanceTimersByTimeAsync(1000)
+ expect(mocks.turnEndedByUser).not.toHaveBeenCalled()
+ expect(mocks.showNativeNotification).not.toHaveBeenCalled()
+ expect(mocks.playSound).not.toHaveBeenCalled()
+ })
+
+ it.each([false, true])('归档后旧异步完成检查返回不通知,期间恢复归档=%s', async (restore) => {
+ let resolveEnd!: (value: boolean) => void
+ mocks.turnEndedByUser.mockImplementationOnce(() => new Promise<boolean>((resolve) => {
+ resolveEnd = resolve
+ }))
+ const { sessionStatus, workspaces } = startNotify(
+ { ids: ['main'], byId: { main: summary('main', { running: true }) } },
+ new Map([['main', status(true)]]),
+ )
+ sessionStatus.publish(new Map([['main', status(false)]]))
+ await vi.advanceTimersByTimeAsync(250)
+ expect(mocks.turnEndedByUser).toHaveBeenCalledExactlyOnceWith('main')
+ workspaces.publish({ archivedSessionIds: ['main'] })
+ if (restore)
+ workspaces.publish({ archivedSessionIds: [] })
+ resolveEnd(false)
+ await vi.advanceTimersByTimeAsync(1000)
+
+ expect(mocks.showNativeNotification).not.toHaveBeenCalled()
+ expect(mocks.playSound).not.toHaveBeenCalled()
+ })
+
+ it('恢复归档重新建立完成和待处理基线,下一轮正常完成仍通知', async () => {
+ const { sessionStatus, workspaces } = startNotify(
+ { ids: ['main'], byId: { main: summary('main', { running: true }) } },
+ new Map([['main', status(true)]]),
+ )
+ workspaces.publish({ archivedSessionIds: ['main'] })
+ sessionStatus.publish(new Map([['main', status(false, { ...APPROVAL_PENDING, sessionId: 'main' })]]))
+ workspaces.publish({ archivedSessionIds: [] })
+ await vi.advanceTimersByTimeAsync(1000)
+ expect(mocks.showNativeNotification).not.toHaveBeenCalled()
+ expect(mocks.playSound).not.toHaveBeenCalled()
+
+ sessionStatus.publish(new Map([['main', status(true)]]))
+ sessionStatus.publish(new Map([['main', status(false)]]))
+ await vi.advanceTimersByTimeAsync(1000)
+ expect(mocks.showNativeNotification).toHaveBeenCalledTimes(1)
+ expect(mocks.showNativeNotification).toHaveBeenCalledWith(expect.objectContaining({ sessionId: 'main', body: 'Turn completed' }))
+ expect(mocks.playSound).toHaveBeenCalledTimes(1)
+ })
+
+ it('宿主没有归档快照时照常通知,只是不做归档抑制', async () => {
+ const { list, sessionStatus } = startNotify(
+ { ids: ['main'], byId: { main: summary('main', { running: true }) } },
+ new Map([['main', status(true)]]),
+ false,
+ )
+ list.publish({ ids: ['main'], byId: { main: summary('main', { running: false }) } })
+ sessionStatus.publish(new Map([['main', status(false)]]))
+ await vi.advanceTimersByTimeAsync(1000)
+
+ expect(mocks.showNativeNotification).toHaveBeenCalledTimes(1)
+ expect(mocks.playSound).toHaveBeenCalledTimes(1)
+ })
+
it('子代理会话跑完不发轮次完成通知', async () => {
const { list, sessionStatus } = startNotify(
{ ids: ['sub'], byId: { sub: summary('sub', { origin: 'subagent', running: true }) } },
@@ -143,6 +232,7 @@ describe('notification notify runtime', () => {
sessionStatus.publish(new Map([['main', status(false)]]))
await vi.advanceTimersByTimeAsync(1000)
+ expect(mocks.playSound).toHaveBeenCalledTimes(1)
expect(mocks.showNativeNotification).toHaveBeenCalledTimes(1)
expect(mocks.showNativeNotification).toHaveBeenCalledWith(expect.objectContaining({
title: 'main',
diff --git a/packages/dsh-tauri-notification/src/client/register/notify.ts b/packages/dsh-tauri-notification/src/client/register/notify.ts
index 47be728e..f97ca5f8 100644
--- a/packages/dsh-tauri-notification/src/client/register/notify.ts
+++ b/packages/dsh-tauri-notification/src/client/register/notify.ts
@@ -1,4 +1,5 @@
-import type { ClientContext } from 'dsh-tauri/client'
+import type { WorkspaceSnapshot } from '@deepseek-ai/dsh-api-workspace-controller/client'
+import type { AdapterListProjection, ClientContext } from 'dsh-tauri/client'
import type { FocusGateInput } from '../service/decision'
import type { NativeNotificationAction, NotificationKind, PendingInteractionFace, SessionsFace, UiSessionFace } from '../types'
import { defineRegister } from 'dsh-tauri/client'
@@ -39,12 +40,19 @@ interface SessionObservation {
* 服务缺席时降级而不是报错。
*/
export const notifyFeature = defineRegister<ClientContext>((controller, ctx, adapter) => {
+ // 归档集合缺席时只丢掉「归档抑制」,通知照常发:新版宿主才有这份快照。
+ const workspaceSource = adapter.has('workspaces.list') ? adapter.workspaces.list as AdapterListProjection<WorkspaceSnapshot> : undefined
+ const isArchived = (sessionId: string): boolean => {
+ const archivedSessionIds: readonly string[] = workspaceSource?.getSnapshot().archivedSessionIds ?? []
+ return archivedSessionIds.includes(sessionId)
+ }
const sound = createSoundPlayer()
controller.add(sound.dispose)
// 内置提示音是壳层 `public/` 下的资源,插件在 iframe 里取不到同源文件:开局先索要一份,
// 免得第一次通知落到合成音兜底上。
requestBuiltinSounds()
+ const observationTokens = new Map<string, object>()
const seenRunning = new Map<string, boolean | undefined>()
const seenPending = new Map<string, string | undefined>()
const timers = new Map<string, () => void>()
@@ -86,6 +94,8 @@ export const notifyFeature = defineRegister<ClientContext>((controller, ctx, ada
}
const notify = (sessionId: string, kind: NotificationKind, title: string, body: string, requireInteraction: boolean, actions?: NativeNotificationAction[], onAction?: (action: string, inputValue: string | null) => void): void => {
+ if (controller.isDisposed() || isArchived(sessionId))
+ return
const settings = notificationSettings.$state
sound.play(settings.sound, settings.customSound)
sequence += 1
@@ -255,7 +265,10 @@ export const notifyFeature = defineRegister<ClientContext>((controller, ctx, ada
const reconcileTurn = (sessionId: string, finished: boolean): void => {
if (!finished)
return
+ const token = observationTokens.get(sessionId)
settle(`${sessionId}:turn`, () => {
+ if (controller.isDisposed() || isArchived(sessionId) || observationTokens.get(sessionId) !== token)
+ return
const status = readUiSession()?.sessionStatus.getSnapshot().get(sessionId)
const summary = readSessions()?.list.getSnapshot().byId[sessionId]
if (status ? status.running === true : summary?.running === true)
@@ -268,6 +281,8 @@ export const notifyFeature = defineRegister<ClientContext>((controller, ctx, ada
void (async () => {
if (await turnEndedByUser(sessionId))
return
+ if (controller.isDisposed() || isArchived(sessionId) || observationTokens.get(sessionId) !== token)
+ return
// 问宿主是异步的,等待期间会话可能又跑起来了:再确认一次,别给正在干活的会话弹「已完成」。
const currentStatus = readUiSession()?.sessionStatus.getSnapshot().get(sessionId)
const currentSummary = readSessions()?.list.getSnapshot().byId[sessionId]
@@ -289,8 +304,10 @@ export const notifyFeature = defineRegister<ClientContext>((controller, ctx, ada
seenRunning.set(sessionId, observed.running)
seenPending.set(sessionId, pendingKey)
// 首次观察只建立基线:插件加载前就存在的完成态与待处理交互不该补弹通知。
- if (!known)
+ if (!known) {
+ observationTokens.set(sessionId, {})
continue
+ }
if (observed.pending && pendingKey !== previousPending)
reconcilePending(sessionId, observed.pending, true)
reconcileTurn(sessionId, previousRunning === true && observed.running !== true)
@@ -298,6 +315,7 @@ export const notifyFeature = defineRegister<ClientContext>((controller, ctx, ada
for (const sessionId of [...seenRunning.keys()]) {
if (entries.has(sessionId))
continue
+ observationTokens.delete(sessionId)
seenRunning.delete(sessionId)
seenPending.delete(sessionId)
syncQuestionWizard(sessionId, undefined)
@@ -317,7 +335,7 @@ export const notifyFeature = defineRegister<ClientContext>((controller, ctx, ada
for (const sessionId of list.ids) {
const summary = list.byId[sessionId]
// 子代理会话由父会话驱动,与桌宠(use-bubble-tracker)一致:不进观察集,也就不发通知。
- if (summary?.origin === 'subagent')
+ if (summary?.origin === 'subagent' || isArchived(sessionId))
continue
const status = statuses?.get(sessionId)
entries.set(sessionId, {
@@ -329,6 +347,8 @@ export const notifyFeature = defineRegister<ClientContext>((controller, ctx, ada
}
// 会话列表是常驻服务:用它驱动观察,顺带拿到标题与当前会话。
+ if (workspaceSource)
+ controller.add(workspaceSource.subscribe(observe))
const listSource = readSessions()?.list
if (listSource) {
controller.add(listSource.subscribe(observe))
diff --git a/packages/dsh-tauri-notification/src/client/service/turn-end.test.ts b/packages/dsh-tauri-notification/src/client/service/turn-end.test.ts
new file mode 100644
index 00000000..37aa358e
--- /dev/null
+++ b/packages/dsh-tauri-notification/src/client/service/turn-end.test.ts
@@ -0,0 +1,33 @@
+import { afterEach, describe, expect, it, vi } from 'vitest'
+import { getTurnEnd } from '../apis'
+import { turnEndedByUser } from './turn-end'
+
+vi.mock('../apis', () => ({ getTurnEnd: vi.fn() }))
+
+afterEach(() => {
+ vi.resetAllMocks()
+ vi.restoreAllMocks()
+})
+
+describe('turnEndedByUser', () => {
+ it.each(['aborted', 'interrupted', 'archived'])('宿主返回 %s 时抑制完成通知', async (reason) => {
+ vi.mocked(getTurnEnd).mockResolvedValue({ reason, turn: 4 })
+ expect(await turnEndedByUser('session')).toBe(true)
+ expect(getTurnEnd).toHaveBeenCalledExactlyOnceWith({ sessionId: 'session' })
+ })
+
+ it('宿主确认正常完成时保留完成通知', async () => {
+ vi.mocked(getTurnEnd).mockResolvedValue({ reason: 'completed', turn: 4 })
+ expect(await turnEndedByUser('session')).toBe(false)
+ })
+
+ it('空会话不请求宿主', async () => {
+ expect(await turnEndedByUser('')).toBe(false)
+ expect(getTurnEnd).not.toHaveBeenCalled()
+ })
+
+ it('宿主请求失败时保留原有通知退级', async () => {
+ vi.mocked(getTurnEnd).mockRejectedValue(new Error('offline'))
+ expect(await turnEndedByUser('session')).toBe(false)
+ })
+})
diff --git a/packages/dsh-tauri-notification/src/client/service/turn-end.ts b/packages/dsh-tauri-notification/src/client/service/turn-end.ts
index e5ff7bca..7dd0698a 100644
--- a/packages/dsh-tauri-notification/src/client/service/turn-end.ts
+++ b/packages/dsh-tauri-notification/src/client/service/turn-end.ts
@@ -6,7 +6,7 @@ import { getTurnEnd } from '../apis'
* 内核把手动中断标成 `aborted`(`completed` 才是正常跑完);`interrupted` 是同类语义的
* 历史别名,一并认掉:两者都不该弹「回合完成」通知。
*/
-const USER_INTERRUPT_REASONS: ReadonlySet<string> = new Set(['aborted', 'interrupted'])
+const USER_INTERRUPT_REASONS: ReadonlySet<string> = new Set(['aborted', 'interrupted', 'archived'])
/**
* 这个会话最近一次回合是不是被用户手动中断的。
diff --git a/packages/dsh-tauri-notification/src/host/events/session-event.test.ts b/packages/dsh-tauri-notification/src/host/events/session-event.test.ts
index 97252487..4263754e 100644
--- a/packages/dsh-tauri-notification/src/host/events/session-event.test.ts
+++ b/packages/dsh-tauri-notification/src/host/events/session-event.test.ts
@@ -1,10 +1,22 @@
-import { beforeEach, describe, expect, it } from 'vitest'
+import type { Context } from '@deepseek-ai/cordis'
+import { afterEach, beforeEach, describe, expect, it } from 'vitest'
+import { server } from '../server'
import { clearTurnEndFacts, turnEndFact } from '../service/turn-end'
import { handleSessionEvent } from './session-event'
describe('handleSessionEvent', () => {
+ let disposeServer: () => void
beforeEach(() => {
clearTurnEndFacts()
+ disposeServer = server({
+ workspaceRegistry: { archivedSessionIds: [] },
+ webServer: { register: () => () => {} },
+ } as unknown as Context)
+ })
+
+ afterEach(() => {
+ disposeServer()
+ clearTurnEndFacts()
})
it('记下 turn/end 的结束原因与回合号', () => {
diff --git a/packages/dsh-tauri-notification/src/host/server/index.test.ts b/packages/dsh-tauri-notification/src/host/server/index.test.ts
index 025bea30..552d79f3 100644
--- a/packages/dsh-tauri-notification/src/host/server/index.test.ts
+++ b/packages/dsh-tauri-notification/src/host/server/index.test.ts
@@ -17,7 +17,9 @@ afterEach(() => {
it('serves turn-end facts and preserves HEAD, allowed methods and disposal', async () => {
const registered = new Map<string, WebRoute>()
+ const workspaceRegistry = { archivedSessionIds: [] as string[] }
const unmount = server({
+ workspaceRegistry,
webServer: {
register(route: WebRoute) {
registered.set(route.path, route)
@@ -43,6 +45,12 @@ it('serves turn-end facts and preserves HEAD, allowed methods and disposal', asy
expect(await (await fetch(base)).json()).toEqual({})
handleSessionEvent({ id: 'session' }, { type: 'turn/end', data: { turn: 3, reason: { kind: 'aborted' } } })
expect(await (await fetch(`${base}?sessionId=session`)).json()).toEqual({ reason: 'aborted', turn: 3 })
+ handleSessionEvent({ id: 'session' }, { type: 'turn/end', data: { turn: 4, reason: { kind: 'completed' } } })
+ workspaceRegistry.archivedSessionIds = ['session', 'without-fact']
+ expect(await (await fetch(`${base}?sessionId=session`)).json()).toEqual({ reason: 'archived', turn: 4 })
+ expect(await (await fetch(`${base}?sessionId=without-fact`)).json()).toEqual({ reason: 'archived', turn: -1 })
+ workspaceRegistry.archivedSessionIds = []
+ expect(await (await fetch(`${base}?sessionId=session`)).json()).toEqual({ reason: 'completed', turn: 4 })
const head = await fetch(base, { method: 'HEAD' })
expect(head.status).toBe(200)
expect(await head.text()).toBe('')
diff --git a/packages/dsh-tauri-notification/src/host/service/turn-end.ts b/packages/dsh-tauri-notification/src/host/service/turn-end.ts
index 1814b386..170579a4 100644
--- a/packages/dsh-tauri-notification/src/host/service/turn-end.ts
+++ b/packages/dsh-tauri-notification/src/host/service/turn-end.ts
@@ -1,3 +1,7 @@
+import type { HostContext } from 'dsh-tauri'
+import { getServerContext } from 'dsh-h3/utils'
+import { server } from '../server'
+
/** 单个会话最近一次 `turn/end` 的结束事实。 */
export interface TurnEndFact {
/** `turn/end` 的 `reason.kind`,例如 `completed` / `aborted`。 */
@@ -14,6 +18,9 @@ export function recordTurnEnd(sessionId: string, fact: TurnEndFact): void {
}
export function turnEndFact(sessionId: string): TurnEndFact | undefined {
+ const archivedSessionIds: readonly string[] | undefined = getServerContext<HostContext>(server).workspaceRegistry?.archivedSessionIds
+ if (archivedSessionIds?.includes(sessionId))
+ return { reason: 'archived', turn: facts.get(sessionId)?.turn ?? -1 }
return facts.get(sessionId)
}
diff --git a/packages/dsh-tauri-notification/src/index.ts b/packages/dsh-tauri-notification/src/index.ts
index 0d83ae05..d3fec771 100644
--- a/packages/dsh-tauri-notification/src/index.ts
+++ b/packages/dsh-tauri-notification/src/index.ts
@@ -2,8 +2,8 @@ import { PLUGIN_ID } from './shared/constants'
export const name = PLUGIN_ID
-/** 宿主服务依赖:`webServer`(注册路由)与 `connection`(路由鉴权闸门,注册期必需)。 */
-export const inject = ['webServer', 'connection']
+/** 宿主服务依赖:`webServer`(注册路由)、`connection`(路由鉴权闸门,注册期必需)与 `workspaceRegistry`(判定会话是否已归档)。 */
+export const inject = ['webServer', 'connection', 'workspaceRegistry']
/**
* 宿主半边只负责回答一个问题:这个会话的回合为什么结束。
diff --git a/packages/dsh-tauri-pet/src/host/server/index.test.ts b/packages/dsh-tauri-pet/src/host/server/index.test.ts
index 9bcfddde..c49b26e6 100644
--- a/packages/dsh-tauri-pet/src/host/server/index.test.ts
+++ b/packages/dsh-tauri-pet/src/host/server/index.test.ts
@@ -67,6 +67,11 @@ interface FakeHost {
listenerCount: (name: string) => number
emitEvent: (session: unknown, event: unknown) => void
emitDisposed: (session: unknown) => void
+ workspaceRegistry: { archivedSessionIds: readonly string[] }
+ emitStop: (sessionId: string) => void
+ emitStatus: (session: unknown, status: string) => void
+ /** 发一次存储域变更广播(归档集合变化的来源)。 */
+ emitDomainChange: () => void
/** 发一帧 agent-scoped 活体助手流帧(`agent/assistant-stream` 的 chunk 帧)。 */
emitAssistantStream: (session: unknown, chunk: unknown) => void
/** 启动真实 http server 并接入一个 SSE 消费者。 */
@@ -117,7 +122,9 @@ function createHost(options: FakeHostOptions = {}): FakeHost {
let lookups = 0
let nodeHandler: ((request: IncomingMessage, response: ServerResponse) => void) | undefined
+ const workspaceRegistry = { archivedSessionIds: [] as readonly string[] }
const ctx = {
+ workspaceRegistry,
get: (name: string) => {
if (name === 'sessionTitle' && options.titleService !== false) {
return {
@@ -162,6 +169,19 @@ function createHost(options: FakeHostOptions = {}): FakeHost {
const host: FakeHost = {
ctx,
routes,
+ workspaceRegistry,
+ emitStop: (sessionId) => {
+ for (const handler of listeners.get('workspace/session-stop') ?? [])
+ handler({ sessionId })
+ },
+ emitStatus: (session, status) => {
+ for (const handler of listeners.get('agent/status') ?? [])
+ handler({ agent: { session }, status })
+ },
+ emitDomainChange: () => {
+ for (const handler of listeners.get('domain/changed') ?? [])
+ handler()
+ },
titleLookups: () => lookups,
listenerCount: name => listeners.get(name)?.size ?? 0,
emitEvent: (session, event) => {
@@ -261,6 +281,134 @@ afterEach(async () => {
})
describe('pet host apply()', () => {
+ it.each(['stop', 'completed', 'error', 'idle', 'stream'])('归档后 %s 先到也只移除气泡,旧事件不得重建且取消归档后正常完成', async (first) => {
+ const host = createHost()
+ apply(host.ctx)
+ const connection = await host.connect()
+ const session = { id: 'archived' }
+ host.emitEvent(session, { type: 'turn/start', seq: 0, time: 0, data: {} })
+ host.emitAssistantStream(session, { type: 'reasoning-delta', text: '归档前思考' })
+ await connection.waitFor(
+ () => connection.payloads.find(frame => (frame.payload.liveActivity as { text?: string } | undefined)?.text === '归档前思考'),
+ '归档前活体帧',
+ )
+ const before = connection.payloads.length
+ host.workspaceRegistry.archivedSessionIds = [session.id]
+ const end = (kind: string) => host.emitEvent(session, {
+ type: 'turn/end',
+ seq: 1,
+ time: 1,
+ data: { reason: { kind, error: { message: '过期错误' } } },
+ })
+ if (first === 'stop')
+ host.emitStop(session.id)
+ else if (first === 'idle')
+ host.emitStatus(session, 'idle')
+ else if (first === 'stream')
+ host.emitAssistantStream(session, { type: 'reasoning-delta', text: '过期思考' })
+ else
+ end(first)
+ await connection.waitFor(
+ () => connection.payloads.find(frame => frame.action === 'remove' && frame.payload.id === session.id),
+ '归档立即移除',
+ )
+ host.emitStop(session.id)
+ end('completed')
+ end('error')
+ host.emitStatus(session, 'idle')
+ host.emitAssistantStream(session, { type: 'reasoning-delta', text: '残留思考' })
+ host.emitAssistantStream(session, { type: 'text-delta', text: '残留正文' })
+ host.emitEvent(session, { type: 'turn/start', seq: 2, time: 2, data: {} })
+ host.emitEvent({ id: 'barrier' }, { type: 'turn/start', seq: 0, time: 0, data: {} })
+ await connection.waitFor(
+ () => connection.payloads.find(frame => frame.payload.id === 'barrier' && frame.payload.workStatus === 'thinking'),
+ '旧事件处理完毕',
+ )
+ expect(connection.payloads.slice(before).filter(frame => frame.payload.id === session.id)).toEqual([
+ { action: 'remove', payload: { id: session.id } },
+ ])
+ expect(host.titleLookups()).toBe(2)
+
+ host.workspaceRegistry.archivedSessionIds = []
+ host.emitEvent(session, { type: 'turn/start', seq: 3, time: 3, data: {} })
+ end('completed')
+ await connection.waitFor(
+ () => connection.payloads.find(frame => frame.payload.id === session.id && frame.payload.workStatus === 'success'),
+ '取消归档后正常成功',
+ )
+ const restored = connection.payloads.slice(before).filter(frame => frame.payload.id === session.id)
+ expect(restored.map(frame => [frame.action, frame.payload.workStatus])).toEqual([
+ ['remove', undefined],
+ ['create', undefined],
+ ['update', 'thinking'],
+ ['update', 'success'],
+ ])
+ expect(restored.at(-1)?.payload).toMatchObject({ running: false })
+ expect(restored.at(-1)?.payload.message).toBeUndefined()
+ expect(restored.at(-1)?.payload.liveActivity).toBeUndefined()
+ expect(host.titleLookups()).toBe(3)
+ })
+
+ it('接入前已归档的会话在事件和活体流入口均不建档或折叠标题', async () => {
+ const host = createHost()
+ host.workspaceRegistry.archivedSessionIds = ['archived']
+ apply(host.ctx)
+ const connection = await host.connect()
+ host.emitEvent({ id: 'archived' }, { type: 'turn/start', seq: 0, time: 0, data: {} })
+ host.emitAssistantStream({ id: 'archived' }, { type: 'reasoning-delta', text: '旧帧' })
+ host.emitStatus({ id: 'archived' }, 'idle')
+ host.emitStop('archived')
+ host.emitEvent({ id: 'barrier' }, { type: 'turn/start', seq: 0, time: 0, data: {} })
+ await connection.waitFor(
+ () => connection.payloads.find(frame => frame.payload.id === 'barrier' && frame.payload.workStatus === 'thinking'),
+ '归档事件处理完毕',
+ )
+ expect(connection.payloads.map(frame => frame.payload.id)).toEqual(['barrier', 'barrier'])
+ expect(host.titleLookups()).toBe(1)
+ })
+
+ it('归档广播到达即移除气泡,不需要该会话再产生事件', async () => {
+ const host = createHost()
+ apply(host.ctx)
+ const connection = await host.connect()
+ const session = { id: 'archived' }
+ host.emitEvent(session, { type: 'turn/start', seq: 0, time: 0, data: {} })
+ host.emitEvent(session, { type: 'turn/end', seq: 1, time: 1, data: { reason: { kind: 'completed' } } })
+ await connection.waitFor(
+ () => connection.payloads.find(frame => frame.payload.id === session.id && frame.payload.workStatus === 'success'),
+ '归档前成功态',
+ )
+
+ host.workspaceRegistry.archivedSessionIds = [session.id]
+ host.emitDomainChange()
+ await connection.waitFor(
+ () => connection.payloads.find(frame => frame.action === 'remove' && frame.payload.id === session.id),
+ '归档广播后移除',
+ )
+ })
+
+ it.each(['completed', 'error'])('未归档会话保留 %s 终态,不被 idle 清除', async (kind) => {
+ const host = createHost()
+ apply(host.ctx)
+ const connection = await host.connect()
+ const session = { id: 'normal' }
+ host.emitEvent(session, { type: 'turn/start', seq: 0, time: 0, data: {} })
+ host.emitEvent(session, { type: 'turn/end', seq: 1, time: 1, data: { reason: { kind, error: { message: '真实错误' } } } })
+ host.emitStatus(session, 'idle')
+ host.emitEvent({ id: 'barrier' }, { type: 'turn/start', seq: 0, time: 0, data: {} })
+ await connection.waitFor(
+ () => connection.payloads.find(frame => frame.payload.id === 'barrier' && frame.payload.workStatus === 'thinking'),
+ '普通终态处理完毕',
+ )
+ const frames = connection.payloads.filter(frame => frame.payload.id === session.id)
+ expect(frames.map(frame => [frame.action, frame.payload.workStatus])).toEqual([
+ ['create', undefined],
+ ['update', 'thinking'],
+ ['update', kind === 'completed' ? 'success' : 'error'],
+ ])
+ expect(frames.at(-1)?.payload.lastAgentError).toBe(kind === 'error' ? '真实错误' : undefined)
+ })
+
it('会话流只声明 GET,POST 与 OPTIONS 返回原生 405 和 GET/HEAD 方法集合', async () => {
const host = createHost()
apply(host.ctx)
@@ -298,6 +446,9 @@ describe('pet host apply()', () => {
apply(host.ctx)
expect(host.listenerCount('session/event')).toBe(0)
expect(host.listenerCount('session/disposed')).toBe(0)
+ expect(host.listenerCount('workspace/session-stop')).toBe(0)
+ expect(host.listenerCount('agent/status')).toBe(0)
+ expect(host.listenerCount('agent/assistant-stream')).toBe(0)
host.emitEvent({ id: 's1' }, chunk(0))
expect(host.titleLookups()).toBe(0)
@@ -308,6 +459,8 @@ describe('pet host apply()', () => {
apply(host.ctx)
await host.connect()
expect(host.listenerCount('session/event')).toBe(1)
+ expect(host.listenerCount('workspace/session-stop')).toBe(1)
+ expect(host.listenerCount('agent/status')).toBe(1)
const session = { id: 's1' }
for (let seq = 0; seq < 500; seq++)
@@ -335,6 +488,8 @@ describe('pet host apply()', () => {
await waitUntil(() => host.listenerCount('session/event') === 0, '断开后注销监听')
expect(host.listenerCount('session/disposed')).toBe(0)
expect(host.listenerCount('agent/assistant-stream')).toBe(0)
+ expect(host.listenerCount('workspace/session-stop')).toBe(0)
+ expect(host.listenerCount('agent/status')).toBe(0)
// 断开期间的会话事件不再产生任何工作(也不读标题)。
host.emitEvent(session, chunk(1))
diff --git a/packages/dsh-tauri-pet/src/host/service/session-stream.ts b/packages/dsh-tauri-pet/src/host/service/session-stream.ts
index 96525746..ed45b9b4 100644
--- a/packages/dsh-tauri-pet/src/host/service/session-stream.ts
+++ b/packages/dsh-tauri-pet/src/host/service/session-stream.ts
@@ -1,7 +1,8 @@
+import type { HostContext } from 'dsh-tauri'
import type { PetSessionPayload, SessionStreamSink } from '../types'
import type { PetSessionEvent, PetSessionPeer, ProjectionRegistryLike, TitleServiceLike } from './session-stream.types'
import { getServerContext } from 'dsh-h3/utils'
-import { defineService } from 'dsh-tauri'
+import { defineService, watchArchive } from 'dsh-tauri'
import {
closeSessionBus,
isSessionBusAttached,
@@ -69,7 +70,7 @@ function attachSessionBus(): void {
if (isSessionBusAttached())
return
// 惰性解析:apply 时服务未必就绪(装配顺序不保证),首个消费者接入时才读。
- const ctx = getServerContext(server)
+ const ctx = getServerContext<HostContext>(server)
titleService = ctx.get?.('sessionTitle') as TitleServiceLike | undefined
projections = ctx.get?.('sessionProjections') as ProjectionRegistryLike | undefined
const disposeEvent = ctx.on('session/event', handleSessionEvent) as () => void
@@ -78,11 +79,19 @@ function attachSessionBus(): void {
const disposeStatus = ctx.on('agent/status', handleAgentStatus) as () => void
// 活体流式帧:0.1.6 起流式增量只在这条 agent-scoped 通知上,是「思考 · …」的唯一来源。
const disposeFrame = ctx.on('agent/assistant-stream', handleAssistantStream) as () => void
+ const disposeStop = ctx.on('workspace/session-stop', ({ sessionId }) => removeKnownSession(sessionId)) as () => void
+ // 归档集合变化:归档后的会话不再产生任何事件,只能靠这条信号把气泡摘掉。
+ const disposeArchive = watchArchive(ctx, (archived) => {
+ for (const id of archived)
+ removeKnownSession(id)
+ })
setSessionBusDispose(() => {
disposeEvent()
disposeDisposed()
disposeStatus()
disposeFrame()
+ disposeStop()
+ disposeArchive()
titleService = undefined
projections = undefined
})
@@ -173,10 +182,23 @@ function titleOnFirstSight(session: unknown): string | undefined {
return projectedTitleOf(session) ?? titleService?.get?.(session)?.title
}
+function removeKnownSession(id: string): void {
+ if (knownSessions.delete(id))
+ reducer.remove(id)
+}
+
+function removeIfArchived(id: string): boolean {
+ const archivedSessionIds: readonly string[] | undefined = getServerContext<HostContext>(server).workspaceRegistry?.archivedSessionIds
+ if (!archivedSessionIds?.includes(id))
+ return false
+ removeKnownSession(id)
+ return true
+}
+
function handleSessionEvent(session: unknown, event: unknown): void {
const petEvent = asPetEvent(event)
const id = sessionIdOf(session, petEvent)
- if (!id)
+ if (!id || removeIfArchived(id))
return
const firstSight = !knownSessions.has(id)
if (firstSight)
@@ -205,12 +227,11 @@ function handleSessionDisposed(session: unknown): void {
*/
function handleAgentStatus(payload: unknown): void {
const event = payload as { status?: unknown, agent?: { session?: { id?: unknown } } } | undefined
- if (event?.status !== 'idle')
+ const id = event?.agent?.session?.id
+ if (typeof id !== 'string' || id.length === 0 || removeIfArchived(id))
return
- const id = event.agent?.session?.id
- if (typeof id !== 'string' || id.length === 0)
- return
- reducer.idle(id)
+ if (event?.status === 'idle')
+ reducer.idle(id)
}
/** 帧路径的占位事件:只借它走同一套 id/peer 推导(流式帧本身不是会话事件)。 */
@@ -229,13 +250,13 @@ const FRAME_EVENT: PetSessionEvent = { type: '', seq: 0, time: 0, data: {} }
*/
function handleAssistantStream(payload: unknown): void {
const event = payload as { agent?: { session?: unknown }, frame?: { type?: unknown, chunk?: unknown } } | undefined
+ const session = event?.agent?.session
+ const id = sessionIdOf(session, FRAME_EVENT)
+ if (!id || removeIfArchived(id))
+ return
const chunk = event?.frame?.chunk
if (event?.frame?.type !== 'chunk' || chunk === undefined || chunk === null)
return
- const session = event.agent?.session
- const id = sessionIdOf(session, FRAME_EVENT)
- if (!id)
- return
// 首次出现的会话在这里建档(带上 origin/title 身份,子代理仍然只靠 origin 静默);
// 已建档的热路径只传 id —— 逐 token 帧不得再走 peerOf(投影标题解析)。
if (!knownSessions.has(id)) {
diff --git a/packages/dsh-tauri-pet/src/index.ts b/packages/dsh-tauri-pet/src/index.ts
index 6ffbca99..e42e93da 100644
--- a/packages/dsh-tauri-pet/src/index.ts
+++ b/packages/dsh-tauri-pet/src/index.ts
@@ -2,8 +2,8 @@ import { PLUGIN_ID } from './shared/constants'
export const name = PLUGIN_ID
-/** 需要的宿主服务:webServer(SSE 路由)、sessions(session/event 总线)、connection(路由工具的连接信任边界)。 */
-export const inject = ['webServer', 'sessions', 'connection']
+/** 需要的宿主服务:webServer(SSE 路由)、sessions(session/event 总线)、connection(路由工具的连接信任边界)、workspaceRegistry(归档集合)。 */
+export const inject = ['webServer', 'sessions', 'connection', 'workspaceRegistry']
export { apply } from './host/apply'
diff --git a/packages/dsh-tauri/src/index.ts b/packages/dsh-tauri/src/index.ts
index 874902cc..676eecfb 100644
--- a/packages/dsh-tauri/src/index.ts
+++ b/packages/dsh-tauri/src/index.ts
@@ -8,6 +8,7 @@ export const inject = ['connection', 'webServer', 'workspaceRegistry']
export { apply } from './host/apply'
export * from './host/config/constants'
export * from './host/service'
+export { watchArchive } from './host/service/archive'
export * from './host/service/request'
export * from './host/types/harness'
export * from './host/utils/atomic'
diff --git a/src/pet/hooks/use-bubble-tracker.test.ts b/src/pet/hooks/use-bubble-tracker.test.ts
index b9c66897..a55cddc8 100644
--- a/src/pet/hooks/use-bubble-tracker.test.ts
+++ b/src/pet/hooks/use-bubble-tracker.test.ts
@@ -212,6 +212,23 @@ describe('createBubbleTracker', () => {
])
})
+ it.each([
+ { status: 'running' },
+ { workStatus: 'thinking' },
+ { workStatus: 'working' },
+ { workStatus: 'waiting' },
+ ])('silently removes an active bubble without a terminal notification: %j', (activity) => {
+ const { bubble, calls } = createFakeBubble()
+ const tracker = createBubbleTracker(bubble)
+ tracker.apply({ id: 's1', title: '会话一', ...activity }, 'create')
+ calls.length = 0
+
+ tracker.apply({ id: 's1' }, 'remove')
+ tracker.flush()
+
+ expect(calls).toEqual([{ type: 'close', id: 's1' }])
+ })
+
it('shows a terminal motion only once until the session leaves it', () => {
const { bubble, calls } = createFakeBubble()
const tracker = createBubbleTracker(bubble)