DeepSeek Harness Tauri 桌面版 | Only 8mb installer, zero environment setup, preset plugins, Windows / macOS / Linux.
fix(worktree): restore session inheritance on kernels without Session.events
hairyf430c13e58773
diff --git a/packages/dsh-tauri-panel-scheduler/src/host/service/executor.ts b/packages/dsh-tauri-panel-scheduler/src/host/service/executor.tsindex c951a674..bad47d3c 100644--- a/packages/dsh-tauri-panel-scheduler/src/host/service/executor.ts+++ b/packages/dsh-tauri-panel-scheduler/src/host/service/executor.ts@@ -10,13 +10,12 @@ import { mkdir } from 'node:fs/promises'import { homedir } from 'node:os'import process from 'node:process'import { defineService } from 'dsh-tauri'-import { compact, filter, findLast, last, map } from 'lodash-es'import { join } from 'pathe'import { getCurrentHostInstance } from '../config/runtime'import { loadSchedulerRuntimeModules, resolveSetupAgent } from '../utils/agent-runtime'import { applyUnattendedPermission } from '../utils/permission'import { schedulerSessionTitle } from '../utils/session-title'-import { decideRunOutcome, waitForTurnStart } from './executor.utils'+import { decideRunOutcome, summarizeRun, waitForTurnStart } from './executor.utils'import { runs } from './runs'const SCHEDULER_RUN_TIMEOUT_MS = 30 * 60 * 1000@@ -112,7 +111,7 @@ export const executor = defineService({}else {await (ctx.sessions as { flush: (session: unknown) => Promise<unknown> }).flush(handle.agent.session)- const outcome = summarizeRun(handle.agent.session.events, firstSeq)+ const outcome = summarizeRun(handle.agent.session, firstSeq)const decision = decideRunOutcome({ started, timedOut, reason: outcome.reason })result = decision.error ? { status: 'failed', error: decision.error } : { status: 'succeeded' }@@ -160,12 +159,6 @@ interface AgentHandleLike {}}-interface SessionEventLike {- readonly seq: number- readonly type: string- readonly data: Record<string, any>-}-async function resolveWorkspace(ctx: HostContext, task: SchedulerTask): Promise<WorkspaceResolution> {if (task.workspaceId) {const record = ctx.workspaceRegistry?.get?.(task.workspaceId) as@@ -250,21 +243,6 @@ async function settle(id: string, status: RunStatus, outcome: ExecuteOutcome): P})}-function summarizeRun(events: readonly SessionEventLike[], firstSeq: number): {- readonly text: string- readonly reason?: Record<string, any>-} {- const scoped = filter(events, event => event.seq >= firstSeq)- const texts = compact(map(filter(scoped, { type: 'assistant/message' }), textOf))- const reason = findLast(scoped, { type: 'turn/end' })?.data.reason as Record<string, any> | undefined- return { text: last(texts) ?? '', ...(reason ? { reason } : {}) }-}--function textOf(event: SessionEventLike): string {- const blocks = (event.data.message?.content ?? []) as readonly { type: string, text?: string }[]- return blocks.filter(block => block.type === 'text').map(block => block.text ?? '').join('')-}-function settlesWithin(promise: Promise<unknown>, timeoutMs: number): Promise<boolean> {let timer: ReturnType<typeof setTimeout> | undefinedtry {diff --git a/packages/dsh-tauri-panel-scheduler/src/host/service/executor.utils.test.ts b/packages/dsh-tauri-panel-scheduler/src/host/service/executor.utils.test.tsindex a6436ca5..4ec9a09f 100644--- a/packages/dsh-tauri-panel-scheduler/src/host/service/executor.utils.test.ts+++ b/packages/dsh-tauri-panel-scheduler/src/host/service/executor.utils.test.ts@@ -1,5 +1,15 @@import { describe, expect, it, vi } from 'vitest'-import { decideRunOutcome, describeFailure, waitForTurnStart } from './executor.utils'+import { decideRunOutcome, describeFailure, summarizeRun, waitForTurnStart } from './executor.utils'++const runEvents = [+ { seq: 0, type: 'turn/end', data: { reason: { kind: 'completed' } } },+ { seq: 1, type: 'turn/start', data: {} },+ { seq: 2, type: 'assistant/message', data: { message: { content: [{ type: 'text', text: 'working' }] } } },+ { seq: 3, type: 'assistant/message', data: { message: { content: [{ type: 'text', text: 'done' }] } } },+ { seq: 4, type: 'turn/end', data: { reason: { kind: 'error', error: { code: 'llm_error', message: 'boom' } } } },+]++const failureReason = { kind: 'error', error: { code: 'llm_error', message: 'boom' } }describe('decideRunOutcome', () => {it('超时优先判失败(即使 turn 已启动)', () => {@@ -53,3 +63,27 @@ describe('waitForTurnStart', () => {}})})++describe('summarizeRun', () => {+ it('内核 0.1.2-rc.1 起改从 snapshotEvents 读日志,失败收尾不会被吞成成功', () => {+ const outcome = summarizeRun({ snapshotEvents: () => runEvents }, 1)+ expect(outcome).toEqual({ text: 'done', reason: failureReason })+ expect(decideRunOutcome({ started: true, timedOut: false, reason: outcome.reason }))+ .toEqual({ status: 'failed', error: { code: 'llm_error', message: 'boom' } })+ })++ it('legacy 内核的 log / events 仍作兜底', () => {+ for (const session of [{ log: runEvents }, { events: runEvents }]) {+ expect(summarizeRun(session, 1)).toEqual({ text: 'done', reason: failureReason })+ }+ })++ it('只统计 firstSeq 之后的事件', () => {+ expect(summarizeRun({ snapshotEvents: () => runEvents }, 5)).toEqual({ text: '' })+ })++ it('日志不可读时退化为「没有 turn/end」,交由 decideRunOutcome 兜底', () => {+ expect(summarizeRun({}, 0)).toEqual({ text: '' })+ expect(summarizeRun(undefined, 0)).toEqual({ text: '' })+ })+})diff --git a/packages/dsh-tauri-panel-scheduler/src/host/service/executor.utils.ts b/packages/dsh-tauri-panel-scheduler/src/host/service/executor.utils.tsindex 7c5d4759..798e5c70 100644--- a/packages/dsh-tauri-panel-scheduler/src/host/service/executor.utils.ts+++ b/packages/dsh-tauri-panel-scheduler/src/host/service/executor.utils.ts@@ -1,4 +1,5 @@import type { RunStatus } from '../types'+import { compact, filter, findLast, last, map } from 'lodash-es'/** 启动窗口:排队的 followup 被 driver 取走前的等待上限。 */export const SCHEDULER_TURN_START_TIMEOUT_MS = 30_000@@ -68,3 +69,46 @@ export function decideRunOutcome(input: {return { status: 'succeeded' }return { status: 'failed', error: describeFailure(input.reason) }}++interface SessionEventLike {+ readonly seq: number+ readonly type: string+ readonly data: Record<string, any>+}++/**+ * 从会话对象读取本轮之后的事件,提取助手正文与 `turn/end` 收尾原因。+ *+ * 取日志必须走 {@link sessionEvents}:直接读 `session.events` 在 0.1.2-rc.1 起的内核上+ * 恒为 `undefined`,会让收尾原因消失、把失败的跑批误判成成功。+ */+export function summarizeRun(session: unknown, firstSeq: number): {+ readonly text: string+ readonly reason?: Record<string, any>+} {+ const scoped = filter(sessionEvents(session), event => event.seq >= firstSeq)+ const texts = compact(map(filter(scoped, { type: 'assistant/message' }), textOf))+ const reason = findLast(scoped, { type: 'turn/end' })?.data.reason as Record<string, any> | undefined+ return { text: last(texts) ?? '', ...(reason ? { reason } : {}) }+}++/** 内核 `Session` 的日志面逐版本漂移:0.1.2-rc.1 起移除 `events` 访问器,以 `snapshotEvents()` 为准,`log` / `events` 仅作兜底。 */+function sessionEvents(value: unknown): readonly SessionEventLike[] {+ if (typeof value !== 'object' || value === null)+ return []+ const session = value as Record<string, unknown>+ const snapshotEvents = session.snapshotEvents+ if (typeof snapshotEvents === 'function') {+ const snapshot: unknown = Reflect.apply(snapshotEvents, value, [])+ if (Array.isArray(snapshot))+ return snapshot as readonly SessionEventLike[]+ }+ if (Array.isArray(session.log))+ return session.log as readonly SessionEventLike[]+ return Array.isArray(session.events) ? session.events as readonly SessionEventLike[] : []+}++function textOf(event: SessionEventLike): string {+ const blocks = (event.data.message?.content ?? []) as readonly { type: string, text?: string }[]+ return blocks.filter(block => block.type === 'text').map(block => block.text ?? '').join('')+}diff --git a/packages/dsh-tauri-worktree/src/host/service/handoff.test.ts b/packages/dsh-tauri-worktree/src/host/service/handoff.test.tsnew file mode 100644index 00000000..49e8966d--- /dev/null+++ b/packages/dsh-tauri-worktree/src/host/service/handoff.test.ts@@ -0,0 +1,126 @@+import type { Binding, PendingHandoff } from '../types'+import { afterEach, describe, expect, it, vi } from 'vitest'+import { clearHostRuntime, setCurrentHostInstance } from '../config/runtime'+import { handoff } from './handoff'++const events = [+ { type: 'user/message', seq: 0, time: 1, data: { message: { role: 'user', content: [{ type: 'text', text: 'hi' }] } } },+ { type: 'turn/end', seq: 1, time: 2, data: { reason: { kind: 'completed' } } },+]++function sourceAgent(): unknown {+ return {+ session: {+ id: 'session-source',+ header: { agentPreset: 'default' },+ snapshotEvents: () => events,+ },+ }+}++interface SetupOptions {+ session?: unknown+ warn?: (message: string) => void+ create?: (options: any) => Promise<unknown>+}++function setup(options: SetupOptions = {}): { created: any[] } {+ const created: any[] = []+ setCurrentHostInstance({+ agents: {+ get: (id: string) => (id === 'session-source'+ ? { session: options.session ?? (sourceAgent() as any).session, ctx: {}, options: {} }+ : undefined),+ create: async (value: any) => {+ created.push(value)+ return options.create?.(value)+ },+ },+ workspaceRegistry: { resolveByPath: async () => undefined },+ logger: { warn: options.warn ?? (() => {}) },+ })+ return { created }+}++afterEach(() => {+ clearHostRuntime()+})++describe('handoff.inherit', () => {+ it('seeds the target session from the kernel snapshot log', async () => {+ const { created } = setup()+ const outcome = await handoff.inherit('session-source', 'session-target', 'C:/worktrees/w1')+ expect(outcome).toEqual({ ok: true, targetSessionId: 'session-target', seedLength: events.length })+ expect(created).toHaveLength(1)+ expect(created[0]).toMatchObject({+ sessionId: 'session-target',+ seed: events,+ inheritedEventCount: events.length,+ meta: {+ cwd: 'C:/worktrees/w1',+ parentSession: 'session-source',+ isSeeded: true,+ agentPreset: 'default',+ },+ })+ })++ it('reads the log through the legacy fallbacks', async () => {+ const legacy = [+ { id: 'session-source', header: {}, log: events },+ { id: 'session-source', header: {}, events },+ ]+ for (const session of legacy) {+ const { created } = setup({ session })+ expect(await handoff.inherit('session-source', 'session-target', 'C:/work')).toEqual({+ ok: true,+ targetSessionId: 'session-target',+ seedLength: events.length,+ })+ expect(created[0]?.seed).toEqual(events)+ }+ })++ it('reports a source session without a readable log', async () => {+ const { created } = setup({ session: { id: 'session-source', header: {} } })+ expect(await handoff.inherit('session-source', 'session-target', 'C:/work')).toEqual({+ ok: false,+ error: '源会话没有可继承的事件:session-source',+ })+ expect(created).toHaveLength(0)+ })++ it('warns when inheritance fails so the silent client fallback stays diagnosable', async () => {+ const warn = vi.fn()+ setup({ session: { id: 'session-source', header: {} }, warn })+ await handoff.inherit('session-source', 'session-target', 'C:/work')+ expect(warn).toHaveBeenCalledWith(expect.stringContaining('session-target'))+ })+})++describe('handoff.complete', () => {+ it('hands the inherited log to the worktree agent', async () => {+ const followup = vi.fn()+ const { created } = setup({ create: async () => ({ agent: { followup } }) })+ const pending: PendingHandoff = {+ sourceAgent: sourceAgent(),+ targetSessionId: 'session-target',+ binding: { worktreePath: 'C:/worktrees/w1', projectPath: 'C:/project' } as Binding,+ }++ await handoff.complete(pending)++ expect(created[0]).toMatchObject({+ sessionId: 'session-target',+ seed: events,+ inheritedEventCount: events.length,+ meta: {+ cwd: 'C:/worktrees/w1',+ parentSession: 'session-source',+ isSeeded: true,+ agentPreset: 'default',+ },+ })+ expect(followup).toHaveBeenCalledTimes(1)+ })+})diff --git a/packages/dsh-tauri-worktree/src/host/service/handoff.ts b/packages/dsh-tauri-worktree/src/host/service/handoff.tsindex c8a556ed..4f13edaa 100644--- a/packages/dsh-tauri-worktree/src/host/service/handoff.ts+++ b/packages/dsh-tauri-worktree/src/host/service/handoff.ts@@ -13,7 +13,10 @@ export const handoff = defineService({targetSessionId: string,cwd: string,): Promise<OperationResult<{ targetSessionId: string, seedLength: number }>> {- return createInherited(sourceSessionId, { cwd, parentSession: sourceSessionId, targetSessionId })+ const inherited = await createInherited(sourceSessionId, { cwd, parentSession: sourceSessionId, targetSessionId })+ if (!inherited.ok)+ getCurrentHostInstance().logger?.warn?.(`dsh-tauri-worktree: session inheritance failed for ${targetSessionId}: ${inherited.error}`)+ return inherited},async handback(@@ -73,7 +76,7 @@ export const handoff = defineService({try {const presets = ctx.get?.('agentPresets')const parentPreset = presets?.composedPreset(sourceAgent.ctx) ?? sourceSession.header.agentPreset- const seed = sourceSession.events+ const seed = sessionEvents(sourceSession)const handle = await ctx.agents.create({sessionId: targetSessionId,seed,@@ -129,7 +132,7 @@ async function createInherited(const sourceSession = agent?.session ?? sessionContext.peek(sourceSessionId)if (!sourceSession)return { ok: false, error: `未找到源会话:${sourceSessionId}` }- const seed = Array.isArray(sourceSession.events) ? sourceSession.events : []+ const seed = sessionEvents(sourceSession)if (seed.length === 0)return { ok: false, error: `源会话没有可继承的事件:${sourceSessionId}` }@@ -170,3 +173,19 @@ async function createInherited(return { ok: false, error: get(error, 'message', String(error)) }}}++/** 内核 `Session` 的日志面逐版本漂移:0.1.2-rc.1 起移除 `events` 访问器,以 `snapshotEvents()` 为准,`log` / `events` 仅作兜底。 */+function sessionEvents(value: unknown): readonly unknown[] {+ if (typeof value !== 'object' || value === null)+ return []+ const session = value as Record<string, unknown>+ const snapshotEvents = session.snapshotEvents+ if (typeof snapshotEvents === 'function') {+ const snapshot: unknown = Reflect.apply(snapshotEvents, value, [])+ if (Array.isArray(snapshot))+ return snapshot+ }+ if (Array.isArray(session.log))+ return session.log+ return Array.isArray(session.events) ? session.events : []+}