Skip to content

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

fix(worktree): 模式选择器始终在访问模式右侧,工作树会话继承完整对话并在切换后归档源会话 (#293)

Mao Mr722925ebaf4b
diff --git a/packages/dsh-tauri-worktree/src/client/apis/client.ts b/packages/dsh-tauri-worktree/src/client/apis/client.ts
index 0d31ee90..6c755673 100644
--- a/packages/dsh-tauri-worktree/src/client/apis/client.ts
+++ b/packages/dsh-tauri-worktree/src/client/apis/client.ts
@@ -17,9 +17,9 @@ export function fetchStatus(sessionId: string): Promise<WorktreeStatus> {
return worktreeApi.request(`/status?sessionId=${encodeURIComponent(sessionId)}`)
}
-/** 为预分配的新会话创建工作树;项目路径从当前源会话解析。 */
-export function createWorktree(sessionId: string, sourceSessionId = sessionId): Promise<WorktreeCreate> {
- return worktreeApi.post('/create', { sessionId, sourceSessionId })
+/** 为预分配的新会话创建工作树;项目路径从当前源会话解析。inherit 打开时宿主用源会话事件建好完整会话。 */
+export function createWorktree(sessionId: string, sourceSessionId = sessionId, inherit = false): Promise<WorktreeCreate> {
+ return worktreeApi.post('/create', { sessionId, sourceSessionId, inherit })
}
/** 将已创建的 worktree 会话正式归属到源项目 Workspace。 */
diff --git a/packages/dsh-tauri-worktree/src/client/components/mode-select.tsx b/packages/dsh-tauri-worktree/src/client/components/mode-select.tsx
index f9f378a3..81fbe6fb 100644
--- a/packages/dsh-tauri-worktree/src/client/components/mode-select.tsx
+++ b/packages/dsh-tauri-worktree/src/client/components/mode-select.tsx
@@ -15,6 +15,7 @@ import { useEffect, useRef, useState } from 'react'
import { createPortal } from 'react-dom'
import {
COMPOSER_MODE_BUTTON_SELECTOR,
+ COMPOSER_PLAN_SLOT_SELECTOR,
COMPOSER_SEAT_SELECTOR,
HERO_PRESET_SLOT_SELECTOR,
MODE_ANCHOR_ATTRIBUTE,
@@ -28,7 +29,7 @@ import {
rememberNewSessionMode,
useWorktreeSession,
} from '../store'
-import { waitForInputActions } from '../utils/worktree'
+import { resolveAccessModeGroup, waitForInputActions, waitForSessionListed } from '../utils/worktree'
import { CircleTreeIcon } from './icons'
export function WorktreeModeSelect(props: ModeSelectProps): ReactElement {
@@ -46,12 +47,18 @@ export function WorktreeModeSelect(props: ModeSelectProps): ReactElement {
let host: HTMLSpanElement | null = null
const place = (): void => {
- // rc.2 exposes the hero preset slot; alpha removed it but keeps the
- // stable composer mode button. Prefer the old anchor and fall back to
- // the button without depending on generated CSS module hashes.
- const presetSlot = composerSeat.querySelector<HTMLElement>(HERO_PRESET_SLOT_SELECTOR)
+ // 访问模式按钮是官方「标准模式」右侧的稳定锚点(aria-label 由 input.accessMode
+ // 提供,见 constants)。选择器始终优先插到其右侧的 .modes 分组(gap 16px),而不是
+ // hero 的 Agent 预设槽位——后者只在 hero 首屏存在,会话开始后消失,会让控件「跳位」。
const modeButton = composerSeat.querySelector<HTMLElement>(COMPOSER_MODE_BUTTON_SELECTOR)
- const target = presetSlot ?? modeButton
+ let target: HTMLElement | null = null
+ if (modeButton) {
+ const planSlot = composerSeat.querySelector<HTMLElement>(COMPOSER_PLAN_SLOT_SELECTOR)
+ target = resolveAccessModeGroup(modeButton, planSlot)
+ }
+ // graceful fallback:composer 与模式按钮都缺失的极端布局下归位到 hero 预设槽位,
+ // 保证控件不消失;此时锚点可能随 hero 卸载而消失,由 MutationObserver 重放。
+ target ??= composerSeat.querySelector<HTMLElement>(HERO_PRESET_SLOT_SELECTOR)
if (!target) {
setPortalHost(null)
host?.remove()
@@ -85,7 +92,7 @@ export function WorktreeModeSelect(props: ModeSelectProps): ReactElement {
)
}
-function WorktreeModeControl({ sessionId, useInput, inputActions, sessionsRuntime }: ModeSelectProps): ReactElement | null {
+function WorktreeModeControl({ sessionId, useInput, inputActions, sessionsRuntime, workspacesRuntime }: ModeSelectProps): ReactElement | null {
const state = useWorktreeSession(sessionId)
const draft = useInput(input => input.draft)
const imageIds = useInput(input => input.imageIds)
@@ -110,7 +117,9 @@ function WorktreeModeControl({ sessionId, useInput, inputActions, sessionsRuntim
const targetSessionId = `session-${crypto.randomUUID()}`
patchSession(sessionId, { mode: 'pending', phase: 'creating', loadingLabel: text('progressCreating'), error: '' })
try {
- const created = await createWorktree(targetSessionId, sessionId)
+ // inherit=true:由宿主用源会话完整事件建好「已是完整会话」的工作树会话
+ // (问题 2 修复)。宿主返回 inherited=false 时才回退官方空白会话路径。
+ const created = await createWorktree(targetSessionId, sessionId, true)
patchSession(targetSessionId, {
mode: 'worktree',
phase: 'created',
@@ -121,7 +130,13 @@ function WorktreeModeControl({ sessionId, useInput, inputActions, sessionsRuntim
projectPath: created.projectPath,
sourceSessionId: created.sourceSessionId,
})
- await sessionsRuntime.create({ cwd: created.worktreePath, sessionId: targetSessionId })
+ if (created.inherited) {
+ // 宿主 seed 建的会话需先进入客户端会话列表才能寻址,等待而非 create(防「已存在会话」)。
+ await waitForSessionListed(sessionsRuntime, targetSessionId)
+ }
+ else {
+ await sessionsRuntime.create({ cwd: created.worktreePath, sessionId: targetSessionId })
+ }
await attachWorktreeSession(targetSessionId)
const nextActions = await waitForInputActions(sessionsRuntime, targetSessionId)
nextActions.setDraft(draft)
@@ -142,6 +157,12 @@ function WorktreeModeControl({ sessionId, useInput, inputActions, sessionsRuntim
for (const imageId of imageIds) nextActions.removeImage(imageId)
}
})
+ // 源会话完整对话已继承进工作树会话:归档源会话,避免侧边栏多出一个重复会话。
+ // 仅 inherited 成功时归档——空白回退路径(inherited=false)下源会话仍保有原始
+ // 对话,删除会造成会话信息丢失。先 open(target) 再 archive(source):archiveSession
+ // 的投影只在被归档会话是当前会话时清空选择,此刻 current 已是目标会话,选择不受影响。
+ if (created.inherited)
+ await workspacesRuntime.archiveSession(sessionId).catch(() => {})
}
catch (error) {
patchSession(sessionId, {
@@ -178,15 +199,18 @@ function WorktreeModeControl({ sessionId, useInput, inputActions, sessionsRuntim
composerSeat.removeEventListener('click', intercept, true)
composerSeat.removeEventListener('keydown', intercept, true)
}
- }, [draft, imageIds, inputActions, sessionId, sessionsRuntime, state.mode])
+ }, [draft, imageIds, inputActions, sessionId, sessionsRuntime, state.mode, workspacesRuntime])
+ // 已是工作树会话:完整对话已迁移进隔离工作树,模式选择不再有意义,整个控件隐藏。
+ // 状态由常驻 surface 提示条(检出本地 / 放弃)接管;重新选回本地走官方检出流程。
+ if (state.mode === 'worktree')
+ return null
// 非 git 目录不提供工作树:隐藏整个模式选择器,会话永远只能停留在本地模式。
if (state.isGit === false)
return null
const pending = state.mode === 'pending'
- const bound = state.mode === 'worktree'
- const activeLabel = bound ? text('modeWorktree') : pending ? text('modeNewWorktree') : text('modeLocal')
+ const activeLabel = pending ? text('modeNewWorktree') : text('modeLocal')
const trigger = (
<button
type="button"
@@ -208,17 +232,13 @@ function WorktreeModeControl({ sessionId, useInput, inputActions, sessionsRuntim
<Menu
open={open}
onClose={() => setOpen(false)}
- items={bound
- ? [{ id: 'worktree', label: text('modeWorktree') }]
- : [
- { id: 'local', label: text('modeLocal') },
- { id: 'pending', label: text('modeWorktree') },
- ]}
- selectedId={bound ? 'worktree' : pending ? 'pending' : 'local'}
+ items={[
+ { id: 'local', label: text('modeLocal') },
+ { id: 'pending', label: text('modeWorktree') },
+ ]}
+ selectedId={pending ? 'pending' : 'local'}
onSelect={(id) => {
setOpen(false)
- if (bound)
- return
const mode = id === 'pending' ? 'pending' : 'local'
rememberNewSessionMode(mode)
patchSession(sessionId, {
diff --git a/packages/dsh-tauri-worktree/src/client/constants/index.ts b/packages/dsh-tauri-worktree/src/client/constants/index.ts
index 5ea540d5..c8019e3f 100644
--- a/packages/dsh-tauri-worktree/src/client/constants/index.ts
+++ b/packages/dsh-tauri-worktree/src/client/constants/index.ts
@@ -86,7 +86,14 @@ export const worktreeStyles = {
export const SESSION_ICON_ATTRIBUTE = 'data-dsh-worktree-icon'
export const SIDEBAR_SELECTOR = '[data-slot="sidebar"]'
export const COMPOSER_SEAT_SELECTOR = '[data-composer-seat]'
+export const COMPOSER_CARD_SELECTOR = '[data-composer-card="true"]'
export const HERO_PRESET_SLOT_SELECTOR = '[data-slot="conversation.hero.agentPreset"]'
-/** rc.2/alpha 共用的稳定模式按钮定位(alpha 已移除 hero preset slot)。 */
-export const COMPOSER_MODE_BUTTON_SELECTOR = '[data-composer-card="true"] button[aria-label*="访问模式"], [data-composer-card="true"] button[aria-label*="Access mode"]'
+/** 输入条内的「规划」计划槽位,用于定位访问模式右侧的 .modes 分组(见 utils/worktree.ts)。 */
+export const COMPOSER_PLAN_SLOT_SELECTOR = '[data-slot="conversation.input.plan"]'
+/**
+ * rc.2/alpha 共用的稳定「访问模式」按钮定位。aria-label 由官方
+ * input.accessMode 文案提供(`.uV2eYG_modes` 是生成 hash,绝不依赖)。
+ * 模式选择器始终锚到此按钮右侧的 .modes 分组,而非 hero 的 Agent 预设槽位。
+ */
+export const COMPOSER_MODE_BUTTON_SELECTOR = `${COMPOSER_CARD_SELECTOR} button[aria-label*="访问模式"], ${COMPOSER_CARD_SELECTOR} button[aria-label*="Access mode"]`
export const MODE_ANCHOR_ATTRIBUTE = 'data-dsh-tauri-worktree-mode-anchor'
diff --git a/packages/dsh-tauri-worktree/src/client/register/mode-select.ts b/packages/dsh-tauri-worktree/src/client/register/mode-select.ts
index c073b2c9..f8900743 100644
--- a/packages/dsh-tauri-worktree/src/client/register/mode-select.ts
+++ b/packages/dsh-tauri-worktree/src/client/register/mode-select.ts
@@ -5,12 +5,15 @@
*/
import type { Context } from '@deepseek-ai/cordis'
-import type { SessionsRuntime } from '../types'
+import type { ModeSelectProps, SessionsRuntime, WorkspacesRuntime } from '../types'
import { compat } from 'dsh-tauri/client'
import { WorktreeModeSelect } from '../components/mode-select'
import { INPUT_DOCK_SLOT, MODE_SELECT_ID, MODE_SELECT_ORDER } from '../constants'
import { NS } from '../locales'
+/** 注入除标准槽位 props(useInput/inputActions)外的自定义注入面。 */
+type ModeSelectInjected = Omit<ModeSelectProps, 'useInput' | 'inputActions'>
+
/** 使用 input.dock 的 session 生命周期,并把控件 portal 到标准模式右侧。 */
export function registerModeSelect(ctx: Context): () => void {
const cx = compat(ctx as import('dsh-tauri/client').ClientContext)
@@ -21,9 +24,14 @@ export function registerModeSelect(ctx: Context): () => void {
id: MODE_SELECT_ID,
order: MODE_SELECT_ORDER,
locale: NS,
- inject: (sessionId: string | undefined) => sessionId === undefined
+ inject: (sessionId: string | undefined): ModeSelectInjected | undefined => sessionId === undefined
? undefined
- : { sessionId, sessionsRuntime: cx.sessions as unknown as SessionsRuntime },
+ : {
+ sessionId,
+ sessionsRuntime: cx.sessions as unknown as SessionsRuntime,
+ // 切换工作树成功后归档源会话(cx.workspaces 提供 archiveSession 服务面)。
+ workspacesRuntime: cx.workspaces as unknown as WorkspacesRuntime,
+ },
} as never,
WorktreeModeSelect,
))
diff --git a/packages/dsh-tauri-worktree/src/client/styles/index.ts b/packages/dsh-tauri-worktree/src/client/styles/index.ts
index db283eca..09490cb2 100644
--- a/packages/dsh-tauri-worktree/src/client/styles/index.ts
+++ b/packages/dsh-tauri-worktree/src/client/styles/index.ts
@@ -33,7 +33,9 @@ export function mountModeSelectStyles(): () => void {
c(`.${MODE_SELECT_CLASSES.triggerOpen}`, { background: 'var(--dsw-alias-interactive-bg-hover)' }),
c(`.${MODE_SELECT_CLASSES.icon}`, { color: 'var(--dsw-alias-label-primary)', display: 'inline-flex', flex: 'none' }),
c(`.${MODE_SELECT_CLASSES.chevron}`, { color: 'var(--dsw-alias-label-caption)', flex: 'none' }),
- c(`.${MODE_SELECT_CLASSES.host}`, { display: 'inline-flex', alignItems: 'center' }),
+ // host 现在是 .tools 的直接 flex 子元素(gap 16px);flex:none 防止长文案触发被压缩、
+ // 以及部分浏览器对 inline-flex 的收缩行为导致控件宽度塌陷。
+ c(`.${MODE_SELECT_CLASSES.host}`, { display: 'inline-flex', alignItems: 'center', flex: 'none' }),
c(`.${MODE_SELECT_CLASSES.anchor}`, { display: 'none' }),
])
style.mount({ id: MODE_SELECT_STYLE_ID, head: true })
diff --git a/packages/dsh-tauri-worktree/src/client/types/runtime.ts b/packages/dsh-tauri-worktree/src/client/types/runtime.ts
index f0a29dd7..14843d4d 100644
--- a/packages/dsh-tauri-worktree/src/client/types/runtime.ts
+++ b/packages/dsh-tauri-worktree/src/client/types/runtime.ts
@@ -16,6 +16,9 @@ export interface SessionsRuntime {
create: (opts: { cwd: string, sessionId: string }) => Promise<string>
open: (sessionId: string) => void
provideInfo: (sessionId: string) => { props?: { inputActions?: InputActions } } | undefined
+ /** 刷新会话列表(宿主侧 seed 创建的会话会发布进来;本插件在 waitForSessionListed 中调用)。 */
+ refresh: () => Promise<void>
+ list: { getSnapshot: () => { ids: string[], current?: string } }
}
export interface ModeSelectProps {
@@ -23,6 +26,8 @@ export interface ModeSelectProps {
useInput: <S>(selector: (state: InputState) => S) => S
inputActions: InputActions
sessionsRuntime: SessionsRuntime
+ /** 归档源会话用:切换工作树成功后,删除被完整继承的源会话,避免侧边栏多出一个重复会话。 */
+ workspacesRuntime: WorkspacesRuntime
}
export interface SurfaceBarProps {
diff --git a/packages/dsh-tauri-worktree/src/client/types/worktree.ts b/packages/dsh-tauri-worktree/src/client/types/worktree.ts
index acd74d91..552eec84 100644
--- a/packages/dsh-tauri-worktree/src/client/types/worktree.ts
+++ b/packages/dsh-tauri-worktree/src/client/types/worktree.ts
@@ -66,6 +66,11 @@ export interface WorktreeCreate {
sourceSessionId: string
log: string[]
existed: boolean
+ /**
+ * 宿主是否已把源会话的完整事件作为 seed 建好工作树会话(问题 2 的修复)。
+ * true 表示客户端不得再用 create 新建空白会话,而应等待该会话 in-list 后直接使用。
+ */
+ inherited: boolean
}
/** 检出本地:把工作树改动带回本地分支,解除绑定,恢复本地会话。 */
diff --git a/packages/dsh-tauri-worktree/src/client/utils/worktree.test.ts b/packages/dsh-tauri-worktree/src/client/utils/worktree.test.ts
new file mode 100644
index 00000000..76a4841e
--- /dev/null
+++ b/packages/dsh-tauri-worktree/src/client/utils/worktree.test.ts
@@ -0,0 +1,53 @@
+/**
+ * worktree.test.ts — worktree.ts 纯函数单测(resolveAccessModeGroup)。
+ *
+ * 用轻量结构替身(只含 parentElement / contains)模拟官方 composer .modes 布局:
+ * 访问模式按钮被包在 Menu root span 里,祖父才是 .modes 分组(含 plan 槽位)。
+ * 不依赖 jsdom,在默认 node 环境即可运行。
+ */
+import { describe, expect, it } from 'vitest'
+import { resolveAccessModeGroup } from './worktree'
+
+interface NodeStub {
+ parentElement: NodeStub | null
+ contains: (other: unknown) => boolean
+}
+
+/** 构造 `button ∈ Menu-root-span ∈ .modes(含 planSlot)` 的最小骨架。 */
+function buildModesSkeleton(): { modes: NodeStub, menuRoot: NodeStub, button: NodeStub, planSlot: NodeStub } {
+ const modes: NodeStub = { parentElement: null, contains: () => false }
+ const menuRoot: NodeStub = { parentElement: modes, contains: () => false }
+ const button: NodeStub = { parentElement: menuRoot, contains: () => false }
+ const planSlot: NodeStub = { parentElement: modes, contains: () => false }
+ // .modes 能包含 plan 槽位与 button(向上找到自身即可命中)。
+ modes.contains = other => other === planSlot || other === menuRoot
+ return { modes, menuRoot, button, planSlot }
+}
+
+describe('resolveAccessModeGroup', () => {
+ it('从访问模式按钮向上定位到包含 plan 槽位的 .modes 分组(而非 Menu root span)', () => {
+ const { modes, button, planSlot } = buildModesSkeleton()
+ // 目标须为能包含 plan 槽位的公共父节点:第二层(button → menuRoot → modes)触发 contains 命中。
+ const target = resolveAccessModeGroup(button as unknown as HTMLElement, planSlot as unknown as Element)
+ expect(target).toBe(modes as unknown as HTMLElement)
+ })
+
+ it('plan 槽位缺失(alpha 变体)时退回 Menu root span 的父节点', () => {
+ const { modes, button } = buildModesSkeleton()
+ const target = resolveAccessModeGroup(button as unknown as HTMLElement, null)
+ expect(target).toBe(modes as unknown as HTMLElement)
+ })
+
+ it('按钮悬浮(向上链路断)时回退返回按钮本身,控件不消失', () => {
+ const button: NodeStub = { parentElement: null, contains: () => false }
+ const target = resolveAccessModeGroup(button as unknown as HTMLElement, null)
+ expect(target).toBe(button as unknown as HTMLElement)
+ })
+
+ it('超过 maxDepth 仍未命中时回退返回按钮本身', () => {
+ const { button, planSlot } = buildModesSkeleton()
+ // 从 button 直达 .modes 需 2 层;maxDepth=1 使循环提前退出,回退按钮本身。
+ const target = resolveAccessModeGroup(button as unknown as HTMLElement, planSlot as unknown as Element, 1)
+ expect(target).toBe(button as unknown as HTMLElement)
+ })
+})
diff --git a/packages/dsh-tauri-worktree/src/client/utils/worktree.ts b/packages/dsh-tauri-worktree/src/client/utils/worktree.ts
index ddb25a6e..b7df64b6 100644
--- a/packages/dsh-tauri-worktree/src/client/utils/worktree.ts
+++ b/packages/dsh-tauri-worktree/src/client/utils/worktree.ts
@@ -4,6 +4,7 @@
*/
import type { SessionsRuntime, WorkspaceSessionOrder } from '../types'
+import { SESSION_SWITCH_MAX_ATTEMPTS, SESSION_SWITCH_RETRY_DELAY_MS } from '../constants'
/**
* 等待新工作树会话的输入服务就绪(新建会话发布与 Session scope 可寻址
@@ -19,6 +20,57 @@ export async function waitForInputActions(sessionsRuntime: SessionsRuntime, sess
throw new Error('新工作树会话的输入服务尚未就绪')
}
+/**
+ * 从「访问模式」按钮向上找到官方输入条里的 `.modes` 分组(访问模式按钮 + 计划槽位所在行)。
+ *
+ * 官方 DOM(dsh 0.1.1-rc.x):访问模式 `<Menu anchor={button}>` 没传 portal,`button`
+ * 被包在 Menu root span 里,祖父才是 `.modes` 分组。直接把控件插到 button 右边会落进
+ * Menu root span 内部(无 gap 且被计划槽位挤压);必须定位到 `.modes` 容器本身。
+ * `.modes` 是生成 CSS module hash(`.uV2eYG_modes`),不能依赖,故用语义判定:
+ * - 有 plan 槽位时,能容纳该 slot 的祖先即是 `.modes`(访问模式按钮与 plan slot 的公共父)。
+ * - 无 plan 槽位(alpha 变体)时退回「Menu root span 的父节点」。
+ * 纯函数、不查 DOM:planSlot 由调用方按需传入。
+ *
+ * @param button 访问模式按钮(closest COMPOSER_MODE_BUTTON_SELECTOR)
+ * @param planSlot 输入条内 plan 槽位节点,缺失时走第二规则
+ * @param maxDepth 向上最多追溯层数(防御性上限,默认 8)
+ * @returns 定位到的 `.modes` 分组节点;找不到时回退返回 button 本身(保证控件不消失)
+ */
+export function resolveAccessModeGroup(button: HTMLElement, planSlot: Element | null, maxDepth = 8): HTMLElement {
+ let previous: HTMLElement = button
+ let node: HTMLElement | null = button.parentElement
+ for (let depth = 0; node && depth < maxDepth; depth++) {
+ if (planSlot ? node.contains(planSlot) : previous !== button)
+ return node
+ previous = node
+ node = node.parentElement
+ }
+ // graceful fallback:未知布局时把控件放在按钮自身之后,避免完整消失。
+ return button
+}
+
+/**
+ * 等待托管侧带 seed 创建的工作树会话进入客户端会话列表。
+ *
+ * 宿主侧 seed 创建的会话必须先经 session-added 帧(或 refreshList 兜底)进入客户端
+ * list,provideInfo/create 才能寻址到它;直接用 create 会抛「已存在会话」或拿不到句柄。
+ * 当 createWorktree 返回 inherited:true 时须走本函数代替 create。
+ */
+export async function waitForSessionListed(
+ sessionsRuntime: SessionsRuntime,
+ sessionId: string,
+ attempts = SESSION_SWITCH_MAX_ATTEMPTS,
+ delayMs = SESSION_SWITCH_RETRY_DELAY_MS,
+): Promise<void> {
+ for (let attempt = 0; attempt < attempts; attempt++) {
+ if (sessionsRuntime.list?.getSnapshot().ids.includes(sessionId))
+ return
+ await sessionsRuntime.refresh?.()
+ await new Promise<void>(resolve => window.setTimeout(resolve, delayMs))
+ }
+ throw new Error('新工作树会话尚未就绪')
+}
+
/** 返回目标工作区与当前首个其他会话,供检出会话插到工作区最上方。 */
export function resolveWorkspaceTopInsertion(
workspaces: readonly WorkspaceSessionOrder[],
diff --git a/packages/dsh-tauri-worktree/src/host/routes/index.ts b/packages/dsh-tauri-worktree/src/host/routes/index.ts
index 18f11c73..63734492 100644
--- a/packages/dsh-tauri-worktree/src/host/routes/index.ts
+++ b/packages/dsh-tauri-worktree/src/host/routes/index.ts
@@ -13,7 +13,7 @@ import { routeHandler, withConnectionAuth } from 'dsh-tauri'
import { join } from 'pathe'
import { WORKTREE_API_PREFIX } from '../../shared/constants.js'
import { gitToplevel } from '../service/git.js'
-import { checkoutToLocalAndHandback } from '../service/handoff.js'
+import { checkoutToLocalAndHandback, inheritSessionIntoWorktree } from '../service/handoff.js'
import { discardWorktree, ensureWorktree, worktreeKey } from '../service/operation.js'
import { findSession, resolveProjectPath } from '../service/session.js'
import { loadLedger } from '../storage/index.js'
@@ -71,6 +71,20 @@ export function buildRoutes(ctx: HostContext, config: PluginConfig): any[] {
})
if (!r.ok)
return [400, { error: r.error }]
+ // 继承源会话完整对话历史:仅当客户端请求 inherit 且源会话确有事件时,宿主才用
+ // sourceSession.events 作为 seed 建好「已是完整会话」的工作树会话(问题 2 的修复)。
+ // 否则回退官方空白会话路径(客户端用 sessionsRuntime.create({ cwd }) 兜底)。
+ let inherited = false
+ if (body.inherit === true) {
+ const inheritedSession = await inheritSessionIntoWorktree(
+ ctx,
+ worktreesRoot,
+ sourceSessionId,
+ sessionId,
+ r.binding.worktreePath,
+ )
+ inherited = inheritedSession.ok
+ }
return [200, {
ok: true,
hash: r.binding.hash,
@@ -81,6 +95,7 @@ export function buildRoutes(ctx: HostContext, config: PluginConfig): any[] {
sourceSessionId: r.binding.sourceSessionId,
log: r.log,
existed: r.existed,
+ inherited,
}]
}, { mutate: true }),
},
diff --git a/packages/dsh-tauri-worktree/src/host/service/handoff.ts b/packages/dsh-tauri-worktree/src/host/service/handoff.ts
index a623e0a4..6841bec7 100644
--- a/packages/dsh-tauri-worktree/src/host/service/handoff.ts
+++ b/packages/dsh-tauri-worktree/src/host/service/handoff.ts
@@ -20,6 +20,102 @@ import { setPendingCheckoutContext } from '../storage/index.js'
import { checkoutToLocal, discardWorktree } from './operation.js'
import { findSession } from './session.js'
+/**
+ * 用源会话的完整事件创建继承会话(cwd 指向目标路径),供「检出本地」「正在新建工作树」
+ * 两类交接复用。继承发生在源会话 events 完整时,否则返回 ok:false。
+ *
+ * @param ctx 宿主根上下文
+ * @param sourceSessionId 源会话 id(其 events 作为 seed)
+ * @param options 创建选项
+ * @param options.seed 显式 seed(缺省取 sourceSession.events)
+ * @param options.cwd 新会话工作目录
+ * @param options.parentSession 记录到 meta.parentSession 的源会话 id
+ * @param options.attach 是否创建后归属到 cwd 对应的 Workspace
+ * @param options.targetSessionId 固定新会话 id(缺省生成随机 id)
+ * @returns 新会话 id + 继承的事件条数
+ */
+export async function createInheritedSession(
+ ctx: HostContext,
+ sourceSessionId: string,
+ options: {
+ seed?: unknown[]
+ cwd: string
+ parentSession?: string
+ attach?: boolean
+ /** 固定新会话 id;缺省时生成随机 id。宿主在预分配会话 id 时(如工作树绑定)必须传入。 */
+ targetSessionId?: string
+ } = { cwd: '' },
+): Promise<OperationResult<{ targetSessionId: string, seedLength: number }>> {
+ const agent = ctx.agents?.get?.(sourceSessionId)
+ const sourceSession = agent?.session ?? findSession(ctx, sourceSessionId)
+ if (!sourceSession)
+ return { ok: false, error: `未找到源会话:${sourceSessionId}` }
+ const seed = options.seed ?? (Array.isArray(sourceSession.events) ? sourceSession.events : [])
+ if (seed.length === 0)
+ return { ok: false, error: `源会话没有可继承的事件:${sourceSessionId}` }
+ const { cwd, attach = false } = options
+ const targetSessionId = options.targetSessionId ?? `session-${randomUUID()}`
+ try {
+ const presets = ctx.get?.('agentPresets')
+ const parentPreset = agent
+ ? (presets?.composedPreset(agent.ctx) ?? sourceSession.header?.agentPreset)
+ : sourceSession.header?.agentPreset
+ const createOptions: any = {
+ sessionId: targetSessionId,
+ seed,
+ meta: {
+ cwd,
+ parentSession: options.parentSession ?? sourceSession.id,
+ seedLength: seed.length,
+ ...(parentPreset ? { agentPreset: parentPreset } : {}),
+ },
+ agentOptions: agent?.options ?? {},
+ }
+ if (agent && presets && parentPreset) {
+ createOptions.setup = (agentCtx: any) => {
+ presets.composeFrom(agentCtx, agent.ctx)
+ }
+ }
+ await ctx.agents.create(createOptions)
+ if (attach) {
+ const workspace = await ctx.workspaceRegistry.resolveByPath(cwd)
+ if (workspace)
+ await workspace.attachSession(targetSessionId)
+ }
+ return { ok: true, targetSessionId, seedLength: seed.length }
+ }
+ catch (error) {
+ return { ok: false, error: error instanceof Error ? error.message : String(error) }
+ }
+}
+
+/**
+ * 创建工作树会话并继承源会话完整对话历史(客户端「工作模式 → 新建工作树」流程)。
+ *
+ * 背景:客户端 UI 用 sessionsRuntime.create({ cwd }) 创建的目标会话是空白的;只有在
+ * 触发工具那一条消息被迁移后才有 1 轮对话(完整源会话对不上)。本函数在创建绑定的同时
+ * 用源会话完整事件作 seed 建好工作树会话,保证新工作树会话带全量上下文。
+ * 注意:**不在宿主内 attach**——沿客户端既有 /attach 步骤归属 Workspace;seed 沿用源会话
+ * 现有事件(此时源 turn 尚未结束,工作树预选流程在消息提交前启用),不做追加。cwd 传入
+ * 新工作树路径(客户端后续把该会话锚定到工作树目录)。
+ *
+ * @returns ok=false 表示源会话无事件可继承(客户端回退官方 create 空白会话路径)。
+ */
+export async function inheritSessionIntoWorktree(
+ ctx: HostContext,
+ worktreesRoot: string,
+ sourceSessionId: string,
+ targetSessionId: string,
+ cwd: string,
+): Promise<OperationResult<{ targetSessionId: string, seedLength: number }>> {
+ void worktreesRoot
+ return createInheritedSession(
+ ctx,
+ sourceSessionId,
+ { cwd, parentSession: sourceSessionId, attach: false, targetSessionId },
+ )
+}
+
/**
* 把工作树会话的完整对话历史带回本地仓库:以工作树会话的全部事件为 seed 创建
* 继承会话,cwd 指向本地项目路径,并归属源 Workspace。