Skip to content

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

fix(turnrewind): harden undo safety, plan claims and client lifecycle

yingtianlan8fbc2dae3cb1
diff --git a/docs/TURN_REWIND.md b/docs/TURN_REWIND.md
index ad79f21d..18ea7493 100644
--- a/docs/TURN_REWIND.md
+++ b/docs/TURN_REWIND.md
@@ -250,7 +250,7 @@ operation_paths(operation_id, path, expected_current_digest,
首版用 `spawnSync` 执行全部 git 命令,大工作区上会冻结整个 Host(所有会话、Web UI、健康检查),叠加 Windows Defender 实时扫描时可达分钟级。现已全部改为异步 `spawn`:
-- 同一会话的捕获、结算按 FIFO 链串行,`turn/end` 的结算自动排队在基线捕获之后;不同会话之间并行;
+- 同一会话的捕获、结算按 FIFO 链串行,`turn/end` 的结算自动排队在基线捕获之后;同一 workspace 被其他 session 占用时,后续 turn 显式记为 `skipped`,不进入共享 snapshot 链;
- `agent/inbox/claimed` 同步占位 active 表条目并创建 baseline deferred;随后由 awaited `agent/pre-step` waterfall 等待基线完成,因此 `step/start`、模型请求和工具执行不会跑在 before snapshot 之前;
- 基线任务仍通过每 session FIFO 串行执行;捕获失败会先记录明确的 `skipped` 原因并释放 barrier,turn 本身继续运行但不提供 Undo;
- 命令 handler 返回 Promise(内核以 `Promise.resolve(output)` 结算),`/undo` 的 diff、冲突检测与恢复均异步执行;
diff --git a/docs/TURN_REWIND_PRODUCTION_AUDIT.md b/docs/TURN_REWIND_PRODUCTION_AUDIT.md
new file mode 100644
index 00000000..2d9586b3
--- /dev/null
+++ b/docs/TURN_REWIND_PRODUCTION_AUDIT.md
@@ -0,0 +1,733 @@
+# dsh-tauri-turnrewind 生产环境审查报告
+
+> 审查对象:`dsh-tauri-turnrewind` 当前 `feature/turn-rewind` 分支代码
+>
+> 审查基线:远端个人 fork 最新提交 `82e84bbe99802c5e3df9b9292ca9e8cbca18f500`
+>
+> 审查性质:生产安全与稳定性审查及修复后复审;报告区分已修复、部分缓解和仍未解决的问题。
+
+## 1. 执行摘要
+
+当前版本适合作为**实验性内部测试插件**,不建议直接作为生产级 Undo 功能发布。
+
+本轮修复后的状态:已关闭部分高风险问题并通过 62 项自动化测试,但仍存在生产阻断项,详见“本轮修复后的最终状态”。
+
+已存在的主要风险集中在:
+
+- baseline barrier 已加入,并已有单元测试;真实 DSH 事件时序仍需集成验证;
+- 同一 workspace 的其他 session 现在会被明确标记为 `skipped`,不再共享 snapshot 链;
+- 未完成的 Undo/Redo operation 会在重启时标记为 `needs-recovery` 并阻断该 workspace,但尚未实现自动 journal 重放;
+- 文件恢复与账本更新仍不是一个完整可崩溃恢复的事务;
+- 文件替换与路径安全检查仍存在原子性和 TOCTOU 问题,悬空 symlink 检查已加固;
+- 确认路由已增加 POST、body 限制和 pending→applying 原子 claim,但 loopback 应用层认证仍较弱;
+- 客户端过期计划、取消失败、会话归属和主要 teardown 清理已修复,浏览器端集成测试仍缺失;
+- 目前测试主要是 Host/core 单测,缺少浏览器、HTTP、并发、崩溃和干净安装集成测试。
+
+### 发布结论
+
+当前建议保持:
+
+```text
+0.1.0-dev / internal test
+```
+
+并限制在:
+
+```text
+可丢弃的测试 workspace
+```
+
+在解决 P0/P1 风险、补齐集成测试前,不建议发布稳定 npm 版本或推荐普通用户在真实项目启用。
+
+## 2. 审查范围
+
+重点审查文件:
+
+- `plugins/dsh-tauri-turnrewind/lib/index.js`
+- `plugins/dsh-tauri-turnrewind/lib/client.js`
+- `plugins/dsh-tauri-turnrewind/lib/core/git-snapshot.js`
+- `plugins/dsh-tauri-turnrewind/lib/core/ledger.js`
+- `plugins/dsh-tauri-turnrewind/lib/core/guard.js`
+- `plugins/dsh-tauri-turnrewind/lib/core/maintenance.js`
+- `plugins/dsh-tauri-turnrewind/lib/purge-workspace.js`
+- `plugins/dsh-tauri-turnrewind/package.json`
+- `plugins/dsh-tauri-turnrewind/cordis.patch.yml`
+- `plugins/dsh-tauri-turnrewind/test/*.test.js`
+- `docs/TURN_REWIND.md`
+
+审查方式:
+
+- 阅读当前实现和相关测试;
+- 对照 DSH agent loop、Client Slot 和 Web Server 约定;
+- 检查 Git 快照、SQLite ledger、HTTP route 和 Client 生命周期;
+- 执行插件测试、语法检查、包内容预检;
+- 对嵌套敏感文件的 Git pathspec 做额外验证。
+
+## 3. 风险等级定义
+
+| 等级 | 含义 |
+|---|---|
+| P0 / Critical | 可能直接造成不可逆数据丢失、错误恢复或严重安全边界失效,应阻止发布 |
+| P1 / High | 生产中较容易触发的完整性、安全或稳定性问题,应在生产候选版前修复 |
+| P2 / Medium | 边界条件、可用性或防御性不足,应在稳定版前修复 |
+| P3 / Low | 长期维护、隐私强化或性能改进项 |
+
+## 4. P0 / Critical 风险
+
+> 本章保留原始风险及修复后的状态;当前是否仍阻断发布,以文末“本轮修复后的最终状态”为准。
+
+### P0-1:异步 baseline capture 可能晚于模型写文件(已部分修复,待集成验证)
+
+**位置:**
+
+- `plugins/dsh-tauri-turnrewind/lib/index.js:757-884`
+- 重点:`active.set()` 与后续 `enqueueTurnTask(... captureSnapshot ...)`
+
+**问题:**
+
+历史版本曾在 `agent/inbox/claimed` 中仅登记 active turn,真正的 `captureSnapshot()` 在后续异步队列执行,因而存在晚于模型工具写入的风险。`82e84bb` 后,`agent/pre-step` 会等待 baseline deferred 完成;本问题当前已部分缓解,但仍需要真实 DSH 事件时序集成测试确认。
+
+潜在时序:
+
+```text
+claim 事件
+ ↓
+active.set()
+ ↓
+claim handler 返回
+ ↓
+模型调用 write/bash/PowerShell
+ ↓
+baseline capture 才开始
+```
+
+如果工具写入先发生,写入可能已经进入 before snapshot,之后 before/after diff 看不到它,Undo 会漏掉文件。
+
+**影响:**
+
+- 用户看到 Agent 创建了文件,但 `/undo` 后文件仍然存在;
+- Undo 的核心承诺不成立;
+- 间歇性时序问题难以复现和诊断。
+
+**建议:**
+
+- 在允许 Agent step/tool 执行前建立明确的 baseline barrier;
+- 若 `agent/inbox/claimed` 不支持等待,需要上游提供 pre-step/turn-start barrier;
+- 或先执行可靠的轻量 baseline,再异步做后续工作;
+- 增加事件级测试:claim 返回后立即写文件,验证写入不进入 before snapshot。
+
+### P0-2:Undo/Redo 崩溃后磁盘和 ledger 可能分离(部分缓解:重启阻断,未自动恢复)
+
+**位置:**
+
+- `plugins/dsh-tauri-turnrewind/lib/index.js:311-327`
+- `plugins/dsh-tauri-turnrewind/lib/index.js:379-429`
+- `plugins/dsh-tauri-turnrewind/lib/core/ledger.js:109`
+- `plugins/dsh-tauri-turnrewind/lib/core/ledger.js:338-347`
+- `plugins/dsh-tauri-turnrewind/lib/core/ledger.js:405-455`
+
+**问题:**
+
+Undo/Redo 先逐文件修改磁盘,之后才提交 ledger 状态和 notice。进程可能在两者之间退出:
+
+```text
+磁盘:部分或全部已恢复
+ledger:operation 仍为 applying,或 turn 状态未更新
+```
+
+历史版本启动恢复只将 `turns.status = 'active'` 标为 abandoned,没有处理 `operations.outcome = 'applying'`。当前已将 applying operation 标记为 `needs-recovery` 并阻断对应 workspace,但尚未实现自动 journal 重放。
+
+**影响:**
+
+- 重启后插件对实际磁盘状态判断错误;
+- 后续 Undo/Redo 可能重复覆盖文件;
+- notice 丢失或重复;
+- 部分恢复无法自动诊断。
+
+**建议:**
+
+实现可恢复 operation journal:
+
+```text
+applying → restoring(path-1) → restoring(path-2) → applied
+```
+
+启动时扫描 applying operation,选择:
+
+- 使用 before snapshot 完整回滚;或
+- 标记为 `needs-recovery`,阻止后续操作并要求人工处理。
+
+增加 kill/crash 注入测试。
+
+## 5. P1 / High 风险
+
+### P1-1:不同 session 共享 workspace 时缺少 workspace 级锁(已改为显式拒绝)
+
+**位置:**
+
+- `lib/index.js:693-733`
+- `lib/index.js:853-857`
+- `lib/index.js:235-268`
+
+**问题:**
+
+任务队列按 `sessionId`,但 `workspaceStores`、`parentRef` 和私有 snapshot repo 按 workspace 共享。两个 session 使用同一 cwd 时,baseline、after snapshot 和 parentRef 可能交叉。
+
+**影响:**
+
+- A turn 可能吸收 B turn 的文件;
+- A 的 Undo 可能删除 B 创建的文件;
+- 快照链和真实写入顺序不一致。
+
+**建议:**
+
+- MVP 直接拒绝同一 workspace 的多 session turnrewind;或
+- 为 capture、settle、undo、redo、purge 统一增加 workspace-level FIFO/mutex;
+- 增加双 session 同 workspace 并发集成测试。
+
+> `docs/TURN_REWIND.md` 当前说明不同 session 可以并行,这与当前实现的 workspace 共享状态不一致,应同步修正文档或先实现锁。
+
+### P1-2:恢复已有文件不是原子替换
+
+**位置:** `lib/core/git-snapshot.js:462-491`
+
+**问题:**
+
+当前流程为:
+
+```text
+写 temp
+删除 target
+rename temp → target
+```
+
+进程在删除和 rename 之间退出时,原文件会永久缺失。
+
+**建议:**
+
+- 使用同目录临时文件、flush/fsync 和经过验证的原子替换 API;
+- Windows、Linux、macOS 分别验证 replace 语义;
+- 恢复前后拒绝 symlink/reparse point;
+- 启动时清理或处理孤儿临时文件;
+- 为 rename 失败、kill 和断电场景增加测试。
+
+### P1-3:路径检查存在 TOCTOU 和 junction/reparse point 竞态
+
+**位置:**
+
+- `lib/core/git-snapshot.js:143-158`
+- `lib/core/git-snapshot.js:384-392`
+- `lib/core/git-snapshot.js:452-485`
+- `lib/core/guard.js:66-107`
+
+**问题:**
+
+`assertSafePath()` 先检查路径,后续才执行 mkdir/lstat/remove/rename。检查和使用之间,其他程序可以替换父目录、目标文件或 Windows junction。
+
+**影响:**
+
+理论上可能写入或删除 workspace 外路径;`--force` 下影响更严重。
+
+**建议:**
+
+- Windows 显式拒绝 reparse point/junction;
+- 使用 no-follow 文件系统 API 或目录句柄/fd 相对操作;
+- 实际打开、替换、删除时再次验证;
+- workspace lock 只能降低竞态,不能替代 no-follow 语义。
+
+### P1-4:确认和取消计划存在 TOCTOU/并发竞态(主要重复执行问题已缓解,HTTP/完整状态机仍需验证)
+
+**位置:**
+
+- `lib/index.js:615-670`
+- `lib/core/ledger.js:198-203`
+
+**问题:**
+
+confirm route 先读取 pending row,随后异步恢复文件;两个 confirm 请求可以同时读到 pending。confirm 与 cancel 也可能交叉。`planRuntime.undoing` 是内存标记,不能替代 ledger 原子状态迁移。
+
+**影响:**
+
+- 重复 restore;
+- 重复 operation 或 notice;
+- cancel 已返回成功但 confirm 仍执行;
+- 多进程/重入时状态不确定。
+
+**建议:**
+
+增加 `applying` 状态并原子 claim:
+
+```sql
+UPDATE pending_plans
+SET status = 'applying'
+WHERE plan_id = ? AND status = 'pending'
+```
+
+只有 affected rows 为 1 的请求可以继续。
+
+### P1-5:本地 HTTP 路由授权边界不足(方法/body/claim 已加固,应用层认证仍不足)
+
+**位置:**
+
+- `lib/index.js:339-369`
+- `lib/index.js:611-691`
+- `lib/core/ledger.js:130-141`
+- `lib/client.js:575-586`
+
+**问题:**
+
+mutation route 只检查 loopback,plan ID 只取 UUID 的前 8 位;status route 不绑定 session;路由没有强制 POST,也没有 body 上限。任意本地进程/恶意网页在获得或枚举 planId/sessionId 后,理论上可以触发恢复或取消。
+
+**建议:**
+
+优先使用 DSH package-private Host RPC。若暂时保留 HTTP:
+
+- 使用完整高熵一次性 token;
+- 服务端绑定 session、workspace 和 plan;
+- confirm/cancel/status 做授权校验;
+- 强制 POST;
+- 校验 Origin 作为补充;
+- 限制请求体大小并拒绝异常 Content-Type。
+
+### P1-6:嵌套敏感文件没有被实际 Git pathspec 排除(已修复)
+
+**位置:** `lib/core/git-snapshot.js:16-39`
+
+**复现:**
+
+当前 pathspec 对根目录文件有效,但以下文件会被 Git 捕获:
+
+```text
+config/credentials.json
+nested/secrets.yaml
+```
+
+原因是 `credentials.*`、`secrets.*` 缺少 `**/` 前缀;而预算 probe 的 basename 判断却会把它们视为排除,导致预检和实际快照不一致。
+
+**建议:**
+
+使用:
+
+```text
+:(exclude,glob)**/credentials.*
+:(exclude,glob)**/secrets.*
+```
+
+让 probe 与 Git pathspec 共用规则来源,并为嵌套路径添加测试。已经进入 Git 对象的历史内容需要通过 purge/rebuild 清理。
+
+### P1-7:客户端插件 teardown 不完整(主要问题已修复,待浏览器集成验证)
+
+**位置:**
+
+- `lib/client.js:436-537`
+- `lib/client.js:556-563`
+- `lib/client.js:611-623`
+
+**问题:**
+
+- unsupported modal 使用 module-global `dialog`,直接挂到 `document.body`,stop/update 时没有删除 DOM 和 listener;
+- commandview 的 `ctx.slots.inject()` disposer 没有从 effect 返回;
+- HMR/reapply 可能留下旧组件、旧 listener 或重复注册。
+
+**建议:**
+
+- effect cleanup 时 remove modal DOM、listener,并重置 global 引用;
+- 返回并保留 `ctx.slots.inject()` disposer;
+- 增加 apply → dispose → reapply 测试,确认只有一个 commandview 且没有旧 timer/DOM。
+
+## 6. P2 / Medium 风险
+
+### P2-1:特殊文件名使用换行分隔解析(已修复)
+
+**位置:** `git-snapshot.js:311-314`、`419-421`
+
+`git diff --name-only` 和 `ls-tree` 结果使用换行拆分、并对路径 trim。含换行、首尾空格的合法文件名会被拆错或丢失。
+
+**建议:** 使用 Git `-z`/NUL 分隔和 `split('\0')`,不对路径无条件 trim。
+
+### P2-2:turn ref 清洗存在碰撞(已修复)
+
+**位置:** `index.js:16-18`
+
+`/[^^\w.-]/gu`(实际实现为 `/[^\w.-]/gu`)把多个不同 turn ID 映射到相同 ref,后一个 snapshot 可能覆盖前一个。
+
+**建议:** ref 使用完整随机 UUID 或 `sha256(turnId)`,原始 turn ID 只存 ledger。
+
+### P2-3:ledger 状态迁移缺少前置状态和 affected-row 校验
+
+**位置:** `ledger.js:232-245`、`293-303`、`405-455`
+
+迟到/重复事件可能重新修改已完成 turn,或者插入幽灵 notice。
+
+**建议:** 明确状态机并在 SQL 中限制预期前置状态,同时要求 `changes === 1`。
+
+建议状态迁移:
+
+```text
+active → settled
+active → interrupted
+active → failed
+settled → undone
+undone → settled
+```
+
+### P2-4:Unix workspace identity 大小写策略不一致(已修复)
+
+**位置:**
+
+- `index.js:38-40`
+- `git-snapshot.js:165-175`
+- `maintenance.js:20-22`
+
+`workspaceKeyFor()` 总是小写,而 snapshot hash 在 Unix 保留大小写。大小写敏感文件系统上可能出现 ledger key 和 snapshot repo 不对应。
+
+**建议:** 统一 canonical identity:Windows 使用 realpath + lowercase,Unix 使用 realpath + 保留大小写。
+
+### P2-5:过期 plan 无限轮询(已修复)
+
+**位置:** `client.js:237-270`、`ledger.js:205-213`
+
+后端过期返回 404,客户端在 `res.ok === false` 时直接 return,不设置 `gone`,也不清理 interval。
+
+**影响:**
+
+- UI 继续显示可操作按钮;
+- 每 1.5 秒请求一次已不存在的计划;
+- 页面长期运行产生无意义请求。
+
+**建议:** 404 时设置 `planStatus = 'gone'`、清理 interval、隐藏按钮并提示重新执行 `/undo`。
+
+### P2-6:客户端确认使用当前选中 session,而非卡片所属 session(已修复)
+
+**位置:** `client.js:575-586`
+
+用户切换 session 后点击旧卡,客户端使用新的 `sessions.list.current` 发送 sessionId。当前通常会 403,但归属逻辑不应依赖全局当前选中项。
+
+**建议:** 使用 command card owner 的 session ID,或让 Host 根据 plan ID 自己解析归属。
+
+### P2-7:取消请求失败时 UI 仍标记为 cancelled(已修复)
+
+**位置:** `client.js:283-305`
+
+cancel 请求失败时仍执行 `setPlanStatus('cancelled')`,卡片折叠且无法重试,但服务端可能仍是 pending。
+
+**建议:** 只有服务端明确返回成功后才设置 cancelled;失败时保持 actionable 并显示错误。
+
+### P2-8:HTTP body 没有限制(已修复)
+
+**位置:** `index.js:339-369`
+
+`req.on('data')` 无限累积 chunks,恶意本地请求可造成内存消耗。
+
+**建议:** 设置几 KB 的 body 上限,超限立即返回 413 并销毁请求。
+
+### P2-9:scan/probe 对权限错误静默跳过(仍未修复)
+
+**位置:** `git-snapshot.js:231-235`、`guard.js:70-77`
+
+目录无法读取时直接 continue,可能生成不完整 baseline,而用户没有得到明确错误。
+
+**建议:** 区分“不存在”和“无权限”;权限错误应拒绝 workspace 或将 turn 标为 capture failed。
+
+### P2-10:`runGitStdin()` 缺少统一输出上限和子进程清理
+
+**位置:** `git-snapshot.js:325-347`
+
+当前辅助函数没有像 `runGit()` 一样限制输出和统一处理 error/close/kill。
+
+**建议:** 复用统一的受限 Git 子进程包装器。
+
+### P2-11:维护清理不是可恢复事务(仍未修复)
+
+**位置:** `lib/core/maintenance.js:20-49`
+
+ledger 删除先提交,snapshot repo 后删除;中途退出会留下半清理状态。也没有检查 runtime 是否正在使用 repo。
+
+**建议:** 使用 purge journal、workspace lock 和可重试状态。
+
+## 7. P3 / Low 风险
+
+### P3-1:快照目录权限未显式收紧
+
+**位置:** `ledger.js:67-70`、`git-snapshot.js:113-130`
+
+依赖系统默认 ACL/权限。快照中仍可能有源代码和配置,在多用户机器上应显式保护。
+
+**建议:**
+
+- Unix:目录 0700、文件 0600;
+- Windows:仅当前用户和 SYSTEM;
+- 启动时检查既有目录权限。
+
+### P3-2:快照长期增长,没有 retention/GC
+
+**位置:** `git-snapshot.js:277-308`、`ledger.js:326-331`
+
+每个 workspace 的 Git 对象和 refs 持续累积,单次 probe 限制不能阻止长期磁盘增长。
+
+**建议:** 增加按时间、数量和磁盘配额的 retention/GC,并保留失败可诊断信息。
+
+### P3-3:workspace 级扫描和 Git 子进程性能偏慢
+
+当前完整测试在提高超时后通过,但 Windows 上大量 Git 子进程成本很高。
+
+主要重复操作包括:
+
+```text
+每个路径重复 ls-tree
+每个路径重复 show
+每个路径重复 hash-object
+每个路径串行 restore
+```
+
+建议缓存 tree/path 元数据,使用 NUL 批量查询,并限制并发恢复数量。
+
+## 8. 测试验证结果
+
+### 已通过
+
+使用较长测试超时、单 worker 运行:
+
+```text
+Test Files: 8 passed
+Tests: 43 passed
+Duration: 95.55s
+```
+
+覆盖:
+
+- 常规创建、修改、删除和恢复;
+- 中断 turn;
+- Undo/Redo 基本流程;
+- 冲突、`--force`、`--skip-conflicts`;
+- Unicode 基础文件名;
+- CRLF/LF 比较;
+- workspace 预算;
+- snapshot repo 自愈;
+- ledger 基础生命周期;
+- projection 基础逻辑。
+
+语法和空白检查:
+
+```text
+node --check:通过
+ git diff --check:通过
+```
+
+npm 包预检:
+
+```text
+npm pack --dry-run:通过
+```
+
+当前 tarball 预期包含:
+
+```text
+README.md
+cordis.patch.yml
+lib/**
+package.json
+```
+
+### 测试超时说明
+
+默认配置下,lifecycle/git-snapshot 测试可能因为 Windows Git 子进程耗时超过单测试 30 秒而超时;这不是当前已观察到的断言失败。提高到 120 秒后完整 43 项通过,但约 95 秒的总耗时本身暴露了生产性能问题。
+
+## 9. 缺失的生产级测试
+
+1. baseline barrier:claim 返回后立即写文件;
+2. 两个 session 同 workspace 并发 capture/settle/undo;
+3. Undo/Redo 恢复中途 kill/crash;
+4. 原子替换失败和孤儿临时文件;
+5. Windows junction/reparse point;
+6. 父目录/目标文件并发替换;
+7. 含换行、首尾空格的文件名;
+8. turn ref collision;
+9. 重复/乱序 turn/end、idle 事件;
+10. applying operation 启动恢复;
+11. confirm + cancel 并发 HTTP 请求;
+12. GET/PUT/错误 Origin 路由拒绝;
+13. plan 过期 UI 和 polling 停止;
+14. Client stop/update/HMR DOM、Slot、timer 清理;
+15. session 切换后点击旧 Undo 卡;
+16. clean tarball 安装后的 Host + Client smoke test;
+17. 嵌套敏感文件和更多凭据文件排除;
+18. Unix 大小写路径和跨平台 workspace identity。
+
+## 10. 推荐修复顺序
+
+### 发布阻断项
+
+```text
+1. baseline capture barrier
+2. workspace-level lock 或明确拒绝共享 workspace
+3. 崩溃可恢复 operation journal
+4. 原子文件替换和 no-follow/reparse-point 防护
+5. confirm/cancel 原子 claim
+6. 敏感文件排除规则统一
+```
+
+### 稳定版前
+
+```text
+7. 修复 HTTP token、方法和 body 限制
+8. 修复过期 plan polling
+9. 修复 Client teardown/disposer/modal 清理
+10. 修复特殊文件名解析
+11. 修复 ref collision
+12. 收紧 ledger 状态迁移
+13. 统一 workspace identity
+```
+
+### 长期质量
+
+```text
+14. Git 查询和恢复性能优化
+15. snapshot retention/GC
+16. 快照目录权限强化
+17. 浏览器和 clean-install 集成测试
+18. 真实 Windows/macOS/Linux 回归
+```
+
+## 11. 当前使用警告
+
+在上述问题修复前,README 和发布说明应持续保留以下警告:
+
+```text
+This is an experimental prototype.
+Use only with disposable workspaces.
+Do not rely on it as the only backup.
+Do not run it on a shared workspace used concurrently by multiple sessions.
+A process crash during restore may require manual recovery.
+```
+
+本报告只记录审查结果,不会自动修改实现,也不替代正式安全评估或备份策略。
+
+## 本轮修复后的最终状态
+
+### 已修复并验证
+
+- baseline barrier 已接入 `agent/pre-step`,新增 barrier 回归测试通过;
+- 同一 workspace 的其他 session 不再进入同一 snapshot 链,而是记录为 `skipped`;
+- nested `credentials/secrets` 结构化配置文件按任意深度排除,同时保留 `credentials.module.ts` 等合法源码;
+- workspace identity 在 index、snapshot hash 和 purge 之间统一,Unix 大小写路径不再被错误折叠;
+- turn snapshot ref 改用 turn ID 的 SHA-256 前缀,避免清洗碰撞;
+- Git 路径列表改用 NUL 分隔,避免换行文件名被错误拆分;
+- pending plan 使用 SQLite 条件 claim,confirm/cancel 竞争时最多一个请求获得执行权;
+- mutation route 强制 POST,并限制请求体大小为 16 KiB;
+- Client 的 404/gone plan 会停止 polling,取消失败不会错误折叠,命令卡使用 session-scoped owner;
+- Client commandview、dialog、polling 和 submit channel 增加生命周期清理;
+- 重启时 applying operation 会标记为 `needs-recovery`,对应 workspace 会阻止新的 Undo/Redo;
+- 悬空符号链接和 turnrewind 临时文件增加了防护与测试。
+
+### 当前验证
+
+```text
+Vitest: 10 test files, 62 passed, 0 failed
+ESLint: 0 errors, 1 warning
+node --check: passed
+ git diff --check: passed
+```
+
+剩余的 1 个 ESLint warning 位于 `lib/client.js:268`,是展开状态在 React effect 中同步 setState 的性能提示,不是 lint error。
+
+### 仍未解决的生产阻断项
+
+- `restorePath()` 仍采用删除目标后再 rename,进程在两步之间退出可能造成文件缺失;
+- 路径检查与实际文件操作仍存在 TOCTOU,Windows junction/reparse point 还没有句柄级 no-follow 保护;
+- applying operation 当前是“重启后阻断并要求人工检查/清理”,不是自动 journal 重放;现有恢复方式是停止 Host 后使用 `purge-workspace.js` 清理该 workspace 的 turnrewind 数据,再重新建立基线;
+- operation 终态仍与文件系统 I/O 分离,完整崩溃一致性仍未实现;
+- loopback HTTP 仍没有强应用层认证,plan status 仍可按 planId 查询;
+- purge 与运行中的 snapshot/restore 没有可恢复事务和 workspace lock;
+- 尚无真实 DSH agent-loop、HTTP server、浏览器 Client、kill/crash、junction 和干净 tarball 安装集成测试;
+- Git 子进程数量较多,Windows 大 workspace 的 Undo 性能仍需要优化和预算。
+
+因此当前仍应保持:
+
+```text
+0.1.0-dev / internal test
+```
+
+不得把它当作正式项目的唯一备份或生产级文件恢复保障。
+
+本轮修复没有创建 commit,也没有推送远端。桌面副本已在本次复审后同步。
+
+## 12. `82e84bb` baseline barrier 更新复审
+
+> 本节记录 barrier 提交本身;本报告上方的“本轮修复后的最终状态”记录当前未提交修复结果。
+
+远端提交:
+
+```text
+82e84bb fix(turnrewind): add baseline execution barrier
+```
+
+本次提交将 baseline 等待接入 `agent/pre-step`:`agent/inbox/claimed` 同步创建 deferred reservation,`agent/pre-step` 在调用下游 `next()` 前等待该 deferred。按 DSH agent loop 的顺序,`next()` 之后才会进入模型请求和工具执行,因此该修改**方向正确,并部分缓解了 P0-1 的 baseline 晚于写入问题**。
+
+相关实现:
+
+- `plugins/dsh-tauri-turnrewind/lib/index.js:50-91`
+- `plugins/dsh-tauri-turnrewind/lib/index.js:796-1004`
+- `plugins/dsh-tauri-turnrewind/test/barrier.test.js`
+
+本次同时增加:
+
+- baseline 失败时将 turn 显式记为 skipped;
+- pre-step abort 不取消后续 bookkeeping;
+- 迟到 claim 和重复 claim 的基本防护;
+- 插件停止时释放 baseline waiter,并等待 session queue 后关闭 SQLite;
+- `DSH_HOME` 改为 apply 时读取,便于隔离测试。
+
+### 12.1 当前验证结果
+
+更新后完整测试结果:
+
+```text
+Test Files: 8 passed, 1 failed
+Tests: 48 passed, 1 failed
+```
+
+失败项:
+
+```text
+test/barrier.test.js
+"does not recreate a completed turn after a duplicate claim"
+```
+
+失败位置:
+
+```text
+plugins/dsh-tauri-turnrewind/test/barrier.test.js:136
+assert.ok(after)
+```
+
+该测试在触发 `turn/end` 后仅固定等待 300ms,就断言 after snapshot ref 已存在。在当前 Windows Git 子进程耗时下,after snapshot 尚未完成,单独重跑也稳定复现。因此当前不能将 `82e84bb` 标记为完整测试通过。
+
+建议测试不要依赖固定 sleep,应等待明确的可观察完成条件,例如:
+
+- 账本中目标 turn 状态已变为 `settled` 或 `interrupted`;
+- after ref 已通过带超时的 polling 出现;
+- 测试 harness 暴露并等待对应 session queue drained 信号。
+
+### 12.2 仍未完全关闭的 baseline 风险
+
+新增测试验证了 `agent/pre-step` 会等待 baseline,但尚未模拟最关键的真实回归场景:
+
+```text
+inbox claim handler 返回
+→ 立即尝试写文件
+→ 验证写入不可能发生在 before snapshot 之前
+```
+
+应补充 agent-loop 级或真实 DSH 集成测试,确保模型工具执行确实受该 waterfall barrier 限制。若 DSH 调整事件顺序或某种工具路径绕过 `agent/pre-step`,当前单元测试不会发现。
+
+### 12.3 复审结论
+
+`82e84bb` 可以视为 P0-1 的有效修复候选,但在以下条件满足前应保持“部分缓解”状态:
+
+```text
+1. 修复新增 barrier 测试的确定性等待;
+2. 完整测试重新达到全绿;
+3. 新增真实 claim → 写入时序集成测试;
+4. 继续处理本报告其余 P0/P1 项,尤其是 workspace 并发、崩溃恢复、原子恢复和路由竞态。
+```
diff --git a/plugins/dsh-tauri-turnrewind/README.md b/plugins/dsh-tauri-turnrewind/README.md
index 84b69609..c26c1ebf 100644
--- a/plugins/dsh-tauri-turnrewind/README.md
+++ b/plugins/dsh-tauri-turnrewind/README.md
@@ -10,7 +10,7 @@
- 为已领取的 Agent turn 建立私有 Git 快照;
- 将快照映射记录到 `$DSH_HOME/ledger.sqlite`;
-- **git 全程异步执行**:快照、diff、恢复都不阻塞 Host 事件循环;同一会话的捕获/结算按 FIFO 串行,不同会话并行;收到 turn 输入后,before snapshot 通过 `agent/pre-step` barrier 完成后才允许模型和工具执行;
+- **git 全程异步执行**:快照、diff、恢复都不阻塞 Host 事件循环;同一会话的捕获/结算按 FIFO 串行;收到 turn 输入后,before snapshot 通过 `agent/pre-step` barrier 完成后才允许模型和工具执行;同一 workspace 被其他 session 占用时,新 turn 会正常运行但记为 `skipped`,避免共享 snapshot 链互相污染;
- **git 可用性探测**:系统没有 git 时,turn 显式记为 `skipped`(原因 `TURNREWIND_GIT_UNAVAILABLE`),而不是静默失败;
- **快照链自愈**:私有快照仓库被删/损坏后,下一次捕获自动降级重建基线(日志有一条 warning),后续 turn 照常可撤销;被清空前留下来的旧 turn 会在 `/undo` 选目标时自动识别为死快照并标记跳过(`snapshot ref missing`),不会甩出 git 原始报错;
- **工作区资格守卫**:家目录、家目录的祖先、盘根目录,以及超过快照预算(文件数 / 总大小 / 单文件大小)的目录不做快照,turn 记为 `skipped` 并向 `/undo` 说明原因(见「工作区资格与快照预算」);
@@ -22,7 +22,7 @@
- 注册人类命令 `/undo`;
- `/undo` 默认处理当前会话最新的单个可恢复 turn,也可指定完整 turn ID;
- 同一 workspace 的活动 turn 或 undo 操作互斥;
-- 插件重启时将未完成 turn 标记为 abandoned;
+- 插件重启时将未完成 turn 标记为 abandoned;未完成的 Undo/Redo operation 会标记为 `needs-recovery`,对应 workspace 在清理前拒绝新的 rewind 操作,避免未知磁盘状态被继续覆盖;当前只能先人工检查 workspace,再停止 Host 并使用 `purge-workspace.js` 清理该 workspace 的 turnrewind 数据后恢复使用;
- 每次 Undo/Redo 的回退提示独立持久化;下一次模型 step 一次性注入全部 pending notice;
- 不修改用户项目的 HEAD、分支、index、stash 或提交历史。
@@ -329,8 +329,18 @@ coverage/
*.pem
*.key
id_rsa*
-credentials.* # 仅根目录
-secrets.* # 仅根目录
+credentials.json # 任意深度
+credentials.yaml
+credentials.yml
+credentials.toml
+credentials.ini
+credentials.cfg
+secrets.json # 任意深度
+secrets.yaml
+secrets.yml
+secrets.toml
+secrets.ini
+secrets.cfg
```
注意两点边界:
diff --git a/plugins/dsh-tauri-turnrewind/lib/client.js b/plugins/dsh-tauri-turnrewind/lib/client.js
index 72590a77..0974a252 100644
--- a/plugins/dsh-tauri-turnrewind/lib/client.js
+++ b/plugins/dsh-tauri-turnrewind/lib/client.js
@@ -12,577 +12,669 @@
// CommonJS-style `require` and must export `apply` (cordis plugin) + `inject`
// (services the apply() context needs). The module system strips a trailing
// `/client` from ids, so this id normalizes to the package name.
-globalThis.__ModuleLoader__.load({
- id: 'dsh-tauri-turnrewind/client',
- factory: (require) => {
- const module = { exports: {} }
- const exports = module.exports
- const React = require('react')
- const jsxRuntime = require('react/jsx-runtime')
- const jsx = jsxRuntime.jsx
- const jsxs = jsxRuntime.jsxs
-
- const inject = ['slots', 'sessions', 'locale']
- // The ✓/✗ buttons post to the plugin's same-origin HTTP routes (the harness
- // page itself is served by the same host, so no auth wiring is needed);
- // assigned from apply() once the ctx is available.
- let submitLine = null
-
- // ------------------------------------------------------------------
- // /undo output parsing: the command prints a structured plain-text plan
- // (summary line, indented file list, per-file unified diff sections)
- // plus a trailing machine-readable `plan <id>` confirmation row.
- // ------------------------------------------------------------------
- function isFileSeparator(raw) {
- return /^--- (?!a\/)(?!b\/)\S/.test(raw)
- }
- function parseUndoOutput(raw) {
- const lines = (raw ?? '').split('\n')
- const result = { summary: lines[0] ?? '', files: [], dividers: [], planId: undefined }
- let current = null
- let inDiffs = false
- for (let i = 1; i < lines.length; i++) {
- const line = lines[i]
- const planRow = /^plan ([0-9a-f-]+)$/.exec(line)
- if (planRow) {
- result.planId = planRow[1]
- continue
- }
- if (/^Send \/undo --(?:confirm|cancel)/.test(line))
- continue
- if (/^(?:Undo will apply|Conflicts \()/.test(line)) {
- inDiffs = true
- result.dividers.push(line)
- continue
- }
- const listed = /^ {2,}(modified|created|deleted) (\S+)$/.exec(line)
- if (listed && !inDiffs) {
- result.files.push({ path: listed[2], change: listed[1], additions: 0, deletions: 0, diff: [] })
- continue
- }
- const separator = /^--- (?!a\/)(?!b\/)(.+)$/.exec(line)
- if (separator && inDiffs) {
- const path = separator[1].trim()
- current = result.files.find(file => file.path === path)
- if (!current) {
- current = { path, change: 'conflict', additions: 0, deletions: 0, diff: [] }
- result.files.push(current)
- }
- current.diff = []
- continue
- }
- if (current && line.trim() !== '' && inDiffs) {
- const trimmed = line.trim()
- if (/^\+/.test(trimmed) && !/^\+\+\+/.test(trimmed))
- current.additions += 1
- else if (trimmed.startsWith('-') && !trimmed.startsWith('---'))
- current.deletions += 1
- current.diff.push(line)
+/**
+ * Build the client bundle. Extracted as a named factory so tests (Node/vitest,
+ * where `__ModuleLoader__` is absent) can load it with a stub `require` and
+ * exercise the pure helpers; the browser path below is unchanged.
+ * @param require - CommonJS-style require provided by the DSH module loader.
+ * @returns the module exports ({ apply, inject, pure helpers }).
+ */
+function createTurnrewindClient(require) {
+ const module = { exports: {} }
+ const exports = module.exports
+ const React = require('react')
+ const jsxRuntime = require('react/jsx-runtime')
+ const jsx = jsxRuntime.jsx
+ const jsxs = jsxRuntime.jsxs
+
+ const inject = ['slots', 'sessions', 'locale']
+ // The ✓/✗ buttons post to the plugin's same-origin HTTP routes (the harness
+ // page itself is served by the same host, so no auth wiring is needed);
+ // assigned from apply() once the ctx is available. Owned by an effect so a
+ // plugin stop clears the channel instead of leaving a stale closure.
+ let submitLine = null
+
+ // ------------------------------------------------------------------
+ // /undo output parsing: the command prints a structured plain-text plan
+ // (summary line, indented file list, per-file unified diff sections)
+ // plus a trailing machine-readable `plan <id>` confirmation row.
+ // ------------------------------------------------------------------
+ function isFileSeparator(raw) {
+ return /^--- (?!a\/)(?!b\/)\S/.test(raw)
+ }
+
+ function parseUndoOutput(raw) {
+ const lines = (raw ?? '').split('\n')
+ const result = { summary: lines[0] ?? '', files: [], dividers: [], planId: undefined }
+ let current = null
+ let inDiffs = false
+ for (let i = 1; i < lines.length; i++) {
+ const line = lines[i]
+ const planRow = /^plan ([0-9a-f-]+)$/.exec(line)
+ if (planRow) {
+ result.planId = planRow[1]
+ continue
+ }
+ if (/^Send \/undo --(?:confirm|cancel)/.test(line))
+ continue
+ if (/^(?:Undo will apply|Conflicts \()/.test(line)) {
+ inDiffs = true
+ result.dividers.push(line)
+ continue
+ }
+ const listed = /^ {2,}(modified|created|deleted) (\S+)$/.exec(line)
+ if (listed && !inDiffs) {
+ result.files.push({ path: listed[2], change: listed[1], additions: 0, deletions: 0, diff: [] })
+ continue
+ }
+ const separator = /^--- (?!a\/)(?!b\/)(.+)$/.exec(line)
+ if (separator && inDiffs) {
+ const path = separator[1].trim()
+ current = result.files.find(file => file.path === path)
+ if (!current) {
+ current = { path, change: 'conflict', additions: 0, deletions: 0, diff: [] }
+ result.files.push(current)
}
+ current.diff = []
+ continue
}
- return result
- }
-
- // ------------------------------------------------------------------
- // /undo command card: rendering.
- // ------------------------------------------------------------------
- const DIFF_COLORS = {
- delBg: 'rgba(248, 81, 73, 0.26)',
- addBg: 'rgba(63, 185, 80, 0.38)',
- del: 'var(--dsw-alias-state-error-primary, #f85149)',
- add: 'var(--dsw-alias-state-success-primary, #3fb950)',
- delText: 'var(--dsw-alias-state-error-primary, #ffb3ab)',
- addText: 'var(--dsw-alias-state-success-primary, #8ff0a4)',
- hunk: 'var(--dsw-alias-label-tertiary, #8b8b8b)',
- meta: 'var(--dsw-alias-label-dimmed, #8b8b8b)',
- text: 'var(--dsw-alias-label-secondary, #cccccc)',
- bg: 'var(--dsw-alias-bg-layer-2, #161b22)',
- border: 'var(--dsw-alias-border-l2, #30363d)',
- }
-
- function diffLineStyle(kind) {
- switch (kind) {
- case 'del': return { background: DIFF_COLORS.delBg, color: DIFF_COLORS.delText }
- case 'add': return { background: DIFF_COLORS.addBg, color: DIFF_COLORS.addText }
- case 'hunk': return { color: DIFF_COLORS.hunk }
- case 'meta': return { color: DIFF_COLORS.meta }
- default: return { color: DIFF_COLORS.text }
+ if (current && line.trim() !== '' && inDiffs) {
+ const trimmed = line.trim()
+ if (/^\+/.test(trimmed) && !/^\+\+\+/.test(trimmed))
+ current.additions += 1
+ else if (trimmed.startsWith('-') && !trimmed.startsWith('---'))
+ current.deletions += 1
+ current.diff.push(line)
}
}
-
- function diffSign(kind) {
- if (kind === 'del')
- return '-'
- if (kind === 'add')
- return '+'
- return ' '
+ return result
+ }
+
+ // ------------------------------------------------------------------
+ // Pure decision for one plan-status poll response. Kept side-effect free
+ // so the polling rules are unit-testable without a browser:
+ // - 404 (expired/already applied on the host) or an explicit `gone`
+ // payload collapses the card and stops polling;
+ // - applied/cancelled stop polling;
+ // - any other failure keeps polling, up to the caller's failure budget.
+ // ------------------------------------------------------------------
+ function resolvePlanStatus(res, payload) {
+ const status = typeof payload?.status === 'string' ? payload.status : null
+ if (res?.status === 404 || status === 'gone')
+ return { status: 'gone', stop: true, resultText: null }
+ if (res?.ok !== true || status === null)
+ return { status: null, stop: false, resultText: null }
+ return {
+ status,
+ stop: status === 'applied' || status === 'cancelled',
+ resultText: typeof payload?.resultText === 'string' ? payload.resultText : null,
}
-
- function DiffLine(props) {
- const entry = props.entry
- return jsxs('div', {
- style: Object.assign(
- { display: 'flex', fontFamily: 'var(--ds-font-family-code, monospace)', fontSize: '12px', lineHeight: '19px', paddingLeft: 8, paddingRight: 8, whiteSpace: 'pre-wrap', wordBreak: 'break-all' },
- diffLineStyle(entry.kind),
- ),
- children: [
- jsx('span', {
- style: { width: 14, flex: 'none', color: entry.kind === 'del' ? DIFF_COLORS.del : entry.kind === 'add' ? DIFF_COLORS.add : 'transparent', userSelect: 'none' },
- children: diffSign(entry.kind),
- }),
- jsx('span', { style: { flex: 1 }, children: entry.text }),
- ],
- })
+ }
+
+ /**
+ * Resolve the session that owns a command card. Session-scoped slots receive
+ * `sessionId` as a standard prop from the renderer (the scope the card is
+ * rendered under), so prefer it, then an explicit node field. Never fall
+ * back to the global current session — the Host re-validates whatever id is
+ * sent, and an unresolvable owner must fail fast instead of silently
+ * attributing the plan to whichever session happens to be selected.
+ * @param props - slot component props.
+ * @returns the owner session id, or null when it cannot be determined.
+ */
+ function resolveOwnerSessionId(props) {
+ const candidates = [props?.sessionId, props?.node?.sessionId]
+ for (const candidate of candidates) {
+ if (typeof candidate === 'string' && candidate.length > 0)
+ return candidate
}
-
- function NumBadge(props) {
- const { additions, deletions } = props
- if (additions === 0 && deletions === 0)
- return null
- return jsxs('span', {
- style: { display: 'inline-flex', gap: 6, flex: 'none', fontFamily: 'var(--ds-font-family-code, monospace)', fontSize: 11 },
- children: [
- jsx('span', { style: { color: 'var(--dsw-alias-state-success-primary, #3fb950)' }, children: `+${additions}` }),
- jsx('span', { style: { color: 'var(--dsw-alias-state-error-primary, #f85149)' }, children: `-${deletions}` }),
- ],
- })
+ return null
+ }
+
+ // ------------------------------------------------------------------
+ // /undo command card: rendering.
+ // ------------------------------------------------------------------
+ const DIFF_COLORS = {
+ delBg: 'rgba(248, 81, 73, 0.26)',
+ addBg: 'rgba(63, 185, 80, 0.38)',
+ del: 'var(--dsw-alias-state-error-primary, #f85149)',
+ add: 'var(--dsw-alias-state-success-primary, #3fb950)',
+ delText: 'var(--dsw-alias-state-error-primary, #ffb3ab)',
+ addText: 'var(--dsw-alias-state-success-primary, #8ff0a4)',
+ hunk: 'var(--dsw-alias-label-tertiary, #8b8b8b)',
+ meta: 'var(--dsw-alias-label-dimmed, #8b8b8b)',
+ text: 'var(--dsw-alias-label-secondary, #cccccc)',
+ bg: 'var(--dsw-alias-bg-layer-2, #161b22)',
+ border: 'var(--dsw-alias-border-l2, #30363d)',
+ }
+
+ // Stop polling after this many consecutive failed status checks so a broken
+ // or unreachable host route cannot spin the interval forever. 404/gone do
+ // not count — they settle the plan immediately instead.
+ const MAX_POLL_FAILURES = 5
+
+ function diffLineStyle(kind) {
+ switch (kind) {
+ case 'del': return { background: DIFF_COLORS.delBg, color: DIFF_COLORS.delText }
+ case 'add': return { background: DIFF_COLORS.addBg, color: DIFF_COLORS.addText }
+ case 'hunk': return { color: DIFF_COLORS.hunk }
+ case 'meta': return { color: DIFF_COLORS.meta }
+ default: return { color: DIFF_COLORS.text }
}
-
- function classifyLine(raw) {
- const line = raw
- if (/^\s*(?:diff --git |index )/.test(line))
- return { kind: 'meta', text: line.trim() }
- if (/^\s*--- a\//.test(line) || /^\s*\+\+\+ b\//.test(line))
- return { kind: 'meta', text: line.trim() }
- if (/^\s*@@/.test(line))
- return { kind: 'hunk', text: line.trim() }
- if (/^\s*-/.test(line))
- return { kind: 'del', text: line.replace(/^\s*-/, '') }
- if (/^\s*\+/.test(line))
- return { kind: 'add', text: line.replace(/^\s*\+/, '') }
- return { kind: 'ctx', text: line.replace(/^\s+/, '') }
+ }
+
+ function diffSign(kind) {
+ if (kind === 'del')
+ return '-'
+ if (kind === 'add')
+ return '+'
+ return ' '
+ }
+
+ function DiffLine(props) {
+ const entry = props.entry
+ return jsxs('div', {
+ style: Object.assign(
+ { display: 'flex', fontFamily: 'var(--ds-font-family-code, monospace)', fontSize: '12px', lineHeight: '19px', paddingLeft: 8, paddingRight: 8, whiteSpace: 'pre-wrap', wordBreak: 'break-all' },
+ diffLineStyle(entry.kind),
+ ),
+ children: [
+ jsx('span', {
+ style: { width: 14, flex: 'none', color: entry.kind === 'del' ? DIFF_COLORS.del : entry.kind === 'add' ? DIFF_COLORS.add : 'transparent', userSelect: 'none' },
+ children: diffSign(entry.kind),
+ }),
+ jsx('span', { style: { flex: 1 }, children: entry.text }),
+ ],
+ })
+ }
+
+ function NumBadge(props) {
+ const { additions, deletions } = props
+ if (additions === 0 && deletions === 0)
+ return null
+ return jsxs('span', {
+ style: { display: 'inline-flex', gap: 6, flex: 'none', fontFamily: 'var(--ds-font-family-code, monospace)', fontSize: 11 },
+ children: [
+ jsx('span', { style: { color: 'var(--dsw-alias-state-success-primary, #3fb950)' }, children: `+${additions}` }),
+ jsx('span', { style: { color: 'var(--dsw-alias-state-error-primary, #f85149)' }, children: `-${deletions}` }),
+ ],
+ })
+ }
+
+ function classifyLine(raw) {
+ const line = raw
+ if (/^\s*(?:diff --git |index )/.test(line))
+ return { kind: 'meta', text: line.trim() }
+ if (/^\s*--- a\//.test(line) || /^\s*\+\+\+ b\//.test(line))
+ return { kind: 'meta', text: line.trim() }
+ if (/^\s*@@/.test(line))
+ return { kind: 'hunk', text: line.trim() }
+ if (/^\s*-/.test(line))
+ return { kind: 'del', text: line.replace(/^\s*-/, '') }
+ if (/^\s*\+/.test(line))
+ return { kind: 'add', text: line.replace(/^\s*\+/, '') }
+ return { kind: 'ctx', text: line.replace(/^\s+/, '') }
+ }
+
+ function DiffBlock(props) {
+ const file = props.file
+ const rows = []
+ for (const line of file.diff) {
+ if (isFileSeparator(line))
+ continue
+ // VSCode-style clean diff: drop git plumbing noise (diff --git / index /
+ // --- a/ / +++ b/ headers and the "\ No newline" markers) and keep only
+ // hunk headers plus +/- content lines.
+ const trimmed = line.trim()
+ if (trimmed.startsWith('diff --git ') || trimmed.startsWith('index ') || trimmed.startsWith('--- a/') || trimmed.startsWith('+++ b/') || trimmed.startsWith('\\'))
+ continue
+ rows.push(jsx(DiffLine, { entry: classifyLine(line) }, `${file.path}:${rows.length}`))
}
-
- function DiffBlock(props) {
- const file = props.file
- const rows = []
- for (const line of file.diff) {
- if (isFileSeparator(line))
- continue
- // VSCode-style clean diff: drop git plumbing noise (diff --git / index /
- // --- a/ / +++ b/ headers and the "\ No newline" markers) and keep only
- // hunk headers plus +/- content lines.
- const trimmed = line.trim()
- if (trimmed.startsWith('diff --git ') || trimmed.startsWith('index ') || trimmed.startsWith('--- a/') || trimmed.startsWith('+++ b/') || trimmed.startsWith('\\'))
- continue
- rows.push(jsx(DiffLine, { entry: classifyLine(line) }, `${file.path}:${rows.length}`))
+ return jsxs('div', {
+ style: { marginTop: 8, border: `1px solid ${DIFF_COLORS.border}`, borderRadius: 8, overflow: 'hidden' },
+ children: [
+ jsxs('div', {
+ style: { display: 'flex', alignItems: 'center', gap: 8, padding: '5px 10px', fontFamily: 'var(--ds-font-family-code, monospace)', fontSize: 11.5, color: 'var(--dsw-alias-label-secondary, #cccccc)', borderBottom: `1px solid ${DIFF_COLORS.border}`, background: 'var(--dsw-alias-bg-layer-1, transparent)' },
+ children: [
+ jsx('span', { style: { color: 'var(--dsw-alias-label-tertiary, #8b8b8b)' }, children: file.change }),
+ jsx('span', { style: { flex: 1, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }, children: file.path }),
+ jsx(NumBadge, { additions: file.additions, deletions: file.deletions }),
+ ],
+ }),
+ jsx('div', { style: { maxHeight: 260, overflowY: 'auto', padding: '3px 0' }, children: rows }),
+ ],
+ })
+ }
+
+ function UndoCommandView(props) {
+ const node = props.node || {}
+ const ownerSessionId = resolveOwnerSessionId(props)
+ const outcome = node.outcome
+ const text = outcome && typeof outcome.text === 'string' ? outcome.text : ''
+ const state = outcome == null ? 'running' : outcome.kind === 'error' ? 'error' : 'ok'
+ const parsed = parseUndoOutput(text)
+ const withDiff = parsed.files.filter(file => (file.diff?.length ?? 0) > 0)
+ const totals = parsed.files.reduce((sum, file) => ({ additions: sum.additions + file.additions, deletions: sum.deletions + file.deletions }), { additions: 0, deletions: 0 })
+ const hasDiff = withDiff.length > 0
+ const summary = parsed.summary || (state === 'error' ? '失败' : state === 'running' ? '运行中' : '完成')
+ // Remember the user's collapse choice per command: a refresh must not
+ // re-expand a card the user deliberately folded.
+ const expandKey = `turnrewind.expanded.${node.id ?? parsed.planId ?? parsed.summary}`
+ const [expanded, setExpanded] = React.useState(hasDiff)
+ React.useEffect(() => {
+ try {
+ const stored = globalThis.localStorage.getItem(expandKey)
+ if (stored === '0' || stored === '1')
+ setExpanded(stored === '1')
}
- return jsxs('div', {
- style: { marginTop: 8, border: `1px solid ${DIFF_COLORS.border}`, borderRadius: 8, overflow: 'hidden' },
- children: [
- jsxs('div', {
- style: { display: 'flex', alignItems: 'center', gap: 8, padding: '5px 10px', fontFamily: 'var(--ds-font-family-code, monospace)', fontSize: 11.5, color: 'var(--dsw-alias-label-secondary, #cccccc)', borderBottom: `1px solid ${DIFF_COLORS.border}`, background: 'var(--dsw-alias-bg-layer-1, transparent)' },
- children: [
- jsx('span', { style: { color: 'var(--dsw-alias-label-tertiary, #8b8b8b)' }, children: file.change }),
- jsx('span', { style: { flex: 1, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }, children: file.path }),
- jsx(NumBadge, { additions: file.additions, deletions: file.deletions }),
- ],
- }),
- jsx('div', { style: { maxHeight: 260, overflowY: 'auto', padding: '3px 0' }, children: rows }),
- ],
- })
- }
-
- function UndoCommandView(props) {
- const node = props.node || {}
- const outcome = node.outcome
- const text = outcome && typeof outcome.text === 'string' ? outcome.text : ''
- const state = outcome == null ? 'running' : outcome.kind === 'error' ? 'error' : 'ok'
- const parsed = parseUndoOutput(text)
- const withDiff = parsed.files.filter(file => (file.diff?.length ?? 0) > 0)
- const totals = parsed.files.reduce((sum, file) => ({ additions: sum.additions + file.additions, deletions: sum.deletions + file.deletions }), { additions: 0, deletions: 0 })
- const hasDiff = withDiff.length > 0
- const summary = parsed.summary || (state === 'error' ? '失败' : state === 'running' ? '运行中' : '完成')
- // Remember the user's collapse choice per command: a refresh must not
- // re-expand a card the user deliberately folded.
- const expandKey = `turnrewind.expanded.${node.id ?? parsed.planId ?? parsed.summary}`
- const [expanded, setExpanded] = React.useState(hasDiff)
- React.useEffect(() => {
+ catch {}
+ }, [expandKey])
+ function toggleExpanded() {
+ setExpanded((v) => {
+ const next = !v
try {
- const stored = globalThis.localStorage.getItem(expandKey)
- if (stored === '0' || stored === '1')
- setExpanded(stored === '1')
+ globalThis.localStorage.setItem(expandKey, next ? '1' : '0')
}
catch {}
- }, [expandKey])
- function toggleExpanded() {
- setExpanded((v) => {
- const next = !v
- try {
- globalThis.localStorage.setItem(expandKey, next ? '1' : '0')
- }
- catch {}
- return next
- })
+ return next
+ })
+ }
+ const [submitted, setSubmitted] = React.useState(null)
+ const [submitError, setSubmitError] = React.useState(null)
+ const [resultText, setResultText] = React.useState(null)
+ // The plan's persisted status is the source of truth: it survives page
+ // reloads, so the card state (buttons vs applied vs cancelled) rebuilds
+ // from it instead of from in-memory React state.
+ const [planStatus, setPlanStatus] = React.useState(null)
+
+ // Poll the plan status: immediately on mount (a reload must rebuild the
+ // card from the persisted state) and until the plan settles. 404/gone
+ // settle the card as expired; repeated transport failures stop the poll
+ // without changing the card state (the Host re-validates any submit).
+ React.useEffect(() => {
+ if (state !== 'ok' || !parsed.planId)
+ return
+ let stop = false
+ let timer = null
+ let failures = 0
+ const controller = new AbortController()
+ function haltPolling() {
+ stop = true
+ if (timer !== null) {
+ clearInterval(timer)
+ timer = null
+ }
}
- const [submitted, setSubmitted] = React.useState(null)
- const [submitError, setSubmitError] = React.useState(null)
- const [resultText, setResultText] = React.useState(null)
- // The plan's persisted status is the source of truth: it survives page
- // reloads, so the card state (buttons vs applied vs cancelled) rebuilds
- // from it instead of from in-memory React state.
- const [planStatus, setPlanStatus] = React.useState(null)
-
- // Poll the plan status: immediately on mount (a reload must rebuild the
- // card from the persisted state) and until the plan settles.
- React.useEffect(() => {
- if (state !== 'ok' || !parsed.planId)
+ async function check() {
+ if (stop)
return
- let stop = false
- let timer = null
- async function check() {
+ try {
+ const res = await fetch(`/api/turnrewind/status?planId=${encodeURIComponent(parsed.planId)}&sessionId=${encodeURIComponent(ownerSessionId ?? '')}`, { signal: controller.signal })
+ const payload = await res.json().catch(() => ({}))
if (stop)
return
- try {
- const res = await fetch(`/api/turnrewind/status?planId=${encodeURIComponent(parsed.planId)}`)
- const payload = await res.json().catch(() => ({}))
- if (stop || res.ok === false)
- return
- setPlanStatus(payload.status)
- if (payload.status === 'applied') {
- setResultText(payload.resultText ?? '已执行')
- clearInterval(timer)
- }
- else if (payload.status === 'cancelled') {
- clearInterval(timer)
- }
+ const next = resolvePlanStatus(res, payload)
+ if (next.status !== null)
+ setPlanStatus(next.status)
+ if (next.status === 'applied')
+ setResultText(next.resultText ?? '已执行')
+ if (next.stop) {
+ haltPolling()
+ return
}
- catch {}
- }
- void check()
- timer = setInterval(check, 1500)
- return () => {
- stop = true
- if (timer !== null)
- clearInterval(timer)
+ failures = next.status === null ? failures + 1 : 0
+ if (failures >= MAX_POLL_FAILURES)
+ haltPolling()
}
- }, [state, parsed.planId])
-
- const titleColor = state === 'error' ? 'var(--dsw-alias-state-error-primary, #f85149)' : 'var(--dsw-alias-label-primary, #cccccc)'
- // Cancelled/expired plans collapse to a minimal red card: no file list,
- // no diffs, no buttons — nothing that a refresh could resurrect.
- const collapsed = planStatus === 'cancelled' || planStatus === 'gone'
- const showBody = expanded && !collapsed && (hasDiff || parsed.files.length > 0)
- const actionable = parsed.planId !== undefined && state === 'ok' && !collapsed && (planStatus === null || planStatus === 'pending')
- // A synchronous ref guard closes the re-render gap: React state updates
- // land a tick later, so fast double-clicks would both pass a state-only
- // check and fire two confirm requests.
- const submittingRef = React.useRef(false)
-
- async function submit(kind) {
- if (submittingRef.current || submitted || !parsed.planId)
- return
- submittingRef.current = true
- try {
- const line = kind === 'confirm'
- ? `/undo --confirm ${parsed.planId}`
- : `/undo --cancel ${parsed.planId}`
- const failure = submitLine ? await submitLine(line) : 'submit channel unavailable'
- if (failure) {
- setSubmitError(failure)
- submittingRef.current = false
- }
- else {
- setSubmitted(kind)
- }
- if (kind === 'cancel')
- setPlanStatus('cancelled')
+ catch {
+ if (stop)
+ return
+ failures += 1
+ if (failures >= MAX_POLL_FAILURES)
+ haltPolling()
}
- catch (error) {
+ }
+ void check()
+ timer = setInterval(check, 1500)
+ return () => {
+ controller.abort()
+ haltPolling()
+ }
+ }, [state, parsed.planId, ownerSessionId])
+
+ const titleColor = state === 'error' ? 'var(--dsw-alias-state-error-primary, #f85149)' : 'var(--dsw-alias-label-primary, #cccccc)'
+ // Cancelled/expired plans collapse to a minimal red card: no file list,
+ // no diffs, no buttons — nothing that a refresh could resurrect.
+ const collapsed = planStatus === 'cancelled' || planStatus === 'gone'
+ const showBody = expanded && !collapsed && (hasDiff || parsed.files.length > 0)
+ const actionable = parsed.planId !== undefined && state === 'ok' && !collapsed && (planStatus === null || planStatus === 'pending')
+ // A synchronous ref guard closes the re-render gap: React state updates
+ // land a tick later, so fast double-clicks would both pass a state-only
+ // check and fire two confirm requests.
+ const submittingRef = React.useRef(false)
+
+ async function submit(kind) {
+ if (submittingRef.current || submitted || !parsed.planId)
+ return
+ submittingRef.current = true
+ try {
+ const line = kind === 'confirm'
+ ? `/undo --confirm ${parsed.planId}`
+ : `/undo --cancel ${parsed.planId}`
+ const failure = submitLine ? await submitLine(line, ownerSessionId) : 'submit channel unavailable'
+ if (failure) {
+ // Keep the card actionable: the plan is still pending on the host,
+ // so the user must be able to retry (or cancel) after the failure.
+ setSubmitError(failure)
submittingRef.current = false
- setSubmitError(String(error?.message ?? error))
+ return
}
+ setSubmitted(kind)
+ // Only a server-confirmed cancel folds the card; an optimistic fold
+ // here would hide a still-pending plan behind a "已取消" label.
+ if (kind === 'cancel')
+ setPlanStatus('cancelled')
}
-
- const confirmLabel = submitted === 'confirm' ? '已提交执行确认' : '✓ 执行'
- const cancelLabel = submitted === 'cancel' ? '已取消' : '✕ 取消'
- const hint = submitError
- ? `执行确认失败:${submitError}`
- : resultText || (planStatus === 'applied' || submitted === 'confirm'
- ? '已提交,等待执行结果…'
- : planStatus === 'cancelled' || submitted === 'cancel' ? '已取消' : planStatus === 'gone' ? '该计划已过期,重新执行 /undo 可生成新预览' : '执行将恢复下方文件到本轮改动前')
- const hintColor = submitError
- ? 'var(--dsw-alias-state-error-primary, #f85149)'
- : resultText || planStatus === 'applied'
- ? 'var(--dsw-alias-state-success-primary, #3fb950)'
- : 'var(--dsw-alias-label-secondary, #333333)'
- // Buttons live only in the actionable footer; the outcome/error hint line
- // must survive after the plan settles, or the success note disappears.
- const showFooter = actionable || resultText !== null || submitError !== null || submitted !== null || planStatus === 'applied'
-
- // Cancelled/expired plans collapse to a frameless slim line, matching
- // the native tool-row look: no card frame, no body, no buttons.
- if (collapsed) {
- return jsxs('div', {
- style: { display: 'flex', alignItems: 'center', gap: 6, padding: '2px 12px 2px 4px', margin: '2px 0 2px 4px', fontSize: 13 },
- children: [
- jsx('span', { style: { color: 'var(--dsw-alias-label-dimmed, #8b8b8b)' }, children: '▸' }),
- jsx('span', { style: { color: 'var(--dsw-alias-label-secondary, #cccccc)' }, children: node.name || 'undo' }),
- jsx('span', { style: { color: 'var(--dsw-alias-label-dimmed, #8b8b8b)' }, children: '·' }),
- jsx('span', { style: { color: 'var(--dsw-alias-state-error-primary, #f85149)' }, children: hint }),
- ],
- })
+ catch (error) {
+ submittingRef.current = false
+ setSubmitError(String(error?.message ?? error))
}
+ }
+ const confirmLabel = submitted === 'confirm' ? '已提交执行确认' : '✓ 执行'
+ const cancelLabel = submitted === 'cancel' ? '已取消' : '✕ 取消'
+ const hint = submitError
+ ? `执行确认失败:${submitError}`
+ : resultText || (planStatus === 'applied' || submitted === 'confirm'
+ ? '已提交,等待执行结果…'
+ : planStatus === 'cancelled' || submitted === 'cancel' ? '已取消' : planStatus === 'gone' ? '该计划已过期,重新执行 /undo 可生成新预览' : '执行将恢复下方文件到本轮改动前')
+ const hintColor = submitError
+ ? 'var(--dsw-alias-state-error-primary, #f85149)'
+ : resultText || planStatus === 'applied'
+ ? 'var(--dsw-alias-state-success-primary, #3fb950)'
+ : 'var(--dsw-alias-label-secondary, #333333)'
+ // Buttons live only in the actionable footer; the outcome/error hint line
+ // must survive after the plan settles, or the success note disappears.
+ const showFooter = actionable || resultText !== null || submitError !== null || submitted !== null || planStatus === 'applied'
+
+ // Cancelled/expired plans collapse to a frameless slim line, matching
+ // the native tool-row look: no card frame, no body, no buttons.
+ if (collapsed) {
return jsxs('div', {
- style: { border: `1px solid ${DIFF_COLORS.border}`, background: 'var(--dsw-alias-bg-layer-1, transparent)', borderRadius: 12, margin: '4px 0 4px 4px', overflow: 'hidden', maxWidth: '100%' },
+ style: { display: 'flex', alignItems: 'center', gap: 6, padding: '2px 12px 2px 4px', margin: '2px 0 2px 4px', fontSize: 13 },
children: [
- jsxs('button', {
- type: 'button',
- onClick() { toggleExpanded() },
- style: { display: 'flex', alignItems: 'center', gap: 8, width: '100%', textAlign: 'left', background: 'transparent', border: 'none', cursor: 'pointer', padding: '8px 12px', color: titleColor, fontSize: 13 },
- children: [
- jsx('span', { style: { transform: expanded ? 'rotate(90deg)' : 'rotate(0deg)', transition: 'transform .12s', display: 'inline-block', color: 'var(--dsw-alias-label-tertiary, #8b8b8b)' }, children: '▸' }),
- jsx('span', { style: { fontWeight: 500 }, children: node.name || 'undo' }),
- jsx(NumBadge, { additions: totals.additions, deletions: totals.deletions }),
- jsx('span', { style: { color: 'var(--dsw-alias-label-secondary, #cccccc)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap', flex: 1, minWidth: 0 }, children: summary }),
- ],
- }),
- showBody
- ? jsx('div', { style: { borderTop: `1px solid ${DIFF_COLORS.border}`, padding: hasDiff ? '6px 10px 10px' : '6px 12px 10px' }, children:
- hasDiff
- ? withDiff.map(file => jsx(DiffBlock, { file }, file.path))
- : parsed.files.map(file => jsxs('div', { style: { display: 'flex', gap: 8, padding: '2px 0', fontFamily: 'var(--ds-font-family-code, monospace)', fontSize: 12 }, children: [
- jsx('span', { style: { color: 'var(--dsw-alias-label-tertiary, #8b8b8b)', width: 64, flex: 'none' }, children: file.change }),
- jsx('span', { children: file.path }),
- ] }, file.path)) })
- : null,
- showFooter
- ? jsxs('div', {
- style: { display: 'flex', alignItems: 'center', gap: 10, borderTop: `1px solid ${DIFF_COLORS.border}`, padding: '8px 12px' },
- children: [
- actionable
- ? jsxs('button', {
- type: 'button',
- onClick() { submit('confirm') },
- disabled: submitted !== null,
- style: { background: 'var(--dsw-alias-button-primary-fill, #4f46e5)', color: 'var(--dsw-alias-label-primary-foreground, #ffffff)', border: 'none', borderRadius: 8, padding: '5px 16px', fontSize: 12.5 },
- children: confirmLabel,
- })
- : null,
- actionable
- ? jsx('button', {
- type: 'button',
- onClick() { submit('cancel') },
- disabled: submitted !== null,
- style: { background: 'transparent', color: submitted === 'cancel' ? 'var(--dsw-alias-label-tertiary, #8b8b8b)' : 'var(--dsw-alias-state-error-primary, #f85149)', border: '1px solid var(--dsw-alias-border-l2, #30363d)', borderRadius: 8, padding: '5px 16px', fontSize: 12.5 },
- children: cancelLabel,
- })
- : null,
- jsx('span', { style: { flex: 1 } }),
- jsx('span', { style: { color: hintColor, fontSize: 11.5, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }, children: hint }),
- ],
- })
- : null,
+ jsx('span', { style: { color: 'var(--dsw-alias-label-dimmed, #8b8b8b)' }, children: '▸' }),
+ jsx('span', { style: { color: 'var(--dsw-alias-label-secondary, #cccccc)' }, children: node.name || 'undo' }),
+ jsx('span', { style: { color: 'var(--dsw-alias-label-dimmed, #8b8b8b)' }, children: '·' }),
+ jsx('span', { style: { color: 'var(--dsw-alias-state-error-primary, #f85149)' }, children: hint }),
],
})
}
- // ------------------------------------------------------------------
- // Unsupported-workspace dialog: storage, DOM, and runner.
- // ------------------------------------------------------------------
- const NS = 'dsh-tauri-turnrewind'
- const SEEN_KEY = 'turnrewind.seenUnsupportedNotices'
- const MAX_SEEN = 100
-
- const dictionaries = {
- zh: {
- title: '撤销功能在此工作区不可用',
- intro: '当前会话的工作区不支持文件撤销。对话照常运行,但本工作区内的文件改动无法用 /undo 撤销。',
- reason: '原因',
- ok: '知道了',
- },
- en: {
- title: 'Undo is unavailable in this workspace',
- intro: 'File undo is disabled for this session\'s workspace. Turns still run normally, but changes in this workspace cannot be reverted with /undo.',
- reason: 'Reason',
- ok: 'Got it',
- },
+ return jsxs('div', {
+ style: { border: `1px solid ${DIFF_COLORS.border}`, background: 'var(--dsw-alias-bg-layer-1, transparent)', borderRadius: 12, margin: '4px 0 4px 4px', overflow: 'hidden', maxWidth: '100%' },
+ children: [
+ jsxs('button', {
+ type: 'button',
+ onClick() { toggleExpanded() },
+ style: { display: 'flex', alignItems: 'center', gap: 8, width: '100%', textAlign: 'left', background: 'transparent', border: 'none', cursor: 'pointer', padding: '8px 12px', color: titleColor, fontSize: 13 },
+ children: [
+ jsx('span', { style: { transform: expanded ? 'rotate(90deg)' : 'rotate(0deg)', transition: 'transform .12s', display: 'inline-block', color: 'var(--dsw-alias-label-tertiary, #8b8b8b)' }, children: '▸' }),
+ jsx('span', { style: { fontWeight: 500 }, children: node.name || 'undo' }),
+ jsx(NumBadge, { additions: totals.additions, deletions: totals.deletions }),
+ jsx('span', { style: { color: 'var(--dsw-alias-label-secondary, #cccccc)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap', flex: 1, minWidth: 0 }, children: summary }),
+ ],
+ }),
+ showBody
+ ? jsx('div', { style: { borderTop: `1px solid ${DIFF_COLORS.border}`, padding: hasDiff ? '6px 10px 10px' : '6px 12px 10px' }, children:
+ hasDiff
+ ? withDiff.map(file => jsx(DiffBlock, { file }, file.path))
+ : parsed.files.map(file => jsxs('div', { style: { display: 'flex', gap: 8, padding: '2px 0', fontFamily: 'var(--ds-font-family-code, monospace)', fontSize: 12 }, children: [
+ jsx('span', { style: { color: 'var(--dsw-alias-label-tertiary, #8b8b8b)', width: 64, flex: 'none' }, children: file.change }),
+ jsx('span', { children: file.path }),
+ ] }, file.path)) })
+ : null,
+ showFooter
+ ? jsxs('div', {
+ style: { display: 'flex', alignItems: 'center', gap: 10, borderTop: `1px solid ${DIFF_COLORS.border}`, padding: '8px 12px' },
+ children: [
+ actionable
+ ? jsxs('button', {
+ type: 'button',
+ onClick() { submit('confirm') },
+ disabled: submitted !== null,
+ style: { background: 'var(--dsw-alias-button-primary-fill, #4f46e5)', color: 'var(--dsw-alias-label-primary-foreground, #ffffff)', border: 'none', borderRadius: 8, padding: '5px 16px', fontSize: 12.5 },
+ children: confirmLabel,
+ })
+ : null,
+ actionable
+ ? jsx('button', {
+ type: 'button',
+ onClick() { submit('cancel') },
+ disabled: submitted !== null,
+ style: { background: 'transparent', color: submitted === 'cancel' ? 'var(--dsw-alias-label-tertiary, #8b8b8b)' : 'var(--dsw-alias-state-error-primary, #f85149)', border: '1px solid var(--dsw-alias-border-l2, #30363d)', borderRadius: 8, padding: '5px 16px', fontSize: 12.5 },
+ children: cancelLabel,
+ })
+ : null,
+ jsx('span', { style: { flex: 1 } }),
+ jsx('span', { style: { color: hintColor, fontSize: 11.5, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }, children: hint }),
+ ],
+ })
+ : null,
+ ],
+ })
+ }
+
+ // ------------------------------------------------------------------
+ // Unsupported-workspace dialog: storage, DOM, and runner.
+ // ------------------------------------------------------------------
+ const NS = 'dsh-tauri-turnrewind'
+ const SEEN_KEY = 'turnrewind.seenUnsupportedNotices'
+ const MAX_SEEN = 100
+
+ const dictionaries = {
+ zh: {
+ title: '撤销功能在此工作区不可用',
+ intro: '当前会话的工作区不支持文件撤销。对话照常运行,但本工作区内的文件改动无法用 /undo 撤销。',
+ reason: '原因',
+ ok: '知道了',
+ },
+ en: {
+ title: 'Undo is unavailable in this workspace',
+ intro: 'File undo is disabled for this session\'s workspace. Turns still run normally, but changes in this workspace cannot be reverted with /undo.',
+ reason: 'Reason',
+ ok: 'Got it',
+ },
+ }
+
+ function readSeen() {
+ try {
+ const raw = globalThis.localStorage.getItem(SEEN_KEY)
+ const list = raw ? JSON.parse(raw) : []
+ return Array.isArray(list) ? list : []
}
-
- function readSeen() {
- try {
- const raw = globalThis.localStorage.getItem(SEEN_KEY)
- const list = raw ? JSON.parse(raw) : []
- return Array.isArray(list) ? list : []
- }
- catch {
- return []
- }
+ catch {
+ return []
}
+ }
- function markSeen(id) {
- try {
- const seen = readSeen().filter(entry => entry !== id)
- seen.push(id)
- globalThis.localStorage.setItem(SEEN_KEY, JSON.stringify(seen.slice(-MAX_SEEN)))
- }
- catch {
- // Storage may be unavailable; the dialog just re-shows next reload.
- }
+ function markSeen(id) {
+ try {
+ const seen = readSeen().filter(entry => entry !== id)
+ seen.push(id)
+ globalThis.localStorage.setItem(SEEN_KEY, JSON.stringify(seen.slice(-MAX_SEEN)))
}
+ catch {
+ // Storage may be unavailable; the dialog just re-shows next reload.
+ }
+ }
- let dialog
-
- function ensureDialog() {
- if (dialog)
- return dialog
- // Colors are app theme tokens (with hardcoded fallbacks), so the dialog
- // follows the in-app light/dark theme live — inline `var()` re-resolves
- // when the theme switches, no rebuild needed.
- const backdrop = document.createElement('div')
- backdrop.setAttribute('role', 'presentation')
- Object.assign(backdrop.style, {
- display: 'none',
- position: 'fixed',
- inset: '0',
- zIndex: '2147483000',
- alignItems: 'center',
- justifyContent: 'center',
- background: 'var(--dsw-alias-bg-mask-1, rgba(0, 0, 0, 0.45))',
- })
-
- const card = document.createElement('div')
- card.setAttribute('role', 'dialog')
- card.setAttribute('aria-modal', 'true')
- Object.assign(card.style, {
- maxWidth: '440px',
- width: 'calc(100vw - 48px)',
- boxSizing: 'border-box',
- background: 'var(--dsw-alias-bg-layer-1, #ffffff)',
- color: 'var(--dsw-alias-label-primary, #111111)',
- border: '1px solid var(--dsw-alias-border-l2, #e5e5e5)',
- borderRadius: '12px',
- padding: '20px 22px',
- fontFamily: 'inherit',
- fontSize: '13px',
- lineHeight: '1.6',
- boxShadow: '0 20px 50px rgba(0, 0, 0, 0.25)',
- })
-
- const title = document.createElement('div')
- Object.assign(title.style, {
- fontSize: '15px',
- fontWeight: '600',
- marginBottom: '10px',
- color: 'var(--dsw-alias-state-error-primary, #d03050)',
- })
-
- const intro = document.createElement('div')
- Object.assign(intro.style, { color: 'var(--dsw-alias-label-secondary, #333333)' })
-
- const reasonLabel = document.createElement('div')
- Object.assign(reasonLabel.style, { marginTop: '12px', color: 'var(--dsw-alias-label-tertiary, #8b8b8b)', fontSize: '12px' })
-
- const reasonBox = document.createElement('div')
- Object.assign(reasonBox.style, {
- marginTop: '6px',
- padding: '8px 10px',
- borderRadius: '8px',
- background: 'var(--dsw-alias-bg-layer-2, #f5f5f5)',
- border: '1px solid var(--dsw-alias-border-l2, #e5e5e5)',
- wordBreak: 'break-all',
- whiteSpace: 'pre-wrap',
- maxHeight: '160px',
- overflowY: 'auto',
- })
-
- const actions = document.createElement('div')
- Object.assign(actions.style, { marginTop: '16px', textAlign: 'right' })
- const button = document.createElement('button')
- button.type = 'button'
- Object.assign(button.style, {
- background: 'var(--dsw-alias-button-primary-fill, #4f46e5)',
- color: 'var(--dsw-alias-label-primary-foreground, #ffffff)',
- border: 'none',
- borderRadius: '8px',
- padding: '6px 18px',
- fontSize: '13px',
- cursor: 'pointer',
- })
- button.addEventListener('mouseover', () => {
- button.style.background = 'var(--dsw-alias-button-primary-hover, #4338ca)'
- })
- button.addEventListener('mouseout', () => {
- button.style.background = 'var(--dsw-alias-button-primary-fill, #4f46e5)'
- })
- actions.appendChild(button)
-
- card.append(title, intro, reasonLabel, reasonBox, actions)
- backdrop.appendChild(card)
- document.body.appendChild(backdrop)
-
- function hide() {
- backdrop.style.display = 'none'
- }
- button.addEventListener('click', hide)
- backdrop.addEventListener('click', (event) => {
- if (event.target === backdrop)
- hide()
- })
+ let dialog
- dialog = { backdrop, title, intro, reasonLabel, reasonBox, button }
+ function ensureDialog() {
+ if (dialog)
return dialog
+ // Colors are app theme tokens (with hardcoded fallbacks), so the dialog
+ // follows the in-app light/dark theme live — inline `var()` re-resolves
+ // when the theme switches, no rebuild needed.
+ const backdrop = document.createElement('div')
+ backdrop.setAttribute('role', 'presentation')
+ Object.assign(backdrop.style, {
+ display: 'none',
+ position: 'fixed',
+ inset: '0',
+ zIndex: '2147483000',
+ alignItems: 'center',
+ justifyContent: 'center',
+ background: 'var(--dsw-alias-bg-mask-1, rgba(0, 0, 0, 0.45))',
+ })
+
+ const card = document.createElement('div')
+ card.setAttribute('role', 'dialog')
+ card.setAttribute('aria-modal', 'true')
+ Object.assign(card.style, {
+ maxWidth: '440px',
+ width: 'calc(100vw - 48px)',
+ boxSizing: 'border-box',
+ background: 'var(--dsw-alias-bg-layer-1, #ffffff)',
+ color: 'var(--dsw-alias-label-primary, #111111)',
+ border: '1px solid var(--dsw-alias-border-l2, #e5e5e5)',
+ borderRadius: '12px',
+ padding: '20px 22px',
+ fontFamily: 'inherit',
+ fontSize: '13px',
+ lineHeight: '1.6',
+ boxShadow: '0 20px 50px rgba(0, 0, 0, 0.25)',
+ })
+
+ const title = document.createElement('div')
+ Object.assign(title.style, {
+ fontSize: '15px',
+ fontWeight: '600',
+ marginBottom: '10px',
+ color: 'var(--dsw-alias-state-error-primary, #d03050)',
+ })
+
+ const intro = document.createElement('div')
+ Object.assign(intro.style, { color: 'var(--dsw-alias-label-secondary, #333333)' })
+
+ const reasonLabel = document.createElement('div')
+ Object.assign(reasonLabel.style, { marginTop: '12px', color: 'var(--dsw-alias-label-tertiary, #8b8b8b)', fontSize: '12px' })
+
+ const reasonBox = document.createElement('div')
+ Object.assign(reasonBox.style, {
+ marginTop: '6px',
+ padding: '8px 10px',
+ borderRadius: '8px',
+ background: 'var(--dsw-alias-bg-layer-2, #f5f5f5)',
+ border: '1px solid var(--dsw-alias-border-l2, #e5e5e5)',
+ wordBreak: 'break-all',
+ whiteSpace: 'pre-wrap',
+ maxHeight: '160px',
+ overflowY: 'auto',
+ })
+
+ const actions = document.createElement('div')
+ Object.assign(actions.style, { marginTop: '16px', textAlign: 'right' })
+ const button = document.createElement('button')
+ button.type = 'button'
+ Object.assign(button.style, {
+ background: 'var(--dsw-alias-button-primary-fill, #4f46e5)',
+ color: 'var(--dsw-alias-label-primary-foreground, #ffffff)',
+ border: 'none',
+ borderRadius: '8px',
+ padding: '6px 18px',
+ fontSize: '13px',
+ cursor: 'pointer',
+ })
+ button.addEventListener('mouseover', () => {
+ button.style.background = 'var(--dsw-alias-button-primary-hover, #4338ca)'
+ })
+ button.addEventListener('mouseout', () => {
+ button.style.background = 'var(--dsw-alias-button-primary-fill, #4f46e5)'
+ })
+ actions.appendChild(button)
+
+ card.append(title, intro, reasonLabel, reasonBox, actions)
+ backdrop.appendChild(card)
+ document.body.appendChild(backdrop)
+
+ function hide() {
+ backdrop.style.display = 'none'
}
-
- function showDialog(t, notices) {
- const el = ensureDialog()
- el.title.textContent = t('title')
- el.intro.textContent = t('intro')
- el.reasonLabel.textContent = t('reason')
- el.reasonBox.textContent = notices.map(notice => notice.reason || notice.id).join('\n')
- el.button.textContent = t('ok')
- el.backdrop.style.display = 'flex'
- }
-
- // ------------------------------------------------------------------
- // Plugin apply: both features share the one cordis plugin this bundle
- // materializes into (the boot manifest imports the package name).
- // ------------------------------------------------------------------
- function apply(ctx) {
- console.warn('[turnrewind] client apply: command card + dialog runner starting')
-
- ctx.effect(() => {
- ctx.slots.inject('conversation.chat.commandview', () => {
- return ctx.slots.register({
- name: 'conversation.chat.commandview',
- key: 'undo',
- }, UndoCommandView)
- })
- }, 'turnrewind command view')
-
- // Unsupported-workspace heads-up runner.
- ctx.effect(() => ctx.locale.register(NS, dictionaries), 'turnrewind locale')
- const t = ctx.locale.bind(NS)
- // Read through the service store, not the ctx.sessions property proxy:
- // the host session service merges a different member under the same name.
- const sessions = ctx.get('sessions')
- // The ✓/✗ buttons post to the plugin's same-origin routes — the most
- // direct client→host channel (no gateway RPC, no auth wiring). Returns
- // an error string so the card can surface real failures instead of
- // silently swallowing an async rejection.
- submitLine = async (line) => {
+ button.addEventListener('click', hide)
+ backdrop.addEventListener('click', (event) => {
+ if (event.target === backdrop)
+ hide()
+ })
+
+ dialog = { backdrop, title, intro, reasonLabel, reasonBox, button }
+ return dialog
+ }
+
+ /**
+ * Tear the modal down: removing the backdrop subtree detaches every
+ * listener created in ensureDialog (they all live on nodes inside it), so a
+ * plugin stop/update/HMR cannot leak the dialog or its handlers. The next
+ * apply() builds a fresh dialog from scratch.
+ */
+ function disposeDialog() {
+ if (!dialog)
+ return
+ dialog.backdrop.remove()
+ dialog = undefined
+ }
+
+ function showDialog(t, notices) {
+ const el = ensureDialog()
+ el.title.textContent = t('title')
+ el.intro.textContent = t('intro')
+ el.reasonLabel.textContent = t('reason')
+ el.reasonBox.textContent = notices.map(notice => notice.reason || notice.id).join('\n')
+ el.button.textContent = t('ok')
+ el.backdrop.style.display = 'flex'
+ }
+
+ // ------------------------------------------------------------------
+ // Plugin apply: both features share the one cordis plugin this bundle
+ // materializes into (the boot manifest imports the package name).
+ // ------------------------------------------------------------------
+ function apply(ctx) {
+ console.warn('[turnrewind] client apply: command card + dialog runner starting')
+
+ // The inject disposer is the effect's owned cleanup: returning it lets the
+ // fiber unwind the declaration wait and any active registration on
+ // stop/update, instead of relying on incidental fiber collection.
+ ctx.effect(() => ctx.slots.inject('conversation.chat.commandview', () => {
+ return ctx.slots.register({
+ name: 'conversation.chat.commandview',
+ key: 'undo',
+ }, UndoCommandView)
+ }), 'turnrewind command view')
+
+ // Unsupported-workspace heads-up runner.
+ ctx.effect(() => ctx.locale.register(NS, dictionaries), 'turnrewind locale')
+ const t = ctx.locale.bind(NS)
+ // Read through the service store, not the ctx.sessions property proxy:
+ // the host session service merges a different member under the same name.
+ const sessions = ctx.get('sessions')
+ // The ✓/✗ buttons post to the plugin's same-origin routes — the most
+ // direct client→host channel (no gateway RPC, no auth wiring). Returns
+ // an error string so the card can surface real failures instead of
+ // silently swallowing an async rejection. The session id comes from the
+ // card's own session scope (never the global current selection); the
+ // Host re-validates it against the plan's owner session either way.
+ ctx.effect(() => {
+ submitLine = async (line, ownerSessionId) => {
try {
- const sessionId = sessions.list.getSnapshot().current
- if (sessionId === undefined)
- return 'no active session in the client session list'
+ if (typeof ownerSessionId !== 'string' || ownerSessionId.length === 0)
+ return '无法确定该卡片所属的会话,请刷新页面后重试'
const kind = line.includes('--confirm') ? 'confirm' : 'cancel'
const planId = line.split(' ').at(-1)
const res = await fetch(`/api/turnrewind/${kind}`, {
method: 'POST',
headers: { 'content-type': 'application/json' },
- body: JSON.stringify({ planId, sessionId }),
+ body: JSON.stringify({ planId, sessionId: ownerSessionId }),
})
const payload = await res.json().catch(() => ({}))
if (!res.ok)
@@ -594,36 +686,53 @@ globalThis.__ModuleLoader__.load({
return String(error?.message ?? error)
}
}
-
- function checkOnce() {
- const state = sessions.list.getSnapshot()
- const summary = state.current !== undefined ? state.byId[state.current] : undefined
- const value = summary?.projectionValues?.turnrewind
- const notices = Array.isArray(value?.notices) ? value.notices : []
- const fresh = notices.filter(notice => notice && typeof notice.id === 'string' && !readSeen().includes(notice.id))
- if (fresh.length === 0)
- return
- console.warn(`[turnrewind] unsupported heads-up visible: ${fresh.map(notice => notice.id).join(', ')}`)
- for (const notice of fresh) markSeen(notice.id)
- showDialog(t, fresh)
+ return () => {
+ submitLine = null
}
-
- ctx.effect(() => {
- const unsubscribe = sessions.list.subscribe(checkOnce)
- // Projection frames can land while the page is loading, before the list
- // store has any subscribers; poll briefly so that ordering can never
- // silently swallow the heads-up.
- const poll = setInterval(checkOnce, 2000)
- const stopPolling = setTimeout(clearInterval, 120000, poll)
- return () => {
- unsubscribe()
- clearInterval(poll)
- clearTimeout(stopPolling)
- }
- }, 'turnrewind dialog runner')
+ }, 'turnrewind submit line')
+
+ function checkOnce() {
+ const state = sessions.list.getSnapshot()
+ const summary = state.current !== undefined ? state.byId[state.current] : undefined
+ const value = summary?.projectionValues?.turnrewind
+ const notices = Array.isArray(value?.notices) ? value.notices : []
+ const fresh = notices.filter(notice => notice && typeof notice.id === 'string' && !readSeen().includes(notice.id))
+ if (fresh.length === 0)
+ return
+ console.warn(`[turnrewind] unsupported heads-up visible: ${fresh.map(notice => notice.id).join(', ')}`)
+ for (const notice of fresh) markSeen(notice.id)
+ showDialog(t, fresh)
}
- Object.assign(exports, { apply, inject, parseUndoOutput })
- return module.exports
- },
-})
+ ctx.effect(() => {
+ const unsubscribe = sessions.list.subscribe(checkOnce)
+ // Projection frames can land while the page is loading, before the list
+ // store has any subscribers; poll briefly so that ordering can never
+ // silently swallow the heads-up.
+ const poll = setInterval(checkOnce, 2000)
+ const stopPolling = setTimeout(clearInterval, 120000, poll)
+ return () => {
+ unsubscribe()
+ clearInterval(poll)
+ clearTimeout(stopPolling)
+ disposeDialog()
+ }
+ }, 'turnrewind dialog runner')
+ }
+
+ Object.assign(exports, { apply, inject, parseUndoOutput, resolveOwnerSessionId, resolvePlanStatus })
+ return module.exports
+}
+
+// Browser boot path: the DSH client module contract, unchanged.
+if (globalThis.__ModuleLoader__) {
+ globalThis.__ModuleLoader__.load({
+ id: 'dsh-tauri-turnrewind/client',
+ factory: createTurnrewindClient,
+ })
+}
+else {
+ // Node/test path: no module loader exists here, so expose the factory
+ // itself — pure helpers stay unit-testable without a browser.
+ globalThis.__turnrewindClientFactory = createTurnrewindClient
+}
diff --git a/plugins/dsh-tauri-turnrewind/lib/core/git-snapshot.js b/plugins/dsh-tauri-turnrewind/lib/core/git-snapshot.js
index f9c26a56..2c512cad 100644
--- a/plugins/dsh-tauri-turnrewind/lib/core/git-snapshot.js
+++ b/plugins/dsh-tauri-turnrewind/lib/core/git-snapshot.js
@@ -26,6 +26,7 @@ const EXCLUDE_PATHS = [
':(exclude,glob)**/coverage/**',
':(exclude,glob).turnrewind/**',
':(exclude,glob)**/.turnrewind/**',
+ ':(exclude,glob)**/*.turnrewind-*.tmp',
':(exclude,glob).env',
':(exclude,glob)**/.env',
':(exclude,glob).env.*',
@@ -34,8 +35,30 @@ const EXCLUDE_PATHS = [
':(exclude,glob)**/*.key',
':(exclude,glob)id_rsa*',
':(exclude,glob)**/id_rsa*',
- ':(exclude,glob)credentials.*',
- ':(exclude,glob)secrets.*',
+ ':(exclude,glob)credentials.json',
+ ':(exclude,glob)**/credentials.json',
+ ':(exclude,glob)credentials.yaml',
+ ':(exclude,glob)**/credentials.yaml',
+ ':(exclude,glob)credentials.yml',
+ ':(exclude,glob)**/credentials.yml',
+ ':(exclude,glob)credentials.toml',
+ ':(exclude,glob)**/credentials.toml',
+ ':(exclude,glob)credentials.ini',
+ ':(exclude,glob)**/credentials.ini',
+ ':(exclude,glob)credentials.cfg',
+ ':(exclude,glob)**/credentials.cfg',
+ ':(exclude,glob)secrets.json',
+ ':(exclude,glob)**/secrets.json',
+ ':(exclude,glob)secrets.yaml',
+ ':(exclude,glob)**/secrets.yaml',
+ ':(exclude,glob)secrets.yml',
+ ':(exclude,glob)**/secrets.yml',
+ ':(exclude,glob)secrets.toml',
+ ':(exclude,glob)**/secrets.toml',
+ ':(exclude,glob)secrets.ini',
+ ':(exclude,glob)**/secrets.ini',
+ ':(exclude,glob)secrets.cfg',
+ ':(exclude,glob)**/secrets.cfg',
]
/**
@@ -151,8 +174,17 @@ function assertSafePath(workspaceDir, path) {
const suffix = relative(root, target)
for (const part of suffix.split(sep).filter(Boolean)) {
current = join(current, part)
- if (existsSync(current) && lstatSync(current).isSymbolicLink()) {
- throw new Error(`TURNREWIND_SYMLINK_UNSUPPORTED: ${path}`)
+ // lstatSync must be used without an existsSync pre-check: existsSync
+ // returns false for dangling links, but a dangling link is still an unsafe
+ // path component and must never be replaced or traversed.
+ try {
+ if (lstatSync(current).isSymbolicLink())
+ throw new Error(`TURNREWIND_SYMLINK_UNSUPPORTED: ${path}`)
+ }
+ catch (error) {
+ if (error?.code === 'ENOENT' || error?.code === 'ENOTDIR')
+ continue
+ throw error
}
}
return target
@@ -162,10 +194,18 @@ function snapshotPathspecs() {
return EXCLUDE_PATHS
}
-export function workspaceHash(workspaceDir) {
+/**
+ * Canonical workspace identity shared by the ledger key, the snapshot repo
+ * hash and maintenance purges: case-folded only on case-insensitive platforms,
+ * so Unix paths differing in case stay distinct while Windows paths unify.
+ */
+export function workspaceKey(workspaceDir) {
const normalized = resolve(workspaceDir)
- const identity = process.platform === 'win32' ? normalized.toLowerCase() : normalized
- return createHash('sha256').update(identity).digest('hex').slice(0, 24)
+ return process.platform === 'win32' ? normalized.toLowerCase() : normalized
+}
+
+export function workspaceHash(workspaceDir) {
+ return createHash('sha256').update(workspaceKey(workspaceDir)).digest('hex').slice(0, 24)
}
/** Pure path computation; the repository itself is ensured lazily on capture. */
@@ -182,13 +222,16 @@ function isExcludedPath(relPath, isDir) {
const base = basename(relPath)
if (isDir)
return EXCLUDE_DIRS.has(base)
+ if (/\.turnrewind-[0-9a-f-]+\.tmp$/iu.test(base))
+ return true
// Files excluded by EXCLUDE_PATHS: .env, .env.*, *.pem, *.key, id_rsa*,
- // credentials.*, secrets.*
+ // and high-confidence structured credentials/secrets files. Keep source and
+ // documentation files such as credentials.module.ts trackable.
if (/^\.env(?:$|\.)/.test(base))
return true
if (/\.(?:pem|key)$/i.test(base))
return true
- if (base.startsWith('id_rsa') || /^credentials\./.test(base) || /^secrets\./.test(base))
+ if (base.startsWith('id_rsa') || /^(?:credentials|secrets)\.(?:json|ya?ml|toml|ini|cfg)$/i.test(base))
return true
return false
}
@@ -309,8 +352,8 @@ export async function captureSnapshot(store, refName, message, parentRef) {
}
export async function snapshotDiff(store, beforeCommit, afterCommit) {
- const output = await runGit(store.repoDir, store.workspaceDir, ['diff', '--name-only', '--no-renames', beforeCommit, afterCommit])
- return [...new Set(output.toString('utf8').split(/\r?\n/).map(value => value.trim()).filter(Boolean))]
+ const output = await runGit(store.repoDir, store.workspaceDir, ['diff', '--name-only', '-z', '--no-renames', beforeCommit, afterCommit])
+ return [...new Set(output.toString('utf8').split('\0').filter(Boolean))]
}
const DEFAULT_MAX_DIFF_LINES = 120
@@ -417,8 +460,8 @@ export async function diffAgainstDisk(store, commit, path, maxLines) {
}
async function commitEntry(store, commit, path) {
- const output = await runGit(store.repoDir, store.workspaceDir, ['ls-tree', '-r', '--name-only', commit, '--', path])
- return output.toString('utf8').split(/\r?\n/).includes(path)
+ const output = await runGit(store.repoDir, store.workspaceDir, ['ls-tree', '-r', '--name-only', '-z', commit, '--', path])
+ return output.toString('utf8').split('\0').includes(path)
}
async function commitBytes(store, commit, path) {
diff --git a/plugins/dsh-tauri-turnrewind/lib/core/ledger.js b/plugins/dsh-tauri-turnrewind/lib/core/ledger.js
index 71aadf27..3e42f241 100644
--- a/plugins/dsh-tauri-turnrewind/lib/core/ledger.js
+++ b/plugins/dsh-tauri-turnrewind/lib/core/ledger.js
@@ -107,6 +107,7 @@ export function openLedger(rootDir) {
// Column already exists.
}
db.exec(`UPDATE turns SET status = 'abandoned', reversible = 0, error = 'plugin restarted during active turn' WHERE status = 'active'`)
+ db.prepare(`UPDATE operations SET outcome = 'needs-recovery', settled_at = COALESCE(settled_at, ?), error = 'plugin restarted while the operation was applying; workspace recovery is required' WHERE outcome = 'applying'`).run(new Date().toISOString())
purgeExpiredPendingPlans(db)
return db
}
@@ -133,7 +134,7 @@ export function createPendingPlan(db, plan) {
// One live plan per session+workspace: a newer preview replaces the older.
db.prepare('DELETE FROM pending_plans WHERE session_id = ? AND workspace_key = ?')
.run(plan.sessionId, plan.workspaceKey)
- const planId = randomUUID().slice(0, 8)
+ const planId = randomUUID()
const createdAt = new Date().toISOString()
db.prepare(`
INSERT INTO pending_plans(plan_id, session_id, workspace_key, turn_id, paths_json, created_at, expires_at)
@@ -156,12 +157,47 @@ export function getPendingPlan(db, planId, sessionId, workspaceKey) {
if (row === undefined)
return undefined
if (row.expires_at < new Date().toISOString()) {
- db.prepare('DELETE FROM pending_plans WHERE plan_id = ?').run(planId)
+ db.prepare('DELETE FROM pending_plans WHERE plan_id = ? AND status = \'pending\'').run(planId)
return undefined
}
return { turnId: row.turn_id, paths: JSON.parse(row.paths_json), createdAt: row.created_at }
}
+/**
+ * Atomically move one pending plan to `applying` so concurrent confirm/cancel
+ * calls cannot interleave: the conditional UPDATE is serialized by SQLite, so
+ * exactly one caller sees changes === 1 and everyone else gets a deterministic
+ * failure. The pre-reads only pick a precise error code; the UPDATE decides.
+ */
+export function claimPendingPlan(db, planId, sessionId) {
+ const row = db.prepare('SELECT * FROM pending_plans WHERE plan_id = ?').get(planId)
+ if (row === undefined)
+ return { ok: false, code: 404, error: 'plan expired or already applied — run /undo again' }
+ if (row.session_id !== sessionId)
+ return { ok: false, code: 403, error: 'the plan belongs to another session' }
+ if (row.status !== 'pending')
+ return { ok: false, code: 409, error: 'this plan was already applied, cancelled, or is being applied — run /undo again' }
+ if (row.expires_at < new Date().toISOString()) {
+ db.prepare('DELETE FROM pending_plans WHERE plan_id = ? AND status = \'pending\'').run(planId)
+ return { ok: false, code: 404, error: 'plan expired or already applied — run /undo again' }
+ }
+ const claimed = db.prepare(`
+ UPDATE pending_plans SET status = 'applying'
+ WHERE plan_id = ? AND session_id = ? AND status = 'pending'
+ `).run(planId, sessionId)
+ if (claimed.changes !== 1)
+ return { ok: false, code: 409, error: 'this plan was already applied, cancelled, or is being applied — run /undo again' }
+ return { ok: true, row: { ...row, paths: JSON.parse(row.paths_json) } }
+}
+
+/** Return an in-flight claim to `pending` after a failed confirm attempt. */
+export function releasePendingPlanClaim(db, planId) {
+ db.prepare(`
+ UPDATE pending_plans SET status = 'pending'
+ WHERE plan_id = ? AND status = 'applying'
+ `).run(planId)
+}
+
/**
* Plan lookup for the confirm HTTP route: keyed by plan id only — the client
* does not know the workspace key, the row itself carries it (and the owner
@@ -171,8 +207,8 @@ export function getPendingPlanRow(db, planId) {
const row = db.prepare('SELECT * FROM pending_plans WHERE plan_id = ?').get(planId)
if (row === undefined)
return undefined
- if (row.expires_at < new Date().toISOString()) {
- db.prepare('DELETE FROM pending_plans WHERE plan_id = ?').run(planId)
+ if (row.status === 'pending' && row.expires_at < new Date().toISOString()) {
+ db.prepare('DELETE FROM pending_plans WHERE plan_id = ? AND status = \'pending\'').run(planId)
return undefined
}
return { ...row, paths: JSON.parse(row.paths_json) }
@@ -194,17 +230,17 @@ export function markPendingPlanCancelled(db, planId, sessionId) {
return result.changes > 0
}
-/** Outcome written by the confirm route so the client card can poll it. */
+/** Outcome written by the confirm route so the client card can poll it. Only a claimed (`applying`) plan can be applied. */
export function markPendingPlanApplied(db, planId, sessionId, message) {
db.prepare(`
UPDATE pending_plans SET status = 'applied', result_text = ?
- WHERE plan_id = ? AND session_id = ? AND status = 'pending'
+ WHERE plan_id = ? AND session_id = ? AND status = 'applying'
`).run(message, planId, sessionId)
}
/** Poll face for the client card: undefined once purged, else the outcome. */
-export function getPendingPlanStatus(db, planId) {
- const row = db.prepare('SELECT status, result_text, expires_at FROM pending_plans WHERE plan_id = ?').get(planId)
+export function getPendingPlanStatus(db, planId, sessionId) {
+ const row = db.prepare('SELECT status, result_text, expires_at FROM pending_plans WHERE plan_id = ? AND session_id = ?').get(planId, sessionId)
if (row === undefined)
return undefined
if (row.status === 'pending' && row.expires_at < new Date().toISOString()) {
@@ -392,6 +428,15 @@ export function claimRewindNotices(db, sessionId, workspaceKey) {
}))
}
+export function listNeedsRecoveryWorkspaces(db) {
+ return db.prepare(`
+ SELECT DISTINCT t.workspace_key
+ FROM operations o
+ JOIN turns t ON t.turn_id = o.target_turn_id
+ WHERE o.outcome = 'needs-recovery'
+ `).all().map(row => row.workspace_key)
+}
+
export function getLatestAppliedUndo(db, sessionId, workspaceKey) {
return db.prepare(`
SELECT o.* FROM operations o
diff --git a/plugins/dsh-tauri-turnrewind/lib/core/maintenance.js b/plugins/dsh-tauri-turnrewind/lib/core/maintenance.js
index 25116d68..8d0a97df 100644
--- a/plugins/dsh-tauri-turnrewind/lib/core/maintenance.js
+++ b/plugins/dsh-tauri-turnrewind/lib/core/maintenance.js
@@ -2,7 +2,7 @@ import { existsSync, rmSync } from 'node:fs'
import { homedir } from 'node:os'
import { join, resolve } from 'node:path'
import process from 'node:process'
-import { workspaceHash } from './git-snapshot.js'
+import { workspaceHash, workspaceKey } from './git-snapshot.js'
import { openLedger } from './ledger.js'
export function resolveRootDir(explicit) {
@@ -18,7 +18,7 @@ export function resolveRootDir(explicit) {
* existed (for example a 250 GB home directory).
*/
export function purgeWorkspace(rootDir, workspaceDir) {
- const workspaceKey = resolve(workspaceDir).toLowerCase()
+ const workspaceIdentity = workspaceKey(workspaceDir)
const repoDir = join(rootDir, 'snapshots', `${workspaceHash(workspaceDir)}.git`)
const summary = { rootDir, repoDir, repoExisted: false, ledger: undefined }
@@ -27,10 +27,10 @@ export function purgeWorkspace(rootDir, workspaceDir) {
const db = openLedger(rootDir)
try {
db.exec('BEGIN')
- const operations = db.prepare('DELETE FROM operations WHERE target_turn_id IN (SELECT turn_id FROM turns WHERE workspace_key = ?)').run(workspaceKey)
- const notices = db.prepare('DELETE FROM rewind_notices WHERE workspace_key = ?').run(workspaceKey)
- const turns = db.prepare('DELETE FROM turns WHERE workspace_key = ?').run(workspaceKey)
- const workspaces = db.prepare('DELETE FROM workspaces WHERE workspace_key = ?').run(workspaceKey)
+ const operations = db.prepare('DELETE FROM operations WHERE target_turn_id IN (SELECT turn_id FROM turns WHERE workspace_key = ?)').run(workspaceIdentity)
+ const notices = db.prepare('DELETE FROM rewind_notices WHERE workspace_key = ?').run(workspaceIdentity)
+ const turns = db.prepare('DELETE FROM turns WHERE workspace_key = ?').run(workspaceIdentity)
+ const workspaces = db.prepare('DELETE FROM workspaces WHERE workspace_key = ?').run(workspaceIdentity)
db.exec('COMMIT')
summary.ledger = {
operations: operations.changes,
diff --git a/plugins/dsh-tauri-turnrewind/lib/index.js b/plugins/dsh-tauri-turnrewind/lib/index.js
index 82a1ed06..13ab9804 100644
--- a/plugins/dsh-tauri-turnrewind/lib/index.js
+++ b/plugins/dsh-tauri-turnrewind/lib/index.js
@@ -1,11 +1,12 @@
-import { randomUUID } from 'node:crypto'
+import { Buffer } from 'node:buffer'
+import { createHash, randomUUID } from 'node:crypto'
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 } from './core/git-snapshot.js'
+import { captureSnapshot, classifyPathChange, createSnapshotStore, currentState, diffAgainstDisk, gitAvailable, gitRef, probeWorkspace, restorePath, snapshotDiff, snapshotFileDiff, stateAt, workspaceKey } from './core/git-snapshot.js'
import { assessWorkspace, defaultBudget } from './core/guard.js'
-import { claimRewindNotices, completeRedoWithNotice, completeUndoWithNotice, createOperation, createPendingPlan, failTurn, getLatestAppliedUndo, getLatestSnapshotRef, getLatestTurnSummary, getPendingPlan, getPendingPlanRow, getPendingPlanStatus, getTurn, insertTurn, listReversibleTurns, markPendingPlanApplied, markPendingPlanCancelled, markTurnSnapshotMissing, openLedger, recordSkippedTurn, registerWorkspace, 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, recordSkippedTurn, registerWorkspace, releasePendingPlanClaim, settleInterruptedTurn, settleNoopTurn, settleOperation, settleTurn, skipTurn } from './core/ledger.js'
import { classifyUndo } from './core/planner.js'
const name = 'dsh-tauri-turnrewind'
@@ -14,10 +15,13 @@ function rootDir() {
return process.env.DSH_HOME ? resolve(process.env.DSH_HOME) : join(homedir(), '.dsh')
}
-const TURN_ID_RE = /[^\w.-]/gu
+export function turnSnapshotRef(turnId, phase) {
+ const digest = createHash('sha256').update(turnId).digest('hex').slice(0, 32)
+ return `refs/turnrewind/turn-${digest}-${phase}`
+}
function refSuffix(turnId, phase) {
- return `refs/turnrewind/turn-${turnId.replace(TURN_ID_RE, '_')}-${phase}`
+ return turnSnapshotRef(turnId, phase)
}
function workspaceForAgent(agent) {
@@ -38,7 +42,7 @@ function workspaceForSession(session) {
}
function workspaceKeyFor(path) {
- return path.toLowerCase()
+ return workspaceKey(path)
}
function workspaceIssue(workspaceDir) {
@@ -278,6 +282,14 @@ function workspaceHasActiveTurn(active, workspaceKey) {
return false
}
+function workspaceHasActiveTurnForOtherSession(active, workspaceKey, sessionId) {
+ for (const entry of active.values()) {
+ if (entry.workspaceKey === workspaceKey && entry.sessionId !== sessionId)
+ return true
+ }
+ return false
+}
+
async function settleActiveTurn(ledger, active, key, reason) {
const current = active.get(key)
if (!current || current.runtime.disposed)
@@ -387,6 +399,8 @@ async function applyRedo(runtime, invocation, workspaceDir, workspaceKey) {
* POST-only JSON in / JSON out, mutation routes restricted to loopback peers
* (the harness web UI itself is served on this host, so its page qualifies).
*/
+const MAX_ROUTE_BODY_BYTES = 16 * 1024
+
function jsonRoute(path, handler, { mutate = false } = {}) {
return {
kind: 'exact',
@@ -397,11 +411,29 @@ function jsonRoute(path, handler, { mutate = false } = {}) {
res.writeHead(code, { 'content-type': 'application/json; charset=utf-8' })
res.end(body)
}
+ if (mutate && req.method !== 'POST') {
+ res.setHeader('allow', 'POST')
+ return send(405, { error: 'mutation routes require POST' })
+ }
const parts = []
- req.on('data', chunk => parts.push(typeof chunk === 'string' ? chunk : chunk.toString('utf8')))
+ let totalBytes = 0
+ let tooLarge = false
+ req.on('data', (chunk) => {
+ if (tooLarge)
+ return
+ const value = typeof chunk === 'string' ? chunk : chunk.toString('utf8')
+ totalBytes += Buffer.byteLength(value, 'utf8')
+ if (totalBytes > MAX_ROUTE_BODY_BYTES) {
+ tooLarge = true
+ return
+ }
+ parts.push(value)
+ })
req.on('error', () => send(400, { error: 'request stream failed' }))
req.on('end', () => {
void (async () => {
+ if (tooLarge)
+ return send(413, { error: 'request body too large' })
if (mutate) {
const peer = req.socket?.remoteAddress ?? ''
const loopback = peer === '127.0.0.1' || peer === '::1' || peer === '::ffff:127.0.0.1'
@@ -522,13 +554,29 @@ async function applyUndo(runtime, active, invocation) {
let target
let pendingPlan
+ let pendingPlanClaimed = false
+ let pendingPlanCommitted = false
+ function abortPendingPlanClaim() {
+ if (pendingPlanClaimed) {
+ releasePendingPlanClaim(runtime.db, parsed.turnId)
+ pendingPlanClaimed = false
+ }
+ runtime.undoing = false
+ }
if (parsed.confirm) {
- pendingPlan = getPendingPlan(runtime.db, parsed.turnId, invocation.agent.session.id, workspaceKey)
- if (!pendingPlan)
- return { kind: 'error', text: `No pending undo plan ${parsed.turnId} for this session (it expired after 5 minutes, was replaced by a newer preview, or already ran). Run /undo again to preview a fresh plan.` }
+ const claim = claimPendingPlan(runtime.db, parsed.turnId, invocation.agent.session.id)
+ if (!claim.ok)
+ return { kind: 'error', text: claim.error }
+ pendingPlanClaimed = true
+ // Reserve the workspace before the first await so another confirm route
+ // cannot start a concurrent restore during snapshot validation.
+ runtime.undoing = true
+ pendingPlan = { turnId: claim.row.turn_id, paths: claim.row.paths, createdAt: claim.row.created_at }
target = getTurn(runtime.db, pendingPlan.turnId)
- if (!target || !await turnRefsExist(runtime.store, target))
+ if (!target || !await turnRefsExist(runtime.store, target)) {
+ abortPendingPlanClaim()
return { kind: 'error', text: 'The pending plan\u0027s snapshot data no longer exists. Run /undo again to preview a fresh plan.' }
+ }
}
else if (parsed.turnId) {
target = getTurn(runtime.db, parsed.turnId)
@@ -558,19 +606,29 @@ async function applyUndo(runtime, active, invocation) {
return { kind: 'error', text: `No reversible turn was found for this session.${detail}` }
}
const ownershipError = assertSessionOwner(target, invocation.agent)
- if (ownershipError)
+ if (ownershipError) {
+ abortPendingPlanClaim()
return ownershipError
- if (target.workspace_key !== workspaceKey)
+ }
+ if (target.workspace_key !== workspaceKey) {
+ abortPendingPlanClaim()
return { kind: 'error', text: 'The selected turn belongs to another workspace.' }
+ }
if (!['settled', 'interrupted'].includes(target.status) || target.reversible !== 1 || !target.before_ref || !target.after_ref) {
+ abortPendingPlanClaim()
return { kind: 'error', text: 'The selected turn does not have a complete reversible snapshot.' }
}
runtime.undoing = true
try {
const paths = await snapshotDiff(runtime.store, target.before_ref, target.after_ref)
- if (paths.length === 0)
+ if (paths.length === 0) {
+ if (pendingPlanClaimed) {
+ markPendingPlanApplied(runtime.db, parsed.turnId, invocation.agent.session.id, 'No file changes were recorded for this turn.')
+ pendingPlanCommitted = true
+ }
return { kind: 'success', text: 'No file changes were recorded for this turn.' }
+ }
const entries = await buildPlanEntries(runtime, workspaceDir, target, paths)
const conflicts = entries.filter(entry => entry.conflict)
@@ -602,8 +660,10 @@ async function applyUndo(runtime, active, invocation) {
// Confirmed execution: re-verify nothing changed on disk since the
// preview before overwriting anything.
- if (parsed.confirm && conflicts.length > 0)
+ if (parsed.confirm && conflicts.length > 0) {
+ abortPendingPlanClaim()
return { kind: 'error', text: `The workspace changed since the preview (${conflicts.length} conflicted file(s)). Run /undo again to refresh the plan; use --force/--skip-conflicts deliberately if needed.` }
+ }
try {
const text = await executeUndoRestore(runtime, {
@@ -614,8 +674,10 @@ async function applyUndo(runtime, active, invocation) {
entries,
skipConflicts: parsed.skipConflicts,
})
- if (parsed.confirm)
+ if (parsed.confirm) {
markPendingPlanApplied(runtime.db, parsed.turnId, invocation.agent.session.id, text)
+ pendingPlanCommitted = true
+ }
return { kind: 'success', text }
}
catch (error) {
@@ -623,7 +685,10 @@ async function applyUndo(runtime, active, invocation) {
}
}
finally {
- runtime.undoing = false
+ if (pendingPlanClaimed && !pendingPlanCommitted)
+ abortPendingPlanClaim()
+ else
+ runtime.undoing = false
}
}
@@ -649,6 +714,7 @@ function apply(ctx, config = {}) {
}, config.guard)
const dataRoot = rootDir()
const ledger = openLedger(dataRoot)
+ const recoveryWorkspaces = new Set(listNeedsRecoveryWorkspaces(ledger))
const active = new Map()
const untrackedTurns = new Set()
const workspaceStores = new Map()
@@ -671,19 +737,24 @@ function apply(ctx, config = {}) {
const sessionId = String(body.sessionId ?? '')
if (planId === '' || sessionId === '')
return [400, { error: 'planId and sessionId are required' }]
- const row = getPendingPlanRow(ledger, planId)
- if (row === undefined)
+ const previewRow = getPendingPlanRow(ledger, planId)
+ if (previewRow === undefined)
return [404, { error: 'plan expired or already applied — run /undo again' }]
- if (row.session_id !== sessionId)
+ if (previewRow.session_id !== sessionId)
return [403, { error: 'the plan belongs to another session' }]
- if (row.status !== 'pending')
+ if (previewRow.status !== 'pending')
return [409, { error: 'this plan was already applied or cancelled — run /undo again' }]
- const planRuntime = workspaceStores.get(row.workspace_key)
+ const planRuntime = workspaceStores.get(previewRow.workspace_key)
if (planRuntime === undefined)
return [409, { error: 'the host restarted since this preview; run /undo again' }]
- if (planRuntime.undoing || workspaceHasActiveTurn(active, row.workspace_key))
+ if (planRuntime.undoing || workspaceHasActiveTurn(active, previewRow.workspace_key))
return [409, { error: 'the workspace is busy — wait for the current turn to finish' }]
+ const claim = claimPendingPlan(ledger, planId, sessionId)
+ if (!claim.ok)
+ return [claim.code, { error: claim.error }]
+ const row = claim.row
planRuntime.undoing = true
+ let committed = false
return (async () => {
try {
const target = getTurn(ledger, row.turn_id)
@@ -692,6 +763,7 @@ function apply(ctx, config = {}) {
const paths = await snapshotDiff(planRuntime.store, target.before_ref, target.after_ref)
if (paths.length === 0) {
markPendingPlanApplied(ledger, planId, sessionId, 'No file changes were recorded for this turn.')
+ committed = true
return [200, { ok: true, message: 'No file changes were recorded for this turn.' }]
}
const entries = await buildPlanEntries(planRuntime, planRuntime.workspaceDir, target, paths)
@@ -707,9 +779,12 @@ function apply(ctx, config = {}) {
skipConflicts: false,
})
markPendingPlanApplied(ledger, planId, sessionId, message)
+ committed = true
return [200, { ok: true, message }]
}
finally {
+ if (!committed)
+ releasePendingPlanClaim(ledger, planId)
planRuntime.undoing = false
}
})()
@@ -727,11 +802,12 @@ function apply(ctx, config = {}) {
function statusRoute(body, req) {
const url = new URL(req.url ?? '/', 'http://localhost')
const planId = String(url.searchParams.get('planId') ?? '')
- if (planId === '')
- return [400, { error: 'planId is required' }]
- const status = getPendingPlanStatus(ledger, planId)
+ const sessionId = String(url.searchParams.get('sessionId') ?? '')
+ if (planId === '' || sessionId === '')
+ return [400, { error: 'planId and sessionId are required' }]
+ const status = getPendingPlanStatus(ledger, planId, sessionId)
if (status === undefined)
- return [404, { error: 'plan expired or already applied — run /undo again' }]
+ return [404, { error: 'plan expired, unavailable, or owned by another session — run /undo again' }]
return [200, status]
}
@@ -858,6 +934,10 @@ function apply(ctx, config = {}) {
}
const workspaceKey = workspaceKeyFor(workspaceDir)
+ if (recoveryWorkspaces.has(workspaceKey)) {
+ recordSkipped(key, sessionId, workspaceKey, startedAt, 'TURNREWIND_RECOVERY_REQUIRED: a previous undo or redo was interrupted; inspect the workspace and clear its recovery state before using rewind again')
+ return undefined
+ }
const issue = workspaceIssue(workspaceDir)
if (issue) {
recordSkipped(key, sessionId, workspaceKey, startedAt, issue)
@@ -878,6 +958,10 @@ function apply(ctx, config = {}) {
recordSkipped(key, sessionId, workspaceKey, startedAt, 'TURNREWIND_WORKSPACE_BUSY: an undo operation is running')
return undefined
}
+ if (workspaceHasActiveTurnForOtherSession(active, workspaceKey, sessionId)) {
+ recordSkipped(key, sessionId, workspaceKey, startedAt, 'TURNREWIND_WORKSPACE_BUSY: another session is using this workspace')
+ return undefined
+ }
// `agent/inbox/claimed` is a fire-and-forget notification. Create the
// deferred synchronously so the awaited pre-step waterfall can always find
@@ -1070,6 +1154,9 @@ function apply(ctx, config = {}) {
return { kind: 'error', text: `Undo is unavailable for this workspace. ${assessment.reason}` }
return { kind: 'error', text: 'Undo is unavailable because this session has no workspace.' }
}
+ const workspaceIdentity = workspaceKeyFor(workspaceDir)
+ if (recoveryWorkspaces.has(workspaceIdentity))
+ return { kind: 'error', text: 'Undo is unavailable because a previous undo or redo was interrupted. Inspect the workspace, then purge its turnrewind data before retrying.' }
const issue = workspaceIssue(workspaceDir)
if (issue)
return { kind: 'error', text: `Undo is unavailable for this workspace. ${issue}` }
diff --git a/plugins/dsh-tauri-turnrewind/test/barrier.test.js b/plugins/dsh-tauri-turnrewind/test/barrier.test.js
index 8e8e031e..2408246a 100644
--- a/plugins/dsh-tauri-turnrewind/test/barrier.test.js
+++ b/plugins/dsh-tauri-turnrewind/test/barrier.test.js
@@ -4,7 +4,7 @@ import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { it } from 'vitest'
import { createSnapshotStore, gitRef } from '../lib/core/git-snapshot.js'
-import { apply } from '../lib/index.js'
+import { apply, turnSnapshotRef } from '../lib/index.js'
function createHarnessContext() {
const events = new Map()
@@ -48,6 +48,17 @@ function createHarnessContext() {
return { ctx, events, cleanups, routes, commands }
}
+async function waitForRef(store, workspace, ref, timeoutMs = 15000) {
+ const deadline = Date.now() + timeoutMs
+ while (Date.now() < deadline) {
+ const value = await gitRef(store.repoDir, workspace, ref)
+ if (value)
+ return value
+ await new Promise(resolvePromise => setTimeout(resolvePromise, 100))
+ }
+ return undefined
+}
+
async function withHarness(test) {
const root = await mkdtemp(join(tmpdir(), 'turnrewind-barrier-test-'))
const workspace = join(root, 'workspace')
@@ -111,8 +122,8 @@ it('keeps consecutive claimed turns independent until both baselines are ready',
await Promise.all([firstStep, secondStep])
const store = createSnapshotStore(dshHome, workspace)
- assert.ok(await gitRef(store.repoDir, workspace, 'refs/turnrewind/turn-barrier-sequence_1-before'))
- assert.ok(await gitRef(store.repoDir, workspace, 'refs/turnrewind/turn-barrier-sequence_2-before'))
+ assert.ok(await waitForRef(store, workspace, turnSnapshotRef('barrier-sequence:1', 'before')))
+ assert.ok(await waitForRef(store, workspace, turnSnapshotRef('barrier-sequence:2', 'before')))
})
})
@@ -130,16 +141,36 @@ it('does not recreate a completed turn after a duplicate claim', async () => {
await new Promise(resolvePromise => setTimeout(resolvePromise, 300))
const store = createSnapshotStore(dshHome, workspace)
- const before = await gitRef(store.repoDir, workspace, 'refs/turnrewind/turn-barrier-duplicate_1-before')
- const after = await gitRef(store.repoDir, workspace, 'refs/turnrewind/turn-barrier-duplicate_1-after')
+ const beforeRef = turnSnapshotRef('barrier-duplicate:1', 'before')
+ const afterRef = turnSnapshotRef('barrier-duplicate:1', 'after')
+ const before = await waitForRef(store, workspace, beforeRef)
+ const after = await waitForRef(store, workspace, afterRef)
assert.ok(before)
assert.ok(after)
claimed[0]({ agent, turn: 1 })
await Promise.resolve()
await new Promise(resolvePromise => setTimeout(resolvePromise, 100))
- assert.equal(await gitRef(store.repoDir, workspace, 'refs/turnrewind/turn-barrier-duplicate_1-before'), before)
- assert.equal(await gitRef(store.repoDir, workspace, 'refs/turnrewind/turn-barrier-duplicate_1-after'), after)
+ assert.equal(await gitRef(store.repoDir, workspace, beforeRef), before)
+ assert.equal(await gitRef(store.repoDir, workspace, afterRef), after)
+ })
+})
+
+it('does not snapshot overlapping turns from another session in the same workspace', async () => {
+ await withHarness(async ({ harness, workspace, dshHome }) => {
+ const claimed = harness.events.get('agent/inbox/claimed')
+ const preStep = harness.events.get('agent/pre-step')
+ const first = { session: { id: 'workspace-owner', header: { cwd: workspace } } }
+ const second = { session: { id: 'workspace-other', header: { cwd: workspace } } }
+
+ claimed[0]({ agent: first, turn: 1 })
+ await preStep[0]({ agent: first, turn: 1, signal: new AbortController().signal }, async () => ({ kind: 'enter', messages: [] }))
+ claimed[0]({ agent: second, turn: 1 })
+ await preStep[0]({ agent: second, turn: 1, signal: new AbortController().signal }, async () => ({ kind: 'enter', messages: [] }))
+
+ const store = createSnapshotStore(dshHome, workspace)
+ assert.ok(await gitRef(store.repoDir, workspace, turnSnapshotRef('workspace-owner:1', 'before')))
+ assert.equal(await gitRef(store.repoDir, workspace, turnSnapshotRef('workspace-other:1', 'before')), undefined)
})
})
@@ -157,6 +188,6 @@ it('ignores a late claim after turn/end without leaving a live baseline', async
assert.equal(decision.kind, 'enter')
await new Promise(resolvePromise => setTimeout(resolvePromise, 100))
const store = createSnapshotStore(dshHome, workspace)
- assert.equal(await gitRef(store.repoDir, workspace, 'refs/turnrewind/turn-barrier-late-claim_2-before'), undefined)
+ assert.equal(await gitRef(store.repoDir, workspace, turnSnapshotRef('barrier-late-claim:2', 'before')), undefined)
})
})
diff --git a/plugins/dsh-tauri-turnrewind/test/client-view.test.js b/plugins/dsh-tauri-turnrewind/test/client-view.test.js
new file mode 100644
index 00000000..6612dff8
--- /dev/null
+++ b/plugins/dsh-tauri-turnrewind/test/client-view.test.js
@@ -0,0 +1,94 @@
+import assert from 'node:assert/strict'
+import { it } from 'vitest'
+import '../lib/client.js'
+
+/**
+ * Load the client bundle the way the tests need it: the DSH module loader is
+ * absent under Node, so client.js exposes its factory on globalThis and the
+ * pure helpers can be exercised with a stub `require` (nothing dereferences
+ * React/jsx-runtime at load time — only inside component bodies).
+ */
+function loadBundle() {
+ const factory = globalThis.__turnrewindClientFactory
+ assert.equal(typeof factory, 'function', 'client.js must expose its factory when __ModuleLoader__ is absent')
+ const stubRequire = () => ({ jsx: () => null, jsxs: () => null })
+ return factory(stubRequire)
+}
+
+it('exposes the cordis plugin face and pure helpers', () => {
+ const bundle = loadBundle()
+ assert.equal(typeof bundle.apply, 'function')
+ assert.deepEqual(bundle.inject, ['slots', 'sessions', 'locale'])
+ assert.equal(typeof bundle.parseUndoOutput, 'function')
+ assert.equal(typeof bundle.resolvePlanStatus, 'function')
+ assert.equal(typeof bundle.resolveOwnerSessionId, 'function')
+})
+
+it('resolvePlanStatus settles an expired plan as gone and stops polling', () => {
+ const bundle = loadBundle()
+ // The host route answers 404 once the pending plan expired or was purged.
+ const expired = bundle.resolvePlanStatus({ ok: false, status: 404 }, {})
+ assert.deepEqual(expired, { status: 'gone', stop: true, resultText: null })
+ // A host that ever reports gone explicitly settles the same way.
+ const explicit = bundle.resolvePlanStatus({ ok: true, status: 200 }, { status: 'gone' })
+ assert.deepEqual(explicit, { status: 'gone', stop: true, resultText: null })
+})
+
+it('resolvePlanStatus stops polling once the plan settles', () => {
+ const bundle = loadBundle()
+ const applied = bundle.resolvePlanStatus({ ok: true, status: 200 }, { status: 'applied', resultText: 'Undid turn x' })
+ assert.deepEqual(applied, { status: 'applied', stop: true, resultText: 'Undid turn x' })
+ // Missing resultText stays null so the card can substitute its own label.
+ const appliedBare = bundle.resolvePlanStatus({ ok: true, status: 200 }, { status: 'applied' })
+ assert.deepEqual(appliedBare, { status: 'applied', stop: true, resultText: null })
+ const cancelled = bundle.resolvePlanStatus({ ok: true, status: 200 }, { status: 'cancelled' })
+ assert.deepEqual(cancelled, { status: 'cancelled', stop: true, resultText: null })
+})
+
+it('resolvePlanStatus keeps polling pending plans', () => {
+ const bundle = loadBundle()
+ const pending = bundle.resolvePlanStatus({ ok: true, status: 200 }, { status: 'pending' })
+ assert.deepEqual(pending, { status: 'pending', stop: false, resultText: null })
+})
+
+it('resolvePlanStatus keeps polling on non-404 failures without touching state', () => {
+ const bundle = loadBundle()
+ for (const res of [{ ok: false, status: 500 }, { ok: false, status: 503 }, { ok: true, status: 200 }]) {
+ const next = bundle.resolvePlanStatus(res, res.ok ? {} : { error: 'boom' })
+ assert.deepEqual(next, { status: null, stop: false, resultText: null })
+ }
+})
+
+it('resolveOwnerSessionId prefers the session-scoped prop over the node', () => {
+ const bundle = loadBundle()
+ assert.equal(bundle.resolveOwnerSessionId({ sessionId: 'session-a', node: { sessionId: 'session-b' } }), 'session-a')
+ // Node field is the fallback for hosts that attach it to the command node.
+ assert.equal(bundle.resolveOwnerSessionId({ node: { sessionId: 'session-b' } }), 'session-b')
+})
+
+it('resolveOwnerSessionId never guesses from missing or invalid ids', () => {
+ const bundle = loadBundle()
+ assert.equal(bundle.resolveOwnerSessionId({}), null)
+ assert.equal(bundle.resolveOwnerSessionId(undefined), null)
+ assert.equal(bundle.resolveOwnerSessionId({ sessionId: '' }), null)
+ assert.equal(bundle.resolveOwnerSessionId({ sessionId: 42 }), null)
+ assert.equal(bundle.resolveOwnerSessionId({ sessionId: 'session-a', node: { sessionId: '' } }), 'session-a')
+})
+
+it('parseUndoOutput still extracts the pending plan id', () => {
+ const bundle = loadBundle()
+ const parsed = bundle.parseUndoOutput([
+ 'Undo preflight: turn s:1; 1 file(s); 0 conflicts.',
+ ' modified a.txt',
+ '',
+ 'Undo will apply (turn output → restored state):',
+ '--- a.txt',
+ ' -v2',
+ ' +v1',
+ 'plan 0f1e2d3c',
+ 'Send /undo --confirm 0f1e2d3c to apply, or /undo --cancel 0f1e2d3c to dismiss.',
+ ].join('\n'))
+ assert.equal(parsed.planId, '0f1e2d3c')
+ assert.equal(parsed.summary, 'Undo preflight: turn s:1; 1 file(s); 0 conflicts.')
+ assert.equal(parsed.files.length, 1)
+})
diff --git a/plugins/dsh-tauri-turnrewind/test/ledger.test.js b/plugins/dsh-tauri-turnrewind/test/ledger.test.js
index 8bac0d13..a975af12 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 { claimRewindNotices, completeRedoWithNotice, completeUndoWithNotice, createOperation, getLatestAppliedUndo, getLatestSnapshotRef, getLatestTurn, getTurn, insertTurn, listReversibleTurns, markTurnSnapshotMissing, openLedger, queueRewindNotice, recordSkippedTurn, 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, 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-'))
@@ -342,6 +342,69 @@ it('lists reversible turns newest-first and marks dead snapshots skipped', async
}
})
+it('claims a pending plan exactly once and serializes cancel/apply outcomes', async () => {
+ const root = await mkdtemp(join(tmpdir(), 'turnrewind-plan-claim-test-'))
+ const db = openLedger(root)
+ try {
+ const planId = createPendingPlan(db, {
+ sessionId: 'session',
+ workspaceKey: 'workspace',
+ turnId: 'session:1',
+ paths: ['a.txt'],
+ })
+ const first = claimPendingPlan(db, planId, 'session')
+ assert.equal(first.ok, true)
+ assert.equal(getPendingPlanStatus(db, planId, 'session').status, 'applying')
+ assert.equal(claimPendingPlan(db, planId, 'session').ok, false)
+ assert.equal(markPendingPlanCancelled(db, planId, 'session'), false)
+
+ releasePendingPlanClaim(db, planId)
+ assert.equal(getPendingPlanStatus(db, planId, 'session').status, 'pending')
+ const second = claimPendingPlan(db, planId, 'session')
+ assert.equal(second.ok, true)
+ markPendingPlanApplied(db, planId, 'session', 'applied once')
+ assert.deepEqual(getPendingPlanStatus(db, planId, 'session'), { status: 'applied', resultText: 'applied once' })
+ assert.equal(claimPendingPlan(db, planId, 'session').ok, false)
+ }
+ finally {
+ db.close()
+ await rm(root, { recursive: true, force: true })
+ }
+})
+
+it('fences applying operations as recovery-required on reopen', async () => {
+ const root = await mkdtemp(join(tmpdir(), 'turnrewind-operation-recovery-test-'))
+ const first = openLedger(root)
+ insertTurn(first, {
+ turnId: 'session:applying',
+ sessionId: 'session',
+ workspaceKey: 'workspace-recovery',
+ startedAt: '2026-01-01T00:00:00.000Z',
+ beforeRef: 'refs/turnrewind/applying-before',
+ })
+ settleTurn(first, 'session:applying', 'refs/turnrewind/applying-after')
+ createOperation(first, {
+ operationId: 'operation-applying',
+ kind: 'undo',
+ targetTurnId: 'session:applying',
+ requestedAt: '2026-01-01T00:01:00.000Z',
+ beforeRef: 'refs/turnrewind/operation-before',
+ })
+ first.close()
+
+ const reopened = openLedger(root)
+ try {
+ const operation = reopened.prepare('SELECT outcome, error FROM operations WHERE operation_id = ?').get('operation-applying')
+ assert.equal(operation.outcome, 'needs-recovery')
+ assert.match(operation.error, /restarted while the operation was applying/u)
+ assert.deepEqual(listNeedsRecoveryWorkspaces(reopened), ['workspace-recovery'])
+ }
+ finally {
+ reopened.close()
+ await rm(root, { recursive: true, force: true })
+ }
+})
+
it('marks an interrupted active turn abandoned on reopen', async () => {
const root = await mkdtemp(join(tmpdir(), 'turnrewind-recovery-test-'))
const first = openLedger(root)
diff --git a/plugins/dsh-tauri-turnrewind/test/security.test.js b/plugins/dsh-tauri-turnrewind/test/security.test.js
index 2b0c5e7c..58ee83eb 100644
--- a/plugins/dsh-tauri-turnrewind/test/security.test.js
+++ b/plugins/dsh-tauri-turnrewind/test/security.test.js
@@ -15,6 +15,10 @@ it('does not capture common secret files into a snapshot', async () => {
await writeFile(join(workspace, 'secrets.yaml'), 'key: do-not-store')
await writeFile(join(workspace, 'server.pem'), '-----BEGIN')
await writeFile(join(workspace, 'safe.txt'), 'safe')
+ await mkdir(join(workspace, 'config'), { recursive: true })
+ await mkdir(join(workspace, 'nested'), { recursive: true })
+ await writeFile(join(workspace, 'config', 'credentials.json'), '{"token":"nested-do-not-store"}')
+ await writeFile(join(workspace, 'nested', 'secrets.yaml'), 'key: nested-do-not-store')
const store = createSnapshotStore(join(root, 'data'), workspace)
const snapshot = await captureSnapshot(store, 'refs/turnrewind/security', 'security')
@@ -22,6 +26,8 @@ it('does not capture common secret files into a snapshot', async () => {
assert.equal((await stateAt(store, snapshot.commit, 'credentials.json')).kind, 'absent')
assert.equal((await stateAt(store, snapshot.commit, 'secrets.yaml')).kind, 'absent')
assert.equal((await stateAt(store, snapshot.commit, 'server.pem')).kind, 'absent')
+ assert.equal((await stateAt(store, snapshot.commit, 'config/credentials.json')).kind, 'absent')
+ assert.equal((await stateAt(store, snapshot.commit, 'nested/secrets.yaml')).kind, 'absent')
assert.equal((await stateAt(store, snapshot.commit, 'safe.txt')).kind, 'file')
const snapshotFiles = await readdir(join(root, 'data', 'snapshots'))
assert.equal(snapshotFiles.length, 1)
@@ -56,6 +62,50 @@ it('keeps legitimate source files whose names resemble secrets', async () => {
}
})
+it('excludes abandoned turnrewind temporary files from snapshots', async () => {
+ const root = await mkdtemp(join(tmpdir(), 'turnrewind-temp-file-test-'))
+ const workspace = join(root, 'workspace')
+ try {
+ await mkdir(join(workspace, 'nested'), { recursive: true })
+ await writeFile(join(workspace, 'file.turnrewind-01234567-89ab-cdef-0123-456789abcdef.tmp'), 'temporary')
+ await writeFile(join(workspace, 'nested', 'file.turnrewind-01234567-89ab-cdef-0123-456789abcdef.tmp'), 'temporary')
+ await writeFile(join(workspace, 'kept.txt'), 'kept')
+ const store = createSnapshotStore(join(root, 'data'), workspace)
+ const snapshot = await captureSnapshot(store, 'refs/turnrewind/temp-files', 'temp files')
+ assert.equal((await stateAt(store, snapshot.commit, 'file.turnrewind-01234567-89ab-cdef-0123-456789abcdef.tmp')).kind, 'absent')
+ assert.equal((await stateAt(store, snapshot.commit, 'nested/file.turnrewind-01234567-89ab-cdef-0123-456789abcdef.tmp')).kind, 'absent')
+ assert.equal((await stateAt(store, snapshot.commit, 'kept.txt')).kind, 'file')
+ }
+ finally {
+ await rm(root, { recursive: true, force: true })
+ }
+})
+
+it('refuses dangling symlink workspace paths during inspection and restore', async () => {
+ const root = await mkdtemp(join(tmpdir(), 'turnrewind-dangling-link-test-'))
+ const workspace = join(root, 'workspace')
+ try {
+ await mkdir(workspace, { recursive: true })
+ try {
+ await symlink(join(root, 'missing-target'), join(workspace, 'dangling'))
+ }
+ catch (error) {
+ if (error.code === 'EPERM' || error.code === 'EACCES')
+ return
+ throw error
+ }
+ const store = createSnapshotStore(join(root, 'data'), workspace)
+ assert.throws(() => currentState(workspace, 'dangling'), /TURNREWIND_SYMLINK_UNSUPPORTED/)
+ await assert.rejects(
+ () => restorePath(store, 'refs/turnrewind/missing', 'dangling'),
+ /TURNREWIND_SYMLINK_UNSUPPORTED/,
+ )
+ }
+ finally {
+ await rm(root, { recursive: true, force: true })
+ }
+})
+
it('refuses symlinked workspace paths during inspection and restore', async () => {
const root = await mkdtemp(join(tmpdir(), 'turnrewind-symlink-test-'))
const workspace = join(root, 'workspace')