DeepSeek Harness Tauri 桌面版 | Only 8mb installer, zero environment setup, preset plugins, Windows / macOS / Linux.
feat(turnrewind): per-file oversize reporting instead of aborting the undo
yingtianlan91a6cae8b7d7
diff --git a/docs/TURN_REWIND_GIT_DIR_PROGRESS.md b/docs/TURN_REWIND_GIT_DIR_PROGRESS.mdindex 0f8d0026..66fe047c 100644--- a/docs/TURN_REWIND_GIT_DIR_PROGRESS.md+++ b/docs/TURN_REWIND_GIT_DIR_PROGRESS.md@@ -69,6 +69,7 @@ DSH_HOME- `maintenance.test.js` 新增 purge 安全测试:purge 只删除该 workspace 的 snapshot repo 与账本行,用户 `.git` 目录、HEAD、porcelain status、工作区文件以及其他 workspace 的 snapshot repo 和账本行全部完好;- `test/git-test-utils.js` 为每个测试仓库显式设置 `core.autocrlf=false`:Git for Windows 系统级默认 `core.autocrlf=true` 会让 worktree checkout/add 发生行尾转换,导致 fixture 依赖机器配置(本机已实测踩到);- 新增 `test/git-gc.test.js`:alternates 失效自愈——构造“文件已删除 + blob 从源仓库借用(`hash-object -w` 不可达对象)+ 源 `gc --prune=now`”的真实断裂场景,验证读取路径断(`stateAt` reject)、下一次 capture 检测到父链缺对象并自愈为自包含基线(alternates 消失、对象物理落本地、后续 capture 独立可读);+- 大文件(>64 MB)行为(2026-09-02 补):超限 blob 仍会捕获进快照;stateAt 以 kind tooLarge 报告(不再抛异常炸整个预览),预览卡标注 [too large],执行时 restorePath 对该单文件抛 TURNREWIND_FILE_TOO_LARGE、undo 循环将其计入「未恢复」清单,其余文件照常恢复、turn 照常记为 undone;大项目实测:6000 文件/94MB 已提交仓库首拍 1.6s、稳态 3.5s、快照 repo 82KB(alternates 借用),大量未 ignore 的未跟踪文件首拍可达分钟级——ignore 卫生决定体验;- 真机 DSH Host 验证已完成(dev 环境:`DSH_HOME=~/.dsh.dev-gitdir`,profile 以 `link:` 挂载本分支插件源码):- 一次 turn 内新建/修改/删除文件 → `snapshots/<hash>.git` 生成、`ledger.sqlite` 有 turns 行;- 两阶段 `/undo`(预览红绿 diff → 卡内 ✓)→ 三个文件全部恢复至 turn 前状态;diff --git a/plugins/dsh-tauri-turnrewind/README.md b/plugins/dsh-tauri-turnrewind/README.mdindex 46ed3fea..d115b305 100644--- a/plugins/dsh-tauri-turnrewind/README.md+++ b/plugins/dsh-tauri-turnrewind/README.md@@ -85,7 +85,7 @@1. **会话内消息**:插件来源的上下文注入消息,模型和用户都可见、可审计;2. **Web UI 弹窗**:宿主端 `turnrewind` 会话投影(`lib/core/dialog-projection.js`)把提示折叠进会话列表快照,客户端半(`lib/client.js`)从 `sessions.list` 的 `projectionValues.turnrewind` 读到后弹出模态对话框,按提示 id 在 `localStorage` 去重——同一浏览器每条提示只弹一次,重装/换浏览器会重弹一次。-大工作区的取舍:不再做预算预扫描,快照耗时与磁盘占用随仓库规模增长(Git ignore 能排除 `node_modules` 等,但容量/性能风险仍由使用者自行承担);单文件恢复上限仍为 64 MB。+大工作区的取舍:不再做预算预扫描,快照耗时与磁盘占用随仓库规模增长(Git ignore 能排除 `node_modules` 等,但容量/性能风险仍由使用者自行承担);单文件快照/恢复上限为 64 MB——超限文件仍会被捕获进快照,`/undo` 预览会以 `[too large]` 标注并在执行后单文件报告为「未恢复」,**不会**导致整次 undo 失败,其余文件照常恢复。若项目里有此类大文件且不希望被追踪,请把它们加进源仓库的 ignore 规则。### 清理已膨胀的快照数据diff --git a/plugins/dsh-tauri-turnrewind/lib/core/git-snapshot.js b/plugins/dsh-tauri-turnrewind/lib/core/git-snapshot.jsindex 1d652e88..05faa1c3 100644--- a/plugins/dsh-tauri-turnrewind/lib/core/git-snapshot.js+++ b/plugins/dsh-tauri-turnrewind/lib/core/git-snapshot.js@@ -354,7 +354,7 @@ export async function classifyPathChange(store, beforeCommit, afterCommit, path)const after = await stateAt(store, afterCommit, path)if (before.kind === 'absent' && after.kind === 'file')return 'created'- if (before.kind === 'file' && after.kind === 'absent')+ if ((before.kind === 'file' || before.kind === 'tooLarge') && after.kind === 'absent')return 'deleted'return 'modified'}@@ -422,6 +422,24 @@ async function commitEntry(store, commit, path) {return output.toString('utf8').split('\0').includes(path)}+/**+ * Blob size of one committed path, or undefined when absent or unknown.+ * Reading only the size never materializes the blob, so an oversized entry can+ * be surfaced without blowing the output limit.+ */+async function commitEntrySize(store, commit, path) {+ const output = await runGit(store.repoDir, store.workspaceDir, ['ls-tree', '-r', '-l', '-z', commit, '--', path])+ for (const line of output.toString('utf8').split('\0')) {+ // mode SP type SP oid TAB size SP path (size is '-' for submodules).+ const tab = line.lastIndexOf('\t')+ if (tab !== -1 && line.slice(tab + 1) === path) {+ const size = Number(line.slice(0, tab).split(' ').at(-1))+ return Number.isFinite(size) ? size : undefined+ }+ }+ return undefined+}+async function commitBytes(store, commit, path) {const output = await runGit(store.repoDir, store.workspaceDir, ['show', `${commit}:${path}`], {}, MAX_FILE_BYTES + 1)if (output.length > MAX_FILE_BYTES)@@ -446,6 +464,10 @@ export async function stateAt(store, commit, path) {// never the filesystem, so a symlinked or odd path simply reads as absent.if (!await commitEntry(store, commit, path))return { kind: 'absent', digest: null }+ // Oversized blobs are reported instead of thrown: the caller can mark the+ // entry and continue, so one huge file never aborts a whole undo preview.+ if (await commitEntrySize(store, commit, path) > MAX_FILE_BYTES)+ return { kind: 'tooLarge', digest: null }const bytes = await commitBytes(store, commit, path)return { kind: 'file', digest: digest(bytes) }}@@ -472,6 +494,11 @@ export async function restorePath(store, commit, path) {return { path, result: 'removed' }}+ // Restoring an oversized blob would require materializing it through the+ // same output-limited channel. Fail this one path with a stable code so the+ // undo loop can report it as not restored instead of dying mid-plan.+ if (await commitEntrySize(store, commit, path) > MAX_FILE_BYTES)+ throw new Error(`TURNREWIND_FILE_TOO_LARGE: ${path} (${MAX_FILE_BYTES}-byte limit) cannot be restored; add it to .gitignore or restore it manually`)const bytes = await commitBytes(store, commit, path)mkdirSync(dirname(target), { recursive: true })const temp = `${target}.turnrewind-${randomUUID()}.tmp`diff --git a/plugins/dsh-tauri-turnrewind/lib/index.js b/plugins/dsh-tauri-turnrewind/lib/index.jsindex 0ee03089..46adbe58 100644--- a/plugins/dsh-tauri-turnrewind/lib/index.js+++ b/plugins/dsh-tauri-turnrewind/lib/index.js@@ -4,7 +4,7 @@ import { homedir } from 'node:os'import { join, resolve } from 'node:path'import process from 'node:process'import { createDialogProjection } from './core/dialog-projection.js'-import { captureSnapshot, classifyPathChange, createSnapshotStore, currentState, diffAgainstDisk, gitAvailable, gitRef, probeWorkspace, restorePath, snapshotDiff, snapshotFileDiff, stateAt, workspaceKey } from './core/git-snapshot.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 { classifyUndo } from './core/planner.js'@@ -186,15 +186,20 @@ async function diskMatchesSnapshot(runtime, workspaceDir, ref, path) {/*** Build the read-only undo plan: for every touched path, how the turn changed it- * (modified/created/deleted) and whether the current on-disk state still matches- * the turn's after snapshot.+ * (modified/created/deleted), whether the current on-disk state still matches+ * the turn's after snapshot, and whether the before-snapshot blob exceeds the+ * restore limit (oversized entries restore as failures, never silently).*/async function buildPlanEntries(runtime, workspaceDir, target, paths) {- return Promise.all(paths.map(async path => ({- path,- change: await classifyPathChange(runtime.store, target.before_ref, target.after_ref, path),- conflict: !await diskMatchesSnapshot(runtime, workspaceDir, target.after_ref, path),- })))+ return Promise.all(paths.map(async (path) => {+ const beforeState = await stateAt(runtime.store, target.before_ref, path)+ return {+ path,+ change: await classifyPathChange(runtime.store, target.before_ref, target.after_ref, path),+ conflict: !await diskMatchesSnapshot(runtime, workspaceDir, target.after_ref, path),+ tooLarge: beforeState.kind === 'tooLarge',+ }+ }))}function summarizeChanges(entries) {@@ -205,11 +210,19 @@ function summarizeChanges(entries) {async function formatPlan(runtime, target, entries, options) {const conflicts = entries.filter(entry => entry.conflict)+ const oversized = entries.filter(entry => entry.tooLarge)const lines = []lines.push(`${options.preview ? 'Undo preview' : options.dryRun ? 'Undo plan' : 'Undo preflight'}: turn ${target.turn_id}; ${entries.length} file(s) (${summarizeChanges(entries)}); ${conflicts.length} conflict(s).`)for (const entry of entries) {const flag = entry.conflict ? ' [conflict]' : ''- lines.push(` ${entry.change.padEnd(8)} ${entry.path}${flag}`)+ const sizeFlag = entry.tooLarge ? ' [too large]' : ''+ lines.push(` ${entry.change.padEnd(8)} ${entry.path}${flag}${sizeFlag}`)+ }+ if (oversized.length > 0) {+ lines.push('')+ lines.push(`Oversized files (over the ${MAX_FILE_BYTES / (1024 * 1024)} MB restore limit) cannot be restored by this undo; they will be reported as not restored:`)+ for (const entry of oversized)+ lines.push(` ${entry.path}`)}if (options.preview || options.withDiffs) {lines.push('')@@ -474,9 +487,20 @@ async function executeUndoRestore(runtime, params) {try {const targets = skipConflicts ? entries.filter(entry => !entry.conflict) : entries- for (const entry of targets)- await restorePath(runtime.store, target.before_ref, entry.path)- const restoredPaths = targets.map(entry => entry.path)+ const restoredPaths = []+ const failedPaths = []+ for (const entry of targets) {+ try {+ await restorePath(runtime.store, target.before_ref, entry.path)+ restoredPaths.push(entry.path)+ }+ catch (error) {+ // One unrestorable file (oversized blob, unsupported target) must not+ // abort the whole undo: the other files still restore, and the failure+ // is reported per path instead of triggering a full rollback.+ failedPaths.push({ path: entry.path, error: String(error.message ?? error) })+ }+ }const skippedPaths = skipConflicts? entries.filter(entry => entry.conflict).map(entry => entry.path): []@@ -493,6 +517,8 @@ async function executeUndoRestore(runtime, params) {let text = `Undid turn ${target.turn_id} and restored ${restoredPaths.length} file(s). The next model request will receive a rewind notice.`if (skippedPaths.length > 0)text += ` Skipped ${skippedPaths.length} conflicted file(s): ${skippedPaths.join(', ')}.`+ if (failedPaths.length > 0)+ text += ` Not restored (${failedPaths.length} file(s)): ${failedPaths.map(failure => `${failure.path} (${failure.error.includes('TURNREWIND_FILE_TOO_LARGE') ? 'over the size limit' : failure.error})`).join('; ')}.`return text}catch (error) {diff --git a/plugins/dsh-tauri-turnrewind/test/oversize.test.js b/plugins/dsh-tauri-turnrewind/test/oversize.test.jsnew file mode 100644index 00000000..0ed7c8c1--- /dev/null+++ b/plugins/dsh-tauri-turnrewind/test/oversize.test.js@@ -0,0 +1,120 @@+import assert from 'node:assert/strict'+import { Buffer } from 'node:buffer'+import { mkdtemp, readFile, rm, writeFile } from 'node:fs/promises'+import { tmpdir } from 'node:os'+import { join, resolve } from 'node:path'+import { it } from 'vitest'+import { captureSnapshot, createSnapshotStore, restorePath, stateAt } from '../lib/core/git-snapshot.js'+import { insertTurn, openLedger, settleTurn } from '../lib/core/ledger.js'+import { applyUndo } from '../lib/index.js'+import { initGitWorkspace } from './git-test-utils.js'++// 64 MiB + 1 byte: the smallest blob over the restore limit. The buffer is+// mostly zeros so compression keeps the fixture cheap, but the blob size+// still crosses the line.+const OVER_LIMIT_BYTES = 64 * 1024 * 1024 + 1++async function undoWithConfirm(runtime, active, invocation) {+ const preview = await applyUndo(runtime, active, invocation(''))+ assert.equal(preview.kind, 'success')+ const planId = /plan ([0-9a-f-]+)/u.exec(preview.text)?.[1]+ assert.ok(planId, 'preview must carry a pending plan id')+ return applyUndo(runtime, active, invocation(`--confirm ${planId}`))+}++it('reports oversized blobs instead of failing the whole preview', async () => {+ const root = await mkdtemp(join(tmpdir(), 'turnrewind-oversize-'))+ const workspace = join(root, 'workspace')+ try {+ await initGitWorkspace(workspace)+ await writeFile(join(workspace, 'small.txt'), 'small\n')+ // A >64 MiB file: sparse so the fixture stays fast, content only at the end.+ const big = Buffer.alloc(OVER_LIMIT_BYTES)+ big.write('payload at the end', OVER_LIMIT_BYTES - 20)+ await writeFile(join(workspace, 'big.bin'), big)++ const store = createSnapshotStore(join(root, 'data'), workspace)+ const before = await captureSnapshot(store, 'refs/turnrewind/size-before', 'before')++ // stateAt surfaces the limit as a kind, not an exception: the plan can+ // keep listing other files and mark this one.+ assert.equal((await stateAt(store, before.commit, 'small.txt')).kind, 'file')+ assert.equal((await stateAt(store, before.commit, 'big.bin')).kind, 'tooLarge')++ // restorePath fails for the oversized entry alone...+ await assert.rejects(+ () => restorePath(store, before.commit, 'big.bin'),+ /TURNREWIND_FILE_TOO_LARGE/,+ )+ // ...while other paths in the same commit keep restoring normally.+ await writeFile(join(workspace, 'small.txt'), 'changed\n')+ await restorePath(store, before.commit, 'small.txt')+ assert.equal(await readFile(join(workspace, 'small.txt'), 'utf8'), 'small\n')+ }+ finally {+ await rm(root, { recursive: true, force: true, maxRetries: 5, retryDelay: 300 })+ }+})++it('undoes the other files while reporting the oversized one as not restored', async () => {+ const root = await mkdtemp(join(tmpdir(), 'turnrewind-oversize-undo-'))+ const workspace = join(root, 'workspace')+ try {+ await initGitWorkspace(workspace)+ await writeFile(join(workspace, 'small.txt'), 'before\n')+ const big = Buffer.alloc(OVER_LIMIT_BYTES)+ big.write('payload at the end', OVER_LIMIT_BYTES - 20)+ await writeFile(join(workspace, 'big.bin'), big)++ const db = openLedger(join(root, 'ledger'))+ const store = createSnapshotStore(join(root, 'data'), workspace)+ await captureSnapshot(store, 'refs/turnrewind/o1-before', 'before')++ // The turn modifies both files; the plan must show the oversize flag.+ await writeFile(join(workspace, 'small.txt'), 'after\n')+ await writeFile(join(workspace, 'big.bin'), big.subarray(0, OVER_LIMIT_BYTES - 1))+ await captureSnapshot(store, 'refs/turnrewind/o1-after', 'after', 'refs/turnrewind/o1-before')+ insertTurn(db, {+ turnId: 'session:1',+ sessionId: 'session',+ workspaceKey: resolve(workspace).toLowerCase(),+ startedAt: '2026-01-01T00:00:00.000Z',+ beforeRef: 'refs/turnrewind/o1-before',+ })+ settleTurn(db, 'session:1', 'refs/turnrewind/o1-after')++ const runtime = {+ db,+ store,+ workspaceKey: resolve(workspace).toLowerCase(),+ parentRef: 'refs/turnrewind/o1-after',+ undoing: false,+ }+ const invocation = (rawInput = '') => ({+ rawInput,+ agent: { session: { id: 'session', header: { cwd: workspace } } },+ })++ const preview = await applyUndo(runtime, new Map(), invocation(''))+ assert.equal(preview.kind, 'success')+ assert.match(preview.text, /big\.bin \[too large\]/u)+ assert.match(preview.text, /Oversized files \(over the 64 MB restore limit\)/u)++ const result = await undoWithConfirm(runtime, new Map(), invocation)+ assert.equal(result.kind, 'success')+ // The normal file came back; the oversized one failed per-path.+ assert.match(result.text, /restored 1 file\(s\)/u)+ assert.match(result.text, /Not restored \(1 file\(s\)\): big\.bin \(over the size limit\)/u)+ assert.equal(await readFile(join(workspace, 'small.txt'), 'utf8'), 'before\n')+ // The oversized file on disk is untouched (still the turn's output).+ assert.equal((await readFile(join(workspace, 'big.bin'))).length, OVER_LIMIT_BYTES - 1)++ // The turn is settled as undone and the ledger's operation completed.+ const row = db.prepare('SELECT status FROM turns WHERE turn_id = ?').get('session:1')+ assert.equal(row.status, 'undone')+ db.close()+ }+ finally {+ await rm(root, { recursive: true, force: true, maxRetries: 5, retryDelay: 300 })+ }+})