Skip to content

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

perf(turnrewind): collapse workspace rev-parse into one subprocess with background refresh, async conflict reads

yingtianland7305fafd795
diff --git a/packages/dsh-tauri-turnrewind-ts/src/host/service/git-snapshot.ts b/packages/dsh-tauri-turnrewind-ts/src/host/service/git-snapshot.ts
index bac1f93c..cd73b1b1 100644
--- a/packages/dsh-tauri-turnrewind-ts/src/host/service/git-snapshot.ts
+++ b/packages/dsh-tauri-turnrewind-ts/src/host/service/git-snapshot.ts
@@ -36,6 +36,7 @@ import {
rmSync,
writeFileSync,
} from 'node:fs'
+import { readFile } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import process from 'node:process'
import { dirname, join, relative, resolve, sep } from 'pathe'
@@ -534,7 +535,7 @@ async function hashDiskFile(store: SnapshotStore, workspaceDir: string, path: st
const info = lstatSync(target)
if (!info.isFile() || info.size > MAX_FILE_BYTES)
return undefined
- const output = await runGitStdin(store.repoDir, store.workspaceDir, ['hash-object', '-w', '--stdin'], readFileSync(target))
+ const output = await runGitStdin(store.repoDir, store.workspaceDir, ['hash-object', '-w', '--stdin'], await readFile(target))
return output.toString('utf8').trim()
}
@@ -633,7 +634,7 @@ export async function stateAt(store: SnapshotStore, commit: string, path: string
return { kind: 'file', digest: digest(bytes), mode: info.mode }
}
-export function currentState(workspaceDir: string, path: string): DiskState {
+export async function currentState(workspaceDir: string, path: string): Promise<DiskState> {
const target = assertSafePath(workspaceDir, path)
if (!existsSync(target))
return { kind: 'absent', digest: null }
@@ -641,11 +642,12 @@ export function currentState(workspaceDir: string, path: string): DiskState {
if (!info.isFile() || info.size > MAX_FILE_BYTES)
return { kind: 'unsupported', digest: null }
// Windows 无法可靠识别可执行位(git core.filemode=false),统一按 100644 报告;
- // POSIX 取真实权限位,使 mode 差异能进入冲突可视与恢复路径。
+ // POSIX 取真实权限位,使 mode 差异能进入冲突可视与恢复路径。文件读取走异步,
+ // 大文件的冲突检测不再阻塞事件循环。
const mode = process.platform === 'win32'
? '100644'
: `100${(info.mode & 0o777).toString(8).padStart(3, '0')}`
- return { kind: 'file', digest: digest(readFileSync(target)), mode }
+ return { kind: 'file', digest: digest(await readFile(target)), mode }
}
/**
diff --git a/packages/dsh-tauri-turnrewind-ts/src/host/service/git-workspace.ts b/packages/dsh-tauri-turnrewind-ts/src/host/service/git-workspace.ts
index 885ebece..c980e817 100644
--- a/packages/dsh-tauri-turnrewind-ts/src/host/service/git-workspace.ts
+++ b/packages/dsh-tauri-turnrewind-ts/src/host/service/git-workspace.ts
@@ -7,7 +7,8 @@
*/
import type { GitWorkspaceInfo } from '../types'
-import { spawnSync } from 'node:child_process'
+import { Buffer } from 'node:buffer'
+import { spawn, spawnSync } from 'node:child_process'
import { existsSync } from 'node:fs'
import process from 'node:process'
import { resolve } from 'pathe'
@@ -58,44 +59,118 @@ function runGitSync(workspaceDir: string, args: string[]): GitSyncResult {
const WORKSPACE_CACHE_TTL_MS = 60 * 1000
const workspaceCache = new Map<string, { at: number, info: GitWorkspaceInfo | undefined }>()
-export function gitWorkspace(workspaceDir: string): GitWorkspaceInfo | undefined {
- const requestedDir = resolve(workspaceDir)
- gitExecutableMissing = false
- const cached = workspaceCache.get(requestedDir)
- if (cached && Date.now() - cached.at < WORKSPACE_CACHE_TTL_MS)
- return cached.info
- const inside = runGitSync(requestedDir, ['rev-parse', '--is-inside-work-tree'])
- if (inside.error?.code === 'ENOENT') {
- gitExecutableMissing = true
- return undefined
- }
- const top = runGitSync(requestedDir, ['rev-parse', '--show-toplevel'])
- const gitDir = runGitSync(requestedDir, ['rev-parse', '--git-dir'])
- const commonDir = runGitSync(requestedDir, ['rev-parse', '--git-common-dir'])
- const index = runGitSync(requestedDir, ['rev-parse', '--git-path', 'index'])
- const infoExclude = runGitSync(requestedDir, ['rev-parse', '--git-path', 'info/exclude'])
- if (!inside.ok || inside.stdout !== 'true' || !top.ok || !gitDir.ok || !commonDir.ok || !index.ok)
- return undefined
+/**
+ * 单次 rev-parse 同时解析全部元数据:原先每次冷解析要 6 个 spawnSync,
+ * 现在合并为 1 个子进程,输出行序与参数顺序一致。
+ */
+const REV_PARSE_ARGS = [
+ 'rev-parse',
+ '--is-inside-work-tree',
+ '--show-toplevel',
+ '--git-dir',
+ '--git-common-dir',
+ '--git-path',
+ 'index',
+ '--git-path',
+ 'info/exclude',
+]
- const workspaceRoot = resolve(requestedDir, top.stdout!)
- const resolvedGitDir = resolve(requestedDir, gitDir.stdout!)
- const resolvedCommonDir = resolve(requestedDir, commonDir.stdout!)
- const resolvedIndex = resolve(requestedDir, index.stdout!)
+function resolveInfo(requestedDir: string, stdout: string): GitWorkspaceInfo | undefined {
+ const lines = stdout.split(/\r?\n/u).filter(line => line.trim() !== '')
+ if (lines.length < 6 || lines[0] !== 'true')
+ return undefined
+ const workspaceRoot = resolve(requestedDir, lines[1]!)
+ const resolvedGitDir = resolve(requestedDir, lines[2]!)
+ const resolvedCommonDir = resolve(requestedDir, lines[3]!)
+ const resolvedIndex = resolve(requestedDir, lines[4]!)
+ const resolvedInfoExclude = resolve(requestedDir, lines[5]!)
if (!existsSync(workspaceRoot) || !existsSync(resolvedGitDir) || !existsSync(resolvedCommonDir))
return undefined
-
- const info: GitWorkspaceInfo = {
+ return {
workspaceDir: workspaceRoot,
requestedDir,
gitDir: resolvedGitDir,
commonDir: resolvedCommonDir,
indexPath: resolvedIndex,
- infoExcludePath: infoExclude.ok ? resolve(requestedDir, infoExclude.stdout!) : undefined,
+ infoExcludePath: resolvedInfoExclude,
}
- workspaceCache.set(requestedDir, { at: Date.now(), info })
- if (workspaceCache.size > 64) {
- const oldest = [...workspaceCache.entries()].sort((a, b) => a[1].at - b[1].at)[0]
- workspaceCache.delete(oldest[0])
+}
+
+function evictOldest(): void {
+ if (workspaceCache.size <= 64)
+ return
+ const oldest = [...workspaceCache.entries()].sort((a, b) => a[1].at - b[1].at)[0]
+ workspaceCache.delete(oldest[0])
+}
+
+/** 后台刷新(stale-while-revalidate 的异步半边):结果直接落缓存。 */
+const refreshInflight = new Map<string, Promise<void>>()
+
+function refreshWorkspaceAsync(requestedDir: string): void {
+ if (refreshInflight.has(requestedDir))
+ return
+ const task = new Promise<GitWorkspaceInfo | undefined>((resolvePromise) => {
+ const child = spawn('git', ['-c', 'core.quotepath=false', ...REV_PARSE_ARGS], {
+ cwd: requestedDir,
+ env: { ...process.env },
+ })
+ const chunks: Buffer[] = []
+ let settled = false
+ const timeout = setTimeout(() => {
+ if (settled)
+ return
+ settled = true
+ child.kill('SIGKILL')
+ resolvePromise(undefined)
+ }, SYNC_GIT_TIMEOUT_MS)
+ child.stdout.on('data', (chunk: Buffer) => chunks.push(chunk))
+ child.on('error', (error: NodeJS.ErrnoException) => {
+ if (settled)
+ return
+ settled = true
+ clearTimeout(timeout)
+ if (error.code === 'ENOENT')
+ gitExecutableMissing = true
+ resolvePromise(undefined)
+ })
+ child.on('close', (code) => {
+ if (settled)
+ return
+ settled = true
+ clearTimeout(timeout)
+ resolvePromise(code === 0
+ ? resolveInfo(requestedDir, Buffer.concat(chunks).toString('utf8'))
+ : undefined)
+ })
+ }).then((info) => {
+ refreshInflight.delete(requestedDir)
+ workspaceCache.set(requestedDir, { at: Date.now(), info })
+ }).catch(() => {
+ refreshInflight.delete(requestedDir)
+ })
+ refreshInflight.set(requestedDir, task)
+}
+
+export function gitWorkspace(workspaceDir: string): GitWorkspaceInfo | undefined {
+ const requestedDir = resolve(workspaceDir)
+ gitExecutableMissing = false
+ const cached = workspaceCache.get(requestedDir)
+ if (cached && Date.now() - cached.at < WORKSPACE_CACHE_TTL_MS)
+ return cached.info
+ if (cached) {
+ // stale-while-revalidate:先回缓存值(元数据短暂陈旧可接受——turn 领取
+ // 路径对同步返回有硬约束),后台异步刷新,不再每个 turn 反复阻塞事件循环。
+ refreshWorkspaceAsync(requestedDir)
+ return cached.info
}
+ // 冷未命中:一次同步 rev-parse。
+ const result = runGitSync(requestedDir, REV_PARSE_ARGS)
+ if (result.error?.code === 'ENOENT') {
+ gitExecutableMissing = true
+ return undefined
+ }
+ const info = result.ok ? resolveInfo(requestedDir, result.stdout ?? '') : undefined
+ workspaceCache.set(requestedDir, { at: Date.now(), info })
+ evictOldest()
return info
}
diff --git a/packages/dsh-tauri-turnrewind-ts/src/host/service/undo.ts b/packages/dsh-tauri-turnrewind-ts/src/host/service/undo.ts
index b06548b3..7f3a7c50 100644
--- a/packages/dsh-tauri-turnrewind-ts/src/host/service/undo.ts
+++ b/packages/dsh-tauri-turnrewind-ts/src/host/service/undo.ts
@@ -72,7 +72,7 @@ async function applyRedo(runtime: WorkspaceRuntime, invocation: UndoInvocation,
const conflicts: string[] = []
for (const path of paths) {
const expected = await stateAt(runtime.store, turn.before_ref, path)
- const actual = currentState(workspaceDir, path)
+ const actual = await currentState(workspaceDir, path)
if (classifyUndo(actual, expected) === 'conflict')
conflicts.push(path)
}
@@ -272,7 +272,7 @@ async function safeDiffAgainstDisk(store: SnapshotStore, ref: string, path: stri
async function diskMatchesSnapshot(runtime: WorkspaceRuntime, workspaceDir: string, ref: string, path: string): Promise<boolean> {
try {
const { currentState } = await import('./git-snapshot')
- return classifyUndo(currentState(workspaceDir, path), await stateAt(runtime.store, ref, path)) !== 'conflict'
+ return classifyUndo(await currentState(workspaceDir, path), await stateAt(runtime.store, ref, path)) !== 'conflict'
}
catch {
return false
diff --git a/packages/dsh-tauri-turnrewind-ts/test/git-snapshot.test.js b/packages/dsh-tauri-turnrewind-ts/test/git-snapshot.test.js
index c8e9f06c..b9e2a36e 100644
--- a/packages/dsh-tauri-turnrewind-ts/test/git-snapshot.test.js
+++ b/packages/dsh-tauri-turnrewind-ts/test/git-snapshot.test.js
@@ -35,7 +35,7 @@ it('persists entry mode in snapshots and restores the executable bit', async ()
await restorePath(store, after.commit, 'run.sh')
const restored = await stat(join(workspace, 'run.sh'))
assert.ok((restored.mode & 0o111) !== 0, 'executable bit must be restored')
- assert.equal(currentState(workspace, 'run.sh').mode, '100755')
+ assert.equal((await currentState(workspace, 'run.sh')).mode, '100755')
}
finally {
await rm(root, { recursive: true, force: true })
@@ -196,7 +196,7 @@ it('does not treat CRLF conversion as a file conflict', async () => {
await writeFile(join(workspace, 'line-endings.txt'), 'after\nline\n')
const after = await captureSnapshot(store, 'refs/turnrewind/crlf-after', 'after', before.commit)
await writeFile(join(workspace, 'line-endings.txt'), 'after\r\nline\r\n')
- assert.equal(currentState(workspace, 'line-endings.txt').digest, (await stateAt(store, after.commit, 'line-endings.txt')).digest)
+ assert.equal((await currentState(workspace, 'line-endings.txt')).digest, (await stateAt(store, after.commit, 'line-endings.txt')).digest)
}
finally {
await rm(root, { recursive: true, force: true })
@@ -294,7 +294,7 @@ it('rejects paths outside the workspace', async () => {
const workspace = join(root, 'workspace')
try {
await initGitWorkspace(workspace)
- assert.throws(() => currentState(workspace, '../outside.txt'), /TURNREWIND_PATH_ESCAPE/)
+ await assert.rejects(() => currentState(workspace, '../outside.txt'), /TURNREWIND_PATH_ESCAPE/)
}
finally {
await rm(root, { recursive: true, force: true })
@@ -313,7 +313,7 @@ it('refuses to restore or inspect the workspace root itself', async () => {
// '.' normalizes to the workspace root; a restore there would delete the
// whole workspace including .git. Both disk-touching entries must refuse.
await assert.rejects(restorePath(store, snapshot.commit, '.'), /TURNREWIND_PATH_ESCAPE/)
- assert.throws(() => currentState(workspace, '.'), /TURNREWIND_PATH_ESCAPE/)
+ await assert.rejects(() => currentState(workspace, '.'), /TURNREWIND_PATH_ESCAPE/)
assert.equal(await readFile(join(workspace, 'a.txt'), 'utf8'), 'one')
}
finally {
diff --git a/packages/dsh-tauri-turnrewind-ts/test/security.test.js b/packages/dsh-tauri-turnrewind-ts/test/security.test.js
index 6b9478eb..e9b4af4a 100644
--- a/packages/dsh-tauri-turnrewind-ts/test/security.test.js
+++ b/packages/dsh-tauri-turnrewind-ts/test/security.test.js
@@ -114,7 +114,7 @@ it('refuses dangling symlink workspace paths during inspection and restore', asy
throw error
}
const store = createSnapshotStore(join(root, 'data'), workspace)
- assert.throws(() => currentState(workspace, 'dangling'), /TURNREWIND_SYMLINK_UNSUPPORTED/)
+ await assert.rejects(() => currentState(workspace, 'dangling'), /TURNREWIND_SYMLINK_UNSUPPORTED/)
await assert.rejects(
() => restorePath(store, 'refs/turnrewind/missing', 'dangling'),
/TURNREWIND_SYMLINK_UNSUPPORTED/,
@@ -142,7 +142,7 @@ it('refuses symlinked workspace paths during inspection and restore', async () =
throw error
}
const store = createSnapshotStore(join(root, 'data'), workspace)
- assert.throws(() => currentState(workspace, 'linked/secret.txt'), /TURNREWIND_SYMLINK_UNSUPPORTED/)
+ await assert.rejects(() => currentState(workspace, 'linked/secret.txt'), /TURNREWIND_SYMLINK_UNSUPPORTED/)
const snapshot = await captureSnapshot(store, 'refs/turnrewind/symlink', 'symlink')
// The snapshot stores the link itself; paths below it are never tracked.
assert.equal((await stateAt(store, snapshot.commit, 'linked/secret.txt')).kind, 'absent')
@@ -237,7 +237,7 @@ it('refuses Windows junction directories like symlinks', async () => {
// symlinks — traversal through them must be refused identically (P1-5).
await symlink(outside, join(workspace, 'junction'), 'junction')
const store = createSnapshotStore(join(root, 'data'), workspace)
- assert.throws(() => currentState(workspace, 'junction/secret.txt'), /TURNREWIND_SYMLINK_UNSUPPORTED/)
+ await assert.rejects(() => currentState(workspace, 'junction/secret.txt'), /TURNREWIND_SYMLINK_UNSUPPORTED/)
const snapshot = await captureSnapshot(store, 'refs/turnrewind/junction', 'junction')
await assert.rejects(
() => restorePath(store, snapshot.commit, 'junction/secret.txt'),