Skip to content

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

fix(turnrewind): clear the remaining P3 review findings

yingtianlan8ed85283af3f
diff --git a/docs/TURN_REWIND_GIT_DIR_PROGRESS.md b/docs/TURN_REWIND_GIT_DIR_PROGRESS.md
index 8581fec9..e95fdd4a 100644
--- a/docs/TURN_REWIND_GIT_DIR_PROGRESS.md
+++ b/docs/TURN_REWIND_GIT_DIR_PROGRESS.md
@@ -98,6 +98,13 @@ Failed: 0
- P2 测试超时统一为 120s(package.json 与 vitest.config.js,Windows 实测有用例超 30s);
- P0 redo 无 operation/回滚/needs-recovery:**按决策暂缓**(功能冻结,README 标注「已知缺陷:redo」与启用条件)。
+### P3 清理(2026-09-02 第二批)
+
+- git 子进程超时:runGit / runGitStdin / git init 异步 spawn 增加 5 分钟墙钟预算(SIGKILL + TURNREWIND_GIT_TIMEOUT),git-workspace 的 spawnSync 增加 timeout+killSignal——卡死的 git 不再永久 pending / 冻结 Host;
+- gitAvailable() 失败缓存改为 5 分钟 TTL:进程运行期间装好 git(或修好 PATH)后无需重启 Host 即恢复;
+- rewind_notices 膨胀:新增 pruneConsumedNotices(consumed 且 claimed_at > 7 天删除,保留 pending 与近期行以维持 unsupported 弹窗去重语义),插件启动时执行一次;
+- 「git 全程异步」措辞修正为「git 子进程模型」,如实标注两处同步路径(工作区解析 spawnSync、冲突检测同步读盘)与异步化待办。
+
### 可选优化
1. 连通性检查的性能优化:当前每次 capture 走全链 `rev-list`(O(链上对象总数))。优化方向:常态走 `--not <parent>` 的增量检查 + 源对象库 mtime 变化时触发全链检查。大仓库上需先实测 capture 耗时;
diff --git a/plugins/dsh-tauri-turnrewind/README.md b/plugins/dsh-tauri-turnrewind/README.md
index 4f93130f..56b010c2 100644
--- a/plugins/dsh-tauri-turnrewind/README.md
+++ b/plugins/dsh-tauri-turnrewind/README.md
@@ -12,7 +12,7 @@
- 为已领取的 Agent turn 建立私有 Git 快照;
- 将快照映射记录到 `$DSH_HOME/ledger.sqlite`;
-- **git 全程异步执行**:快照、diff、恢复都不阻塞 Host 事件循环;同一会话的捕获/结算按 FIFO 串行;收到 turn 输入后,before snapshot 通过 `agent/pre-step` barrier 完成后才允许模型和工具执行;同一 workspace 被其他 session 占用时,新 turn 会正常运行但记为 `skipped`,避免共享 snapshot 链互相污染;
+- **git 子进程模型**:快照、diff、恢复走异步 spawn,不阻塞 Host 事件循环;同一会话的捕获/结算按 FIFO 串行;收到 turn 输入后,before snapshot 通过 `agent/pre-step` barrier 完成后才允许模型和工具执行;同一 workspace 被其他 session 占用时,新 turn 会正常运行但记为 `skipped`,避免共享 snapshot 链互相污染。**仍有两处同步路径**:工作区解析(git-workspace.js 的 rev-parse spawnSync,每次 turn 领取触发数次,单次 <100ms)与冲突检测的磁盘读取(currentState 同步读单个文件,上限 64MB)——超重工作区上可能短暂卡顿,异步化在待办中;
- **git 可用性探测**:系统没有 git 时,turn 显式记为 `skipped`(原因 `TURNREWIND_GIT_UNAVAILABLE`),而不是静默失败;
- **快照链自愈**:私有快照仓库被删/损坏后,下一次捕获自动降级重建基线(日志有一条 warning),后续 turn 照常可撤销;被清空前留下来的旧 turn 会在 `/undo` 选目标时自动识别为死快照并标记跳过(`snapshot ref missing`),不会甩出 git 原始报错;
- **alternates 失效自愈**:私有 repo 通过 alternates 借用源仓库对象,而源仓库 `git gc --prune=now`(amend/rebase 的日常残留)可能删掉被借用且不可达的对象;每次 capture 后做连通性检查(`git rev-list --objects --missing=print`),发现缺对象即降级为自包含存储(不再借用、不再复制源 index)并重建基线,旧 turn 走死快照跳过路径;
diff --git a/plugins/dsh-tauri-turnrewind/lib/core/git-snapshot.js b/plugins/dsh-tauri-turnrewind/lib/core/git-snapshot.js
index c83f7c69..bb0625f0 100644
--- a/plugins/dsh-tauri-turnrewind/lib/core/git-snapshot.js
+++ b/plugins/dsh-tauri-turnrewind/lib/core/git-snapshot.js
@@ -22,6 +22,13 @@ const SNAPSHOT_PATHSPECS = [
]
const SNAPSHOT_REF_PREFIX = 'refs/turnrewind/'
+/**
+ * Hard wall-clock budget per git subprocess. A wedged git (hung remote fs,
+ * antivirus stall) would otherwise leave the async path pending forever and
+ * the sync paths frozen; 5 minutes is far above any legitimate capture.
+ */
+const GIT_SUBPROCESS_TIMEOUT_MS = 5 * 60 * 1000
+
/**
* Run one git command without blocking the host event loop. All snapshot I/O
* used to be synchronous, which froze the whole host — every session, the web
@@ -37,14 +44,17 @@ function runGit(repoDir, workspaceDir, args, extraEnv = {}, maxBytes = MAX_OUTPU
const errors = []
let total = 0
let settled = false
-
+ let timeout
const fail = (error) => {
if (settled)
return
settled = true
- child.kill()
+ clearTimeout(timeout)
+ child.kill('SIGKILL')
rejectPromise(error)
}
+ // SIGKILL so a git stuck in uninterruptible I/O cannot outlive the budget.
+ timeout = setTimeout(() => fail(new Error(`TURNREWIND_GIT_TIMEOUT: git ${args.join(' ')} exceeded ${GIT_SUBPROCESS_TIMEOUT_MS / 1000}s`)), GIT_SUBPROCESS_TIMEOUT_MS)
child.stdout.on('data', (chunk) => {
if (settled)
return
@@ -64,8 +74,11 @@ function runGit(repoDir, workspaceDir, args, extraEnv = {}, maxBytes = MAX_OUTPU
if (settled)
return
settled = true
+ clearTimeout(timeout)
const stdout = Buffer.concat(chunks)
- if (code !== 0) {
+ // code null = killed by the timeout's SIGKILL; the timeout already
+ // rejected the promise, this only guards the normal exit path.
+ if (code !== null && code !== 0) {
const detail = Buffer.concat(errors).toString('utf8').trim() || stdout.toString('utf8').trim() || `exit ${code}`
rejectPromise(new Error(`TURNREWIND_GIT_FAILED: ${detail}`))
return
@@ -81,15 +94,38 @@ async function runGitText(repoDir, workspaceDir, args, extraEnv = {}) {
}
let gitProbeResult
+let gitProbeFailedAt = 0
-/** Resolve once per host process: whether a git executable is usable at all. */
+/** Re-probe a failed availability check after this long (git may be installed while the host runs). */
+const GIT_PROBE_RETRY_MS = 5 * 60 * 1000
+
+/**
+ * Whether a usable git executable is on PATH. Successful probes are cached for
+ * the host process; failed probes expire after GIT_PROBE_RETRY_MS so a git
+ * installed (or PATH fixed) mid-session is picked up without a host restart.
+ */
export function gitAvailable() {
+ const failedRecently = gitProbeResult !== undefined && gitProbeFailedAt > 0 && Date.now() - gitProbeFailedAt > GIT_PROBE_RETRY_MS
+ if (failedRecently) {
+ gitProbeResult = undefined
+ gitProbeFailedAt = 0
+ }
gitProbeResult ??= new Promise((resolvePromise) => {
const child = spawn('git', ['--version'])
let settled = false
+ const markFailure = () => {
+ gitProbeFailedAt = Date.now()
+ }
const settle = value => (settled ? undefined : (settled = true, resolvePromise(value)))
- child.on('error', () => settle(false))
- child.on('close', code => settle(code === 0))
+ child.on('error', () => {
+ markFailure()
+ settle(false)
+ })
+ child.on('close', (code) => {
+ if (code !== 0)
+ markFailure()
+ settle(code === 0)
+ })
})
return gitProbeResult
}
@@ -104,9 +140,25 @@ async function ensureRepository(store) {
await new Promise((resolvePromise, rejectPromise) => {
const child = spawn('git', ['init', '--bare', repoDir])
const errors = []
+ let settled = false
+ const timeout = setTimeout(() => {
+ settled = true
+ child.kill('SIGKILL')
+ rejectPromise(new Error(`TURNREWIND_GIT_TIMEOUT: git init exceeded ${GIT_SUBPROCESS_TIMEOUT_MS / 1000}s`))
+ }, GIT_SUBPROCESS_TIMEOUT_MS)
child.stderr.on('data', chunk => errors.push(chunk))
- child.on('error', error => rejectPromise(new Error(`TURNREWIND_GIT_INIT: ${error.message}`)))
+ child.on('error', (error) => {
+ if (settled)
+ return
+ settled = true
+ clearTimeout(timeout)
+ rejectPromise(new Error(`TURNREWIND_GIT_INIT: ${error.message}`))
+ })
child.on('close', (code) => {
+ if (settled)
+ return
+ settled = true
+ clearTimeout(timeout)
if (code !== 0) {
rejectPromise(new Error(`TURNREWIND_GIT_INIT: ${Buffer.concat(errors).toString('utf8').trim() || 'git init failed'}`))
return
@@ -332,12 +384,27 @@ function runGitStdin(repoDir, workspaceDir, args, input) {
})
const chunks = []
const errors = []
+ let settled = false
+ let timeout
+ const fail = (error) => {
+ if (settled)
+ return
+ settled = true
+ clearTimeout(timeout)
+ child.kill('SIGKILL')
+ rejectPromise(error)
+ }
+ timeout = setTimeout(() => fail(new Error(`TURNREWIND_GIT_TIMEOUT: git ${args.join(' ')} exceeded ${GIT_SUBPROCESS_TIMEOUT_MS / 1000}s`)), GIT_SUBPROCESS_TIMEOUT_MS)
child.stdout.on('data', chunk => chunks.push(chunk))
child.stderr.on('data', chunk => errors.push(chunk))
- child.on('error', error => rejectPromise(new Error(`TURNREWIND_GIT_EXEC: ${error.message}`)))
+ child.on('error', error => fail(new Error(`TURNREWIND_GIT_EXEC: ${error.message}`)))
child.on('close', (code) => {
- if (code !== 0) {
- rejectPromise(new Error(`TURNREWIND_GIT_FAILED: ${Buffer.concat(errors).toString('utf8').trim() || `exit ${code}`}`))
+ if (settled)
+ return
+ settled = true
+ clearTimeout(timeout)
+ if (code !== null && code !== 0) {
+ fail(new Error(`TURNREWIND_GIT_FAILED: ${Buffer.concat(errors).toString('utf8').trim() || `exit ${code}`}`))
return
}
resolvePromise(Buffer.concat(chunks))
diff --git a/plugins/dsh-tauri-turnrewind/lib/core/git-workspace.js b/plugins/dsh-tauri-turnrewind/lib/core/git-workspace.js
index 0eef57b8..35d846c3 100644
--- a/plugins/dsh-tauri-turnrewind/lib/core/git-workspace.js
+++ b/plugins/dsh-tauri-turnrewind/lib/core/git-workspace.js
@@ -4,6 +4,9 @@ import { resolve } from 'node:path'
import process from 'node:process'
const MAX_OUTPUT_BYTES = 1024 * 1024
+// spawnSync blocks the event loop; a hard timeout keeps a wedged git from
+// freezing the host forever (same wall clock as the async spawn budget).
+const SYNC_GIT_TIMEOUT_MS = 5 * 60 * 1000
function runGitSync(workspaceDir, args) {
const result = spawnSync('git', ['-c', 'core.quotepath=false', ...args], {
@@ -11,6 +14,8 @@ function runGitSync(workspaceDir, args) {
env: { ...process.env },
encoding: 'utf8',
maxBuffer: MAX_OUTPUT_BYTES,
+ timeout: SYNC_GIT_TIMEOUT_MS,
+ killSignal: 'SIGKILL',
})
if (result.error)
return { ok: false, error: result.error }
diff --git a/plugins/dsh-tauri-turnrewind/lib/core/ledger.js b/plugins/dsh-tauri-turnrewind/lib/core/ledger.js
index 3e42f241..6d1f1f20 100644
--- a/plugins/dsh-tauri-turnrewind/lib/core/ledger.js
+++ b/plugins/dsh-tauri-turnrewind/lib/core/ledger.js
@@ -499,3 +499,14 @@ export function completeRedoWithNotice(db, operationId, turnId, notice) {
throw error
}
}
+
+/**
+ * Delete long-consumed notice rows. Consumed rows keep two jobs — the
+ * unsupported-heads-up dedup (one dialog per session+workspace) and audit —
+ * so they are pruned by age instead of on claim: 7 days is far beyond any
+ * session's lifetime while keeping the ledger from growing without bound.
+ */
+export function pruneConsumedNotices(db, maxAgeMs = 7 * 24 * 60 * 60 * 1000) {
+ const cutoff = new Date(Date.now() - maxAgeMs).toISOString()
+ return db.prepare(`DELETE FROM rewind_notices WHERE status = 'consumed' AND claimed_at < ?`).run(cutoff).changes
+}
diff --git a/plugins/dsh-tauri-turnrewind/lib/index.js b/plugins/dsh-tauri-turnrewind/lib/index.js
index 46adbe58..3945edca 100644
--- a/plugins/dsh-tauri-turnrewind/lib/index.js
+++ b/plugins/dsh-tauri-turnrewind/lib/index.js
@@ -6,7 +6,7 @@ import process from 'node:process'
import { createDialogProjection } from './core/dialog-projection.js'
import { captureSnapshot, classifyPathChange, createSnapshotStore, currentState, diffAgainstDisk, gitAvailable, gitRef, MAX_FILE_BYTES, probeWorkspace, restorePath, snapshotDiff, snapshotFileDiff, stateAt, workspaceKey } from './core/git-snapshot.js'
import { isSystemSensitiveWorkspace } from './core/guard.js'
-import { claimPendingPlan, claimRewindNotices, completeRedoWithNotice, completeUndoWithNotice, createOperation, createPendingPlan, failTurn, getLatestAppliedUndo, getLatestSnapshotRef, getLatestTurnSummary, getPendingPlanRow, getPendingPlanStatus, getTurn, insertTurn, listNeedsRecoveryWorkspaces, listReversibleTurns, markPendingPlanApplied, markPendingPlanCancelled, markTurnSnapshotMissing, openLedger, recordSkippedTurn, registerWorkspace, releasePendingPlanClaim, settleInterruptedTurn, settleNoopTurn, settleOperation, settleTurn, skipTurn } from './core/ledger.js'
+import { claimPendingPlan, claimRewindNotices, completeRedoWithNotice, completeUndoWithNotice, createOperation, createPendingPlan, failTurn, getLatestAppliedUndo, getLatestSnapshotRef, getLatestTurnSummary, getPendingPlanRow, getPendingPlanStatus, getTurn, insertTurn, listNeedsRecoveryWorkspaces, listReversibleTurns, markPendingPlanApplied, markPendingPlanCancelled, markTurnSnapshotMissing, openLedger, pruneConsumedNotices, recordSkippedTurn, registerWorkspace, releasePendingPlanClaim, settleInterruptedTurn, settleNoopTurn, settleOperation, settleTurn, skipTurn } from './core/ledger.js'
import { classifyUndo } from './core/planner.js'
const name = 'dsh-tauri-turnrewind'
@@ -725,6 +725,10 @@ function apply(ctx) {
const dataRoot = rootDir()
const ledger = openLedger(dataRoot)
const recoveryWorkspaces = new Set(listNeedsRecoveryWorkspaces(ledger))
+ // One-shot at startup: consumed notices older than a week have no readers
+ // left (their dedup window is long gone) and would otherwise accumulate
+ // without bound on long-lived installs.
+ pruneConsumedNotices(ledger)
const active = new Map()
const untrackedTurns = new Set()
const workspaceStores = new Map()
diff --git a/plugins/dsh-tauri-turnrewind/test/ledger.test.js b/plugins/dsh-tauri-turnrewind/test/ledger.test.js
index a975af12..8305e77b 100644
--- a/plugins/dsh-tauri-turnrewind/test/ledger.test.js
+++ b/plugins/dsh-tauri-turnrewind/test/ledger.test.js
@@ -3,7 +3,7 @@ import { mkdtemp, rm } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { it } from 'vitest'
-import { claimPendingPlan, claimRewindNotices, completeRedoWithNotice, completeUndoWithNotice, createOperation, createPendingPlan, getLatestAppliedUndo, getLatestSnapshotRef, getLatestTurn, getPendingPlanStatus, getTurn, insertTurn, listNeedsRecoveryWorkspaces, listReversibleTurns, markPendingPlanApplied, markPendingPlanCancelled, markTurnSnapshotMissing, openLedger, queueRewindNotice, recordSkippedTurn, releasePendingPlanClaim, settleInterruptedTurn, settleNoopTurn, settleOperation, settleTurn } from '../lib/core/ledger.js'
+import { claimPendingPlan, claimRewindNotices, completeRedoWithNotice, completeUndoWithNotice, createOperation, createPendingPlan, getLatestAppliedUndo, getLatestSnapshotRef, getLatestTurn, getPendingPlanStatus, getTurn, insertTurn, listNeedsRecoveryWorkspaces, listReversibleTurns, markPendingPlanApplied, markPendingPlanCancelled, markTurnSnapshotMissing, openLedger, pruneConsumedNotices, queueRewindNotice, recordSkippedTurn, releasePendingPlanClaim, settleInterruptedTurn, settleNoopTurn, settleOperation, settleTurn } from '../lib/core/ledger.js'
it('persists turn lifecycle and resumes from the latest durable snapshot', async () => {
const root = await mkdtemp(join(tmpdir(), 'turnrewind-ledger-test-'))
@@ -426,3 +426,31 @@ it('marks an interrupted active turn abandoned on reopen', async () => {
await rm(root, { recursive: true, force: true })
}
})
+
+it('prunes only long-consumed notices and keeps the dedup rows', async () => {
+ const root = await mkdtemp(join(tmpdir(), 'turnrewind-notice-prune-'))
+ try {
+ const db = openLedger(root)
+ db.exec('BEGIN')
+ // Old consumed row (past the cutoff) and a fresh consumed row.
+ db.prepare(`INSERT INTO rewind_notices(notice_id, session_id, workspace_key, target_turn_id, turns_json, paths_json, kind, status, created_at, claimed_at)
+ VALUES ('old', 's1', 'ws1', 't1', '[]', '[]', 'undo', 'consumed', ?, ?)`).run('2020-01-01T00:00:00.000Z', '2020-01-01T00:00:01.000Z')
+ db.prepare(`INSERT INTO rewind_notices(notice_id, session_id, workspace_key, target_turn_id, turns_json, paths_json, kind, status, created_at, claimed_at)
+ VALUES ('fresh', 's2', 'ws1', 't2', '[]', '[]', 'undo', 'consumed', ?, ?)`).run(new Date().toISOString(), new Date().toISOString())
+ // A pending row must survive regardless of age.
+ db.prepare(`INSERT INTO rewind_notices(notice_id, session_id, workspace_key, target_turn_id, turns_json, paths_json, kind, status, created_at)
+ VALUES ('pending', 's3', 'ws1', 't3', '[]', '[]', 'unsupported', 'pending', '2020-01-01T00:00:00.000Z')`).run()
+ db.exec('COMMIT')
+
+ db.exec('PRAGMA wal_checkpoint(TRUNCATE)')
+ const removed = pruneConsumedNotices(db)
+ assert.equal(removed, 1)
+ const survivors = db.prepare('SELECT notice_id FROM rewind_notices ORDER BY notice_id').all().map(row => row.notice_id)
+ assert.deepEqual(survivors, ['fresh', 'pending'])
+ db.exec('PRAGMA wal_checkpoint(TRUNCATE)')
+ db.close()
+ }
+ finally {
+ await rm(root, { recursive: true, force: true, maxRetries: 5, retryDelay: 300 })
+ }
+})