Skip to content

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

feat(turnrewind): persist and restore file modes (P1-4)

yingtianland27815a18222
diff --git a/packages/dsh-tauri-turnrewind-ts/README.md b/packages/dsh-tauri-turnrewind-ts/README.md
index b816c6d9..e51e409b 100644
--- a/packages/dsh-tauri-turnrewind-ts/README.md
+++ b/packages/dsh-tauri-turnrewind-ts/README.md
@@ -359,7 +359,7 @@ pnpm --filter dsh-tauri-turnrewind test
- 快照容量治理:按 turn 数/容量/保留期清理旧 snapshot ref(当前只做断链自愈,不清理历史);
- 实现父对话递归 undo;
- 实现消息旁 Undo 按钮;
-- 明确二进制、重命名、权限位等策略(symlink 已定义:捕获进快照但 undo 标注 `[unsupported]` 并跳过,见下文「符号链接策略」);
+- 明确重命名与特殊文件(submodule、设备文件)策略(symlink 与 mode/权限位已落地:mode 进快照状态、POSIX 下恢复可执行位,Windows 按 git filemode=false 约定统一 100644);
- 重新开放 redo:移除解析层禁用分支、恢复端到端 redo 测试(底层加固已完成,见「已禁用:redo」)。
### 符号链接策略(P1-3)
diff --git a/packages/dsh-tauri-turnrewind-ts/src/client/components/command-view.ts b/packages/dsh-tauri-turnrewind-ts/src/client/components/command-view.ts
index 3c65f8d2..b214fd68 100644
--- a/packages/dsh-tauri-turnrewind-ts/src/client/components/command-view.ts
+++ b/packages/dsh-tauri-turnrewind-ts/src/client/components/command-view.ts
@@ -118,16 +118,18 @@ export function UndoCommandView(props: CommandViewProps): React.ReactElement {
const summary = parsed.summary || (state === 'error' ? '失败' : state === 'running' ? '运行中' : '完成')
// 展开状态按命令持久化:用户折叠后刷新不重新展开。
+ // 惰性初始化读取持久化值(node.id 稳定,expandKey 不会在生命周期内变化),
+ // 避免 effect 内同步 setState。
const expandKey = `turnrewind.expanded.${node.id ?? parsed.planId ?? parsed.summary}`
- const [expanded, setExpanded] = useState(hasDiff)
- useEffect(() => {
+ const [expanded, setExpanded] = useState(() => {
try {
const stored = globalThis.localStorage.getItem(expandKey)
if (stored === '0' || stored === '1')
- setExpanded(stored === '1')
+ return stored === '1'
}
catch {}
- }, [expandKey])
+ return hasDiff
+ })
function toggleExpanded(): void {
setExpanded((v) => {
diff --git a/packages/dsh-tauri-turnrewind-ts/src/client/index.ts b/packages/dsh-tauri-turnrewind-ts/src/client/index.ts
index cdf3a68e..e3c49c72 100644
--- a/packages/dsh-tauri-turnrewind-ts/src/client/index.ts
+++ b/packages/dsh-tauri-turnrewind-ts/src/client/index.ts
@@ -10,7 +10,7 @@ import type { ClientContext } from 'dsh-tauri/client'
import type { LocaleKey } from './locales'
import { compat } from 'dsh-tauri/client'
import { setSubmitLine } from './components/command-view'
-import { TURNREWIND_HTTP_BASE, TURNREWIND_LOCALE_NS } from './constants'
+import { TURNREWIND_HTTP_BASE, TURNREWIND_LOCALE_NS, TURNREWIND_POLL_INTERVAL_MS, TURNREWIND_POLL_STOP_MS } from './constants'
import { LOCALES } from './locales'
import { registerCommandView } from './register/command-view'
import { disposeDialog, listNotices, showDialog } from './register/dialog'
@@ -130,8 +130,8 @@ export function apply(ctx: ClientContext): void {
return () => {}
const unsubscribe = sessions.list.subscribe(checkOnce)
// 页面加载时投影帧可能在订阅建立前到达;短暂轮询保证时序不会吞掉提示。
- const poll = setInterval(checkOnce, 2000)
- const stopPolling = setTimeout(clearInterval, 120000, poll)
+ const poll = setInterval(checkOnce, TURNREWIND_POLL_INTERVAL_MS)
+ const stopPolling = setTimeout(clearInterval, TURNREWIND_POLL_STOP_MS, poll)
return () => {
unsubscribe()
clearInterval(poll)
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 0c66b691..e3157037 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
@@ -24,6 +24,7 @@ import { Buffer } from 'node:buffer'
import { spawn } from 'node:child_process'
import { createHash, randomUUID } from 'node:crypto'
import {
+ chmodSync,
copyFileSync,
existsSync,
lstatSync,
@@ -501,7 +502,7 @@ async function ensureEmptyBlob(store: SnapshotStore): Promise<string> {
}
async function blobFor(store: SnapshotStore, commit: string, path: string): Promise<string> {
- if (!await commitEntry(store, commit, path))
+ if (!await commitEntryInfo(store, commit, path))
return ensureEmptyBlob(store)
return (await runGit(store.repoDir, store.workspaceDir, ['rev-parse', `${commit}:${path}`])).toString('utf8').trim()
}
@@ -541,46 +542,32 @@ export async function diffAgainstDisk(store: SnapshotStore, commit: string, path
return truncateDiff(output.toString('utf8'), maxLines)
}
-async function commitEntry(store: SnapshotStore, commit: string, path: string): Promise<boolean> {
- const output = await runGit(store.repoDir, store.workspaceDir, ['ls-tree', '-r', '--name-only', '-z', 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.
+ * 一次 `ls-tree -l` 读取条目的 mode 与 size:stateAt/restorePath/blobFor
+ * 共用,避免同一路径多次子进程调用。size 为 undefined 表示未知(submodule)。
*/
-async function commitEntrySize(store: SnapshotStore, commit: string, path: string): Promise<number | undefined> {
+interface CommitEntryInfo {
+ mode: string
+ size: number | undefined
+}
+
+async function commitEntryInfo(store: SnapshotStore, commit: string, path: string): Promise<CommitEntryInfo | undefined> {
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
+ const meta = line.slice(0, tab).split(' ')
+ const size = Number(meta.at(-1))
+ return {
+ mode: meta[0] ?? '100644',
+ size: Number.isFinite(size) && meta.at(-1) !== '-' ? size : undefined,
+ }
}
}
return undefined
}
-/**
- * Git mode of one committed path ('100644' regular, '100755' executable,
- * '120000' symlink, '160000' submodule), or undefined when absent.
- * P1-3: symlinks are identified here so stateAt/restore can refuse them
- * instead of silently writing the link target as file content.
- */
-async function commitEntryMode(store: SnapshotStore, commit: string, path: string): Promise<string | undefined> {
- const output = await runGit(store.repoDir, store.workspaceDir, ['ls-tree', '-r', '-z', commit, '--', path])
- for (const line of output.toString('utf8').split('\0')) {
- // mode SP type SP oid TAB path
- const tab = line.lastIndexOf('\t')
- if (tab !== -1 && line.slice(tab + 1) === path)
- return line.slice(0, tab).split(' ')[0]
- }
- return undefined
-}
-
async function commitBytes(store: SnapshotStore, commit: string, path: string): Promise<Buffer> {
const output = await runGit(store.repoDir, store.workspaceDir, ['show', `${commit}:${path}`], {}, MAX_FILE_BYTES + 1)
if (output.length > MAX_FILE_BYTES)
@@ -606,16 +593,17 @@ export async function stateAt(store: SnapshotStore, commit: string, path: string
// P1-3: a symlink entry ('120000') must not masquerade as a regular file —
// its blob is just the link target text. Report it as unsupported so the
// plan flags it and restore refuses, instead of writing wrong content.
- if ((await commitEntryMode(store, commit, path)) === GIT_SYMLINK_MODE)
- return { kind: 'unsupported', digest: null }
- if (!await commitEntry(store, commit, path))
+ const info = await commitEntryInfo(store, commit, path)
+ if (!info)
return { kind: 'absent', digest: null }
+ if (info.mode === GIT_SYMLINK_MODE)
+ return { kind: 'unsupported', 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) ?? 0) > MAX_FILE_BYTES)
+ if ((info.size ?? 0) > MAX_FILE_BYTES)
return { kind: 'tooLarge', digest: null }
const bytes = await commitBytes(store, commit, path)
- return { kind: 'file', digest: digest(bytes) }
+ return { kind: 'file', digest: digest(bytes), mode: info.mode }
}
export function currentState(workspaceDir: string, path: string): DiskState {
@@ -625,7 +613,12 @@ export function currentState(workspaceDir: string, path: string): DiskState {
const info = lstatSync(target)
if (!info.isFile() || info.size > MAX_FILE_BYTES)
return { kind: 'unsupported', digest: null }
- return { kind: 'file', digest: digest(readFileSync(target)) }
+ // Windows 无法可靠识别可执行位(git core.filemode=false),统一按 100644 报告;
+ // 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 }
}
/**
@@ -666,7 +659,8 @@ function rmSyncWithRetry(target: string, attempts: number = 5): void {
*/
export async function restorePath(store: SnapshotStore, commit: string, path: string): Promise<RestoreResult> {
const target = assertSafePath(store.workspaceDir, path)
- if (!await commitEntry(store, commit, path)) {
+ const entry = await commitEntryInfo(store, commit, path)
+ if (!entry) {
if (existsSync(target)) {
const info = lstatSync(target)
if (info.isSymbolicLink() || (!info.isFile() && !info.isDirectory()))
@@ -692,18 +686,21 @@ export async function restorePath(store: SnapshotStore, commit: string, path: st
// P1-3: a symlink entry must never be "restored" by writing the link target
// text as a regular file. Fail this one path with a stable code so the undo
// loop reports it as not restored instead of corrupting the workspace type.
- if ((await commitEntryMode(store, commit, path)) === GIT_SYMLINK_MODE)
+ if (entry.mode === GIT_SYMLINK_MODE)
throw new Error(`TURNREWIND_UNSUPPORTED_TARGET: ${path} is a symlink in the snapshot; undo cannot restore symlinks (recreate the link manually if intended)`)
// 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) ?? 0) > MAX_FILE_BYTES)
+ if ((entry.size ?? 0) > 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`
writeFileSync(temp, bytes, { flag: 'wx' })
+ // P1-4: restore the snapshot's git mode (executable bit). Windows chmod
+ // only toggles the read-only bit, so this is safe cross-platform.
+ chmodSync(temp, entry.mode === '100755' ? 0o755 : 0o644)
let bak: string | undefined
try {
if (existsSync(target)) {
@@ -804,13 +801,3 @@ export function restoreCrashedSwaps(workspaceDir: string): string[] {
visit(root)
return resurrected
}
-
-export function pathIsSafe(workspaceDir: string, path: string): boolean {
- try {
- assertSafePath(workspaceDir, path)
- return true
- }
- catch {
- return false
- }
-}
diff --git a/packages/dsh-tauri-turnrewind-ts/src/host/service/ledger.ts b/packages/dsh-tauri-turnrewind-ts/src/host/service/ledger.ts
index f8f416c5..3d4e35b3 100644
--- a/packages/dsh-tauri-turnrewind-ts/src/host/service/ledger.ts
+++ b/packages/dsh-tauri-turnrewind-ts/src/host/service/ledger.ts
@@ -446,13 +446,6 @@ export function failTurn(db: Ledger, turnId: string, error: unknown): void {
.run(new Date().toISOString(), String(error), turnId)
}
-export function abandonTurn(db: Ledger, turnId: string, reason: string): void {
- db.prepare(`
- UPDATE turns SET status = 'abandoned', settled_at = ?, reversible = 0, error = ?
- WHERE turn_id = ? AND status = 'active'
- `).run(new Date().toISOString(), reason, turnId)
-}
-
export function skipTurn(db: Ledger, turn: { turnId: string, sessionId: string, workspaceKey: string, startedAt: string }, reason: string): void {
db.prepare(`
INSERT INTO turns(turn_id, session_id, workspace_key, status, started_at, settled_at, reversible, error)
diff --git a/packages/dsh-tauri-turnrewind-ts/src/host/types/index.ts b/packages/dsh-tauri-turnrewind-ts/src/host/types/index.ts
index aaade57e..86acebcd 100644
--- a/packages/dsh-tauri-turnrewind-ts/src/host/types/index.ts
+++ b/packages/dsh-tauri-turnrewind-ts/src/host/types/index.ts
@@ -29,10 +29,10 @@ export interface Snapshot {
refName: string
}
-/** 文件在某个快照提交里的状态。 */
+/** 文件在某个快照提交里的状态。mode 为 git 条目 mode('100644'/'100755')。 */
export type PathState
= | { kind: 'absent', digest: null }
- | { kind: 'file', digest: string }
+ | { kind: 'file', digest: string, mode: string }
| { kind: 'tooLarge', digest: null }
| { kind: 'unsupported', digest: null }
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 05a1872c..8ea8c698 100644
--- a/packages/dsh-tauri-turnrewind-ts/test/git-snapshot.test.js
+++ b/packages/dsh-tauri-turnrewind-ts/test/git-snapshot.test.js
@@ -1,5 +1,5 @@
import assert from 'node:assert/strict'
-import { mkdir, mkdtemp, readFile, rm, stat, symlink, writeFile } from 'node:fs/promises'
+import { chmod, mkdir, mkdtemp, readFile, rm, stat, symlink, writeFile } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join } from 'pathe'
import { it } from 'vitest'
@@ -7,6 +7,41 @@ import { captureSnapshot, classifyPathChange, createSnapshotStore, currentState,
import { completeUndoTransaction, createOperation, getLatestTurn, insertTurn, openLedger, settleInterruptedTurn, settleTurn } from '../src/host/service/ledger'
import { initGitWorkspace } from './git-test-utils.js'
+it('persists entry mode in snapshots and restores the executable bit', async () => {
+ const root = await mkdtemp(join(tmpdir(), 'turnrewind-mode-test-'))
+ const workspace = join(root, 'workspace')
+ try {
+ await initGitWorkspace(workspace)
+ await writeFile(join(workspace, 'run.sh'), '#!/bin/sh\necho hi\n')
+ const store = createSnapshotStore(join(root, 'data'), workspace)
+ const before = await captureSnapshot(store, 'refs/turnrewind/mode-before', 'before')
+ // Windows git (core.filemode=false) always records 100644; POSIX records
+ // the real mode. Both platforms must surface the mode on the state.
+ assert.equal((await stateAt(store, before.commit, 'run.sh')).mode, '100644')
+
+ if (process.platform === 'win32')
+ return
+
+ // POSIX round trip: the turn flips the exec bit — a mode-only change that
+ // must appear in the diff and be restorable with the bit intact.
+ await chmod(join(workspace, 'run.sh'), 0o755)
+ const after = await captureSnapshot(store, 'refs/turnrewind/mode-after', 'after', before.commit)
+ assert.equal((await stateAt(store, after.commit, 'run.sh')).mode, '100755')
+ assert.deepEqual(await snapshotDiff(store, before.commit, after.commit), ['run.sh'])
+
+ // Clear the bit on disk, then restore from the exec snapshot: the mode
+ // comes back with the content.
+ await chmod(join(workspace, 'run.sh'), 0o644)
+ 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')
+ }
+ finally {
+ await rm(root, { recursive: true, force: true })
+ }
+})
+
it('reports snapshot symlinks as unsupported and refuses to restore them', async () => {
const root = await mkdtemp(join(tmpdir(), 'turnrewind-symlink-snap-'))
const workspace = join(root, 'workspace')