Skip to content

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

fix(worktree): 兼容 0.1.5-alpha.1 附件 API 并自动链接依赖目录

hairyf128818df7c33
diff --git a/packages/dsh-tauri-worktree/README.md b/packages/dsh-tauri-worktree/README.md
index 07bc9d71..e0bc1f42 100644
--- a/packages/dsh-tauri-worktree/README.md
+++ b/packages/dsh-tauri-worktree/README.md
@@ -7,6 +7,7 @@
## 功能
- 按项目路径和会话 ID 创建稳定、可复用的隔离工作树。
+- 新建工作树自动把源仓库的依赖目录(默认 `node_modules`)链接进来,开箱即用;执行安装命令前自动断开链接,使安装在工作树内物化成一份独立依赖。
- 注册 `create_worktree`、`checkout_worktree` 工具。
- `create_worktree` / `checkout_worktree` 支持可选 `carry_staged` 参数(默认 `false`):把已暂存(index)改动携带进新工作树、或携带回本地检出,避免暂存内容在隔离/移除工作树时丢失。
- 提供创建、状态、检出和放弃 API:`/api/dsh-worktree/*`。
@@ -38,6 +39,25 @@ checkout_worktree({ worktree_hash_dirname: '[hash]/[dirname]', branch_name: 'dsh
- 创建时始终以本地 `refs/heads/main` 为内容来源;若该分支不存在或无法解析,创建会在执行 worktree 操作前明确失败。
- 创建时携带失败会回滚刚创建的工作树;检出时携带失败会回滚到检出前分支并保留工作树。
+## 依赖目录自动链接(安装后独立)
+
+`git worktree add` 只检出 tracked 文件,`node_modules` 等被 gitignore 的依赖目录不会跟随。
+每次都完整安装代价高,因此新建工作树时默认把**源仓库的依赖目录以目录联接挂进工作树**
+(Windows junction / POSIX 目录符号链接),工作树开箱即用。
+
+链接是共享的:包管理器若直接写入会穿透链接污染源仓库 —— pnpm 还会把源仓库的 workspace
+链接改写成指向工作树,工作树删除后留下一批悬空链接(
+[pnpm#14286](https://github.com/pnpm/pnpm/issues/14286))。因此插件在 `tools/execute`
+钩子里检测到安装类命令(`pnpm/npm/yarn/bun install|add|ci…`、`pip/uv/poetry`、`cargo`、
+`go mod`、`bundle`、`composer` 等)时,会**先摘掉工作树内的链接**,让这次安装在
+工作树内物化成一份独立目录,源仓库不受影响。
+
+- 断开只删链接本身,绝不递归链接目标;已独立安装的真实目录原样保留。
+- 放弃/检出删除工作树前同样先断开链接,确保 `fs.rm` 不会进入源仓库。
+- 链接失败(权限/占用/跨卷)只记录日志,不阻断工作树创建;此时按提示自行安装即可。
+- 链接目录可配置:`linkDependencies`(默认 `true`)与 `linkDependencyDirectories`
+ (默认 `['node_modules']`)。
+
## 可靠删除(junction 安全)
放弃/检出会移除工作树目录。Git for Windows 旧版本递归删除时会跟随 NTFS junction,
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 15c70950..5d382811 100644
--- a/packages/dsh-tauri-worktree/src/client/components/mode-select.tsx
+++ b/packages/dsh-tauri-worktree/src/client/components/mode-select.tsx
@@ -27,6 +27,7 @@ import {
rememberNewSessionMode,
useWorktreeSession,
} from '../store'
+import { addDraftAttachments, draftAttachmentIds, removeDraftAttachment } from '../utils/draft-attachments'
import { resolveAccessModeGroup, waitForInputActions, waitForSessionListed } from '../utils/worktree'
export function WorktreeModeSelect(props: ModeSelectProps): ReactElement {
@@ -92,7 +93,7 @@ export function WorktreeModeSelect(props: ModeSelectProps): ReactElement {
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)
+ const imageIds = useInput(draftAttachmentIds)
useLocale()
const [open, setOpen] = useState(false)
const submittingRef = useRef(false)
@@ -137,10 +138,10 @@ function WorktreeModeControl({ sessionId, useInput, inputActions, sessionsRuntim
await attachWorktreeSession(targetSessionId)
const nextActions = await waitForInputActions(sessionsRuntime, targetSessionId)
nextActions.setDraft(draft)
- if (imageIds.length > 0 && !nextActions.addImages(imageIds))
+ if (!addDraftAttachments(nextActions, imageIds))
throw new Error('无法迁移消息附件到工作树会话')
inputActions.setDraft('')
- for (const imageId of imageIds) inputActions.removeImage(imageId)
+ for (const imageId of imageIds) removeDraftAttachment(inputActions, imageId)
patchSession(sessionId, { mode: 'local', phase: 'idle', loadingLabel: '' })
sessionsRuntime.open(targetSessionId)
// 迁移草稿后提交到新工作树会话;submit() 会在进入时同步捕获草稿/附件快照再发送。
@@ -151,7 +152,7 @@ function WorktreeModeControl({ sessionId, useInput, inputActions, sessionsRuntim
}
finally {
nextActions.setDraft('')
- for (const imageId of imageIds) nextActions.removeImage(imageId)
+ for (const imageId of imageIds) removeDraftAttachment(nextActions, imageId)
}
})
// 源会话完整对话已继承进工作树会话:归档源会话,避免侧边栏多出一个重复会话。
diff --git a/packages/dsh-tauri-worktree/src/client/types/runtime.ts b/packages/dsh-tauri-worktree/src/client/types/runtime.ts
index 40a96b4a..22108d06 100644
--- a/packages/dsh-tauri-worktree/src/client/types/runtime.ts
+++ b/packages/dsh-tauri-worktree/src/client/types/runtime.ts
@@ -24,15 +24,25 @@ export interface WorkspaceSnapshot {
items: readonly WorkspaceView[]
}
+/**
+ * 输入条草稿状态。字段名跨核心版本不一致,两个都声明为可选:
+ * - rc.x 及更早:`imageIds`
+ * - 0.1.5-alpha.1 起:`attachmentIds`
+ * 消费方必须经 `utils/draft-attachments.ts` 的兼容读取函数访问,不能直接取单一字段。
+ */
export interface InputState {
draft: string
- imageIds: string[]
+ imageIds?: string[]
+ attachmentIds?: string[]
}
+/** 输入条动作面;同样按核心版本二选一(rc.x 的 addImages/removeImage ↔ alpha 的 addAttachments/removeAttachment)。 */
export interface InputActions {
setDraft: (text: string) => void
- addImages: (ids: string[]) => boolean
- removeImage: (id: string) => void
+ addImages?: (ids: string[]) => boolean
+ removeImage?: (id: string) => void
+ addAttachments?: (ids: string[]) => boolean
+ removeAttachment?: (id: string) => void
submit: () => void
}
diff --git a/packages/dsh-tauri-worktree/src/client/utils/draft-attachments.test.ts b/packages/dsh-tauri-worktree/src/client/utils/draft-attachments.test.ts
new file mode 100644
index 00000000..b9c0daf3
--- /dev/null
+++ b/packages/dsh-tauri-worktree/src/client/utils/draft-attachments.test.ts
@@ -0,0 +1,73 @@
+/**
+ * draft-attachments.test.ts — 输入条附件 API 的跨核心版本兼容回归。
+ *
+ * 0.1.5-alpha.1 把 imageIds/addImages/removeImage 改名为
+ * attachmentIds/addAttachments/removeAttachment;旧核心下读 attachmentIds 会拿到
+ * undefined,旧插件直接取 imageIds 则是新核心下 `Cannot read properties of undefined
+ * (reading 'length')` 的根因。
+ */
+
+import { describe, expect, it, vi } from 'vitest'
+import {
+ addDraftAttachments,
+ draftAttachmentIds,
+ NO_DRAFT_ATTACHMENTS,
+ removeDraftAttachment,
+} from './draft-attachments'
+
+describe('draftAttachmentIds', () => {
+ it('prefers the alpha attachmentIds field', () => {
+ expect(draftAttachmentIds({ draft: '', attachmentIds: ['a'] })).toEqual(['a'])
+ })
+
+ it('falls back to the legacy imageIds field', () => {
+ expect(draftAttachmentIds({ draft: '', imageIds: ['b'] })).toEqual(['b'])
+ })
+
+ it('returns a stable empty array when neither field is present', () => {
+ const first = draftAttachmentIds({ draft: '' })
+ const second = draftAttachmentIds(undefined)
+ expect(first).toBe(NO_DRAFT_ATTACHMENTS)
+ expect(second).toBe(NO_DRAFT_ATTACHMENTS)
+ expect(first.length).toBe(0)
+ })
+})
+
+describe('addDraftAttachments', () => {
+ it('uses addAttachments when the alpha action face is present', () => {
+ const addAttachments = vi.fn(() => true)
+ const addImages = vi.fn(() => true)
+ expect(addDraftAttachments({ setDraft: vi.fn(), submit: vi.fn(), addAttachments, addImages }, ['a'])).toBe(true)
+ expect(addAttachments).toHaveBeenCalledWith(['a'])
+ expect(addImages).not.toHaveBeenCalled()
+ })
+
+ it('uses the legacy addImages action when addAttachments is absent', () => {
+ const addImages = vi.fn(() => true)
+ expect(addDraftAttachments({ setDraft: vi.fn(), submit: vi.fn(), addImages }, ['a'])).toBe(true)
+ expect(addImages).toHaveBeenCalledWith(['a'])
+ })
+
+ it('is a no-op success without attachments and a failure when the action face is missing', () => {
+ expect(addDraftAttachments({ setDraft: vi.fn(), submit: vi.fn() }, [])).toBe(true)
+ expect(addDraftAttachments({ setDraft: vi.fn(), submit: vi.fn() }, ['a'])).toBe(false)
+ expect(addDraftAttachments(undefined, ['a'])).toBe(false)
+ })
+})
+
+describe('removeDraftAttachment', () => {
+ it('prefers removeAttachment over the legacy removeImage', () => {
+ const removeAttachment = vi.fn()
+ const removeImage = vi.fn()
+ removeDraftAttachment({ setDraft: vi.fn(), submit: vi.fn(), removeAttachment, removeImage }, 'a')
+ expect(removeAttachment).toHaveBeenCalledWith('a')
+ expect(removeImage).not.toHaveBeenCalled()
+ })
+
+ it('falls back to removeImage and tolerates a missing action face', () => {
+ const removeImage = vi.fn()
+ removeDraftAttachment({ setDraft: vi.fn(), submit: vi.fn(), removeImage }, 'a')
+ expect(removeImage).toHaveBeenCalledWith('a')
+ expect(() => removeDraftAttachment(undefined, 'a')).not.toThrow()
+ })
+})
diff --git a/packages/dsh-tauri-worktree/src/client/utils/draft-attachments.ts b/packages/dsh-tauri-worktree/src/client/utils/draft-attachments.ts
new file mode 100644
index 00000000..e4186e61
--- /dev/null
+++ b/packages/dsh-tauri-worktree/src/client/utils/draft-attachments.ts
@@ -0,0 +1,46 @@
+/**
+ * draft-attachments.ts — 输入条草稿附件的跨核心版本兼容读取。
+ *
+ * DSH 核心在 0.1.5-alpha.1 把输入条草稿字段与动作从
+ * `imageIds` / `addImages` / `removeImage` 改名为
+ * `attachmentIds` / `addAttachments` / `removeAttachment`。
+ * 工作树插件需要同时兼容两条版本线:直接读 `input.imageIds` 在新核心下是
+ * undefined,`imageIds.length` 会抛
+ * `Cannot read properties of undefined (reading 'length')`,
+ * 使「新建工作树」在宿主创建成功后于客户端阶段整体失败。
+ *
+ * 纯函数、无副作用,便于单测;消费方一律经本模块访问,不直接取单一字段名。
+ */
+
+import type { InputActions, InputState } from '../types'
+
+/** 稳定空数组:useInput 选择器每次返回新数组会触发无谓重渲染。 */
+export const NO_DRAFT_ATTACHMENTS: readonly string[] = []
+
+/** 读取草稿附件 id 列表(优先新核心的 attachmentIds,回退旧核心的 imageIds)。 */
+export function draftAttachmentIds(state: InputState | undefined): readonly string[] {
+ return state?.attachmentIds ?? state?.imageIds ?? NO_DRAFT_ATTACHMENTS
+}
+
+/**
+ * 把草稿附件迁移到目标会话的输入动作面。
+ * @returns 是否全部迁移成功;无附件恒为 true,确有附件但两个动作面都缺失时为 false。
+ */
+export function addDraftAttachments(actions: InputActions | undefined, ids: readonly string[]): boolean {
+ if (ids.length === 0)
+ return true
+ if (typeof actions?.addAttachments === 'function')
+ return actions.addAttachments([...ids])
+ if (typeof actions?.addImages === 'function')
+ return actions.addImages([...ids])
+ return false
+}
+
+/** 从输入动作面移除单个草稿附件(兼容两种核心版本的动作名)。 */
+export function removeDraftAttachment(actions: InputActions | undefined, id: string): void {
+ if (typeof actions?.removeAttachment === 'function') {
+ actions.removeAttachment(id)
+ return
+ }
+ actions?.removeImage?.(id)
+}
diff --git a/packages/dsh-tauri-worktree/src/host/apply.ts b/packages/dsh-tauri-worktree/src/host/apply.ts
index b416ac44..3f640550 100644
--- a/packages/dsh-tauri-worktree/src/host/apply.ts
+++ b/packages/dsh-tauri-worktree/src/host/apply.ts
@@ -16,6 +16,7 @@ import { WORKTREE_SECTION_ORDER } from '../shared/constants'
import { createWorktreeHooks } from './hooks'
import { buildRoutes } from './routes'
import { completeWorktreeHandoff } from './service/handoff'
+import { materializeLinkedDependencies } from './service/install-hook'
import { unregisterWorktreeWorkspace, worktreeKey } from './service/operation'
import {
clearPendingCheckoutContext,
@@ -64,6 +65,20 @@ export function apply(ctx: HostContext, config: PluginConfig = {}): void {
void hooks.callHook('session:turn-end', session, event)
})
+ // 1.5) 安装依赖前断开工作树内的共享链接:链接让工作树开箱可用,但包管理器直接写入会
+ // 穿透链接污染源仓库(pnpm 还会把源仓库的 workspace 链接改写成指向工作树)。
+ // 在工具真正执行前(tools/execute,位于策略与审批之后)断开,安装即在
+ // 工作树内物化成独立依赖目录。钩子失败只记录日志,绝不阻断工具调用。
+ ctx.on('tools/execute', async (exec: any, next: any) => {
+ try {
+ await materializeLinkedDependencies(ctx, worktreesRoot, cfg.linkDependencyDirectories, exec)
+ }
+ catch (error) {
+ ctx.logger?.warn?.(`dsh-tauri-worktree: dependency link materialization failed: ${String(error)}`)
+ }
+ return next()
+ })
+
// 2) 旧版本遗留自愈:拆除整表 ledger.json(一次性迁移到按会话文件),并只注销
// 普通 Workspace 记录,不删工作树或会话。
ctx.effect(() => {
@@ -117,8 +132,9 @@ export function apply(ctx: HostContext, config: PluginConfig = {}): void {
+ `Worktree path: ${binding.worktreePath}\n`
+ `Project path: ${binding.projectPath}\n\n`
+ `Make code changes inside the bound worktree and use its path as the shell workdir. `
- + `The worktree contains only tracked files: node_modules and generated build dirs are not carried over, `
- + `so if the project needs its dependencies, run the package manager install (e.g. \`pnpm install\`) inside the worktree first. `
+ + `Dependency directories (e.g. node_modules) are linked from the source repository so the worktree works out of the box. `
+ + `Running a package manager install (e.g. \`pnpm install\`) inside the worktree first detaches that link and materializes an independent copy, `
+ + `leaving the source repository untouched. `
+ `checkout_worktree is user-authorized only: call it only after a direct human user explicitly requests or approves checkout. `
+ `Task completion, a merged PR, or inferred convenience is not permission to call it. When checkout would be a natural next step, `
+ `such as after a PR is merged, you may ask the user whether they want to check out the worktree; wait for their approval before calling.`
diff --git a/packages/dsh-tauri-worktree/src/host/routes/index.ts b/packages/dsh-tauri-worktree/src/host/routes/index.ts
index 77916d9a..9cb6f8cf 100644
--- a/packages/dsh-tauri-worktree/src/host/routes/index.ts
+++ b/packages/dsh-tauri-worktree/src/host/routes/index.ts
@@ -61,7 +61,7 @@ export function buildRoutes(ctx: HostContext, config: PluginConfig): any[] {
const result = await discardWorktree(ctx, worktreesRoot, {
sessionId: job.sessionId,
worktree_hash_dirname: worktreeHashDirname,
- })
+ }, { linkDependencyDirectories: config.linkDependencyDirectories })
if (result.ok) {
const updated: DiscardJob = { ...job, state: 'completed' }
discardJobs.set(job.jobId, updated)
@@ -147,6 +147,8 @@ export function buildRoutes(ctx: HostContext, config: PluginConfig): any[] {
const r = await ensureWorktree(ctx, worktreesRoot, projectPath, sessionId, {
sourceSessionId,
carryStaged: body.carryStaged === true,
+ linkDependencies: config.linkDependencies,
+ linkDependencyDirectories: config.linkDependencyDirectories,
})
if (!r.ok)
return [400, { error: r.error }]
@@ -205,7 +207,10 @@ export function buildRoutes(ctx: HostContext, config: PluginConfig): any[] {
sessionId: String(body.sessionId ?? ''),
worktree_hash_dirname: String(body.worktreeHashDirname ?? ''),
branch_name: String(body.branchName ?? ''),
- }, { carryStaged: body.carryStaged === true })
+ }, {
+ carryStaged: body.carryStaged === true,
+ linkDependencyDirectories: config.linkDependencyDirectories,
+ })
if (!r.ok)
return [400, { error: r.error }]
return [200, {
diff --git a/packages/dsh-tauri-worktree/src/host/service/dependencies.test.ts b/packages/dsh-tauri-worktree/src/host/service/dependencies.test.ts
new file mode 100644
index 00000000..92f046d9
--- /dev/null
+++ b/packages/dsh-tauri-worktree/src/host/service/dependencies.test.ts
@@ -0,0 +1,138 @@
+/**
+ * dependencies.test.ts — 依赖目录链接/断开的真实文件系统行为与安装命令识别。
+ *
+ * 关键回归:断开链接必须只摘链接、不递归目标(否则会删掉源仓库的 node_modules),
+ * 且真实目录(已独立安装)必须原样保留。
+ */
+
+import { lstat, mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises'
+import { tmpdir } from 'node:os'
+import { join } from 'pathe'
+import { afterEach, describe, expect, it } from 'vitest'
+import {
+ isDependencyInstallCommand,
+ linkWorktreeDependencies,
+ normalizeLinkDirectories,
+ unlinkWorktreeDependencies,
+} from './dependencies'
+
+const temporaryDirectories: string[] = []
+
+async function temporaryRoot(prefix: string): Promise<string> {
+ const root = await mkdtemp(join(tmpdir(), prefix))
+ temporaryDirectories.push(root)
+ return root
+}
+
+/** 构造「源仓库 + 工作树」两目录,源仓库的 node_modules/pkg/index.js 有内容。 */
+async function createFixture(): Promise<{ project: string, worktree: string, marker: string }> {
+ const project = await temporaryRoot('dsh-deps-project-')
+ const worktree = await temporaryRoot('dsh-deps-worktree-')
+ const marker = join(project, 'node_modules', 'pkg', 'index.js')
+ await mkdir(join(project, 'node_modules', 'pkg'), { recursive: true })
+ await writeFile(marker, 'shared-dependency\n')
+ return { project, worktree, marker }
+}
+
+afterEach(async () => {
+ await Promise.all(temporaryDirectories.splice(0).map(path => rm(path, { recursive: true, force: true })))
+})
+
+describe('normalizeLinkDirectories', () => {
+ it('falls back to node_modules for empty input and dedupes preserving order', () => {
+ expect(normalizeLinkDirectories()).toEqual(['node_modules'])
+ expect(normalizeLinkDirectories([])).toEqual(['node_modules'])
+ expect(normalizeLinkDirectories(['.venv', 'node_modules', '.venv'])).toEqual(['.venv', 'node_modules'])
+ })
+
+ it('rejects path traversal and separator-bearing entries', () => {
+ expect(normalizeLinkDirectories(['../evil', 'a/b', 'a\\b', '.', '..', '', ' '])).toEqual([])
+ expect(normalizeLinkDirectories(['node_modules/'])).toEqual(['node_modules'])
+ })
+})
+
+describe('isDependencyInstallCommand', () => {
+ it.each([
+ 'pnpm install',
+ 'pnpm i',
+ 'pnpm add lodash',
+ 'npm ci',
+ 'npm install --frozen-lockfile',
+ 'yarn',
+ 'yarn add react',
+ 'bun install',
+ 'cd packages/app && pnpm install',
+ 'pip install -r requirements.txt',
+ 'uv sync',
+ 'cargo build',
+ 'go mod download',
+ 'bundle install',
+ 'composer install',
+ ])('detects %s', (command) => {
+ expect(isDependencyInstallCommand(command)).toBe(true)
+ })
+
+ it.each([
+ '',
+ 'pnpm run build',
+ 'npm test',
+ 'pnpm exec tsc --noEmit',
+ 'git status',
+ 'npm run lint --fix',
+ 'node scripts/build.js',
+ ])('ignores %s', (command) => {
+ expect(isDependencyInstallCommand(command)).toBe(false)
+ })
+})
+
+describe('linkWorktreeDependencies', () => {
+ it('links the source dependency directory into the worktree and reads through it', async () => {
+ const { project, worktree } = await createFixture()
+ const result = await linkWorktreeDependencies(project, worktree, ['node_modules'])
+
+ expect(result.linked).toEqual(['node_modules'])
+ const stats = await lstat(join(worktree, 'node_modules'))
+ expect(stats.isSymbolicLink()).toBe(true)
+ expect(await readFile(join(worktree, 'node_modules', 'pkg', 'index.js'), 'utf8')).toBe('shared-dependency\n')
+ })
+
+ it('skips missing source directories and already-populated targets', async () => {
+ const project = await temporaryRoot('dsh-deps-project-')
+ const worktree = await temporaryRoot('dsh-deps-worktree-')
+ await mkdir(join(worktree, 'node_modules'), { recursive: true })
+
+ const missingSource = await linkWorktreeDependencies(project, worktree, ['node_modules'])
+ expect(missingSource).toEqual({ linked: [], skipped: ['node_modules'] })
+
+ const { project: withSource, worktree: emptyWorktree } = await createFixture()
+ await mkdir(join(emptyWorktree, 'node_modules'), { recursive: true })
+ const occupiedTarget = await linkWorktreeDependencies(withSource, emptyWorktree, ['node_modules'])
+ expect(occupiedTarget).toEqual({ linked: [], skipped: ['node_modules'] })
+ })
+})
+
+describe('unlinkWorktreeDependencies', () => {
+ it('removes only the link and keeps the source dependency tree intact', async () => {
+ const { project, worktree, marker } = await createFixture()
+ await linkWorktreeDependencies(project, worktree, ['node_modules'])
+
+ await expect(unlinkWorktreeDependencies(worktree, ['node_modules'])).resolves.toEqual(['node_modules'])
+ await expect(lstat(join(worktree, 'node_modules'))).rejects.toMatchObject({ code: 'ENOENT' })
+ expect(await readFile(marker, 'utf8')).toBe('shared-dependency\n')
+ })
+
+ it('leaves a real (independently installed) directory untouched', async () => {
+ const worktree = await temporaryRoot('dsh-deps-worktree-')
+ const installed = join(worktree, 'node_modules', 'pkg')
+ await mkdir(installed, { recursive: true })
+ await writeFile(join(installed, 'index.js'), 'independent\n')
+
+ await expect(unlinkWorktreeDependencies(worktree, ['node_modules'])).resolves.toEqual([])
+ expect(await readFile(join(installed, 'index.js'), 'utf8')).toBe('independent\n')
+ })
+
+ it('is idempotent when the directory is absent', async () => {
+ const worktree = await temporaryRoot('dsh-deps-worktree-')
+ await expect(unlinkWorktreeDependencies(worktree, ['node_modules'])).resolves.toEqual([])
+ })
+})
diff --git a/packages/dsh-tauri-worktree/src/host/service/dependencies.ts b/packages/dsh-tauri-worktree/src/host/service/dependencies.ts
new file mode 100644
index 00000000..57450be5
--- /dev/null
+++ b/packages/dsh-tauri-worktree/src/host/service/dependencies.ts
@@ -0,0 +1,156 @@
+/**
+ * dependencies.ts — 工作树依赖目录的自动链接,以及安装前的「独立化」断开。
+ *
+ * 背景:`git worktree add` 只检出 tracked 文件,node_modules 等被 gitignore 的依赖
+ * 目录不会跟随,新建工作树因此开箱不可用。完整安装代价高,所以默认把源仓库的依赖
+ * 目录以目录联接(Windows junction / POSIX 目录符号链接)挂进工作树。
+ *
+ * 但链接是共享的:包管理器若直接写入会穿透链接污染源仓库 —— pnpm 会把源仓库的
+ * workspace 链接改写成指向工作树,工作树删除后留下一批悬空链接(见
+ * https://github.com/pnpm/pnpm/issues/14286)。因此安装类命令执行前必须先断开链接,
+ * 让这次安装在**工作树内**物化成一份独立目录(用户要求:「假如安装的话应该会独立为
+ * 一份新的 node_modules」)。
+ *
+ * 约定:
+ * - 链接目标必须是绝对路径(Windows junction 要求),故一律先 resolve。
+ * - 断开只删链接本身,绝不递归链接目标;真实目录(已独立安装)原样保留。
+ * - 所有 fs 失败都不抛出:链接是便利能力,不得阻断工作树创建/删除主流程。
+ */
+
+import { existsSync } from 'node:fs'
+import { lstat, rm, symlink } from 'node:fs/promises'
+import process from 'node:process'
+import { resolve } from 'pathe'
+
+/** 默认链接的依赖目录名。 */
+export const DEFAULT_LINK_DIRECTORIES: readonly string[] = ['node_modules']
+
+/**
+ * 安装类命令的识别模式。只匹配「包管理器 + 安装动作」的组合,避免把
+ * `pnpm run build`、`npm test` 等普通命令误判成安装。
+ */
+const INSTALL_PATTERNS: readonly RegExp[] = [
+ // npm/pnpm/yarn/bun 及其 runner:安装/增删/更新依赖。
+ /\b(?:npm|pnpm|yarn|yarnpkg|bun|corepack|pnpx|npx)\s+(?:install|i|ci|add|update|upgrade|up|remove|rm|uninstall|unlink|link|dedupe|prune|rebuild|install-test|it)\b/i,
+ // 裸 `yarn`(无子命令)等价于 yarn install。
+ /(?:^|[\s;&|()])yarn\s*(?:$|[\s;&|()])/i,
+ // Python 生态。
+ /\b(?:pip|pip3|pipenv|poetry|uv|conda|mamba)\s+(?:install|sync|add|update|upgrade|lock|remove|uninstall)\b/i,
+ // Rust / Go / Ruby / PHP / .NET / JVM 生态(当用户把 target/vendor 等目录加入链接时同样适用)。
+ /\bcargo\s+(?:fetch|build|install|update)\b/i,
+ /\bgo\s+(?:mod\s+(?:download|tidy|vendor)|get)\b/i,
+ /\b(?:bundle|bundler)\s+install\b/i,
+ /\bcomposer\s+(?:install|update|require|remove)\b/i,
+ /\bdotnet\s+(?:restore|add\s+package)\b/i,
+ /\b(?:mvn|maven|gradle|gradlew)\b[^\n;&|]+\bdependenc(?:y|ies)\b/i,
+]
+
+/**
+ * 归一化待链接目录名:去空白/尾分隔符、拒绝空值与 `.`/`..`、拒绝含路径分隔符的
+ * 条目(否则会链接到工作树之外),去重且保持声明顺序。空输入回退默认值。
+ */
+export function normalizeLinkDirectories(directories?: readonly string[]): string[] {
+ const source = directories && directories.length > 0 ? directories : DEFAULT_LINK_DIRECTORIES
+ const seen = new Set<string>()
+ const normalized: string[] = []
+ for (const raw of source) {
+ const name = String(raw ?? '').trim().replace(/[\\/]+$/, '')
+ if (!name || name === '.' || name === '..')
+ continue
+ if (name.includes('/') || name.includes('\\'))
+ continue
+ const key = process.platform === 'win32' ? name.toLowerCase() : name
+ if (seen.has(key))
+ continue
+ seen.add(key)
+ normalized.push(name)
+ }
+ return normalized
+}
+
+/** 命令文本是否疑似安装依赖(用于安装前断开共享链接)。 */
+export function isDependencyInstallCommand(command: string): boolean {
+ const text = String(command ?? '')
+ if (text.length === 0)
+ return false
+ return INSTALL_PATTERNS.some(pattern => pattern.test(text))
+}
+
+async function pathExists(path: string): Promise<boolean> {
+ try {
+ await lstat(path)
+ return true
+ }
+ catch {
+ return false
+ }
+}
+
+/**
+ * 把源仓库的依赖目录链接进新工作树。
+ *
+ * @param projectPath 源仓库顶层
+ * @param worktreePath 工作树目录
+ * @param directories 待链接的目录名(默认 node_modules)
+ * @returns linked 为成功建立链接的目录名;skipped 为源目录缺失或目标已存在的目录名
+ */
+export async function linkWorktreeDependencies(
+ projectPath: string,
+ worktreePath: string,
+ directories: readonly string[] = DEFAULT_LINK_DIRECTORIES,
+): Promise<{ linked: string[], skipped: string[] }> {
+ const linked: string[] = []
+ const skipped: string[] = []
+ for (const name of normalizeLinkDirectories(directories)) {
+ // Windows junction 要求绝对目标;相对目标会创建出读不通的链接。
+ const source = resolve(projectPath, name)
+ const target = resolve(worktreePath, name)
+ if (!existsSync(source) || await pathExists(target)) {
+ skipped.push(name)
+ continue
+ }
+ try {
+ await symlink(source, target, process.platform === 'win32' ? 'junction' : 'dir')
+ linked.push(name)
+ }
+ catch {
+ // 权限/占用/跨卷失败:保持工作树可用,退化为「需要自行安装」。
+ skipped.push(name)
+ }
+ }
+ return { linked, skipped }
+}
+
+/**
+ * 断开工作树内的依赖链接(安装前物化独立目录、删除工作树前保护源仓库)。
+ * 只删除符号链接/junction 本身;真实目录(已独立安装)不动。
+ *
+ * @returns 实际被断开的目录名
+ */
+export async function unlinkWorktreeDependencies(
+ worktreePath: string,
+ directories: readonly string[] = DEFAULT_LINK_DIRECTORIES,
+): Promise<string[]> {
+ const unlinked: string[] = []
+ for (const name of normalizeLinkDirectories(directories)) {
+ const target = resolve(worktreePath, name)
+ let stats
+ try {
+ stats = await lstat(target)
+ }
+ catch {
+ continue
+ }
+ if (!stats.isSymbolicLink())
+ continue
+ try {
+ // recursive:false 只摘链接,绝不进入链接目标;Windows junction 亦适用。
+ await rm(target, { recursive: false, force: true })
+ unlinked.push(name)
+ }
+ catch {
+ /* 删除失败保留链接:由后续重试或人工处理,不阻断主流程 */
+ }
+ }
+ return unlinked
+}
diff --git a/packages/dsh-tauri-worktree/src/host/service/install-hook.test.ts b/packages/dsh-tauri-worktree/src/host/service/install-hook.test.ts
new file mode 100644
index 00000000..9fe4e758
--- /dev/null
+++ b/packages/dsh-tauri-worktree/src/host/service/install-hook.test.ts
@@ -0,0 +1,133 @@
+/**
+ * install-hook.test.ts — 安装命令识别与「安装前断开共享链接」的真实文件系统回归。
+ */
+
+import { lstat, mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises'
+import { tmpdir } from 'node:os'
+import { join } from 'pathe'
+import { afterEach, describe, expect, it, vi } from 'vitest'
+import { linkWorktreeDependencies } from './dependencies'
+import { materializeLinkedDependencies, shellCommandFrom } from './install-hook'
+
+const temporaryDirectories: string[] = []
+
+async function temporaryRoot(prefix: string): Promise<string> {
+ const root = await mkdtemp(join(tmpdir(), prefix))
+ temporaryDirectories.push(root)
+ return root
+}
+
+afterEach(async () => {
+ await Promise.all(temporaryDirectories.splice(0).map(path => rm(path, { recursive: true, force: true })))
+})
+
+/** 构造源仓库 + 已链接依赖的工作树 + 指向该工作树的 ledger 记录。 */
+async function createLinkedWorktreeFixture(sessionId: string): Promise<{
+ project: string
+ worktree: string
+ worktreesRoot: string
+ marker: string
+}> {
+ const project = await temporaryRoot('dsh-install-hook-project-')
+ const worktree = await temporaryRoot('dsh-install-hook-worktree-')
+ const worktreesRoot = await temporaryRoot('dsh-install-hook-root-')
+ const marker = join(project, 'node_modules', 'pkg', 'index.js')
+ await mkdir(join(project, 'node_modules', 'pkg'), { recursive: true })
+ await writeFile(marker, 'shared-dependency\n')
+ await linkWorktreeDependencies(project, worktree, ['node_modules'])
+
+ await mkdir(join(worktreesRoot, 'ledger'), { recursive: true })
+ await writeFile(join(worktreesRoot, 'ledger', `${sessionId}.json`), JSON.stringify({
+ sessionId,
+ sourceSessionId: sessionId,
+ hash: 'hash',
+ dirname: 'project',
+ worktreePath: worktree,
+ projectPath: project,
+ branchName: '(detached)',
+ ownsBranch: false,
+ createdAt: new Date().toISOString(),
+ log: [],
+ linkedDependencies: ['node_modules'],
+ }))
+
+ return { project, worktree, worktreesRoot, marker }
+}
+
+describe('shellCommandFrom', () => {
+ it('reads the command from known shell tools', () => {
+ expect(shellCommandFrom({ name: 'pwsh', arguments: { command: 'pnpm install' } })).toBe('pnpm install')
+ expect(shellCommandFrom({ name: 'bash', arguments: { cmd: 'npm ci' } })).toBe('npm ci')
+ expect(shellCommandFrom({ name: 'shell', arguments: { script: 'yarn' } })).toBe('yarn')
+ })
+
+ it('ignores non-shell tools and malformed executions', () => {
+ expect(shellCommandFrom({ name: 'read', arguments: { command: 'pnpm install' } })).toBe('')
+ expect(shellCommandFrom({ name: 'pwsh', arguments: {} })).toBe('')
+ expect(shellCommandFrom({ name: 'pwsh' })).toBe('')
+ expect(shellCommandFrom(undefined)).toBe('')
+ })
+})
+
+describe('materializeLinkedDependencies', () => {
+ it('unlinks the shared dependency directory before an install command runs', async () => {
+ const sessionId = 'session-install'
+ const { project, worktree, worktreesRoot, marker } = await createLinkedWorktreeFixture(sessionId)
+ const info = vi.fn()
+
+ const unlinked = await materializeLinkedDependencies(
+ { logger: { info } },
+ worktreesRoot,
+ undefined,
+ { name: 'pwsh', arguments: { command: 'pnpm install' }, agent: { session: { id: sessionId } } },
+ )
+
+ expect(unlinked).toEqual(['node_modules'])
+ await expect(lstat(join(worktree, 'node_modules'))).rejects.toMatchObject({ code: 'ENOENT' })
+ // 源仓库依赖必须完好,否则工作树删除会连带毁掉本地主工作区。
+ expect(await readFile(marker, 'utf8')).toBe('shared-dependency\n')
+ expect(await readFile(join(project, 'node_modules', 'pkg', 'index.js'), 'utf8')).toBe('shared-dependency\n')
+ expect(info).toHaveBeenCalledTimes(1)
+ })
+
+ it('leaves the link in place for non-install commands and unknown sessions', async () => {
+ const sessionId = 'session-other'
+ const { worktree, worktreesRoot } = await createLinkedWorktreeFixture(sessionId)
+
+ const nonInstall = await materializeLinkedDependencies(
+ { logger: {} },
+ worktreesRoot,
+ undefined,
+ { name: 'pwsh', arguments: { command: 'pnpm run build' }, agent: { session: { id: sessionId } } },
+ )
+ expect(nonInstall).toEqual([])
+
+ const unknownSession = await materializeLinkedDependencies(
+ { logger: {} },
+ worktreesRoot,
+ undefined,
+ { name: 'pwsh', arguments: { command: 'pnpm install' }, agent: { session: { id: 'session-missing' } } },
+ )
+ expect(unknownSession).toEqual([])
+ expect((await lstat(join(worktree, 'node_modules'))).isSymbolicLink()).toBe(true)
+ })
+
+ it('honors configured extra dependency directories recorded in the binding', async () => {
+ const sessionId = 'session-venv'
+ const { project, worktree, worktreesRoot } = await createLinkedWorktreeFixture(sessionId)
+ await mkdir(join(project, '.venv', 'lib'), { recursive: true })
+ await linkWorktreeDependencies(project, worktree, ['.venv'])
+
+ const unlinked = await materializeLinkedDependencies(
+ { logger: {} },
+ worktreesRoot,
+ ['.venv'],
+ { name: 'pwsh', arguments: { command: 'uv sync' }, agent: { session: { id: sessionId } } },
+ )
+
+ // binding 记录的 node_modules ∪ 配置新增的 .venv 都会被断开。
+ expect(unlinked).toEqual(['node_modules', '.venv'])
+ await expect(lstat(join(worktree, '.venv'))).rejects.toMatchObject({ code: 'ENOENT' })
+ await expect(lstat(join(worktree, 'node_modules'))).rejects.toMatchObject({ code: 'ENOENT' })
+ })
+})
diff --git a/packages/dsh-tauri-worktree/src/host/service/install-hook.ts b/packages/dsh-tauri-worktree/src/host/service/install-hook.ts
new file mode 100644
index 00000000..add31725
--- /dev/null
+++ b/packages/dsh-tauri-worktree/src/host/service/install-hook.ts
@@ -0,0 +1,71 @@
+/**
+ * install-hook.ts — 安装类命令执行前的依赖链接断开。
+ *
+ * 工作树默认把源仓库的依赖目录链接进来(见 service/dependencies.ts)。链接是共享的:
+ * 若包管理器直接写入会穿透链接污染源仓库。本模块在 `tools/execute` 钩子里检测到
+ * 「安装依赖」类命令时,先摘掉工作树内的链接,让这次安装在**工作树内**物化成一份
+ * 独立目录 —— 满足「agent 依旧可以安装,但安装后是独立 node_modules」的要求。
+ *
+ * 钩子体保持纯编排:命令识别、链接断开、ledger 读取都委托给各自模块;任何失败都
+ * 只记录日志,绝不阻断工具调用本身。
+ */
+
+import type { HostContext } from '../types'
+import { loadBindingSync } from '../storage'
+import { isDependencyInstallCommand, normalizeLinkDirectories, unlinkWorktreeDependencies } from './dependencies'
+
+/**
+ * shell 类工具名白名单:只有这些工具的 `command` 参数才可能是安装命令。
+ * 未知工具名直接跳过,避免把普通参数误判成命令。
+ */
+const SHELL_TOOL_NAMES = new Set(['bash', 'pwsh', 'shell', 'sh', 'zsh', 'terminal', 'run_command', 'exec'])
+
+/** 从工具执行上下文里取命令文本(兼容 command/cmd/script 三种参数名)。 */
+export function shellCommandFrom(exec: unknown): string {
+ const name = (exec as { name?: unknown } | undefined)?.name
+ if (typeof name !== 'string' || !SHELL_TOOL_NAMES.has(name))
+ return ''
+ const args = (exec as { arguments?: unknown } | undefined)?.arguments
+ if (!args || typeof args !== 'object')
+ return ''
+ for (const key of ['command', 'cmd', 'script']) {
+ const value = (args as Record<string, unknown>)[key]
+ if (typeof value === 'string' && value)
+ return value
+ }
+ return ''
+}
+
+/**
+ * 若本次工具调用是「在工作树里安装依赖」,先断开共享链接。
+ *
+ * @returns 实际断开的目录名(无操作时为空数组)
+ */
+export async function materializeLinkedDependencies(
+ ctx: HostContext,
+ worktreesRoot: string,
+ configuredDirectories: readonly string[] | undefined,
+ exec: unknown,
+): Promise<string[]> {
+ const command = shellCommandFrom(exec)
+ if (!command || !isDependencyInstallCommand(command))
+ return []
+ const sessionId = (exec as { agent?: { session?: { id?: unknown } } } | undefined)?.agent?.session?.id
+ if (typeof sessionId !== 'string' || !sessionId)
+ return []
+ const binding = loadBindingSync(worktreesRoot, sessionId)
+ if (!binding?.worktreePath)
+ return []
+ const directories = normalizeLinkDirectories([
+ ...(binding.linkedDependencies ?? []),
+ ...normalizeLinkDirectories(configuredDirectories),
+ ])
+ const unlinked = await unlinkWorktreeDependencies(binding.worktreePath, directories)
+ if (unlinked.length > 0) {
+ ctx.logger?.info?.(
+ `dsh-tauri-worktree: unlinked ${unlinked.join(', ')} before install in ${binding.worktreePath}; `
+ + 'the package manager will materialize an independent copy',
+ )
+ }
+ return unlinked
+}
diff --git a/packages/dsh-tauri-worktree/src/host/service/operation.test.ts b/packages/dsh-tauri-worktree/src/host/service/operation.test.ts
index 3d9f4179..c22c2876 100644
--- a/packages/dsh-tauri-worktree/src/host/service/operation.test.ts
+++ b/packages/dsh-tauri-worktree/src/host/service/operation.test.ts
@@ -2,7 +2,7 @@
* operation.test.ts — ensureWorktree 的 Git 来源与分支行为。
*/
-import { existsSync } from 'node:fs'
+import { existsSync, lstatSync, readFileSync } from 'node:fs'
import { mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join } from 'pathe'
@@ -221,4 +221,43 @@ describe('ensureWorktree', () => {
expect(existsSync(container)).toBe(false)
expect(existsSync(trashContainer)).toBe(false)
})
+
+ it('links source dependency directories into the worktree and unlinks before discard', async () => {
+ const repository = await createRepository('main')
+ const dependency = join(repository, 'node_modules', 'pkg', 'index.js')
+ await mkdir(join(repository, 'node_modules', 'pkg'), { recursive: true })
+ await writeFile(dependency, 'shared-dependency\n')
+ const worktreesRoot = await mkdtemp(join(tmpdir(), 'dsh-worktrees-root-'))
+ temporaryDirectories.push(worktreesRoot)
+
+ const created = await ensureWorktree({}, worktreesRoot, repository, 'linked-session')
+
+ expect(created.ok).toBe(true)
+ if (!created.ok)
+ return
+ expect(created.binding.linkedDependencies).toEqual(['node_modules'])
+ const link = join(created.binding.worktreePath, 'node_modules')
+ expect(lstatSync(link).isSymbolicLink()).toBe(true)
+ expect(readFileSync(join(link, 'pkg', 'index.js'), 'utf8')).toBe('shared-dependency\n')
+
+ await expect(discardWorktree({}, worktreesRoot, { sessionId: 'linked-session' })).resolves.toMatchObject({ ok: true })
+ // 删除工作树只能摘链接,绝不能穿透链接删掉源仓库的 node_modules。
+ expect(readFileSync(dependency, 'utf8')).toBe('shared-dependency\n')
+ })
+
+ it('skips dependency linking when linkDependencies is false', async () => {
+ const repository = await createRepository('main')
+ await mkdir(join(repository, 'node_modules', 'pkg'), { recursive: true })
+ await writeFile(join(repository, 'node_modules', 'pkg', 'index.js'), 'shared-dependency\n')
+ const worktreesRoot = await mkdtemp(join(tmpdir(), 'dsh-worktrees-root-'))
+ temporaryDirectories.push(worktreesRoot)
+
+ const created = await ensureWorktree({}, worktreesRoot, repository, 'unlinked-session', { linkDependencies: false })
+
+ expect(created.ok).toBe(true)
+ if (!created.ok)
+ return
+ expect(created.binding.linkedDependencies).toBeUndefined()
+ expect(existsSync(join(created.binding.worktreePath, 'node_modules'))).toBe(false)
+ })
})
diff --git a/packages/dsh-tauri-worktree/src/host/service/operation.ts b/packages/dsh-tauri-worktree/src/host/service/operation.ts
index 266cdf81..1e60eeee 100644
--- a/packages/dsh-tauri-worktree/src/host/service/operation.ts
+++ b/packages/dsh-tauri-worktree/src/host/service/operation.ts
@@ -25,6 +25,7 @@ import process from 'node:process'
import { join, resolve } from 'pathe'
import { WORKTREE_BRANCH_NAME_PATTERN } from '../constants'
import { listBindings, loadBinding, removeBinding, saveBinding } from '../storage'
+import { linkWorktreeDependencies, normalizeLinkDirectories, unlinkWorktreeDependencies } from './dependencies'
import { removeDirectoryReliably } from './filesystem'
import {
applyStagedPatch,
@@ -136,10 +137,16 @@ async function removeWorktreeOnDisk(
path: string,
hash: string,
dirname: string,
+ linkDirectories: readonly string[] = [],
signal?: AbortSignal,
): Promise<OperationResult> {
await stopWorktreeProcesses(ctx, sessionId, path)
+ // 依赖目录是目录联接:先摘链接再删目录,确保 fs.rm 不会进入(也绝不删除)
+ // 源仓库的 node_modules。已独立安装的真实目录不受影响。
+ if (linkDirectories.length > 0)
+ await unlinkWorktreeDependencies(path, linkDirectories)
+
try {
await removeDirectoryReliably(path, worktreeTrashPath(worktreesRoot, hash, dirname))
}
@@ -155,6 +162,17 @@ async function removeWorktreeOnDisk(
return pruneWorktreeAdmin(root, signal)
}
+/**
+ * 删除工作树时需要断开的依赖链接目录:binding 记录 ∪ 当前配置,回退默认 node_modules。
+ * 旧 ledger 没有 linkedDependencies,但可能仍残留 node_modules 链接,故回退默认值。
+ */
+function removalLinkDirectories(binding: Binding, configured?: readonly string[]): string[] {
+ const configuredDirectories = normalizeLinkDirectories(configured)
+ if (!binding.linkedDependencies || binding.linkedDependencies.length === 0)
+ return configuredDirectories
+ return normalizeLinkDirectories([...binding.linkedDependencies, ...configuredDirectories])
+}
+
async function deleteOwnedBranch(root: string, branch: string, signal?: AbortSignal): Promise<OperationResult> {
// for-each-ref succeeds with empty output when the branch is absent, letting
// us distinguish an idempotent retry from a real Git/cancellation failure.
@@ -192,6 +210,9 @@ export async function ensureWorktree(
const hash = computeHash(projectPath, sessionId)
const dirname = projectDirname(projectPath)
const path = worktreePath(worktreesRoot, hash, dirname)
+ // 依赖链接配置在建/删两条路径上共用:创建时建立,删除前断开。
+ const linkDirectories = normalizeLinkDirectories(opts.linkDependencyDirectories)
+ const linkDependencies = opts.linkDependencies !== false
const existing = await loadBinding(worktreesRoot, sessionId)
if (existing && !samePath(existing.worktreePath, path)) {
@@ -228,7 +249,7 @@ export async function ensureWorktree(
}
// State B: a prior interrupted removal left only the directory. Delete the
// orphan before pruning metadata; prune alone never removes disk content.
- const removed = await removeWorktreeOnDisk(ctx, sessionId, worktreesRoot, root, path, hash, dirname, opts.signal)
+ const removed = await removeWorktreeOnDisk(ctx, sessionId, worktreesRoot, root, path, hash, dirname, linkDirectories, opts.signal)
if (!removed.ok)
return { ok: false, error: `清理孤儿工作树目录失败:${removed.error}` }
}
@@ -270,7 +291,7 @@ export async function ensureWorktree(
const carried = await carryStagedChanges(root, path, { signal: opts.signal })
if (!carried.ok) {
const rollbackFailures: string[] = []
- const removed = await removeWorktreeOnDisk(ctx, sessionId, worktreesRoot, root, path, hash, dirname, opts.signal)
+ const removed = await removeWorktreeOnDisk(ctx, sessionId, worktreesRoot, root, path, hash, dirname, linkDirectories, opts.signal)
if (!removed.ok)
rollbackFailures.push(`移除工作树失败:${removed.error}`)
if (branchName) {
@@ -294,6 +315,27 @@ export async function ensureWorktree(
log.push(`HEAD is now at ${await shortHead(path)} ${await headSubject(path)}`)
log.push(`Worktree created at ${path}`)
+ // 依赖目录自动链接:工作树只检出 tracked 文件,node_modules 等被 gitignore 的目录
+ // 不会跟随。默认把源仓库的依赖目录以目录联接挂进工作树,使其开箱可用;安装类命令
+ // 执行前会先断开链接(见 apply.ts 的 tools/execute 钩子),从而物化为独立目录。
+ // 链接失败仅记录日志,绝不让工作树创建失败。
+ const linkedDependencies: string[] = []
+ if (linkDependencies) {
+ try {
+ const linked = await linkWorktreeDependencies(root, path, linkDirectories)
+ linkedDependencies.push(...linked.linked)
+ if (linked.linked.length > 0)
+ log.push(`Linked dependencies from the source repository (${linked.linked.join(', ')}); install will materialize an independent copy`)
+ for (const name of linked.skipped) {
+ if (existsSync(join(root, name)))
+ log.push(`Dependency directory already present, kept as-is (${name})`)
+ }
+ }
+ catch (error) {
+ log.push(`Dependency link skipped: ${error instanceof Error ? error.message : String(error)}`)
+ }
+ }
+
const binding = {
sessionId,
sourceSessionId: opts.sourceSessionId || sessionId,
@@ -305,6 +347,7 @@ export async function ensureWorktree(
ownsBranch: Boolean(branchName),
createdAt: new Date().toISOString(),
log,
+ ...(linkedDependencies.length > 0 ? { linkedDependencies } : {}),
}
// 绑定落盘失败时回滚刚创建的 git worktree 与分支,避免留下未被 ledger 引用的
// 孤儿目录。saveBinding 只原子写本会话自己的文件,不再整表读写;saveBinding 内部
@@ -314,7 +357,7 @@ export async function ensureWorktree(
}
catch {
const rollbackFailures: string[] = []
- const removed = await removeWorktreeOnDisk(ctx, sessionId, worktreesRoot, root, path, hash, dirname, opts.signal)
+ const removed = await removeWorktreeOnDisk(ctx, sessionId, worktreesRoot, root, path, hash, dirname, linkDirectories, opts.signal)
if (!removed.ok)
rollbackFailures.push(`移除工作树失败:${removed.error}`)
if (branchName) {
@@ -388,6 +431,8 @@ export async function checkoutToLocal(
return { ok: false, error: `工作树目录不存在:${binding.worktreePath}` }
const root = binding.projectPath
+ // 删除工作树前需断开的依赖链接(binding 记录 ∪ 当前配置)。
+ const linkDirectories = removalLinkDirectories(binding, opts.linkDependencyDirectories)
// 本地分支名完全使用调用方输入;UI 默认填 `dsh/`,但用户可删除该前缀。
const branch = String(params.branch_name ?? binding.branchName ?? '').trim()
if (!branch || branch.endsWith('/'))
@@ -526,6 +571,7 @@ export async function checkoutToLocal(
binding.worktreePath,
binding.hash,
binding.dirname,
+ linkDirectories,
opts.signal,
)
if (!removed.ok) {
@@ -550,13 +596,14 @@ export async function checkoutToLocal(
* @param params 放弃参数(worktree_hash_dirname / sessionId)
* @param opts 选项
* @param opts.signal 可选取消信号
+ * @param opts.linkDependencyDirectories 删除前需断开的依赖链接目录名
* @returns 放弃结果
*/
export async function discardWorktree(
ctx: HostContext,
worktreesRoot: string,
params: WorktreeParams,
- opts: { signal?: AbortSignal } = {},
+ opts: { signal?: AbortSignal, linkDependencyDirectories?: string[] } = {},
): Promise<OperationResult<{ worktreePath: string }>> {
const { binding } = await resolveBinding(worktreesRoot, params.sessionId, params.worktreeHashDirname)
if (!binding)
@@ -572,6 +619,7 @@ export async function discardWorktree(
binding.worktreePath,
binding.hash,
binding.dirname,
+ removalLinkDirectories(binding, opts.linkDependencyDirectories),
opts.signal,
)
if (!removed.ok)
diff --git a/packages/dsh-tauri-worktree/src/host/tools/index.ts b/packages/dsh-tauri-worktree/src/host/tools/index.ts
index 6992a10d..753905a4 100644
--- a/packages/dsh-tauri-worktree/src/host/tools/index.ts
+++ b/packages/dsh-tauri-worktree/src/host/tools/index.ts
@@ -84,6 +84,8 @@ export function createToolSet(
sourceSessionId: sourceSession.id,
branchName: String(args.branch_name ?? ''),
carryStaged: args.carry_staged === true,
+ linkDependencies: config.linkDependencies,
+ linkDependencyDirectories: config.linkDependencyDirectories,
signal: exec?.signal,
})
if (!created.ok)
@@ -158,6 +160,7 @@ export function createToolSet(
}, {
signal: exec?.signal,
carryStaged: args.carry_staged === true,
+ linkDependencyDirectories: config.linkDependencyDirectories,
})
if (!r.ok)
return { ok: false, error: r.error }
diff --git a/packages/dsh-tauri-worktree/src/host/types/index.ts b/packages/dsh-tauri-worktree/src/host/types/index.ts
index 3080845c..137c1ecb 100644
--- a/packages/dsh-tauri-worktree/src/host/types/index.ts
+++ b/packages/dsh-tauri-worktree/src/host/types/index.ts
@@ -9,6 +9,10 @@ export type JsonBody = Record<string, unknown>
export interface PluginConfig {
worktreesRoot?: string
+ /** 是否把源仓库的依赖目录链接进新工作树(默认 true)。 */
+ linkDependencies?: boolean
+ /** 需要链接的依赖目录名,默认 `['node_modules']`。 */
+ linkDependencyDirectories?: string[]
}
export interface Binding {
@@ -22,6 +26,8 @@ export interface Binding {
ownsBranch: boolean
createdAt: string
log: string[]
+ /** 本工作树内由插件建立链接的依赖目录名(安装前会被断开物化)。 */
+ linkedDependencies?: string[]
}
export type Ledger = Record<string, Binding>
@@ -45,12 +51,18 @@ export interface EnsureOptions extends GitOptions {
branchName?: string
/** 是否把源仓库已暂存(index)内容携带进新工作树;默认 false。 */
carryStaged?: boolean
+ /** 是否把源仓库的依赖目录链接进新工作树;默认 true。 */
+ linkDependencies?: boolean
+ /** 需要链接的依赖目录名;默认 `['node_modules']`。 */
+ linkDependencyDirectories?: string[]
}
export interface CheckoutOptions extends GitOptions {
beforeRemove?: (checkout: { branch: string, projectPath: string, worktreePath: string }) => Promise<OperationResult<any>>
/** 是否把工作树已暂存(index)内容携带回本地检出;默认 false。 */
carryStaged?: boolean
+ /** 删除工作树前需要断开的依赖链接目录名;默认 `['node_modules']`。 */
+ linkDependencyDirectories?: string[]
}
export interface CheckoutInfo {