Skip to content

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

fix(turnrewind): preserve interrupted turns and queued notices

yingtianlan61e5c401d0f1
diff --git a/docs/TURN_REWIND.md b/docs/TURN_REWIND.md
index fee4c261..068a2b25 100644
--- a/docs/TURN_REWIND.md
+++ b/docs/TURN_REWIND.md
@@ -783,7 +783,7 @@ changes still exist; re-read the files before making further edits.
当前 DSH 的 agent loop 会把 `agent/pre-step` 接受后的 messages 作为 `user/message` 追加到 append-only session log。因此本插件的第一版采用**插件来源的用户角色 notice**:它不伪装为人类输入,带 `source.kind: 'plugin'`、插件名和 `form: 'rewind-notice'`,但会在下一次 step 的历史中留下一个可审计的显式记录。这样模型能收到它,用户也能看见发生了什么,而原有用户消息和 LLM 回复不会被删除或重写。
-notice 只在下一次成功进入的 step 消费一次;如果该 step 被拒绝或取消,notice 保持 pending。连续 Undo 会将同一 session/workspace 旧的 pending notice 标记为 `superseded`,只让模型看到最新回退状态。
+notice 只在下一次成功进入的 step 消费一次;如果该 step 被拒绝或取消,全部 notice 保持 pending。连续 Undo 为每次操作保留独立 notice;下一次 step 会按 Undo 顺序把所有 pending notice 一次性注入,形成一批连续的回退说明,不覆盖也不合并单次 Undo 的记录。
**主要风险:**原会话历史仍然包含“修改已经存在”的旧 LLM 回复,所以 notice 必须明确要求“以当前磁盘文件为准并重新读取”。
diff --git a/plugins/dsh-tauri-turnrewind/README.md b/plugins/dsh-tauri-turnrewind/README.md
index 2fdbde90..12054096 100644
--- a/plugins/dsh-tauri-turnrewind/README.md
+++ b/plugins/dsh-tauri-turnrewind/README.md
@@ -16,16 +16,262 @@
- 恢复前比较当前文件与 turn 完成时的快照,发现变化则拒绝覆盖;
- 同一 workspace 的活动 turn 或 undo 操作互斥;
- 插件重启时将未完成 turn 标记为 abandoned;
+- 每次 Undo 的回退提示独立持久化;下一次模型 step 一次性注入全部 pending notice;
- 不修改用户项目的 HEAD、分支、index、stash 或提交历史。
-当前尚未启用:
+## 使用方法
-- 父对话递归 undo;
-- 消息旁的 Client Undo 按钮;
-- redo;
-- 大型仓库增量扫描和完整的特殊文件支持。
+在已加载本插件的 DSH 会话中:
-## 本地安装到 debug profile
+```text
+/undo --dry-run
+```
+
+先查看撤销预检。它只检查,不修改文件。
+
+确认预检结果中的文件和冲突数量正确后,再执行:
+
+```text
+/undo
+```
+
+也可以指定完整 turn ID:
+
+```text
+/undo <session-id>:<turn-number>
+```
+
+当前支持的命令:
+
+```text
+/undo
+/undo --dry-run
+/undo <turn-id>
+```
+
+当前不支持:
+
+```text
+/undo --subtree
+```
+
+父对话递归撤销、redo、消息旁 Undo 按钮和设置页模式切换尚未实现。
+
+## Undo 的工作区范围
+
+Undo 的范围是:
+
+```text
+当前 session 绑定的 workspace(session header 的 cwd)
+```
+
+例如当前 session 的工作区是:
+
+```text
+C:\Users\YT16228\Desktop\test
+```
+
+插件只会比较和恢复该目录以内、且被快照规则允许的文件。它不是“恢复整台电脑”,也不是“恢复所有 Agent 访问过的路径”。
+
+一次 turn 的文件范围是:
+
+```text
+turn 开始时的 workspace 快照
+ ↓
+Agent 执行
+ ↓
+turn 结束时的 workspace 快照
+ ↓
+两次快照之间发生变化的文件
+```
+
+Undo 只恢复两次快照之间发生变化的文件:
+
+- Agent 修改的文件:恢复到 turn 开始前;
+- Agent 新建的文件:Undo 时删除;
+- Agent 删除的文件:Undo 时恢复;
+- 未发生变化的文件:不处理。
+
+## Workspace 外的文件
+
+如果 Agent 访问或修改了 workspace 外的文件,当前版本**不会捕获,也不会 Undo**。
+
+例如当前 workspace 是:
+
+```text
+C:\Users\YT16228\Desktop\test
+```
+
+Agent 修改了:
+
+```text
+C:\Users\YT16228\Desktop\test\a.txt
+C:\Users\YT16228\Desktop\other\b.txt
+```
+
+执行 `/undo` 时:
+
+```text
+test\a.txt → 可能被恢复
+test 之外的 b.txt → 不会被处理
+```
+
+workspace 外的修改不会:
+
+- 写入 turn 的 before/after snapshot;
+- 出现在 `/undo --dry-run` 文件列表;
+- 被 `/undo` 恢复;
+- 出现在 rewind notice 的文件列表中。
+
+在 `workspace-write` 权限模式下,宿主 sandbox 通常会阻止 Agent 写出 workspace;但如果使用 `danger-full-access` 或其他方式允许外部写入,**Agent 能写成功不代表 turnrewind 能回退这些文件**。
+
+插件自己的恢复操作会拒绝以下路径:
+
+```text
+../outside.txt
+C:\OtherProject\file.txt
+workspace 内指向外部的符号链接路径
+```
+
+如果确实需要管理多个项目,应将它们作为独立 workspace 分别运行,不要把多个项目目录混成一个恢复域。
+
+## 不同修改方式的捕获规则
+
+当前插件按 workspace 在 turn 前后的实际差异捕获,不按工具名称判断来源。因此以下 Agent 修改方式通常都会被纳入当前 turn:
+
+- Agent `write`;
+- Agent `edit`;
+- Agent 使用 Git Bash/bash;
+- Agent 使用 PowerShell/pwsh;
+- Agent 运行格式化工具;
+- Agent 运行生成脚本;
+- Agent 通过 Git 命令间接修改文件;
+- Agent 执行其他会改写 workspace 文件的程序。
+
+准确语义是:
+
+```text
+该 workspace 在本 turn 期间发生的允许范围内变化
+```
+
+不是:
+
+```text
+百分之百证明该变化由 AI 直接写入
+```
+
+如果用户或其他程序在 Agent turn 执行期间同时修改同一个 workspace,当前 MVP 可能无法区分来源,也可能把这些变化一起记录到该 turn。建议等待 Agent 完成或打断后,再手动编辑同一 workspace。
+
+如果用户是在 turn 完成后修改文件,Undo 预检会将当前内容与 Agent turn 完成时的快照进行比较。内容不一致时会显示冲突,并默认拒绝覆盖。
+
+## 冲突是什么意思
+
+Undo 不是无条件覆盖。它会检查:
+
+```text
+当前文件状态 == Agent turn 完成时的文件状态?
+```
+
+如果相等,文件可以安全恢复到 turn 开始前。
+
+如果不相等,就会显示类似:
+
+```text
+Undo preflight: turn <turn-id>; 5 file(s); 5 conflict(s): 4.txt, 5.txt, 6.txt, 7.json, 8.md.
+```
+
+含义是:
+
+- 目标 turn 涉及 5 个文件;
+- 当前文件与该 turn 完成时的快照不一致;
+- 插件无法确认这些变化是否来自用户、其他 turn 或外部程序;
+- 默认不会覆盖,文件保持当前状态。
+
+Windows 的 `CRLF` 与 Unix 的 `LF` 换行差异会被文本状态比较规范化,不应单独造成冲突。二进制文件仍按原始字节比较。
+
+当前没有“跳过冲突文件”和“强制覆盖冲突文件”的用户命令;遇到冲突应先检查文件,再决定是否手动处理。
+
+## 多次 Undo 与模型提示
+
+每次 Undo 都会产生一条独立的 pending rewind notice:
+
+```text
+Undo C → notice C
+Undo B → notice B
+Undo A → notice A
+```
+
+如果在发送下一条普通消息之前连续执行多次 Undo,下一次模型 step 会一次性收到全部 notice,顺序为:
+
+```text
+C、B、A
+```
+
+每条 notice 会列出:
+
+- 被撤销的 turn;
+- 该次 Undo 涉及的文件;
+- “当前磁盘文件是权威状态”;
+- “不要假设旧修改仍存在,请重新读取文件”。
+
+notice 只消费一次。下一次模型 step 后不会重复注入。
+
+## Git 与快照存储
+
+快照存放在插件私有目录:
+
+```text
+$DSH_HOME/turnrewind/snapshots/<workspace-hash>.git
+```
+
+账本存放在:
+
+```text
+$DSH_HOME/turnrewind/ledger.sqlite
+```
+
+插件不会调用用户项目的:
+
+```bash
+git reset --hard
+git checkout .
+git clean -fd
+```
+
+也不会修改用户项目的:
+
+```text
+HEAD
+当前分支
+index
+stash
+commit history
+```
+
+## 默认排除项
+
+为降低敏感信息和无关产物进入私有 snapshot 的风险,默认排除:
+
+```text
+.git/
+node_modules/
+dist/
+build/
+coverage/
+.turnrewind/
+.env
+.env.*
+*.pem
+*.key
+id_rsa*
+credentials*
+*secret*
+*token*
+```
+
+这些规则意味着:被排除文件的变化不会进入本 turn 的 Undo 范围。插件仍是实验原型,不应把它当作秘密信息保护工具。
+
+## Debug 安装
在当前 checkout 中执行:
@@ -35,10 +281,28 @@ $env:DSH_HOME = "$env:USERPROFILE\.dsh.dev"
node "$env:APPDATA\io.github.hairyf.deepseek-harness-desktop\dependencies\dsh\node_modules\@deepseek-ai\dsh\lib\bin.js" plugin --profile web add "$(Resolve-Path plugins/dsh-tauri-turnrewind)"
```
-或者把 `cordis.patch.yml` 的 `turnrewind` row 合并到 profile 的 `cordis.patch.yml`。插件包必须先通过 `pnpm add` / `dsh plugin add` 安装,不能仅把源码目录放在项目里就期待 DSH 加载。
+插件包必须先通过 `pnpm add` / `dsh plugin add` 安装,不能仅把源码目录放在项目里就期待 DSH 加载。修改 Host 代码后需要重启对应的 DSH debug Host 进程。
+
+## 测试
+
+运行插件测试:
+
+```powershell
+pnpm exec eslint plugins/dsh-tauri-turnrewind
+pnpm exec vitest run plugins/dsh-tauri-turnrewind/test --testTimeout=30000
+```
+
+当前测试覆盖 Git 快照、增删改恢复、中文路径、CRLF、路径逃逸、符号链接、敏感文件排除、账本生命周期、interrupted turn 和多次 notice。
-## 安全边界
+## 当前限制
-快照存放在 `$DSH_HOME/turnrewind/snapshots/<workspace-hash>.git`。插件不会调用用户项目的 `git reset --hard`、`git checkout .` 或 `git clean -fd`。
+这是实验版本,正式启用前仍需要:
-这是实验版本,正式启用前还需要通过真实 DSH 页面验证 turn 生命周期、文件扫描边界和 profile 重启恢复。
+- 接入受控的宿主 sandbox/Tauri bridge;
+- 完成真实 DSH lifecycle integration tests;
+- 完善多 workspace 并发锁;
+- 实现父对话递归 undo;
+- 实现 redo 和冲突处理 UI;
+- 实现消息旁 Undo 按钮;
+- 增加 snapshot 数量/容量清理;
+- 明确二进制、重命名、权限位和特殊文件策略。
diff --git a/plugins/dsh-tauri-turnrewind/lib/core/git-snapshot.js b/plugins/dsh-tauri-turnrewind/lib/core/git-snapshot.js
index dd44aeca..6bbd2178 100644
--- a/plugins/dsh-tauri-turnrewind/lib/core/git-snapshot.js
+++ b/plugins/dsh-tauri-turnrewind/lib/core/git-snapshot.js
@@ -3,6 +3,7 @@ import { createHash, randomUUID } from 'node:crypto'
import { existsSync, lstatSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs'
import { dirname, join, relative, resolve, sep } from 'node:path'
import process from 'node:process'
+import { TextDecoder, TextEncoder } from 'node:util'
const MAX_FILE_BYTES = 64 * 1024 * 1024
const EXCLUDE_PATHS = [
@@ -159,7 +160,15 @@ function commitBytes(store, commit, path) {
}
function digest(bytes) {
- return createHash('sha256').update(bytes).digest('hex')
+ let comparable = bytes
+ try {
+ const text = new TextDecoder('utf-8', { fatal: true }).decode(bytes)
+ comparable = new TextEncoder().encode(text.replaceAll('\r\n', '\n'))
+ }
+ catch {
+ // Binary data has no newline normalization; compare its exact bytes.
+ }
+ return createHash('sha256').update(comparable).digest('hex')
}
export function stateAt(store, commit, path) {
diff --git a/plugins/dsh-tauri-turnrewind/lib/core/ledger.js b/plugins/dsh-tauri-turnrewind/lib/core/ledger.js
index 912d0640..843be977 100644
--- a/plugins/dsh-tauri-turnrewind/lib/core/ledger.js
+++ b/plugins/dsh-tauri-turnrewind/lib/core/ledger.js
@@ -41,6 +41,7 @@ const SCHEMA = `
session_id TEXT NOT NULL,
workspace_key TEXT NOT NULL,
target_turn_id TEXT NOT NULL,
+ turns_json TEXT NOT NULL DEFAULT '[]',
paths_json TEXT NOT NULL,
status TEXT NOT NULL,
created_at TEXT NOT NULL,
@@ -61,6 +62,12 @@ export function openLedger(rootDir) {
catch {
// Column already exists.
}
+ try {
+ db.exec('ALTER TABLE rewind_notices ADD COLUMN turns_json TEXT NOT NULL DEFAULT \'[]\'')
+ }
+ catch {
+ // Column already exists.
+ }
db.exec(`UPDATE turns SET status = 'abandoned', reversible = 0, error = 'plugin restarted during active turn' WHERE status = 'active'`)
return db
}
@@ -85,6 +92,11 @@ export function settleTurn(db, turnId, afterRef) {
.run(new Date().toISOString(), afterRef, turnId)
}
+export function settleInterruptedTurn(db, turnId, afterRef, reason) {
+ db.prepare(`UPDATE turns SET status = 'interrupted', settled_at = ?, after_ref = ?, reversible = 1, error = ? WHERE turn_id = ?`)
+ .run(new Date().toISOString(), afterRef, reason, turnId)
+}
+
export function settleNoopTurn(db, turnId, afterRef) {
db.prepare(`UPDATE turns SET status = 'settled', settled_at = ?, after_ref = ?, reversible = 0, error = ? WHERE turn_id = ?`)
.run(new Date().toISOString(), afterRef, 'no file changes', turnId)
@@ -95,6 +107,13 @@ export function failTurn(db, turnId, error) {
.run(new Date().toISOString(), String(error), turnId)
}
+export function abandonTurn(db, turnId, reason) {
+ 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 getTurn(db, turnId) {
return db.prepare('SELECT * FROM turns WHERE turn_id = ?').get(turnId)
}
@@ -102,11 +121,20 @@ export function getTurn(db, turnId) {
export function getLatestTurn(db, sessionId, workspaceKey) {
return db.prepare(`
SELECT * FROM turns
- WHERE session_id = ? AND workspace_key = ? AND status = 'settled' AND reversible = 1
+ WHERE session_id = ? AND workspace_key = ?
+ AND reversible = 1
+ AND status IN ('settled', 'interrupted')
ORDER BY started_at DESC LIMIT 1
`).get(sessionId, workspaceKey)
}
+export function getLatestTurnSummary(db, sessionId) {
+ return db.prepare(`
+ SELECT turn_id, workspace_key, status, reversible, settled_at
+ FROM turns WHERE session_id = ? ORDER BY started_at DESC LIMIT 1
+ `).get(sessionId)
+}
+
export function getLatestSnapshotRef(db, workspaceKey) {
return db.prepare(`
SELECT after_ref FROM turns
@@ -133,40 +161,46 @@ export function settleOperation(db, operationId, outcome, error) {
export function queueRewindNotice(db, notice) {
db.prepare(`
- UPDATE rewind_notices SET status = 'superseded'
- WHERE session_id = ? AND workspace_key = ? AND status = 'pending'
- `).run(notice.sessionId, notice.workspaceKey)
- db.prepare(`
- INSERT INTO rewind_notices(notice_id, session_id, workspace_key, target_turn_id, paths_json, status, created_at)
- VALUES (?, ?, ?, ?, ?, 'pending', ?)
+ INSERT INTO rewind_notices(notice_id, session_id, workspace_key, target_turn_id, turns_json, paths_json, status, created_at)
+ VALUES (?, ?, ?, ?, ?, ?, 'pending', ?)
`).run(
notice.noticeId,
notice.sessionId,
notice.workspaceKey,
notice.targetTurnId,
+ JSON.stringify([notice.targetTurnId]),
JSON.stringify(notice.paths),
notice.createdAt,
)
}
-export function claimRewindNotice(db, sessionId, workspaceKey) {
- const notice = db.prepare(`
+export function claimRewindNotices(db, sessionId, workspaceKey) {
+ const notices = db.prepare(`
SELECT * FROM rewind_notices
WHERE session_id = ? AND workspace_key = ? AND status = 'pending'
- ORDER BY created_at DESC LIMIT 1
- `).get(sessionId, workspaceKey)
- if (!notice)
- return undefined
- const result = db.prepare(`
+ ORDER BY created_at ASC
+ `).all(sessionId, workspaceKey)
+ if (notices.length === 0)
+ return []
+ const claimedAt = new Date().toISOString()
+ const statement = db.prepare(`
UPDATE rewind_notices SET status = 'consumed', claimed_at = ?
WHERE notice_id = ? AND status = 'pending'
- `).run(new Date().toISOString(), notice.notice_id)
- if (result.changes !== 1)
- return undefined
- return {
+ `)
+ db.exec('BEGIN')
+ try {
+ for (const notice of notices) statement.run(claimedAt, notice.notice_id)
+ db.exec('COMMIT')
+ }
+ catch (error) {
+ db.exec('ROLLBACK')
+ throw error
+ }
+ return notices.map(notice => ({
...notice,
+ turns: JSON.parse(notice.turns_json || '[]'),
paths: JSON.parse(notice.paths_json),
- }
+ }))
}
export function completeUndoWithNotice(db, turnId, notice) {
@@ -174,17 +208,14 @@ export function completeUndoWithNotice(db, turnId, notice) {
try {
db.prepare(`UPDATE turns SET status = 'undone' WHERE turn_id = ?`).run(turnId)
db.prepare(`
- UPDATE rewind_notices SET status = 'superseded'
- WHERE session_id = ? AND workspace_key = ? AND status = 'pending'
- `).run(notice.sessionId, notice.workspaceKey)
- db.prepare(`
- INSERT INTO rewind_notices(notice_id, session_id, workspace_key, target_turn_id, paths_json, status, created_at)
- VALUES (?, ?, ?, ?, ?, 'pending', ?)
+ INSERT INTO rewind_notices(notice_id, session_id, workspace_key, target_turn_id, turns_json, paths_json, status, created_at)
+ VALUES (?, ?, ?, ?, ?, ?, 'pending', ?)
`).run(
notice.noticeId,
notice.sessionId,
notice.workspaceKey,
notice.targetTurnId,
+ JSON.stringify([notice.targetTurnId]),
JSON.stringify(notice.paths),
notice.createdAt,
)
diff --git a/plugins/dsh-tauri-turnrewind/lib/index.js b/plugins/dsh-tauri-turnrewind/lib/index.js
index 86ba4c0e..d34fbaa4 100644
--- a/plugins/dsh-tauri-turnrewind/lib/index.js
+++ b/plugins/dsh-tauri-turnrewind/lib/index.js
@@ -3,7 +3,7 @@ import { homedir } from 'node:os'
import { join, resolve } from 'node:path'
import process from 'node:process'
import { captureSnapshot, createSnapshotStore, currentState, restorePath, snapshotDiff, stateAt } from './core/git-snapshot.js'
-import { claimRewindNotice, completeUndoWithNotice, createOperation, failTurn, getLatestSnapshotRef, getLatestTurn, getTurn, insertTurn, openLedger, registerWorkspace, settleNoopTurn, settleOperation, settleTurn } from './core/ledger.js'
+import { claimRewindNotices, completeUndoWithNotice, createOperation, failTurn, getLatestSnapshotRef, getLatestTurn, getLatestTurnSummary, getTurn, insertTurn, openLedger, registerWorkspace, settleInterruptedTurn, settleNoopTurn, settleOperation, settleTurn } from './core/ledger.js'
import { classifyUndo } from './core/planner.js'
const name = 'dsh-tauri-turnrewind'
@@ -16,7 +16,11 @@ function refSuffix(turnId, phase) {
}
function workspaceForAgent(agent) {
- const cwd = agent?.session?.header?.cwd
+ return workspaceForSession(agent?.session)
+}
+
+function workspaceForSession(session) {
+ const cwd = session?.header?.cwd
return typeof cwd === 'string' && cwd.length > 0 ? resolve(cwd) : undefined
}
@@ -64,7 +68,8 @@ function formatPlan(target, paths, conflicts, dryRun) {
function createRewindNoticeMessage(notice) {
const paths = notice.paths.map(path => `- ${path}`).join('\n')
- const text = `[Turn rewind notice]\nThe workspace was reverted to the state before turn ${notice.target_turn_id}.\n\nReverted files:\n${paths}\n\nTreat the current files on disk as authoritative. Do not assume the reverted changes still exist; re-read the listed files before making further edits.`
+ const turns = notice.turns.length > 0 ? notice.turns.join(', ') : notice.target_turn_id
+ const text = `[Turn rewind notice]\nThe workspace was reverted by these undo operations: ${turns}.\n\nReverted files in this operation:\n${paths}\n\nTreat the current files on disk as authoritative. Do not assume any reverted changes still exist; re-read the listed files before making further edits.`
return {
id: `turnrewind-notice-${notice.notice_id}`,
role: 'user',
@@ -86,6 +91,40 @@ function workspaceHasActiveTurn(active, workspaceKey) {
return false
}
+function settleActiveTurn(ledger, active, key, reason) {
+ const current = active.get(key)
+ if (!current)
+ return
+ try {
+ const afterRef = refSuffix(current.turnId, 'after')
+ captureSnapshot(current.runtime.store, afterRef, `turnrewind after ${current.turnId}`, current.beforeRef)
+ const changed = snapshotDiff(current.runtime.store, current.beforeRef, afterRef)
+ if (changed.length === 0) {
+ settleNoopTurn(ledger, current.turnId, afterRef)
+ }
+ else if (reason) {
+ settleInterruptedTurn(ledger, current.turnId, afterRef, reason)
+ }
+ else {
+ settleTurn(ledger, current.turnId, afterRef)
+ }
+ current.runtime.parentRef = afterRef
+ }
+ catch (error) {
+ failTurn(ledger, current.turnId, error)
+ }
+ finally {
+ active.delete(key)
+ }
+}
+
+function settleSessionTurns(ledger, active, sessionId, reason) {
+ for (const [key] of active) {
+ if (key.startsWith(`${sessionId}:`))
+ settleActiveTurn(ledger, active, key, reason)
+ }
+}
+
async function applyUndo(runtime, active, invocation) {
const parsed = parseUndoInput(invocation.rawInput)
if (parsed.error)
@@ -104,14 +143,19 @@ async function applyUndo(runtime, active, invocation) {
const target = parsed.turnId
? getTurn(runtime.db, parsed.turnId)
: getLatestTurn(runtime.db, invocation.agent.session.id, workspaceKey)
- if (!target)
- return { kind: 'error', text: 'No reversible turn was found for this session.' }
+ if (!target) {
+ const latest = getLatestTurnSummary(runtime.db, invocation.agent.session.id)
+ const detail = latest
+ ? ` Latest turn ${latest.turn_id} is ${latest.status} (reversible=${latest.reversible}) in workspace ${latest.workspace_key}.`
+ : ''
+ return { kind: 'error', text: `No reversible turn was found for this session.${detail}` }
+ }
const ownershipError = assertSessionOwner(target, invocation.agent)
if (ownershipError)
return ownershipError
if (target.workspace_key !== workspaceKey)
return { kind: 'error', text: 'The selected turn belongs to another workspace.' }
- if (target.status !== 'settled' || target.reversible !== 1 || !target.before_ref || !target.after_ref) {
+ if (!['settled', 'interrupted'].includes(target.status) || target.reversible !== 1 || !target.before_ref || !target.after_ref) {
return { kind: 'error', text: 'The selected turn does not have a complete reversible snapshot.' }
}
@@ -214,12 +258,12 @@ function apply(ctx) {
const workspaceDir = workspaceForAgent(agent)
if (!workspaceDir)
return decision
- const notice = claimRewindNotice(ledger, agent.session.id, workspaceKeyFor(workspaceDir))
- if (!notice)
+ const notices = claimRewindNotices(ledger, agent.session.id, workspaceKeyFor(workspaceDir))
+ if (notices.length === 0)
return decision
return {
...decision,
- messages: [...decision.messages, createRewindNoticeMessage(notice)],
+ messages: [...decision.messages, ...notices.map(createRewindNoticeMessage)],
}
})
@@ -229,10 +273,17 @@ function apply(ctx) {
return
const sessionId = payload.agent.session.id
const key = activeKey(sessionId, payload.turn)
- if (active.has(key) || runtime.undoing || workspaceHasActiveTurn(active, runtime.workspaceKey)) {
- console.error(`turnrewind: skipped duplicate or locked turn ${key}`)
+ if (runtime.undoing) {
+ console.error(`turnrewind: skipped turn ${key} while an undo is running`)
+ return
+ }
+ if (active.has(key)) {
+ console.error(`turnrewind: skipped duplicate claim for turn ${key}`)
return
}
+ // A model switch can open B immediately after A is interrupted. Finalize A
+ // before capturing B's baseline so B does not absorb A's partial files.
+ settleSessionTurns(ledger, active, sessionId, 'interrupted by a newer turn in the same session')
try {
const turnId = key
const beforeRef = refSuffix(turnId, 'before')
@@ -245,49 +296,35 @@ function apply(ctx) {
startedAt: new Date().toISOString(),
beforeRef,
})
- active.set(key, { runtime, workspaceKey: runtime.workspaceKey, turnId, beforeRef, turn: payload.turn })
+ active.set(key, { runtime, sessionId, workspaceKey: runtime.workspaceKey, turnId, beforeRef, turn: payload.turn })
}
catch (error) {
console.error(`turnrewind: failed to start turn ${key}: ${String(error)}`)
}
})
- function settle(payload, error) {
- const sessionId = payload.agent.session.id
- const key = activeKey(sessionId, payload.turn)
- const current = active.get(key)
- if (!current)
+ ctx.on('session/event', (session, event) => {
+ if (event.type !== 'turn/end' || typeof event.data?.turn !== 'number')
return
- try {
- const afterRef = refSuffix(current.turnId, 'after')
- captureSnapshot(current.runtime.store, afterRef, `turnrewind after ${current.turnId}`, current.beforeRef)
- const changed = snapshotDiff(current.runtime.store, current.beforeRef, afterRef)
- if (changed.length === 0) {
- settleNoopTurn(ledger, current.turnId, afterRef)
- }
- else if (error) {
- failTurn(ledger, current.turnId, error)
- }
- else {
- settleTurn(ledger, current.turnId, afterRef)
- }
- current.runtime.parentRef = afterRef
- }
- catch (captureError) {
- try {
- failTurn(ledger, current.turnId, captureError)
- }
- catch (ledgerError) {
- console.error(`turnrewind: failed to record capture error: ${String(ledgerError)}`)
- }
- }
- finally {
- active.delete(key)
- }
- }
-
- ctx.on('agent/turn-stopping', payload => settle(payload))
- ctx.on('agent/error', payload => settle(payload, payload.error))
+ const key = activeKey(session.id, event.data.turn)
+ const reason = event.data.reason?.kind
+ const interrupted = reason === 'aborted' || reason === 'error' || reason === 'cancelled'
+ settleActiveTurn(ledger, active, key, interrupted ? `turn ended with ${reason}` : undefined)
+ })
+ ctx.on('agent/turn-stopping', () => {
+ // A normal turn reaches the durable turn/end event immediately after this
+ // listener. Wait for that authoritative boundary so interrupted writes are
+ // included in the after snapshot.
+ })
+ ctx.on('agent/error', (payload) => {
+ // Keep the active record until turn/end or the idle fallback. In particular,
+ // model switching can emit an error before the final partial writes finish.
+ console.error(`turnrewind: observed agent error for ${activeKey(payload.agent.session.id, payload.turn)}: ${String(payload.error)}`)
+ })
+ ctx.on('agent/status', ({ agent, status }) => {
+ if (status === 'idle')
+ settleSessionTurns(ledger, active, agent.session.id, 'agent became idle after interruption')
+ })
ctx.effect(() => () => ledger.close(), 'turnrewind ledger')
ctx.effect(() => () => {
active.clear()
diff --git a/plugins/dsh-tauri-turnrewind/test/git-snapshot.test.js b/plugins/dsh-tauri-turnrewind/test/git-snapshot.test.js
index 41201691..d81f225c 100644
--- a/plugins/dsh-tauri-turnrewind/test/git-snapshot.test.js
+++ b/plugins/dsh-tauri-turnrewind/test/git-snapshot.test.js
@@ -4,6 +4,7 @@ import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { it } from 'vitest'
import { captureSnapshot, createSnapshotStore, currentState, restorePath, snapshotDiff, stateAt } from '../lib/core/git-snapshot.js'
+import { completeUndoWithNotice, getLatestTurn, insertTurn, openLedger, settleInterruptedTurn, settleTurn } from '../lib/core/ledger.js'
it('captures and restores modified, added, and deleted files', async () => {
const root = await mkdtemp(join(tmpdir(), 'turnrewind-test-'))
@@ -37,6 +38,59 @@ it('captures and restores modified, added, and deleted files', async () => {
}
})
+it('allows sequential undo of an interrupted turn after a later turn', async () => {
+ const root = await mkdtemp(join(tmpdir(), 'turnrewind-sequence-test-'))
+ const workspace = join(root, 'workspace')
+ const filesA = ['a-1.txt', 'a-2.txt']
+ const filesB = ['b-1.txt', 'b-2.txt']
+ const db = openLedger(join(root, 'ledger'))
+ try {
+ await mkdir(workspace, { recursive: true })
+ const store = createSnapshotStore(join(root, 'data'), workspace)
+ const beforeA = captureSnapshot(store, 'refs/turnrewind/a-before', 'A before')
+ for (const file of filesA) await writeFile(join(workspace, file), 'A')
+ const afterA = captureSnapshot(store, 'refs/turnrewind/a-after', 'A after', beforeA.commit)
+ insertTurn(db, {
+ turnId: 'session:A',
+ sessionId: 'session',
+ workspaceKey: workspace.toLowerCase(),
+ startedAt: '2026-01-01T00:00:00.000Z',
+ beforeRef: 'refs/turnrewind/a-before',
+ })
+ settleInterruptedTurn(db, 'session:A', 'refs/turnrewind/a-after', 'interrupted')
+
+ const beforeB = captureSnapshot(store, 'refs/turnrewind/b-before', 'B before', afterA.commit)
+ for (const file of filesB) await writeFile(join(workspace, file), 'B')
+ const afterB = captureSnapshot(store, 'refs/turnrewind/b-after', 'B after', beforeB.commit)
+ insertTurn(db, {
+ turnId: 'session:B',
+ sessionId: 'session',
+ workspaceKey: workspace.toLowerCase(),
+ startedAt: '2026-01-01T00:01:00.000Z',
+ beforeRef: 'refs/turnrewind/b-before',
+ })
+ settleTurn(db, 'session:B', 'refs/turnrewind/b-after')
+
+ for (const file of snapshotDiff(store, beforeB.commit, afterB.commit)) restorePath(store, beforeB.commit, file)
+ completeUndoWithNotice(db, 'session:B', {
+ noticeId: 'notice-b',
+ sessionId: 'session',
+ workspaceKey: workspace.toLowerCase(),
+ targetTurnId: 'session:B',
+ paths: filesB,
+ createdAt: '2026-01-01T00:02:00.000Z',
+ })
+ assert.equal(getLatestTurn(db, 'session', workspace.toLowerCase()).turn_id, 'session:A')
+
+ for (const file of snapshotDiff(store, beforeA.commit, afterA.commit)) restorePath(store, beforeA.commit, file)
+ for (const file of [...filesA, ...filesB]) await assert.rejects(stat(join(workspace, file)))
+ }
+ finally {
+ db.close()
+ await rm(root, { recursive: true, force: true })
+ }
+})
+
it('handles non-ASCII paths without reporting a false restore', async () => {
const root = await mkdtemp(join(tmpdir(), 'turnrewind-unicode-test-'))
const workspace = join(root, 'workspace')
@@ -57,6 +111,24 @@ it('handles non-ASCII paths without reporting a false restore', async () => {
}
})
+it('does not treat CRLF conversion as a file conflict', async () => {
+ const root = await mkdtemp(join(tmpdir(), 'turnrewind-crlf-test-'))
+ const workspace = join(root, 'workspace')
+ try {
+ await mkdir(workspace, { recursive: true })
+ await writeFile(join(workspace, 'line-endings.txt'), 'before\nline\n')
+ const store = createSnapshotStore(join(root, 'data'), workspace)
+ const before = captureSnapshot(store, 'refs/turnrewind/crlf-before', 'before')
+ await writeFile(join(workspace, 'line-endings.txt'), 'after\nline\n')
+ const after = 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, stateAt(store, after.commit, 'line-endings.txt').digest)
+ }
+ finally {
+ await rm(root, { recursive: true, force: true })
+ }
+})
+
it('rejects paths outside the workspace', async () => {
const root = await mkdtemp(join(tmpdir(), 'turnrewind-path-test-'))
const workspace = join(root, 'workspace')
diff --git a/plugins/dsh-tauri-turnrewind/test/ledger.test.js b/plugins/dsh-tauri-turnrewind/test/ledger.test.js
index 37d778d1..8eda46ce 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 { claimRewindNotice, completeUndoWithNotice, getLatestSnapshotRef, getLatestTurn, getTurn, insertTurn, openLedger, queueRewindNotice, settleNoopTurn, settleTurn } from '../lib/core/ledger.js'
+import { claimRewindNotices, completeUndoWithNotice, getLatestSnapshotRef, getLatestTurn, getTurn, insertTurn, openLedger, queueRewindNotice, settleInterruptedTurn, settleNoopTurn, 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-'))
@@ -58,9 +58,10 @@ it('marks undo and queues its one-time notice atomically', async () => {
createdAt: '2026-01-01T00:01:00.000Z',
})
assert.equal(getTurn(db, 'session:undo').status, 'undone')
- const notice = claimRewindNotice(db, 'session', 'workspace')
- assert.equal(notice.notice_id, 'notice-undo')
- assert.deepEqual(notice.paths, ['src/reverted.ts'])
+ const notices = claimRewindNotices(db, 'session', 'workspace')
+ assert.equal(notices.length, 1)
+ assert.equal(notices[0].notice_id, 'notice-undo')
+ assert.deepEqual(notices[0].paths, ['src/reverted.ts'])
}
finally {
db.close()
@@ -68,7 +69,7 @@ it('marks undo and queues its one-time notice atomically', async () => {
}
})
-it('delivers only the latest pending rewind notice once', async () => {
+it('merges multiple pending rewind notices and delivers them once', async () => {
const root = await mkdtemp(join(tmpdir(), 'turnrewind-notice-test-'))
const db = openLedger(root)
try {
@@ -88,10 +89,126 @@ it('delivers only the latest pending rewind notice once', async () => {
paths: ['src/new.ts'],
createdAt: '2026-01-01T00:01:00.000Z',
})
- const notice = claimRewindNotice(db, 'session', 'workspace')
- assert.equal(notice.notice_id, 'notice-two')
- assert.deepEqual(notice.paths, ['src/new.ts'])
- assert.equal(claimRewindNotice(db, 'session', 'workspace'), undefined)
+ const notices = claimRewindNotices(db, 'session', 'workspace')
+ assert.equal(notices.length, 2)
+ assert.deepEqual(notices.map(notice => notice.notice_id), ['notice-one', 'notice-two'])
+ assert.deepEqual(notices.map(notice => notice.turns), [['session:1'], ['session:2']])
+ assert.deepEqual(notices.map(notice => notice.paths), [['src/old.ts'], ['src/new.ts']])
+ assert.deepEqual(claimRewindNotices(db, 'session', 'workspace'), [])
+ }
+ finally {
+ db.close()
+ await rm(root, { recursive: true, force: true })
+ }
+})
+
+it('merges a C-B-A undo sequence into one complete notice', async () => {
+ const root = await mkdtemp(join(tmpdir(), 'turnrewind-cba-test-'))
+ const db = openLedger(root)
+ try {
+ for (const [turnId, time] of [
+ ['session:A', '2026-01-01T00:00:00.000Z'],
+ ['session:B', '2026-01-01T00:01:00.000Z'],
+ ['session:C', '2026-01-01T00:02:00.000Z'],
+ ]) {
+ insertTurn(db, {
+ turnId,
+ sessionId: 'session',
+ workspaceKey: 'workspace',
+ startedAt: time,
+ beforeRef: `${turnId}-before`,
+ })
+ settleTurn(db, turnId, `${turnId}-after`)
+ }
+ for (const [turnId, path, time] of [
+ ['session:C', 'c.ts', '2026-01-01T00:03:00.000Z'],
+ ['session:B', 'b.ts', '2026-01-01T00:04:00.000Z'],
+ ['session:A', 'a.ts', '2026-01-01T00:05:00.000Z'],
+ ]) {
+ completeUndoWithNotice(db, turnId, {
+ noticeId: `notice-${turnId}`,
+ sessionId: 'session',
+ workspaceKey: 'workspace',
+ targetTurnId: turnId,
+ paths: [path],
+ createdAt: time,
+ })
+ }
+ const notices = claimRewindNotices(db, 'session', 'workspace')
+ assert.deepEqual(notices.map(notice => notice.turns), [['session:C'], ['session:B'], ['session:A']])
+ assert.deepEqual(notices.map(notice => notice.paths), [['c.ts'], ['b.ts'], ['a.ts']])
+ assert.deepEqual(claimRewindNotices(db, 'session', 'workspace'), [])
+ }
+ finally {
+ db.close()
+ await rm(root, { recursive: true, force: true })
+ }
+})
+
+it('keeps an interrupted turn reversible when it captured file changes', async () => {
+ const root = await mkdtemp(join(tmpdir(), 'turnrewind-interrupt-test-'))
+ const db = openLedger(root)
+ try {
+ insertTurn(db, {
+ turnId: 'session:settled',
+ sessionId: 'session',
+ workspaceKey: 'workspace',
+ startedAt: '2026-01-01T00:00:00.000Z',
+ beforeRef: 'refs/turnrewind/settled-before',
+ })
+ settleTurn(db, 'session:settled', 'refs/turnrewind/settled-after')
+ insertTurn(db, {
+ turnId: 'session:interrupted',
+ sessionId: 'session',
+ workspaceKey: 'workspace',
+ startedAt: '2026-01-01T00:01:00.000Z',
+ beforeRef: 'refs/turnrewind/interrupted-before',
+ })
+ settleInterruptedTurn(
+ db,
+ 'session:interrupted',
+ 'refs/turnrewind/interrupted-after',
+ 'agent became idle after interruption',
+ )
+ assert.equal(getTurn(db, 'session:interrupted').status, 'interrupted')
+ assert.equal(getTurn(db, 'session:interrupted').reversible, 1)
+ assert.equal(getLatestTurn(db, 'session', 'workspace').turn_id, 'session:interrupted')
+ }
+ finally {
+ db.close()
+ await rm(root, { recursive: true, force: true })
+ }
+})
+
+it('selects an interrupted turn after a later turn is undone', async () => {
+ const root = await mkdtemp(join(tmpdir(), 'turnrewind-sequence-test-'))
+ const db = openLedger(root)
+ try {
+ insertTurn(db, {
+ turnId: 'session:interrupted',
+ sessionId: 'session',
+ workspaceKey: 'workspace',
+ startedAt: '2026-01-01T00:00:00.000Z',
+ beforeRef: 'refs/turnrewind/interrupted-before',
+ })
+ settleInterruptedTurn(db, 'session:interrupted', 'refs/turnrewind/interrupted-after', 'interrupted')
+ insertTurn(db, {
+ turnId: 'session:later',
+ sessionId: 'session',
+ workspaceKey: 'workspace',
+ startedAt: '2026-01-01T00:01:00.000Z',
+ beforeRef: 'refs/turnrewind/later-before',
+ })
+ settleTurn(db, 'session:later', 'refs/turnrewind/later-after')
+ completeUndoWithNotice(db, 'session:later', {
+ noticeId: 'notice-later',
+ sessionId: 'session',
+ workspaceKey: 'workspace',
+ targetTurnId: 'session:later',
+ paths: ['later.txt'],
+ createdAt: '2026-01-01T00:02:00.000Z',
+ })
+ assert.equal(getLatestTurn(db, 'session', 'workspace').turn_id, 'session:interrupted')
}
finally {
db.close()