Skip to content

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

feat(kernel): 只读映射原生计划、子代理与后台任务 (#1066)

Hairy282e176f0dbe
diff --git a/packages/dsh-tauri-kernel/src/client/components/native-activity.test.tsx b/packages/dsh-tauri-kernel/src/client/components/native-activity.test.tsx
new file mode 100644
index 00000000..30e2f749
--- /dev/null
+++ b/packages/dsh-tauri-kernel/src/client/components/native-activity.test.tsx
@@ -0,0 +1,68 @@
+// @vitest-environment jsdom
+import type { NativeActivityState } from '../../shared/activity'
+import type { KernelBinding } from '../../shared/types'
+import type { NativeActivityProps } from './native-activity'
+import { cleanup, render } from '@testing-library/react'
+import { useRef } from 'react'
+import { afterEach, describe, expect, it, vi } from 'vitest'
+import { NativeActivity } from './native-activity'
+
+vi.mock('../locales', () => ({ locale: { useLocale: () => {}, text: (key: string) => key } }))
+afterEach(() => {
+ cleanup()
+ vi.restoreAllMocks()
+})
+
+const BINDING: KernelBinding = { sessionId: 'session-a', nativeSessionId: 'native-a', backend: 'codex' }
+const ACTIVITY: NativeActivityState = {
+ plan: { steps: [{ content: 'Inspect contracts', status: 'completed' }], explanation: 'Native explanation' },
+ subagents: [{ id: 'native-child', label: '<script>not markup</script>', status: 'waiting_remote', details: 'Native details', parentId: 'native-a' }],
+ jobs: [{ id: 'native-job' }],
+ unavailable: { plan: null, subagents: null, jobs: 'not-exposed' },
+}
+
+function props(binding: KernelBinding | null | undefined, activity?: NativeActivityState): NativeActivityProps {
+ return { sessionId: 'session-a', useProjection(key: string) {
+ useRef(null)
+ return key === 'bridgeKernel' ? binding : activity
+ } } as unknown as NativeActivityProps
+}
+
+describe('native activity dock', () => {
+ it('renders native statuses verbatim with unknown fallback and no execution controls', () => {
+ const view = render(<NativeActivity {...props(BINDING, ACTIVITY)} />)
+ expect(view.getByText('Inspect contracts — activity.completed')).toBeTruthy()
+ expect(view.getByText('<script>not markup</script> — waiting_remote')).toBeTruthy()
+ expect(view.getByText('native-job — activity.unknown')).toBeTruthy()
+ expect(view.getByText('Native explanation')).toBeTruthy()
+ expect(view.getByText('Native details')).toBeTruthy()
+ expect(view.container.querySelector('script')).toBeNull()
+ expect(view.queryAllByRole('button')).toHaveLength(0)
+ expect(view.queryAllByRole('link')).toHaveLength(0)
+ expect(view.getAllByRole('status').map(node => node.textContent)).toEqual(['activity.unavailable'])
+ })
+
+ it('updates native status from new projection values while preserving partial-list notices', () => {
+ const view = render(<NativeActivity {...props(BINDING, ACTIVITY)} />)
+ view.rerender(<NativeActivity {...props(BINDING, { ...ACTIVITY, subagents: [{ id: 'native-child', status: 'completed' }], unavailable: { ...ACTIVITY.unavailable, subagents: 'partial' } })} />)
+ expect(view.getByText('native-child — completed')).toBeTruthy()
+ expect(view.queryByText('<script>not markup</script> — waiting_remote')).toBeNull()
+ expect(view.getAllByRole('status').map(node => node.textContent)).toEqual(['activity.partial', 'activity.unavailable'])
+ })
+
+ it('does not leak prior native state into official, unknown or forked sessions', () => {
+ const view = render(<NativeActivity {...props(BINDING, ACTIVITY)} />)
+ for (const binding of [null, undefined, { ...BINDING, sessionId: 'parent-session' }]) {
+ view.rerender(<NativeActivity {...props(binding, ACTIVITY)} />)
+ expect(view.container.innerHTML).toBe('')
+ }
+ })
+
+ it('distinguishes missing capability, parse failure and observed empty lists', () => {
+ const view = render(<NativeActivity {...props(BINDING)} />)
+ expect(view.getByRole('status').textContent).toBe('activity.unavailable')
+ view.rerender(<NativeActivity {...props(BINDING, { plan: null, subagents: [], jobs: [], unavailable: { plan: 'mapping-failed', subagents: null, jobs: null } })} />)
+ expect(view.getAllByRole('status').map(node => node.textContent)).toEqual(['activity.mappingFailed'])
+ expect(view.getAllByText('activity.empty')).toHaveLength(3)
+ })
+})
diff --git a/packages/dsh-tauri-kernel/src/client/components/native-activity.tsx b/packages/dsh-tauri-kernel/src/client/components/native-activity.tsx
new file mode 100644
index 00000000..9e2e05ec
--- /dev/null
+++ b/packages/dsh-tauri-kernel/src/client/components/native-activity.tsx
@@ -0,0 +1,66 @@
+import type { PropsRuntime } from '@deepseek-ai/dsh-client-ui-slots'
+import type { NativeActivityItem, NativeActivityState } from '../../shared/activity'
+import type {} from './slot-contract'
+import { locale } from '../locales'
+import { backendFromIdentity, isForkedIdentity } from '../service/kernel-identity'
+
+export type NativeActivityProps = PropsRuntime<'conversation.input.dock'>
+
+export function NativeActivity(props: NativeActivityProps) {
+ locale.useLocale()
+ const binding = props.useProjection('bridgeKernel')
+ const activity = props.useProjection('bridgeActivity')
+ const backend = backendFromIdentity(binding)
+ if (backend === undefined || backend === 'dsh' || isForkedIdentity(binding, props.sessionId))
+ return null
+ return (
+ <section aria-label={locale.text('activity.title')} data-dsh-native-activity={props.sessionId} className="w-full text-secondary">
+ <p>{locale.text('activity.readOnly')}</p>
+ {activity === undefined ? <p role="status">{locale.text('activity.unavailable')}</p> : <ActivityContent activity={activity} />}
+ </section>
+ )
+}
+
+function ActivityContent({ activity }: { activity: NativeActivityState }) {
+ const sections = ['subagents', 'jobs'] as const
+ return (
+ <>
+ <details>
+ <summary>{locale.text('activity.plan')}</summary>
+ {activity.unavailable.plan !== null ? <Unavailable reason={activity.unavailable.plan} /> : null}
+ {activity.plan?.explanation ? <p>{activity.plan.explanation}</p> : null}
+ {activity.plan === null || activity.plan.steps.length === 0
+ ? <p>{locale.text('activity.empty')}</p>
+ : (
+ <ol>
+ {activity.plan.steps.map((step, index) => <li key={`${index}:${step.content}`}>{`${step.content} — ${locale.text(`activity.${step.status}`)}`}</li>)}
+ </ol>
+ )}
+ </details>
+ {sections.map(section => (
+ <details key={section}>
+ <summary>{`${locale.text(`activity.${section}`)} (${activity[section].length})`}</summary>
+ {activity.unavailable[section] !== null ? <Unavailable reason={activity.unavailable[section]} /> : null}
+ {activity[section].length === 0
+ ? <p>{locale.text('activity.empty')}</p>
+ : <ul>{activity[section].map(item => <ActivityItem key={item.id} item={item} />)}</ul>}
+ </details>
+ ))}
+ </>
+ )
+}
+
+function Unavailable({ reason }: { reason: string }) {
+ const key = reason === 'partial' ? 'activity.partial' : reason === 'mapping-failed' ? 'activity.mappingFailed' : 'activity.unavailable'
+ return <p role="status">{locale.text(key)}</p>
+}
+
+function ActivityItem({ item }: { item: NativeActivityItem }) {
+ return (
+ <li>
+ <span>{`${item.label ?? item.id} — ${item.status ?? locale.text('activity.unknown')}`}</span>
+ {item.parentId ? <p>{`${locale.text('activity.parent')}: ${item.parentId}`}</p> : null}
+ {item.details ? <p className="whitespace-pre-wrap">{item.details}</p> : null}
+ </li>
+ )
+}
diff --git a/packages/dsh-tauri-kernel/src/client/index.ts b/packages/dsh-tauri-kernel/src/client/index.ts
index f8366cae..83608786 100644
--- a/packages/dsh-tauri-kernel/src/client/index.ts
+++ b/packages/dsh-tauri-kernel/src/client/index.ts
@@ -2,6 +2,7 @@ import type { ClientContext } from 'dsh-tauri/client'
import { PLUGIN_ID } from '../shared/constants'
import { locale } from './locales'
import { kernel } from './register/kernel'
+import { nativeActivity } from './register/native-activity'
export const name = PLUGIN_ID
export const inject = ['slots', 'locale', 'sessions', 'uiWorkspace', 'layout']
@@ -9,4 +10,5 @@ export const inject = ['slots', 'locale', 'sessions', 'uiWorkspace', 'layout']
export function apply(ctx: ClientContext): void {
ctx.effect(locale.registerLocale, `${PLUGIN_ID}: locale`)
ctx.effect(kernel, `${PLUGIN_ID}: kernel`)
+ ctx.effect(nativeActivity, `${PLUGIN_ID}: native activity`)
}
diff --git a/packages/dsh-tauri-kernel/src/client/locales/index.ts b/packages/dsh-tauri-kernel/src/client/locales/index.ts
index a57f8929..56fb2fac 100644
--- a/packages/dsh-tauri-kernel/src/client/locales/index.ts
+++ b/packages/dsh-tauri-kernel/src/client/locales/index.ts
@@ -3,6 +3,20 @@ import { PLUGIN_ID } from '../../shared/constants'
export const locale = defineLocale(PLUGIN_ID, {
zh: {
+ 'activity.title': '原生活动',
+ 'activity.readOnly': '仅展示原生内核状态,不支持在此控制执行。',
+ 'activity.plan': '计划',
+ 'activity.subagents': '子代理',
+ 'activity.jobs': '后台任务',
+ 'activity.unavailable': '不可用:原生内核尚未提供此状态。',
+ 'activity.mappingFailed': '不可用:无法解析原生内核状态。',
+ 'activity.partial': '仅显示原生内核已提供的部分记录,完整列表不可用。',
+ 'activity.empty': '暂无记录',
+ 'activity.unknown': '状态未知',
+ 'activity.parent': '父任务',
+ 'activity.pending': '待处理',
+ 'activity.in_progress': '进行中',
+ 'activity.completed': '已完成',
'kernel.label': '内核',
'kernel.pending': '正在读取会话内核',
'kernel.unavailable': '未安装',
@@ -25,6 +39,20 @@ export const locale = defineLocale(PLUGIN_ID, {
'kernel.clear': '清空内核选择',
},
en: {
+ 'activity.title': 'Native activity',
+ 'activity.readOnly': 'Read-only native state; execution controls are unavailable here.',
+ 'activity.plan': 'Plan',
+ 'activity.subagents': 'Subagents',
+ 'activity.jobs': 'Background tasks',
+ 'activity.unavailable': 'Unavailable: the native kernel has not exposed this state.',
+ 'activity.mappingFailed': 'Unavailable: native state could not be parsed.',
+ 'activity.partial': 'Only native-observed records are shown; the complete list is unavailable.',
+ 'activity.empty': 'No records',
+ 'activity.unknown': 'Unknown status',
+ 'activity.parent': 'Parent task',
+ 'activity.pending': 'Pending',
+ 'activity.in_progress': 'In progress',
+ 'activity.completed': 'Completed',
'kernel.label': 'Kernel',
'kernel.pending': 'Reading session kernel',
'kernel.unavailable': 'Not installed',
diff --git a/packages/dsh-tauri-kernel/src/client/register/native-activity.test.ts b/packages/dsh-tauri-kernel/src/client/register/native-activity.test.ts
new file mode 100644
index 00000000..0904c023
--- /dev/null
+++ b/packages/dsh-tauri-kernel/src/client/register/native-activity.test.ts
@@ -0,0 +1,32 @@
+import type {} from '@deepseek-ai/dsh-client-ui-conversation/client'
+import type { ClientContext } from 'dsh-tauri/client'
+import { SlotCore } from '@deepseek-ai/dsh-client-ui-slots'
+import { afterEach, describe, expect, it, vi } from 'vitest'
+import { nativeActivity } from './native-activity'
+
+vi.mock('dsh-tauri/client', async () => await import('../../../../dsh-tauri/src/client/register/index'))
+vi.mock('../components/native-activity', () => ({ NativeActivity: () => null }))
+afterEach(() => vi.restoreAllMocks())
+
+describe('native activity registration', () => {
+ it('adds to the existing session dock without replacing official entries and removes on unload', () => {
+ const core = new SlotCore()
+ core.register({ name: 'root', children: { 'conversation.input.dock': { kind: 'list', scope: 'session' } } }, (props: { renderSlot: unknown }) => {
+ void props.renderSlot
+ return null
+ })
+ core.register({ name: 'conversation.input.dock', id: 'official-todo' }, () => null)
+ const slots = { spec: core.spec.bind(core), register: core.register.bind(core), inject: (_key: string, setup: () => () => void) => setup() }
+ const dispose = nativeActivity.call({ get: (name: string) => name === 'slots' ? slots : undefined } as unknown as ClientContext)
+ expect(core.entries('conversation.input.dock').map(entry => entry.options.id)).toEqual(['official-todo', 'dsh-tauri-kernel:activity'])
+ dispose()
+ expect(core.entries('conversation.input.dock').map(entry => entry.options.id)).toEqual(['official-todo'])
+ })
+
+ it('warns explicitly when the official dock registration capability is absent', () => {
+ const warning = vi.spyOn(console, 'warn').mockImplementation(() => {})
+ const dispose = nativeActivity.call({ get: () => undefined } as unknown as ClientContext)
+ expect(warning).toHaveBeenCalledExactlyOnceWith('[dsh-tauri-kernel] native activity unavailable; official dock registration APIs are missing')
+ dispose()
+ })
+})
diff --git a/packages/dsh-tauri-kernel/src/client/register/native-activity.ts b/packages/dsh-tauri-kernel/src/client/register/native-activity.ts
new file mode 100644
index 00000000..2fb83c41
--- /dev/null
+++ b/packages/dsh-tauri-kernel/src/client/register/native-activity.ts
@@ -0,0 +1,22 @@
+import type { ClientContext, SlotRegistry } from 'dsh-tauri/client'
+import { defineRegister } from 'dsh-tauri/client'
+import { PLUGIN_ID } from '../../shared/constants'
+import { NativeActivity } from '../components/native-activity'
+
+const ACTIVITY_SLOT = 'conversation.input.dock'
+
+export const nativeActivity = defineRegister<ClientContext>((controller, _ctx, adapter) => {
+ const slots = adapter.service<SlotRegistry>('slots')
+ if (typeof slots?.inject !== 'function' || typeof slots.register !== 'function' || typeof slots.spec !== 'function') {
+ console.warn(`[${PLUGIN_ID}] native activity unavailable; official dock registration APIs are missing`)
+ return
+ }
+ controller.add(slots.inject(ACTIVITY_SLOT, () => {
+ const spec = slots.spec(ACTIVITY_SLOT)
+ if (spec?.kind !== 'list' || spec.scope !== 'session') {
+ console.warn(`[${PLUGIN_ID}] native activity unavailable; official dock contract differs`)
+ return () => {}
+ }
+ return slots.register({ name: ACTIVITY_SLOT, id: `${PLUGIN_ID}:activity`, registrant: PLUGIN_ID, order: 1 }, NativeActivity)
+ }))
+})
diff --git a/packages/dsh-tauri-kernel/src/host/apply.ts b/packages/dsh-tauri-kernel/src/host/apply.ts
index 5452315b..db8e6ed8 100644
--- a/packages/dsh-tauri-kernel/src/host/apply.ts
+++ b/packages/dsh-tauri-kernel/src/host/apply.ts
@@ -3,6 +3,7 @@ import type { HostContext } from './types'
import { PLUGIN_ID } from '../shared/constants'
import { runtime } from './config/runtime'
import { server } from './server'
+import { activity } from './service/activity'
import { adapter } from './service/adapter'
import { checkpoint } from './service/checkpoint'
import { identity } from './service/identity'
@@ -17,6 +18,7 @@ export function apply(ctx: HostContext, config: Config = {}): void {
yield () => session.dispose()
yield await identity.register()
yield await model.register()
+ yield await activity.register()
yield await checkpoint.register()
yield ctx.provide('nativeSessionBridge', { create: session.createInherited, prepare: session.prepare })
yield ctx.on('agent/pre-step', adapter.admit, { global: true, prepend: true })
diff --git a/packages/dsh-tauri-kernel/src/host/backends/claude.test.ts b/packages/dsh-tauri-kernel/src/host/backends/claude.test.ts
index 9f413607..b14021c6 100644
--- a/packages/dsh-tauri-kernel/src/host/backends/claude.test.ts
+++ b/packages/dsh-tauri-kernel/src/host/backends/claude.test.ts
@@ -801,6 +801,35 @@ describe('claude native stream-json control contract', () => {
expect(fixture.kill).not.toHaveBeenCalled()
})
+ it('preserves native execution when activity observation throws on background task events', async () => {
+ const fixture = claudeProcess()
+ const activity = vi.fn((_message: Frame) => {
+ throw new Error('activity projection failed')
+ })
+ const sink = Object.assign(createSink(), { activity })
+ const session = await open(null, sink)
+ activity.mockClear()
+ const snapshot = { type: 'system', subtype: 'background_tasks_changed', tasks: [{ task_id: 'observed-shell', task_type: 'local_bash', description: 'Inspect repository' }], uuid: 'observed-snapshot', session_id: session.id }
+ const before = [...fixture.frames]
+ fixture.send(snapshot)
+ expect(activity).toHaveBeenCalledExactlyOnceWith(snapshot)
+ expect(fixture.frames).toEqual(before)
+ const submitted = session.submit([user()], new AbortController().signal)
+ const frames = [...fixture.frames]
+ const started = { type: 'system', subtype: 'task_started', task_id: 'observed-shell', task_type: 'local_bash', description: 'Inspect repository', uuid: 'observed-start', session_id: session.id }
+ fixture.send(started)
+ fixture.send({ type: 'assistant', uuid: 'observed-tool-frame', session_id: session.id, message: { id: 'observed-message', content: [{ type: 'tool_use', id: 'observed-tool', name: 'Bash', input: { command: 'git status --short' } }] } })
+ fixture.send({ type: 'user', session_id: session.id, message: { role: 'user', content: [{ type: 'tool_result', tool_use_id: 'observed-tool', content: ' M fixture.ts\n', is_error: false }] } })
+ fixture.send({ type: 'system', subtype: 'task_notification', task_id: 'observed-shell', status: 'completed', output_file: 'C:/fixture/output', summary: 'Repository inspected', uuid: 'observed-complete', session_id: session.id })
+ result(fixture, session.id)
+ await submitted
+ expect(activity).toHaveBeenCalledWith(started)
+ expect(sink.toolStart.mock.calls).toEqual([['observed-tool', 'Bash', '{"command":"git status --short"}']])
+ expect(sink.toolEnd.mock.calls).toEqual([['observed-tool', ' M fixture.ts\n', false]])
+ expect(fixture.frames).toEqual(frames)
+ expect(fixture.kill).not.toHaveBeenCalled()
+ })
+
it('records one native tool call and error result without echoing native user messages', async () => {
const fixture = claudeProcess()
const sink = createSink()
diff --git a/packages/dsh-tauri-kernel/src/host/backends/claude.ts b/packages/dsh-tauri-kernel/src/host/backends/claude.ts
index f99d82a3..00037c3a 100644
--- a/packages/dsh-tauri-kernel/src/host/backends/claude.ts
+++ b/packages/dsh-tauri-kernel/src/host/backends/claude.ts
@@ -461,6 +461,12 @@ class ClaudeSession implements NativeSession {
this.startupModel ??= message.model
}
}
+ try {
+ this.sink.activity?.(message)
+ }
+ catch {
+ // Visibility must not affect native execution.
+ }
if (!run) {
if (type === 'assistant' || type === 'stream_event' || (type === 'system' && message.subtype === 'task_started'))
throw new NativeBridgeError('BRIDGE_UNEXPECTED_TURN', 'Claude produced work outside the official agent turn')
diff --git a/packages/dsh-tauri-kernel/src/host/backends/codex.test.ts b/packages/dsh-tauri-kernel/src/host/backends/codex.test.ts
index 9cb86697..f932274b 100644
--- a/packages/dsh-tauri-kernel/src/host/backends/codex.test.ts
+++ b/packages/dsh-tauri-kernel/src/host/backends/codex.test.ts
@@ -879,6 +879,35 @@ describe('codex native app-server contract', () => {
expect(sink.assistant.mock.calls).toEqual([['reasoning-2', [{ type: 'thinking', text: 'summary reasoning' }]]])
})
+ it('preserves native execution when activity observation throws on plan notifications', async () => {
+ const { fixture } = codexProcess()
+ const activity = vi.fn((_message: Frame) => {
+ throw new Error('activity projection failed')
+ })
+ const sink = Object.assign(createSink(), { activity })
+ const session = await open(null, sink)
+ const plan = { method: 'turn/plan/updated', params: { threadId: session.id, turnId: 'turn-1', explanation: null, plan: [{ step: 'Inspect repository', status: 'inProgress' }] } }
+ const before = [...fixture.frames]
+ fixture.send(plan)
+ expect(activity).toHaveBeenCalledWith(plan)
+ expect(fixture.frames).toEqual(before)
+ const started = fixture.next(frame => frame.method === 'turn/start')
+ const submitted = session.submit([user()], new AbortController().signal)
+ await started
+ const frames = [...fixture.frames]
+ fixture.send(plan)
+ const item = { id: 'observed-command', type: 'commandExecution', command: 'git status --short', cwd: 'C:/fixture/workspace', status: 'inProgress' }
+ notify(fixture, 'item/started', { item })
+ notify(fixture, 'item/completed', { item: { ...item, status: 'completed', aggregatedOutput: ' M fixture.ts\n', exitCode: 0 } })
+ completed(fixture)
+ await submitted
+ expect(activity.mock.calls.filter(([message]) => message.method === 'turn/plan/updated')).toHaveLength(2)
+ expect(sink.toolStart.mock.calls).toEqual([['observed-command', 'commandExecution', '{"command":"git status --short","cwd":"C:/fixture/workspace"}']])
+ expect(sink.toolEnd.mock.calls).toEqual([['observed-command', ' M fixture.ts\n', false]])
+ expect(fixture.frames).toEqual(frames)
+ expect(fixture.kill).not.toHaveBeenCalled()
+ })
+
it('preserves native tool ids and error results without executing DSH tools', async () => {
const { fixture } = codexProcess()
const sink = createSink()
diff --git a/packages/dsh-tauri-kernel/src/host/backends/codex.ts b/packages/dsh-tauri-kernel/src/host/backends/codex.ts
index 8c1b582e..d1d9676f 100644
--- a/packages/dsh-tauri-kernel/src/host/backends/codex.ts
+++ b/packages/dsh-tauri-kernel/src/host/backends/codex.ts
@@ -579,6 +579,14 @@ class CodexSession implements NativeSession {
})().catch(error => this.transport.fail(errorFrom(error)))
}
}
+ if (params.threadId === this.id) {
+ try {
+ this.sink.activity?.(message)
+ }
+ catch {
+ // Visibility must not affect native execution.
+ }
+ }
const turn = this.active
if (!turn || params.threadId !== this.id)
return
diff --git a/packages/dsh-tauri-kernel/src/host/backends/types.ts b/packages/dsh-tauri-kernel/src/host/backends/types.ts
index 7a24ac0c..68b592fb 100644
--- a/packages/dsh-tauri-kernel/src/host/backends/types.ts
+++ b/packages/dsh-tauri-kernel/src/host/backends/types.ts
@@ -54,6 +54,7 @@ export interface NativeQuestion {
}
export interface NativeSink {
+ activity?: (message: Record<string, unknown>) => void
text: (id: string, delta: string) => void
thinking: (id: string, delta: string) => void
assistant: (id: string, content: readonly NativeContent[]) => void
diff --git a/packages/dsh-tauri-kernel/src/host/config/runtime.ts b/packages/dsh-tauri-kernel/src/host/config/runtime.ts
index 08c3b72b..88c90c7d 100644
--- a/packages/dsh-tauri-kernel/src/host/config/runtime.ts
+++ b/packages/dsh-tauri-kernel/src/host/config/runtime.ts
@@ -1,10 +1,11 @@
import type { Agent } from '@deepseek-ai/dsh-agent'
import type { z } from 'zod'
+import type { NativeActivityState } from '../../shared/activity'
import type { NativeModelCatalog, NativeTurnOptions } from '../../shared/native-model'
import type { BackendDetection, KernelBinding } from '../../shared/types'
import type { NativeSink } from '../backends/types'
import type { OfficialSink } from '../service/sink.types'
-import type { AdmittedStep, BridgeRecordType, NativeEntry, NativePending, RecordWatermark } from '../types'
+import type { AdmittedStep, BridgeRecordType, NativeEntry, NativePending, RecordWatermark, RuntimeModules } from '../types'
export const runtime = {
detections: new Map<string, BackendDetection>(),
@@ -23,6 +24,9 @@ export const runtime = {
bindingSchema: undefined as z.ZodType<KernelBinding> | undefined,
optionsSchema: undefined as z.ZodType<NativeTurnOptions> | undefined,
catalogSchema: undefined as z.ZodType<NativeModelCatalog> | undefined,
+ activitySchema: undefined as z.ZodType<NativeActivityState> | undefined,
+ appendActivity: undefined as RuntimeModules['appendPluginRecord'],
+ activityPlans: new WeakMap<Agent, Map<string, NativeActivityState['plan']>>(),
ready: false,
lifetime: new AbortController(),
}
@@ -32,6 +36,9 @@ export async function resetRuntime(): Promise<void> {
runtime.bindingSchema = undefined
runtime.optionsSchema = undefined
runtime.catalogSchema = undefined
+ runtime.activitySchema = undefined
+ runtime.appendActivity = undefined
+ runtime.activityPlans = new WeakMap()
runtime.lifetime.abort(new Error('BRIDGE_DISPOSED'))
for (const controller of runtime.controllers.values())
controller.abort(new Error('BRIDGE_DISPOSED'))
diff --git a/packages/dsh-tauri-kernel/src/host/service/activity.test.ts b/packages/dsh-tauri-kernel/src/host/service/activity.test.ts
new file mode 100644
index 00000000..5b677d2c
--- /dev/null
+++ b/packages/dsh-tauri-kernel/src/host/service/activity.test.ts
@@ -0,0 +1,90 @@
+import type { Agent } from '@deepseek-ai/dsh-agent'
+import type { SessionEvent } from '@deepseek-ai/dsh-session'
+import type { NativeActivityState } from '../../shared/activity'
+import type { HostContext } from '../types'
+import { Context } from '@deepseek-ai/cordis'
+import { Session, SessionId, SessionLogOffset, SessionSeq } from '@deepseek-ai/dsh-session'
+import { SessionProjectionRegistry } from '@deepseek-ai/dsh-session-projection'
+import { getServerContext } from 'dsh-h3/utils'
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import * as zodModule from 'zod'
+import { resetRuntime, runtime } from '../config/runtime'
+import { activity } from './activity'
+
+vi.mock('dsh-h3/utils', () => ({ getServerContext: vi.fn() }))
+vi.mock('../server', () => ({ server: vi.fn() }))
+
+const STATE: NativeActivityState = {
+ plan: { steps: [{ content: 'Native step', status: 'in_progress' }] },
+ subagents: [{ id: 'native-child', status: 'waiting_remote' }],
+ jobs: [],
+ unavailable: { plan: null, subagents: 'partial', jobs: 'not-exposed' },
+}
+let context: Context
+let projections: SessionProjectionRegistry
+
+function event(value: NativeActivityState): SessionEvent {
+ return { type: 'plugin:dsh-tauri-kernel/activity', ignorable: true, seq: SessionSeq(0), time: 1000, data: value } as unknown as SessionEvent
+}
+
+beforeEach(async () => {
+ await resetRuntime()
+ runtime.lifetime = new AbortController()
+ context = new Context()
+ projections = new SessionProjectionRegistry(context)
+ context.provide('loader', { import: async () => zodModule, unwrapExports: (value: unknown) => value } as unknown as HostContext['loader'])
+ vi.mocked(getServerContext).mockReturnValue(context)
+})
+afterEach(async () => {
+ await context.fiber.dispose()
+ await resetRuntime()
+ vi.restoreAllMocks()
+})
+
+describe('native activity durable projection', () => {
+ it('restores full observed state through real checkpoint replay without adding model history', async () => {
+ await activity.register()
+ const session = Session.create(SessionId('session-a'), [event(STATE)])
+ expect(projections.snapshot(session).values.bridgeActivity).toEqual(STATE)
+ const checkpoint = JSON.parse(JSON.stringify(projections.checkpoint(session)))
+ const restored = projections.restore(checkpoint, [event(STATE)], SessionLogOffset(0), session.header, SessionLogOffset(0))
+ expect(restored.snapshot.values.bridgeActivity).toEqual(STATE)
+ expect(projections.viewCheckpoint(restored.checkpoint).bridgeActivity).toEqual(STATE)
+ expect(event(STATE).surfaceOp).toBeUndefined()
+ })
+
+ it('does not project a fork-inherited native activity record into the child session', async () => {
+ await activity.register()
+ const session = Session.create(SessionId('child'))
+ const restored = projections.restore({}, [event(STATE)], SessionLogOffset(0), { ...session.header, parentSession: SessionId('parent'), isSeeded: true }, SessionLogOffset(1))
+ expect(restored.snapshot.values.bridgeActivity).toEqual({ plan: null, subagents: [], jobs: [], unavailable: { plan: 'not-exposed', subagents: 'not-exposed', jobs: 'not-exposed' } })
+ })
+
+ it('keeps native execution alive when durable activity publication fails', async () => {
+ await activity.register()
+ const session = Session.create(SessionId('session-a'))
+ const agent = { id: session.id, session } as Agent
+ const controller = new AbortController()
+ runtime.controllers.set(agent.id, controller)
+ context.provide('agents', { get: () => agent } as unknown as HostContext['agents'])
+ context.provide('sessions', { get: () => session } as unknown as HostContext['sessions'])
+ runtime.appendActivity = vi.fn(() => {
+ throw new Error('STORAGE_UNAVAILABLE')
+ })
+ const warning = vi.spyOn(context.logger, 'warn').mockImplementation(() => {})
+ expect(() => activity.update(agent, controller, 'codex', { method: 'turn/plan/updated', params: { plan: [{ step: 'Native step', status: 'inProgress' }] } })).not.toThrow()
+ expect(runtime.appendActivity).toHaveBeenCalledTimes(2)
+ expect(controller.signal.aborted).toBe(false)
+ expect(projections.snapshot(session).values.bridgeActivity?.unavailable.plan).toBe('not-exposed')
+ expect(warning).toHaveBeenCalledTimes(2)
+ })
+
+ it('clears projection capability on unload instead of retaining stale observed state', async () => {
+ const dispose = await activity.register()
+ const session = Session.create(SessionId('session-a'), [event(STATE)])
+ expect(projections.snapshot(session).values.bridgeActivity).toEqual(STATE)
+ dispose()
+ expect(projections.snapshot(session).values).toEqual({})
+ expect(runtime.activitySchema).toBeUndefined()
+ })
+})
diff --git a/packages/dsh-tauri-kernel/src/host/service/activity.ts b/packages/dsh-tauri-kernel/src/host/service/activity.ts
new file mode 100644
index 00000000..84786250
--- /dev/null
+++ b/packages/dsh-tauri-kernel/src/host/service/activity.ts
@@ -0,0 +1,97 @@
+import type { Agent } from '@deepseek-ai/dsh-agent'
+import type { NativeActivityState } from '../../shared/activity'
+import type { KernelBinding } from '../../shared/types'
+import type { HostContext } from '../types'
+import { getServerContext } from 'dsh-h3/utils'
+import { defineService } from 'dsh-tauri'
+import { runtime } from '../config/runtime'
+import { server } from '../server'
+import { loadRuntimeZod } from '../utils/runtime-modules'
+import { reduceActivity } from './activity.utils'
+
+const RECORD_TYPE = 'plugin:dsh-tauri-kernel/activity'
+const EMPTY: NativeActivityState = { plan: null, subagents: [], jobs: [], unavailable: { plan: 'not-exposed', subagents: 'not-exposed', jobs: 'not-exposed' } }
+
+export const activity = defineService({
+ async register(): Promise<() => void> {
+ const ctx = getServerContext<HostContext>(server)
+ try {
+ const lifetime = runtime.lifetime
+ const z = await loadRuntimeZod(ctx.loader)
+ lifetime.signal.throwIfAborted()
+ if (runtime.lifetime !== lifetime || getServerContext<HostContext>(server) !== ctx)
+ return () => {}
+ const item = z.object({ id: z.string().min(1).max(1024), label: z.string().max(16384).optional(), status: z.string().max(256).optional(), details: z.string().max(65536).optional(), parentId: z.string().max(1024).optional() }).strict()
+ const reason = z.string().nullable()
+ const schema = z.object({
+ plan: z.object({ steps: z.array(z.object({ content: z.string().max(16384), status: z.enum(['pending', 'in_progress', 'completed']) }).strict()).max(1024), explanation: z.string().max(65536).optional() }).strict().nullable(),
+ subagents: z.array(item).max(1024),
+ jobs: z.array(item).max(1024),
+ unavailable: z.object({ plan: reason, subagents: reason, jobs: reason }).strict(),
+ }).strict()
+ const stateSchema = z.object({ inheritedEventCount: z.number().int().nonnegative(), activity: schema }).strict()
+ const dispose = ctx.sessionProjections.register({
+ key: 'bridgeActivity',
+ stateSchema,
+ init: (_header, inheritedEventCount) => ({ inheritedEventCount, activity: EMPTY }),
+ apply(state, event) {
+ const type: string = event.type
+ return event.seq >= state.inheritedEventCount && type === RECORD_TYPE && event.ignorable === true ? { ...state, activity: schema.parse(event.data) } : state
+ },
+ wire: { viewSchema: schema, view: state => state.activity },
+ stateVersion: 1,
+ })
+ runtime.activitySchema = schema
+ runtime.appendActivity = undefined
+ return () => {
+ dispose()
+ if (runtime.activitySchema === schema) {
+ runtime.activitySchema = undefined
+ runtime.appendActivity = undefined
+ }
+ }
+ }
+ catch (error) {
+ ctx.logger.warn('dsh-tauri-kernel: native activity projection unavailable', error)
+ return () => {}
+ }
+ },
+
+ update(agent: Agent, controller: AbortController, backend: KernelBinding['backend'], message: Record<string, unknown>): void {
+ if (controller.signal.aborted || runtime.lifetime.signal.aborted || runtime.controllers.get(agent.id) !== controller)
+ return
+ const ctx = getServerContext<HostContext>(server)
+ try {
+ if (!runtime.activitySchema || !runtime.appendActivity || ctx.agents.get(agent.id) !== agent || ctx.sessions.get(agent.id) !== agent.session)
+ return
+ const state = ctx.sessionProjections.stateOf(agent.session, 'bridgeActivity')
+ if (!state)
+ return
+ let pending = runtime.activityPlans.get(agent)
+ if (!pending) {
+ pending = new Map()
+ runtime.activityPlans.set(agent, pending)
+ }
+ const next = reduceActivity(state.activity, backend, message, pending)
+ if (next && JSON.stringify(next) !== JSON.stringify(state.activity))
+ runtime.appendActivity(agent.session, RECORD_TYPE, runtime.activitySchema.parse(next))
+ }
+ catch (error) {
+ ctx.logger.warn('dsh-tauri-kernel: native activity mapping failed; execution unchanged', error)
+ try {
+ const state = ctx.sessionProjections.stateOf(agent.session, 'bridgeActivity')?.activity
+ if (state && runtime.appendActivity && !controller.signal.aborted && runtime.controllers.get(agent.id) === controller && ctx.agents.get(agent.id) === agent && ctx.sessions.get(agent.id) === agent.session) {
+ const capability = message.method === 'turn/plan/updated' || message.type === 'assistant' || message.type === 'user' ? 'plan' : backend === 'codex' ? 'subagents' : 'jobs'
+ runtime.appendActivity(agent.session, RECORD_TYPE, { ...state, unavailable: { ...state.unavailable, [capability]: 'mapping-failed' } })
+ }
+ }
+ catch (failure) {
+ ctx.logger.warn('dsh-tauri-kernel: native activity error could not be recorded', failure)
+ }
+ }
+ },
+})
+
+declare module '@deepseek-ai/dsh-session-projection/types' {
+ interface SessionProjectionStateMap { bridgeActivity: { inheritedEventCount: number, activity: NativeActivityState } }
+}
diff --git a/packages/dsh-tauri-kernel/src/host/service/activity.utils.test.ts b/packages/dsh-tauri-kernel/src/host/service/activity.utils.test.ts
new file mode 100644
index 00000000..3b63d073
--- /dev/null
+++ b/packages/dsh-tauri-kernel/src/host/service/activity.utils.test.ts
@@ -0,0 +1,53 @@
+import type { NativeActivityState } from '../../shared/activity'
+import { describe, expect, it } from 'vitest'
+import { reduceActivity } from './activity.utils'
+
+const empty: NativeActivityState = { plan: null, subagents: [], jobs: [], unavailable: { plan: 'not-exposed', subagents: 'not-exposed', jobs: 'not-exposed' } }
+
+describe('native activity observation', () => {
+ it('maps Codex plan statuses without changing the native notification', () => {
+ const event = { method: 'turn/plan/updated', params: { plan: [{ step: 'Ship', status: 'inProgress' }], explanation: 'Now' } }
+ const original = JSON.stringify(event)
+ expect(reduceActivity(empty, 'codex', event, new Map())).toEqual({ ...empty, plan: { steps: [{ content: 'Ship', status: 'in_progress' }], explanation: 'Now' }, unavailable: { ...empty.unavailable, plan: null } })
+ expect(JSON.stringify(event)).toBe(original)
+ })
+
+ it('retains native agent identities and reported statuses, without inventing child sessions', () => {
+ const event = { method: 'item/completed', params: { item: { type: 'collabAgentToolCall', receiverThreadIds: ['native-a', 'native-b'], agentsStates: { 'native-a': { status: 'errored', message: 'Failure' } } } } }
+ expect(reduceActivity(empty, 'codex', event, new Map())?.subagents).toEqual([{ id: 'native-a', status: 'errored', details: 'Failure' }, { id: 'native-b' }])
+ expect(empty.subagents).toEqual([])
+ })
+
+ it('commits Claude todos only after the successful original tool result', () => {
+ const pending = new Map<string, NativeActivityState['plan']>()
+ const call = { type: 'assistant', message: { content: [{ type: 'tool_use', id: 'todo', name: 'TodoWrite', input: { todos: [{ content: 'Ship', status: 'pending' }] } }] } }
+ expect(reduceActivity(empty, 'claude', call, pending)).toBeUndefined()
+ expect(reduceActivity(empty, 'claude', { type: 'user', message: { content: [{ type: 'tool_result', tool_use_id: 'todo', is_error: true }] } }, pending)).toBeUndefined()
+ reduceActivity(empty, 'claude', call, pending)
+ const result = reduceActivity(empty, 'claude', { type: 'user', message: { content: [{ type: 'tool_result', tool_use_id: 'todo', content: 'unchanged' }] } }, pending)
+ expect(result?.plan).toEqual({ steps: [{ content: 'Ship', status: 'pending' }] })
+ expect(pending.size).toBe(0)
+ })
+
+ it('keeps task lifecycle facts and marks the incomplete task view as partial', () => {
+ const start = reduceActivity(empty, 'claude', { type: 'system', subtype: 'task_started', task_id: 'task-a', task_type: 'local_agent', is_backgrounded: true, description: 'Inspect' }, new Map())!
+ expect(start.jobs).toEqual([{ id: 'task-a', label: 'Inspect' }])
+ expect(start.unavailable.jobs).toBe('partial')
+ const end = reduceActivity(start, 'claude', { type: 'system', subtype: 'task_updated', task_id: 'task-a', patch: { status: 'completed' } }, new Map())!
+ expect(end.subagents).toEqual([{ id: 'task-a', label: 'Inspect', status: 'completed' }])
+ })
+
+ it('does not mislabel a foreground agent as a background task or infer completion from snapshot absence', () => {
+ const start = reduceActivity(empty, 'claude', { type: 'system', subtype: 'task_started', task_id: 'front', task_type: 'local_agent' }, new Map())!
+ expect(start.jobs).toEqual([])
+ expect(start.subagents).toEqual([{ id: 'front' }])
+ const snapshot = reduceActivity(start, 'claude', { type: 'system', subtype: 'background_tasks_changed', tasks: [] }, new Map())!
+ expect(snapshot.subagents).toEqual([{ id: 'front' }])
+ expect(snapshot.jobs).toEqual([])
+ })
+
+ it('leaves unexposed capabilities unavailable and rejects malformed observed plans', () => {
+ expect(reduceActivity(empty, 'codex', { method: 'item/started', params: { item: { type: 'commandExecution', processId: '123' } } }, new Map())).toBeUndefined()
+ expect(() => reduceActivity(empty, 'codex', { method: 'turn/plan/updated', params: { plan: [{ step: 'Bad', status: 'guessed' }] } }, new Map())).toThrow('Native plan step is invalid')
+ })
+})
diff --git a/packages/dsh-tauri-kernel/src/host/service/activity.utils.ts b/packages/dsh-tauri-kernel/src/host/service/activity.utils.ts
new file mode 100644
index 00000000..32d2b776
--- /dev/null
+++ b/packages/dsh-tauri-kernel/src/host/service/activity.utils.ts
@@ -0,0 +1,116 @@
+import type { NativeActivityItem, NativeActivityState } from '../../shared/activity'
+
+function object(value: unknown): Record<string, unknown> {
+ return value !== null && typeof value === 'object' && !Array.isArray(value) ? value as Record<string, unknown> : {}
+}
+
+function text(value: unknown): string | undefined {
+ return typeof value === 'string' && value.length > 0 ? value : undefined
+}
+
+function upsert(items: NativeActivityItem[], item: NativeActivityItem): NativeActivityItem[] {
+ const previous = items.find(value => value.id === item.id)
+ return [...items.filter(value => value.id !== item.id), { ...previous, ...item }].slice(-1024)
+}
+
+function plan(values: unknown, codex = false): NonNullable<NativeActivityState['plan']> {
+ if (!Array.isArray(values) || values.length > 1024)
+ throw new Error('Native plan is not a bounded array')
+ return { steps: values.map((value) => {
+ const item = object(value)
+ const content = codex ? item.step : item.content
+ const status = item.status === 'inProgress' ? 'in_progress' : item.status
+ if (typeof content !== 'string' || !['pending', 'in_progress', 'completed'].includes(String(status)))
+ throw new Error('Native plan step is invalid')
+ return { content, status: status as 'pending' | 'in_progress' | 'completed' }
+ }) }
+}
+
+export function reduceActivity(state: NativeActivityState, backend: 'codex' | 'claude', message: Record<string, unknown>, pending: Map<string, NativeActivityState['plan']>): NativeActivityState | undefined {
+ if (backend === 'codex') {
+ const params = object(message.params)
+ if (message.method === 'turn/plan/updated') {
+ const next = plan(params.plan, true)
+ if (typeof params.explanation === 'string')
+ next.explanation = params.explanation
+ return { ...state, plan: next, unavailable: { ...state.unavailable, plan: null } }
+ }
+ if (message.method !== 'item/started' && message.method !== 'item/completed')
+ return undefined
+ const item = object(params.item)
+ if (item.type === 'subAgentActivity') {
+ const id = text(item.agentThreadId)
+ if (!id)
+ throw new Error('Native agent identity is missing')
+ return { ...state, subagents: upsert(state.subagents, { id, ...text(item.agentPath) ? { label: String(item.agentPath) } : {}, ...text(item.kind) ? { status: String(item.kind) } : {} }), unavailable: { ...state.unavailable, subagents: null } }
+ }
+ if (item.type === 'collabAgentToolCall') {
+ const agents = object(item.agentsStates)
+ if (!Array.isArray(item.receiverThreadIds))
+ throw new Error('Native agent identities are missing')
+ let subagents = state.subagents
+ for (const id of item.receiverThreadIds) {
+ if (typeof id !== 'string' || id === '')
+ throw new Error('Native agent identity is invalid')
+ const info = object(agents[id])
+ subagents = upsert(subagents, { id, ...text(info.status) ? { status: String(info.status) } : {}, ...text(info.message) ? { details: String(info.message) } : {} })
+ }
+ return { ...state, subagents, unavailable: { ...state.unavailable, subagents: null } }
+ }
+ return undefined
+ }
+ if (message.type === 'system') {
+ if (message.subtype === 'background_tasks_changed') {
+ if (!Array.isArray(message.tasks) || message.tasks.length > 1024)
+ throw new Error('Native background task snapshot is invalid')
+ let jobs = state.jobs
+ let subagents = state.subagents
+ for (const value of message.tasks) {
+ const task = object(value)
+ const id = text(task.task_id)
+ if (!id)
+ throw new Error('Native background task identity is missing')
+ const item = { id, ...text(task.description) ? { label: String(task.description) } : {}, ...text(task.parent_task_id) ? { parentId: String(task.parent_task_id) } : {} }
+ jobs = upsert(jobs, item)
+ if (task.task_type === 'local_agent')
+ subagents = upsert(subagents, item)
+ }
+ return { ...state, jobs, subagents, unavailable: { ...state.unavailable, jobs: 'partial', ...subagents !== state.subagents ? { subagents: 'partial' } : {} } }
+ }
+ const id = text(message.task_id)
+ if (!id || !['task_started', 'task_progress', 'task_updated', 'task_notification'].includes(String(message.subtype)))
+ return undefined
+ const patch = message.subtype === 'task_updated' ? object(message.patch) : message
+ const status = text(patch.status)
+ const label = text(patch.description)
+ const details = text(patch.summary) ?? text(patch.last_tool_name)
+ const item = { id, ...label ? { label } : {}, ...status ? { status } : {}, ...details ? { details } : {} }
+ const jobs = patch.is_backgrounded === true || state.jobs.some(item => item.id === id) ? upsert(state.jobs, item) : state.jobs
+ const subagents = message.task_type === 'local_agent' || message.task_type === 'remote_agent' || state.subagents.some(item => item.id === id) ? upsert(state.subagents, item) : state.subagents
+ return { ...state, jobs, subagents, unavailable: { ...state.unavailable, ...jobs !== state.jobs ? { jobs: 'partial' } : {}, ...subagents !== state.subagents ? { subagents: 'partial' } : {} } }
+ }
+ const body = object(message.message)
+ if (!Array.isArray(body.content) || message.parent_tool_use_id != null)
+ return undefined
+ let next: NativeActivityState | undefined
+ for (const value of body.content) {
+ const block = object(value)
+ if (message.type === 'assistant' && block.type === 'tool_use' && block.name === 'TodoWrite') {
+ const id = text(block.id)
+ if (id) {
+ if (pending.size >= 1024)
+ pending.clear()
+ pending.set(id, plan(object(block.input).todos))
+ }
+ }
+ else if (message.type === 'user' && block.type === 'tool_result') {
+ const id = text(block.tool_use_id)
+ const current = id ? pending.get(id) : undefined
+ if (id)
+ pending.delete(id)
+ if (current && block.is_error !== true)
+ next = { ...(next ?? state), plan: current, unavailable: { ...(next ?? state).unavailable, plan: null } }
+ }
+ }
+ return next
+}
diff --git a/packages/dsh-tauri-kernel/src/host/service/adapter.ts b/packages/dsh-tauri-kernel/src/host/service/adapter.ts
index 353f80b5..aa28f965 100644
--- a/packages/dsh-tauri-kernel/src/host/service/adapter.ts
+++ b/packages/dsh-tauri-kernel/src/host/service/adapter.ts
@@ -53,6 +53,7 @@ export const adapter = defineService({
}
}
const dispose = ctx.llm.registerAdapter([BRIDGE_PROVIDER], new NativeAdapter() as LlmAdapter)
+ runtime.appendActivity = modules.appendPluginRecord
runtime.ready = true
return () => {
runtime.ready = false
diff --git a/packages/dsh-tauri-kernel/src/host/service/session.test.ts b/packages/dsh-tauri-kernel/src/host/service/session.test.ts
index 92603f20..4d3c625b 100644
--- a/packages/dsh-tauri-kernel/src/host/service/session.test.ts
+++ b/packages/dsh-tauri-kernel/src/host/service/session.test.ts
@@ -849,6 +849,42 @@ describe('independent native worktree session setup', () => {
expect(announced).toEqual([parent.agent])
}, 10_000)
+ it('publishes a child when native task progress arrives outside a turn during the awaited fork', async () => {
+ const { handle: parent, connection: original } = await conversation('claude')
+ const source = parent.agent.session
+ const observe = vi.mocked(createClaudeSession).mock.calls[0]![3].activity!
+ observe({ type: 'system', subtype: 'background_tasks_changed', tasks: [{ task_id: 'background-task', task_type: 'local_bash', description: 'Inspecting' }] })
+ expect(projections.stateOf(source, 'bridgeActivity')?.activity.jobs).toEqual([{ id: 'background-task', label: 'Inspecting' }])
+ const prefix = source.snapshotEvents()
+ const messages = source.deriveMessages()
+ const ack = deferred<NativeSession>()
+ const started = deferred<void>()
+ const connection = native('worktree-progress-child')
+ releases.push(() => ack.resolve(connection))
+ vi.mocked(createClaudeSession).mockImplementationOnce(async () => {
+ started.resolve()
+ return ack.promise
+ })
+ const task = fork(parent.agent, 'worktree-progress-official')
+ await started.promise
+ expect(parent.agent.status).not.toBe('running')
+ observe({ type: 'system', subtype: 'task_progress', task_id: 'background-task', description: 'Still inspecting', last_tool_name: 'Read' })
+ expect(source.seq).toBe(prefix.length + 1)
+ expect(projections.stateOf(source, 'bridgeActivity')?.activity.jobs).toEqual([{ id: 'background-task', label: 'Still inspecting', details: 'Read' }])
+ ack.resolve(connection)
+ const child = await task
+ expect(agents.get(child.agent.id)).toBe(child.agent)
+ expect(child.agent.session.inheritedEventCount).toBe(prefix.length)
+ expect(child.agent.session.snapshotEvents().slice(0, prefix.length)).toEqual(prefix)
+ expect(projections.stateOf(child.agent.session, 'bridgeActivity')?.activity.jobs).toEqual([])
+ expect(identity.resolve(child.agent)).toEqual({ backend: 'claude', nativeSessionId: 'worktree-progress-child', sessionId: child.agent.id })
+ expect(source.deriveMessages()).toEqual(messages)
+ expect(connection.dispose).not.toHaveBeenCalled()
+ expect(original.submit).toHaveBeenCalledOnce()
+ expect(createClaudeSession).toHaveBeenCalledTimes(2)
+ expect(errors).toEqual([])
+ }, 10_000)
+
it('refuses a parent changed during native fork instead of silently inheriting a newer history', async () => {
const { handle: parent, connection: original } = await conversation()
const ack = deferred<NativeSession>()
diff --git a/packages/dsh-tauri-kernel/src/host/service/session.ts b/packages/dsh-tauri-kernel/src/host/service/session.ts
index 627c4ebb..6441e57d 100644
--- a/packages/dsh-tauri-kernel/src/host/service/session.ts
+++ b/packages/dsh-tauri-kernel/src/host/service/session.ts
@@ -19,6 +19,7 @@ import { BRIDGE_PROVIDER, KERNEL_RECORD_TYPE, SESSION_TITLE_PURPOSE } from '../c
import { resetRuntime, runtime } from '../config/runtime'
import { server } from '../server'
import { waitFor } from '../utils/abort'
+import { activity } from './activity'
import { backend } from './backend'
import { checkpoint } from './checkpoint'
import { identity } from './identity'
@@ -129,7 +130,7 @@ export const session = defineService({
try {
signal.throwIfAborted()
lifetime.signal.throwIfAborted()
- if (runtime.lifetime !== lifetime || source.seq !== cursor || ctx.agents.get(source.id) !== parent)
+ if (runtime.lifetime !== lifetime || !unchangedSince(source, cursor) || ctx.agents.get(source.id) !== parent)
throw new Error('BRIDGE_FORK_SOURCE_CHANGED: 源会话在原生派生期间发生变化。')
return handle
}
@@ -171,13 +172,13 @@ export const session = defineService({
const cursor = agent.session.inheritedEventCount
await waitFor(parent.runMaintenance(async (maintenance) => {
const repairing = AbortSignal.any([scoped, maintenance])
- if (parent.session.seq !== cursor)
+ if (!unchangedSince(parent.session, cursor))
throw new Error('BRIDGE_FORK_SOURCE_CHANGED: 父会话已改变,不能将较新的原生历史替代继承前缀。')
const commit = await bindFork(agent, inherited, repairing, parent.session)
commit.commit()
await checkpoint.flush(agent, repairing)
repairing.throwIfAborted()
- if (parent.session.seq !== cursor)
+ if (!unchangedSince(parent.session, cursor))
throw new Error('BRIDGE_FORK_SOURCE_CHANGED: 父会话在原生派生期间发生变化。')
}), scoped)
signal.throwIfAborted()
@@ -406,9 +407,13 @@ async function resolveParent(sessionId: string, signal: AbortSignal): Promise<Ag
return result.agent
}
+function unchangedSince(value: Session, cursor: number): boolean {
+ return value.seq >= cursor && value.snapshotEvents().slice(cursor).every(event => String(event.type) === 'plugin:dsh-tauri-kernel/activity' && event.ignorable === true)
+}
+
function assertForkSource(parent: Session, child: Agent, binding: KernelBinding): void {
const ctx = getServerContext<HostContext>(server)
- if (parent.id !== child.session.header.parentSession || parent.seq !== child.session.inheritedEventCount || !sameBinding(ctx.sessionProjections.stateOf(parent, 'bridgeKernel')?.binding, binding))
+ if (parent.id !== child.session.header.parentSession || !unchangedSince(parent, child.session.inheritedEventCount) || !sameBinding(ctx.sessionProjections.stateOf(parent, 'bridgeKernel')?.binding, binding))
throw new Error('BRIDGE_FORK_SOURCE_CHANGED: 父会话与当前继承前缀不一致,请重新创建工作树会话。')
}
@@ -480,6 +485,7 @@ async function connect(agent: Agent, id: KernelBinding['backend'], storedId: str
if (!resolved.detection.installed || !resolved.command || resolved.detection.auth === 'missing')
throw new Error(resolved.detection.hint ?? 'BRIDGE_BACKEND_UNAVAILABLE: 本机内核不可用。')
const nativeSink: NativeSink = {
+ activity: message => activity.update(agent, controller, id, message),
text: (...args) => activeSink(agent, controller).text(...args),
thinking: (...args) => activeSink(agent, controller).thinking(...args),
assistant: (...args) => activeSink(agent, controller).assistant(...args),
diff --git a/packages/dsh-tauri-kernel/src/host/types/index.ts b/packages/dsh-tauri-kernel/src/host/types/index.ts
index 3611aee1..11e53d7c 100644
--- a/packages/dsh-tauri-kernel/src/host/types/index.ts
+++ b/packages/dsh-tauri-kernel/src/host/types/index.ts
@@ -10,6 +10,7 @@ import type {} from '@deepseek-ai/dsh-user-approval'
import type {} from '@deepseek-ai/dsh-user-questions'
import type {} from '@deepseek-ai/dsh-workspace'
import type { HostContext as DesktopHostContext } from 'dsh-tauri'
+import type { NativeActivityState } from '../../shared/activity'
import type { NativeTurnOptions } from '../../shared/native-model'
import type { KernelBinding } from '../../shared/types'
import type { NativeSession } from '../backends/types'
@@ -24,7 +25,7 @@ export interface RuntimeModules {
ToolCallId: typeof LlmRuntime.ToolCallId
LlmAdapter: typeof LlmRuntime.LlmAdapter
isAgentLoopRequest: typeof LlmRuntime.isAgentLoopRequest
- appendPluginRecord?: (session: Session, type: 'plugin:dsh-tauri-kernel/kernel' | 'plugin:dsh-tauri-kernel/model', data: KernelBinding | NativeTurnOptions) => number
+ appendPluginRecord?: (session: Session, type: 'plugin:dsh-tauri-kernel/kernel' | 'plugin:dsh-tauri-kernel/model' | 'plugin:dsh-tauri-kernel/activity', data: KernelBinding | NativeTurnOptions | NativeActivityState) => number
pluginRecordOf?: (event: SessionEvent) => { type: string, data: unknown } | undefined
}
diff --git a/packages/dsh-tauri-kernel/src/shared/activity.ts b/packages/dsh-tauri-kernel/src/shared/activity.ts
new file mode 100644
index 00000000..42c9fd4a
--- /dev/null
+++ b/packages/dsh-tauri-kernel/src/shared/activity.ts
@@ -0,0 +1,20 @@
+export interface NativeActivityItem {
+ id: string
+ label?: string
+ status?: string
+ details?: string
+ parentId?: string
+}
+
+export interface NativeActivityState {
+ plan: { steps: { content: string, status: 'pending' | 'in_progress' | 'completed' }[], explanation?: string } | null
+ subagents: NativeActivityItem[]
+ jobs: NativeActivityItem[]
+ unavailable: { plan: string | null, subagents: string | null, jobs: string | null }
+}
+
+declare module '@deepseek-ai/dsh-session-projection/types' {
+ interface SessionProjectionMap {
+ bridgeActivity: NativeActivityState
+ }
+}