Skip to content

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

perf(worktree): 新工作树用构建缓存种子拷贝,Rust 依赖不再全量重编

hairyff209fe66f1fa
diff --git a/packages/dsh-tauri-worktree/src/host/service/worktree.test.ts b/packages/dsh-tauri-worktree/src/host/service/worktree.test.ts
index f899f1a4..a04dadd6 100644
--- a/packages/dsh-tauri-worktree/src/host/service/worktree.test.ts
+++ b/packages/dsh-tauri-worktree/src/host/service/worktree.test.ts
@@ -430,6 +430,48 @@ describe('依赖链接', () => {
expect(created.binding.linkedDependencies).toBeUndefined()
})
+ it('默认把源仓库的构建缓存复制进工作树并刷新本地源码时间戳', async () => {
+ const repository = createRepository()
+ mkdirSync(join(repository, 'src-tauri', 'src'), { recursive: true })
+ writeFileSync(join(repository, 'src-tauri', 'src', 'main.rs'), 'fn main() {}\n')
+ writeFileSync(join(repository, '.gitignore'), 'src-tauri/target\n')
+ mkdirSync(join(repository, 'src-tauri', 'target', 'debug', 'deps'), { recursive: true })
+ writeFileSync(join(repository, 'src-tauri', 'target', 'debug', 'deps', 'libdemo.rlib'), 'artifact\n')
+ git(repository, 'add', '.')
+ git(repository, 'commit', '-m', 'rust sources')
+ const sessionId = 'seeded-session'
+
+ const created = await worktree.create(repository, sessionId)
+ expect(created.ok).toBe(true)
+ if (!created.ok)
+ return
+
+ const seeded = join(created.binding.worktreePath, 'src-tauri', 'target', 'debug', 'deps', 'libdemo.rlib')
+ expect(readFileSync(seeded, 'utf8')).toBe('artifact\n')
+ const seedLog = created.log.find(line => line.startsWith('Seeded the build cache from '))
+ expect(seedLog).toContain(basename(repository))
+ expect(seedLog).toContain('(src-tauri/target); marked 1 local source file(s) for rebuild')
+
+ const removed = await worktree.remove(sessionId)
+ expect(removed.ok).toBe(true)
+ expect(existsSync(join(created.binding.worktreePath, 'src-tauri'))).toBe(false)
+ expect(existsSync(join(repository, 'src-tauri', 'target', 'debug', 'deps', 'libdemo.rlib'))).toBe(true)
+ })
+
+ it('seedDependencies 为 false 时跳过构建缓存复制', async () => {
+ const repository = createRepository()
+ mkdirSync(join(repository, 'src-tauri', 'target'), { recursive: true })
+ writeFileSync(join(repository, 'src-tauri', 'target', 'marker'), 'x\n')
+ const sessionId = 'unseeded-session'
+
+ const created = await worktree.create(repository, sessionId, { seedDependencies: false })
+ expect(created.ok).toBe(true)
+ if (!created.ok)
+ return
+
+ expect(existsSync(join(created.binding.worktreePath, 'src-tauri', 'target'))).toBe(false)
+ })
+
it('无条件继承 .agents(复制而非链接),即使关闭依赖链接', async () => {
const repository = createRepository()
mkdirSync(join(repository, '.agents', 'skills', 'handle'), { recursive: true })
diff --git a/packages/dsh-tauri-worktree/src/host/service/worktree.ts b/packages/dsh-tauri-worktree/src/host/service/worktree.ts
index c953ee71..fbc8cf77 100644
--- a/packages/dsh-tauri-worktree/src/host/service/worktree.ts
+++ b/packages/dsh-tauri-worktree/src/host/service/worktree.ts
@@ -18,6 +18,8 @@ import {
isDependencyInstallCommand,
linkWorktreeDependencies,
normalizeLinkDirectories,
+ normalizeSeedDirectories,
+ seedWorktreeDirectories,
shellCommandFrom,
shellSessionIdFrom,
unlinkWorktreeDependencies,
@@ -51,6 +53,8 @@ const AGENT_SKILLS_DIRECTORY = '.agents'
const LINK_DEPENDENCIES = true
+const SEED_DEPENDENCIES = true
+
const SWEEP_MIN_AGE_MS = 60_000
export const worktree = defineService({
@@ -68,6 +72,8 @@ export const worktree = defineService({
const path = worktreePath(hash, dirname)
const linkDirectories = normalizeLinkDirectories(options.linkDependencyDirectories)
const linkDependencies = options.linkDependencies ?? LINK_DEPENDENCIES
+ const seedDirectories = normalizeSeedDirectories(options.seedDependencyDirectories)
+ const seedDependencies = options.seedDependencies ?? SEED_DEPENDENCIES
const existing = ledger.load(sessionId)
if (existing && !samePath(existing.worktreePath, path)) {
@@ -174,6 +180,19 @@ export const worktree = defineService({
}
}
+ if (seedDependencies && seedDirectories.length > 0) {
+ try {
+ const seedRoots = await seedSourceRoots(root, path, seedDirectories[0])
+ const seeded = await seedWorktreeDirectories(seedRoots, path, seedDirectories)
+ if (seeded.seeded.length > 0)
+ log.push(`Seeded the build cache from ${seeded.sources.join(', ')} (${seeded.seeded.join(', ')}); marked ${seeded.touched} local source file(s) for rebuild`)
+ log.push(...map(seeded.errors, error => `Build cache seed skipped: ${error}`))
+ }
+ catch (error) {
+ log.push(`Build cache seed skipped: ${get(error, 'message', String(error))}`)
+ }
+ }
+
const binding: Binding = {
sessionId,
sourceSessionId: options.sourceSessionId || sessionId,
@@ -503,6 +522,36 @@ async function inheritAgentSkills(root: string, path: string, log: string[]): Pr
}
}
+/**
+ * 构建缓存的种子来源:优先源仓库,其次回退到同一项目里最近构建过的工作树(源仓库可能自己还没构建过)。
+ * 只认 `.git` 指回同一仓库的工作树,避免把无关项目的缓存搬进来。
+ */
+async function seedSourceRoots(projectPath: string, worktreePath: string, seedDirectory: string): Promise<string[]> {
+ const worktreesRoot = join(DSH_HOME, WORKTREES_DIR)
+ const candidates: { path: string, mtime: number }[] = []
+ for (const hash of listDirectoryNames(worktreesRoot)) {
+ for (const name of listDirectoryNames(join(worktreesRoot, hash))) {
+ const path = join(worktreesRoot, hash, name)
+ if (samePath(path, worktreePath) || !samePath(projectFromWorktree(path), projectPath))
+ continue
+ const mtime = directoryMtime(join(path, seedDirectory))
+ if (mtime > 0)
+ candidates.push({ path, mtime })
+ }
+ }
+ candidates.sort((left, right) => right.mtime - left.mtime)
+ return [projectPath, ...map(candidates, candidate => candidate.path)]
+}
+
+function directoryMtime(path: string): number {
+ try {
+ return statSync(path).mtimeMs
+ }
+ catch {
+ return 0
+ }
+}
+
function samePath(a: string, b: string): boolean {
const left = resolve(a)
const right = resolve(b)
diff --git a/packages/dsh-tauri-worktree/src/host/types/index.ts b/packages/dsh-tauri-worktree/src/host/types/index.ts
index 36927a86..170825c9 100644
--- a/packages/dsh-tauri-worktree/src/host/types/index.ts
+++ b/packages/dsh-tauri-worktree/src/host/types/index.ts
@@ -40,6 +40,8 @@ export interface EnsureOptions extends GitOptions {
carryStaged?: boolean
linkDependencies?: boolean
linkDependencyDirectories?: string[]
+ seedDependencies?: boolean
+ seedDependencyDirectories?: string[]
}
export interface CheckoutOptions extends GitOptions {
diff --git a/packages/dsh-tauri-worktree/src/host/utils/dependencies.test.ts b/packages/dsh-tauri-worktree/src/host/utils/dependencies.test.ts
index 0b1dcf8f..69f18463 100644
--- a/packages/dsh-tauri-worktree/src/host/utils/dependencies.test.ts
+++ b/packages/dsh-tauri-worktree/src/host/utils/dependencies.test.ts
@@ -1,4 +1,4 @@
-import { lstat, mkdir, mkdtemp, readFile, rm, symlink, writeFile } from 'node:fs/promises'
+import { lstat, mkdir, mkdtemp, readFile, rm, stat, symlink, utimes, writeFile } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import process from 'node:process'
import { join } from 'pathe'
@@ -8,6 +8,8 @@ import {
isDependencyInstallCommand,
linkWorktreeDependencies,
normalizeLinkDirectories,
+ normalizeSeedDirectories,
+ seedWorktreeDirectories,
unlinkWorktreeDependencies,
} from './dependencies'
@@ -28,6 +30,22 @@ async function createFixture(): Promise<{ project: string, worktree: string, mar
return { project, worktree, marker }
}
+async function createBuildCacheFixture(): Promise<{ project: string, worktree: string, source: string }> {
+ const project = await temporaryRoot('dsh-seed-project-')
+ const worktree = await temporaryRoot('dsh-seed-worktree-')
+ const artifact = join(project, 'src-tauri', 'target', 'debug', 'deps', 'libdemo.rlib')
+ await mkdir(join(project, 'src-tauri', 'target', 'debug', 'incremental'), { recursive: true })
+ await mkdir(join(project, 'src-tauri', 'target', 'debug', 'deps'), { recursive: true })
+ await writeFile(artifact, 'artifact\n')
+ await writeFile(join(project, 'src-tauri', 'target', 'debug', 'incremental', 'cache.bin'), 'incremental\n')
+ await mkdir(join(project, 'src-tauri', 'target', 'debug', 'build'), { recursive: true })
+ await writeFile(join(project, 'src-tauri', 'target', 'debug', 'build', 'generated.rs'), '// generated\n')
+ const source = join(worktree, 'src-tauri', 'src', 'main.rs')
+ await mkdir(join(worktree, 'src-tauri', 'src'), { recursive: true })
+ await writeFile(source, 'fn main() {}\n')
+ return { project, worktree, source }
+}
+
async function createSkillsFixture(): Promise<{ project: string, worktree: string, skill: string }> {
const project = await temporaryRoot('dsh-deps-project-')
const worktree = await temporaryRoot('dsh-deps-worktree-')
@@ -140,6 +158,60 @@ describe('unlinkWorktreeDependencies', () => {
})
})
+describe('normalizeSeedDirectories', () => {
+ it('falls back to the tauri build cache and keeps nested paths', () => {
+ expect(normalizeSeedDirectories()).toEqual(['src-tauri/target'])
+ expect(normalizeSeedDirectories([])).toEqual(['src-tauri/target'])
+ expect(normalizeSeedDirectories(['src-tauri\\target\\', 'target'])).toEqual(['src-tauri/target', 'target'])
+ })
+
+ it('rejects traversal, absolute and duplicate entries', () => {
+ expect(normalizeSeedDirectories(['../evil', 'src/../../etc', '.', '..', '', ' ', '/etc/passwd', 'C:\\Windows'])).toEqual([])
+ const deduped = normalizeSeedDirectories(['src-tauri/target', 'SRC-TAURI/TARGET'])
+ expect(deduped).toEqual(process.platform === 'win32' ? ['src-tauri/target'] : ['src-tauri/target', 'SRC-TAURI/TARGET'])
+ })
+})
+
+describe('seedWorktreeDirectories', () => {
+ it('copies the build cache, drops incremental state and refreshes local rust sources', async () => {
+ const { project, worktree, source } = await createBuildCacheFixture()
+ await utimes(source, new Date(0), new Date(0))
+ const startedAt = Date.now()
+
+ const result = await seedWorktreeDirectories([project], worktree, ['src-tauri/target'])
+
+ expect(result).toEqual({ seeded: ['src-tauri/target'], skipped: [], touched: 1, errors: [], sources: [project] })
+ expect(await readFile(join(worktree, 'src-tauri', 'target', 'debug', 'deps', 'libdemo.rlib'), 'utf8')).toBe('artifact\n')
+ expect(await readFile(join(worktree, 'src-tauri', 'target', 'debug', 'build', 'generated.rs'), 'utf8')).toBe('// generated\n')
+ await expect(lstat(join(worktree, 'src-tauri', 'target', 'debug', 'incremental'))).rejects.toMatchObject({ code: 'ENOENT' })
+ expect((await stat(source)).mtimeMs).toBeGreaterThanOrEqual(startedAt - 1000)
+ })
+
+ it('keeps the source cache intact and skips missing sources or occupied targets', async () => {
+ const { project, worktree } = await createBuildCacheFixture()
+
+ const emptyProject = await temporaryRoot('dsh-seed-empty-')
+ const missingSource = await seedWorktreeDirectories([emptyProject], worktree, ['src-tauri/target'])
+ expect(missingSource).toEqual({ seeded: [], skipped: ['src-tauri/target'], touched: 0, errors: [], sources: [] })
+
+ await mkdir(join(worktree, 'src-tauri', 'target'), { recursive: true })
+ const occupiedTarget = await seedWorktreeDirectories([project], worktree, ['src-tauri/target'])
+ expect(occupiedTarget).toEqual({ seeded: [], skipped: ['src-tauri/target'], touched: 0, errors: [], sources: [] })
+ expect(await readFile(join(project, 'src-tauri', 'target', 'debug', 'deps', 'libdemo.rlib'), 'utf8')).toBe('artifact\n')
+ })
+
+ it('falls back to the next source root that carries the directory', async () => {
+ const { project, worktree } = await createBuildCacheFixture()
+ const emptyProject = await temporaryRoot('dsh-seed-empty-')
+
+ const result = await seedWorktreeDirectories([emptyProject, project], worktree, ['src-tauri/target'])
+
+ expect(result.seeded).toEqual(['src-tauri/target'])
+ expect(result.sources).toEqual([project])
+ expect(await readFile(join(worktree, 'src-tauri', 'target', 'debug', 'deps', 'libdemo.rlib'), 'utf8')).toBe('artifact\n')
+ })
+})
+
describe('copyMissingChildren', () => {
it('copies a missing source directory into the target as a real directory', async () => {
const { project, skill } = await createSkillsFixture()
diff --git a/packages/dsh-tauri-worktree/src/host/utils/dependencies.ts b/packages/dsh-tauri-worktree/src/host/utils/dependencies.ts
index a6e153c3..2bbe7fd0 100644
--- a/packages/dsh-tauri-worktree/src/host/utils/dependencies.ts
+++ b/packages/dsh-tauri-worktree/src/host/utils/dependencies.ts
@@ -1,11 +1,16 @@
import { existsSync, readdirSync, statSync } from 'node:fs'
-import { cp, lstat, mkdir, rm, symlink } from 'node:fs/promises'
+import { cp, lstat, mkdir, readdir, rm, symlink, utimes } from 'node:fs/promises'
import process from 'node:process'
import { filter, find, get, isEmpty, isString, map, trimEnd, uniqBy } from 'lodash-es'
-import { resolve } from 'pathe'
+import { basename, dirname, resolve } from 'pathe'
const DEFAULT_LINK_DIRECTORIES: readonly string[] = ['node_modules']
+const DEFAULT_SEED_DIRECTORIES: readonly string[] = ['src-tauri/target']
+
+// 增量编译目录绑定原路径且体积可观,换路径复用没有意义
+const SEED_EXCLUDED_NAMES: ReadonlySet<string> = new Set(['incremental'])
+
const SHELL_TOOL_NAMES: ReadonlySet<string> = new Set([
'bash',
'pwsh',
@@ -36,6 +41,17 @@ export function normalizeLinkDirectories(directories?: readonly string[]): strin
return uniqBy(valid, name => (process.platform === 'win32' ? name.toLowerCase() : name))
}
+export function normalizeSeedDirectories(directories?: readonly string[]): string[] {
+ const source = isEmpty(directories) ? DEFAULT_SEED_DIRECTORIES : directories ?? []
+ const names = map(source, raw => trimEnd(String(raw ?? '').trim(), '/\\').replace(/\\/g, '/'))
+ const valid = filter(names, name =>
+ Boolean(name)
+ && !name.startsWith('/')
+ && !/^[a-z]:/i.test(name)
+ && !name.split('/').some(segment => segment === '.' || segment === '..'))
+ return uniqBy(valid, name => (process.platform === 'win32' ? name.toLowerCase() : name))
+}
+
export function isDependencyInstallCommand(command: string): boolean {
const text = String(command ?? '')
return text.length > 0 && INSTALL_PATTERNS.some(pattern => pattern.test(text))
@@ -80,6 +96,51 @@ export async function linkWorktreeDependencies(
return { linked, skipped }
}
+/**
+ * 把源仓库的构建缓存复制进工作树,让 Rust 依赖不必在新工作树里重编。
+ *
+ * 必须是复制而不是链接:共享同一个 target 目录时 cargo 会用同一份 `-C metadata` 把两棵树的
+ * 同名单元当作同一个,源仓库构建过之后工作树会被判成新鲜,静默跑起源仓库的产物。
+ * 复制完成后还要刷新工作树本地源码的时间戳——复制来的指纹比新检出的源码更新,不刷新的话
+ * 工作区 crate 同样会被判成新鲜,编译出的应用仍是源仓库那份。
+ */
+export async function seedWorktreeDirectories(
+ sourceRoots: readonly string[],
+ worktreePath: string,
+ directories: readonly string[] = DEFAULT_SEED_DIRECTORIES,
+): Promise<{ seeded: string[], skipped: string[], touched: number, errors: string[], sources: string[] }> {
+ const seeded: string[] = []
+ const skipped: string[] = []
+ const errors: string[] = []
+ const sources: string[] = []
+ let touched = 0
+ for (const name of normalizeSeedDirectories(directories)) {
+ const sourceRoot = find(sourceRoots, root => existsSync(resolve(root, name)))
+ const target = resolve(worktreePath, name)
+ if (!sourceRoot || await pathExists(target)) {
+ skipped.push(name)
+ continue
+ }
+ try {
+ await mkdir(dirname(target), { recursive: true })
+ await cp(resolve(sourceRoot, name), target, {
+ recursive: true,
+ preserveTimestamps: true,
+ filter: path => !SEED_EXCLUDED_NAMES.has(basename(path)),
+ })
+ touched += await touchRustSources(dirname(target), target)
+ seeded.push(name)
+ if (!sources.includes(sourceRoot))
+ sources.push(sourceRoot)
+ }
+ catch (error) {
+ await rm(target, { recursive: true, force: true }).catch(() => {})
+ errors.push(`${name}: ${get(error, 'message', String(error))}`)
+ }
+ }
+ return { seeded, skipped, touched, errors, sources }
+}
+
export async function unlinkWorktreeDependencies(
worktreePath: string,
directories: readonly string[] = DEFAULT_LINK_DIRECTORIES,
@@ -148,6 +209,29 @@ export async function copyMissingChildren(sourceDirectory: string, targetDirecto
// --- internal ---
+async function touchRustSources(root: string, skip: string): Promise<number> {
+ const entries = await readdir(root, { withFileTypes: true }).catch(() => [])
+ let touched = 0
+ for (const entry of entries) {
+ const path = resolve(root, entry.name)
+ if (path === skip)
+ continue
+ if (entry.isDirectory()) {
+ touched += await touchRustSources(path, skip)
+ continue
+ }
+ if (!entry.name.endsWith('.rs'))
+ continue
+ try {
+ const now = new Date()
+ await utimes(path, now, now)
+ touched += 1
+ }
+ catch {}
+ }
+ return touched
+}
+
async function isSymbolicLink(path: string): Promise<boolean> {
try {
return (await lstat(path)).isSymbolicLink()
diff --git a/packages/dsh-tauri-worktree/src/host/utils/worktree-facts.ts b/packages/dsh-tauri-worktree/src/host/utils/worktree-facts.ts
index ae889379..9111171e 100644
--- a/packages/dsh-tauri-worktree/src/host/utils/worktree-facts.ts
+++ b/packages/dsh-tauri-worktree/src/host/utils/worktree-facts.ts
@@ -17,7 +17,7 @@ export function worktreeSectionText(binding: Binding): string {
`${worktreeFactsText(binding)}\n\n`
+ `Resolve every path inside the worktree path. The project path is a different checkout: `
+ `do not read from or modify it in this session, even when the inherited history refers to it. `
- + `Dependency directories (e.g. node_modules) are linked from the source repository, and the agent skills directory (.agents) is copied into the worktree, so it works out of the box. `
+ + `Dependency directories (e.g. node_modules) are linked from the source repository, the Rust build cache (src-tauri/target) is seeded with a copy so the backend does not recompile from scratch, and the agent skills directory (.agents) is copied into the worktree, so it 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. `
diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.toml
index 3258f73d..cf0ac178 100644
--- a/src-tauri/Cargo.toml
+++ b/src-tauri/Cargo.toml
@@ -128,6 +128,10 @@ tray-icon = { version = "0.25", default-features = false, features = [ "ksni" ]
[patch.crates-io]
tauri-plugin-wdio-webdriver = { path = "vendor/tauri-plugin-wdio-webdriver" }
+# 行号表而非完整调试信息:panic 与回溯仍能定位到行,target 体积、链接耗时和新工作树的构建缓存拷贝量都随之下降
+[profile.dev]
+debug = 1
+
[target.'cfg(windows)'.dependencies]
rfd = "0.16"
webview2-com = "0.38"