@twinsearth/timemachine-dsh-plugin 0.2.3 → 0.2.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,32 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.2.5 — 2026-12-03
4
+
5
+ ### 还原不中断
6
+
7
+ - 第三方插件逐个尝试安装;单个插件失败只汇总为黄色提示「安装失败,请自行手动安装!」,不再返回 `RESTORE_PLUGIN_INSTALL_FAILED` 终止还原,会话、附件、配置和工作区继续落盘。
8
+ - 失败插件保留在结果 `plugins.failed`,成功插件仍合并回归档 `package.json`;UI 在还原完成横幅展示失败插件名。
9
+
10
+ ### DSH 兼容性预检
11
+
12
+ - 新增 `src/plugin-compat.mjs`:安装前读取 npm latest 或离线 tgz 的 `engines.dsh` / DSH peer 依赖,使用内置 semver 子集与当前 DSH 客户端版本比对。
13
+ - 当前 DSH 版本从 `resources/runtime/primary-runtime/runtime.json` 或显式传入值解析;不兼容插件标记 `PLUGIN_DSH_INCOMPATIBLE`、提示并跳过,不再安装后才被下次启动拒绝。
14
+
15
+ ### 缺失存储盘
16
+
17
+ - Windows 下工作区目标路径所在盘符不存在时,`/plan` 返回 `path_issues`,计划弹窗红字提示「本机没有该存储盘」并禁用确认,要求修改工作区文件夹。
18
+ - `/restore` 与 `applyRestore` 二次校验盘符,避免绕过 UI 写入不存在的盘;`/import` 同时返回导入点的缺失盘提示。
19
+
20
+ ### 标题栏入口
21
+
22
+ - Windows 原生「应用」菜单补丁项显式 `visible: true`,保持「DSH一键还原点」可见。
23
+ - 纯插件标题栏备用入口改为常驻:`CAPTION_AUTO_HIDE_MS` 改为 `CAPTION_DISCOVERY_MS`,只在宿主标题栏从未出现时停止观察,不再 30 秒后移除按钮;标题栏重绘后会补挂。
24
+
25
+ ### 验证与发布
26
+
27
+ - `npm test` 32/32;`npm run check` 30/30;`npm run pack-check` 通过。
28
+ - GitHub 与 npm 双通道发布 `0.2.5`。
29
+
3
30
  ## 0.2.3 — 2026-12-03
4
31
 
5
32
  ### 版本与统计
package/README.md CHANGED
@@ -6,7 +6,7 @@
6
6
 
7
7
  DSH 一键还原点(Time Machine)。它把 DSH 客户端的会话、工作区、配置与插件清单打包成一个可迁移的还原点,并在需要时把整台机器上的 DSH 恢复成还原点里的样子。
8
8
 
9
- - 版本:`0.2.3`
9
+ - 版本:`0.2.5`
10
10
  - 宿主:DeepSeek Harness(DSH)桌面客户端 `0.2.x`
11
11
  - 平台:Windows / macOS / Linux(Windows 默认目录,macOS/Linux 由用户选择目录)
12
12
  - 许可:MIT
@@ -74,7 +74,7 @@ DSH 一键还原点:
74
74
 
75
75
  完整面板右上角固定显示两枚胶囊:
76
76
 
77
- - `Time Machine v0.2.3`:版本号来自服务端 `status.version`,不是客户端硬编码;插件更新后随包变化。
77
+ - `Time Machine v0.2.5`:版本号来自服务端 `status.version`,不是客户端硬编码;插件更新后随包变化。
78
78
  - `在线 X · 7日 Y · 安装 Z`:通过本地 `GET /api/twinsearth/timemachine/stats` 代理独立统计服务。
79
79
 
80
80
  统计口径:
@@ -188,8 +188,8 @@ sessions/<project-key>/<encoded-session-id>/
188
188
 
189
189
  1. **DSH 通用设置**:`设置 -> 通用` 里新增「DSH 一键还原点」一行,可直接「立即备份」「一键还原」或「打开完整面板」。「一键还原」先打开还原计划确认弹窗,确认后还原最近一份手动/自动还原点,并自动打开还原后的会话。
190
190
  2. **左上角侧栏**:`sidebar.panellist` 顶部新增入口,位置在品牌行下方、会话列表上方。macOS 显示「时间机器」,Windows 显示「一键还原点」,点击打开完整面板。该入口在插件启动 **10 秒后自动隐藏**,让出导航位;之后仍可从通用设置行点「打开完整面板」。
191
- 3. **Windows 标题栏(纯插件备用入口)**:插件运行时在左上角「应用 / 编辑」右侧追加「DSH一键还原点」按钮,点击直接打开完整面板。该按钮在启动 **30 秒后自动隐藏**。它不需要改 `app.asar`;只在 DSH 桌面客户端存在 `[data-windows-menu]` 时生效,用浏览器打开 Web UI 不会显示。
192
- 4. **原生应用菜单(需求 4.2 的精确入口)**:包内提供 `scripts/host-menu-patch.mjs`,在 DSH 的 `app.asar` 的「应用 -> 开发者工具」后插入「DSH一键还原点」,点击后调用插件暴露的 `window.__DSH_TIMEMACHINE_OPEN__()` 打开面板。
191
+ 3. **Windows 标题栏(纯插件备用入口)**:插件运行时在左上角「应用 / 编辑」右侧追加「DSH一键还原点」按钮,点击直接打开完整面板。该按钮**常驻,不再自动隐藏**;标题栏重绘后会补挂。它不需要改 `app.asar`;只在 DSH 桌面客户端存在 `[data-windows-menu]` 时生效,用浏览器打开 Web UI 不会显示。
192
+ 4. **原生应用菜单(需求 4.2 的精确入口)**:包内提供 `scripts/host-menu-patch.mjs`,在 DSH 的 `app.asar` 的「应用 -> 开发者工具」后插入显式 `visible: true` 的「DSH一键还原点」,点击后调用插件暴露的 `window.__DSH_TIMEMACHINE_OPEN__()` 打开面板。
193
193
 
194
194
  原生菜单必须由宿主补丁实现,因为 DSH 桌面端的「应用」菜单由主进程硬编码(关于/检查更新/管理 dsh 命令/开发者工具/重启应用/退出),插件 API 没有“向应用菜单追加菜单项”的能力,`windowsMenu` IPC 也只接受 `application`/`edit` 两个菜单名。标题栏第三个按钮是纯插件的降级入口;如果要求严格出现在「应用 -> 开发者工具」下面,执行下面的补丁。本机真实客户端已执行;换一台机器部署时仍需执行一次。
195
195
 
@@ -269,7 +269,7 @@ npm run check # 静态交付检查
269
269
  npm run pack-check
270
270
  ```
271
271
 
272
- 测试覆盖:手动/自动创建、范围选择、保留份数、计划与还原、跳过插件安装、导入、设置持久化、损坏归档拒绝、HTTP 路由挂载、客户端 bundle 槽位注册、侧栏入口 10 秒自动隐藏与标题栏按钮 30 秒自动隐藏、标题随系统自适应、locale 五项详情、文件夹结构树与单分支展开、会话引导修复、运行中 `workspaceRegistry` 实时注册。真实客户端验收记录见 `docs/TESTPLAN.md`。
272
+ 测试覆盖:手动/自动创建、范围选择、保留份数、计划与还原、插件安装失败不中断、DSH 版本兼容性跳过、导入、设置持久化、损坏归档拒绝、缺失盘符检测、HTTP 路由挂载、客户端 bundle 槽位注册、侧栏入口 10 秒自动隐藏与标题栏入口常驻、标题随系统自适应、locale 五项详情、文件夹结构树与单分支展开、会话引导修复、运行中 `workspaceRegistry` 实时注册。真实客户端验收记录见 `docs/TESTPLAN.md`。
273
273
 
274
274
  ## 数据与安全
275
275
 
@@ -289,7 +289,9 @@ npm run pack-check
289
289
  | 提示同名 Session ID 冲突 | 目标 DSH 已有同一个 Session ID 的会话;还原点用于新机器/新工作区时不会出现。可先归档或移走旧会话再还原 |
290
290
  | 标题栏没有「DSH一键还原点」 | 该按钮只存在于 DSH 桌面客户端;用浏览器访问 Web UI 时没有 `[data-windows-menu]`。桌面端仍不出现时,改用侧栏入口或执行下面的原生菜单补丁 |
291
291
  | 原生菜单项不出现 | 目标机必须完全退出 DSH 后,对 `D:\DSH\resources\app.asar` 执行 `host-menu-patch.mjs` 并重启;只装插件不会自动改宿主菜单。本机真实 asar 已补丁,可用 `--check` 复核 |
292
- | 第三方插件安装失败 | 检查网络与 npm registry;可改用「同时备份插件安装包」离线还原 |
292
+ | 还原/导入提示「本机没有该存储盘」 | 还原点来自另一台机器,工作区路径在 `D:` / `E:` 等本机不存在的盘。按红字提示修改工作区文件夹后再确认;不要强行使用不存在的盘符 |
293
+ | 第三方插件安装失败 | 现在只显示黄色提示「安装失败,请自行手动安装!」,不会中断会话/配置还原;按提示手动安装该插件,或改用「同时备份插件安装包」离线还原 |
294
+ | 插件因 DSH 版本不兼容被跳过 | 插件声明了 `engines.dsh`(或 DSH peer 依赖),当前客户端版本不满足。升级 DSH 或换兼容版本插件后重试;该插件不会阻塞其余还原 |
293
295
  | 还原点过大 | 改用「活跃会话」范围,或关闭附件备份 |
294
296
 
295
297
  ## 版本
@@ -147,7 +147,7 @@ service.restore -> restore.restorePoint
147
147
 
148
148
  `layout.selectPanel('timemachine')` 依赖 `main` 注册项的 `options.key === 'timemachine'`。客户端必须声明 `inject: ['slots', 'layout']`;缺少 `layout` 时 Cordis 会在访问 `ctx.layout` 时抛 `cannot get property "layout" without inject`,整个客户端模块不会激活。`uiWorkspace` / `sessions` 用 `ctx.get` 可选读取,不加入硬注入;直接属性访问 `ctx.uiWorkspace` 会抛 `cannot get property "uiWorkspace" without inject`,这也是 0.1.0 修复过的坑。
149
149
 
150
- 除槽位外,`installCaptionEntry` 在 Windows 桌面客户端的 `[data-windows-menu]` open shadowRoot 里追加 `data-timemachine-caption` 按钮。宿主节点不存在(浏览器 Web UI)时用 `MutationObserver` 等 30 秒后静默放弃;组件卸载只移除自己追加的按钮,不碰宿主已有「应用 / 编辑」按钮。
150
+ 除槽位外,`installCaptionEntry` 在 Windows 桌面客户端的 `[data-windows-menu]` open shadowRoot 里追加 `data-timemachine-caption` 按钮。该按钮常驻,不设自动隐藏定时器;`MutationObserver` 在标题栏重绘后补挂。宿主节点从未出现(浏览器 Web UI)时,观察器在 30 秒后发现仍无按钮才静默停止;组件卸载只移除自己追加的按钮,不碰宿主已有「应用 / 编辑」按钮。
151
151
 
152
152
  ### 6.1 完整面板的文件夹详情
153
153
 
@@ -191,7 +191,9 @@ service.restore -> restore.restorePoint
191
191
  - 服务端所有写操作经过 `guarded` 单操作互斥;并发的第二个请求返回 409。
192
192
  - 归档写入先写临时文件再 rename,避免半成品被列为还原点。
193
193
  - 还原写入前生成预还原副本;校验失败回滚新增文件、删除新建空目录。
194
- - pnpm 安装失败时回滚 `package.json` / `cordis.patch.yml`;`node_modules` 可能处于部分更新状态,这是已知权衡,会在结果里返回 `stage: plugin-install`。
194
+ - 第三方插件逐个安装;单个安装失败只记入 `plugins.failed` 并产生黄色提示「安装失败,请自行手动安装!」,会话、附件、配置和工作区继续应用。只有 profile 不存在或离线包结构不可读等致命错误才返回 `stage: plugin-install` 并恢复 `package.json` / `cordis.patch.yml`;`node_modules` 可能处于部分更新状态,这是已知权衡。
195
+ - 安装前 `src/plugin-compat.mjs` 读取插件 `engines.dsh` 或 DSH peer 依赖,与 `resources/runtime/primary-runtime/runtime.json` 的 `desktopVersion` 比对;不满足时标记 `PLUGIN_DSH_INCOMPATIBLE` 并跳过,避免安装后才被 DSH 启动拒绝。
196
+ - Windows 下 `planRestore` 对每个目标工作区检查盘符是否存在;缺失时返回 `path_issues` 并让计划弹窗红字提示、禁用确认。`restorePoint` 和 `applyRestore` 均二次拒绝,防止绕过 UI 写不存在的盘。
195
197
 
196
198
  ## 8. 原生菜单补丁
197
199
 
@@ -200,7 +202,7 @@ DSH 桌面端的「应用」菜单在 `app.asar` 的 `lib/main.js` 中由 `appli
200
202
  ```
201
203
  读 app.asar header(pickle)
202
204
  定位 lib/main.js 的 toggleDevTools 块
203
- 在其后插入 { id: "twinsearth-timemachine-menu-v1", label: "DSH一键还原点", click }
205
+ 在其后插入 { id: "twinsearth-timemachine-menu-v1", label: "DSH一键还原点", visible: true, click }
204
206
  click: 取 focused/first BrowserWindow -> show/focus -> executeJavaScript("window.__DSH_TIMEMACHINE_OPEN__?.()")
205
207
  重建 data section:重排所有 packed 文件 offset
206
208
  更新 lib/main.js 的 size / integrity.hash / blocks
@@ -99,4 +99,14 @@ node scripts/host-menu-patch.mjs --app-asar "D:\DSH\resources\app.asar" --restor
99
99
  - [x] 版本号、在线/7日/安装统计胶囊(静态与协议测试通过)
100
100
  - [x] 399 分钟租约、3 小时随机回执、补投与 400 分钟重连(服务端单测 + 公网端到端通过)
101
101
  - [x] 独立租约服务部署到 Debian 12 `43.142.74.71:38081`(systemd `timemachine-lease`)
102
- - [ ] 四方发布 `0.2.3`(Git tag、GitHub Release、GitHub Package、npm)
102
+ - [x] 四方发布 `0.2.3`(Git tag、GitHub Release、GitHub Package、npm)
103
+ - [x] GitHub Actions CI(Linux/Windows/macOS matrix;SHA-256 仓库使用 `git init --object-format=sha256` 后检出)
104
+
105
+ ### 0.2.5 还原韧性
106
+
107
+ - [x] 单个第三方插件安装失败只黄色提示「安装失败,请自行手动安装!」,不中断还原
108
+ - [x] 安装前检查插件 `engines.dsh` / DSH peer 依赖,不兼容时提示并跳过
109
+ - [x] 导入/还原检测本机缺失的 Windows 存储盘,红字提示修改工作区文件夹
110
+ - [x] Windows「应用」菜单补丁项 `visible: true`;纯插件标题栏入口常驻、标题栏重绘后补挂
111
+ - [ ] 真实 DSH 客户端中「应用」菜单项与常驻标题栏按钮的点击验收
112
+ - [ ] GitHub 与 npm 双通道发布 `0.2.5`(发布完成后勾选)
package/docs/TESTPLAN.md CHANGED
@@ -183,6 +183,16 @@ npm run pack-check
183
183
  - 公网 `43.142.74.71:38081` 已验证 `/health`、`/v1/lease`、`/v1/receipt`、`/v1/miss`、`/v1/stats`;测试 token 已清理,生产统计归零。
184
184
  - 真实 DSH 面板右上角显示、真实安装 token 落盘与 399 分钟续租仍待真机点击/长跑验收。
185
185
 
186
+ ### 3.14 0.2.5 还原韧性与兼容性(自动化通过)
187
+
188
+ - `npm test` 32/32、`npm run check` 30/30。
189
+ - 插件失败用例:两个插件均让假 runner 返回 exit 1,断言两个都被尝试、`failed.length=2`、`ok=true`、警告含「安装失败,请自行手动安装!」。
190
+ - 还原失败不中断用例:真实创建还原点后,`restorePoint` 使用失败 runner 安装第三方插件,断言 `stage=restored`、工作区已落盘、`plugin_warnings` 含黄色提示。
191
+ - 兼容性用例:manifest `engines.dsh >=9.0.0`、当前 DSH `0.2.2`,断言 runner 调用次数为 0、`PLUGIN_DSH_INCOMPATIBLE`、提示已跳过;覆盖 `>=`、`^`、`~`、`||`、预发布版本与 tgz manifest 读取。
192
+ - 缺失盘用例:`missingDriveForPath('Z:\\workspace', {platform:'win32', exists:()=>false})` 返回 `Z:`;`/plan`/`/restore` 的 `path_issues` 与 UI 红字静态断言通过。
193
+ - 标题栏用例:客户端 bundle 断言 `CAPTION_AUTO_HIDE_MS` 已移除、`CAPTION_DISCOVERY_MS=30_000`,标题栏按钮不再定时移除;原生菜单补丁静态断言 `visible: true`。
194
+ - 真实 DSH 客户端「应用」菜单点击、常驻标题栏按钮出现/点击和缺失盘现场仍未做人工点击验收。
195
+
186
196
  ## 4. 待人工验收
187
197
 
188
198
  - 安装 tarball 到真实 DSH profile `desktop` 后:
@@ -199,20 +209,27 @@ npm run pack-check
199
209
  - 插件管理器详情显示五项能力,不再回退到包名
200
210
  - 真实 DSH 桌面客户端左上角标题栏:
201
211
  - 「应用 / 编辑」右侧出现「DSH一键还原点」
212
+ - 启动 30 秒后按钮仍存在,标题栏重绘后也不会消失
202
213
  - 点击打开插件面板;关闭/卸载插件后按钮消失
203
214
  - 浏览器 Web UI 不显示该按钮(无 `[data-windows-menu]`),属预期
204
215
  - 还原计划弹窗含插件时:
205
216
  - 显示「安装并还原第三方插件」勾选框,默认勾选
206
217
  - 取消勾选后确认,服务端 `installPlugins:false`,不联网安装
218
+ - 单个插件安装失败只出现黄色「安装失败,请自行手动安装!」,其余文件/会话/配置仍完成还原
219
+ - 插件 `engines.dsh` 与当前 DSH 不兼容时,计划/结果提示并跳过
220
+ - 工作区目标盘符在本机不存在时:
221
+ - 计划弹窗出现红字「本机没有该存储盘」,确认按钮禁用
222
+ - 修改到存在的盘后可确认;直接提交无效路径时服务端拒绝
207
223
  - 真实 `D:\DSH\resources\app.asar` 原生菜单补丁已执行(`patched:true`,备份已保留);重启 DSH 后验收:
208
224
  - 「应用 -> 开发者工具」下出现「DSH一键还原点」
225
+ - 原生菜单项 `visible: true`,不隐藏
209
226
  - 点击能打开插件面板(需真实 `desktop` profile 已安装本插件)
210
227
  - 第三方插件联网安装 latest 的真实网络路径(本次未执行,避免改动真实 profile)
211
228
  - 跨平台(macOS/Linux)文件夹选择弹窗与路径映射
212
229
 
213
230
  ## 5. 回归门槛
214
231
 
215
- - `npm test` 26/26 通过
216
- - `npm run check` 27/27 通过
217
- - `npm run pack-check` tarball 内容符合 `files`(33 个文件)
232
+ - `npm test` 32/32 通过
233
+ - `npm run check` 30/30 通过
234
+ - `npm run pack-check` tarball 内容符合 `files`(34 个文件,390.3 KiB)
218
235
  - 任何失败先定位到具体断言,不通过放宽断言“修复”
package/lib/client.js CHANGED
@@ -13,7 +13,7 @@ window.__ModuleLoader__.load({
13
13
  const STYLE_ID = 'timemachine-dsh-style';
14
14
  const PANEL_ID = 'timemachine';
15
15
  const SIDEBAR_AUTO_HIDE_MS = 10_000;
16
- const CAPTION_AUTO_HIDE_MS = 30_000;
16
+ const CAPTION_DISCOVERY_MS = 30_000;
17
17
 
18
18
  async function request(path, init = {}) {
19
19
  const response = await fetch(PREFIX + path, {
@@ -216,8 +216,10 @@ window.__ModuleLoader__.load({
216
216
  .tm-empty{border:1px dashed var(--dsh-border,#d1d5db);border-radius:10px;padding:20px;text-align:center;color:var(--dsh-text-secondary,#6b7280);font-size:12px}
217
217
  .tm-banner{border-radius:10px;padding:9px 12px;font-size:12px;display:flex;align-items:flex-start;justify-content:space-between;gap:10px}
218
218
  .tm-banner.error{background:#fef2f2;border:1px solid #fecaca;color:#991b1b}
219
+ .tm-banner.warn{background:#fffbeb;border:1px solid #fcd34d;color:#92400e}
219
220
  .tm-banner.success{background:#ecfdf5;border:1px solid #a7f3d0;color:#065f46}
220
221
  .tm-banner.info{background:#eff6ff;border:1px solid #bfdbfe;color:#1e40af}
222
+ .tm-input-error{border-color:#dc2626!important;background:#fef2f2!important;color:#991b1b!important}
221
223
  .tm-grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(120px,1fr));gap:8px}
222
224
  .tm-kv{border:1px solid var(--dsh-border,#e5e7eb);border-radius:9px;padding:8px 10px;background:var(--dsh-bg-secondary,#fafafa)}
223
225
  .tm-kv b{display:block;font-size:15px;line-height:1.2;margin-bottom:2px}
@@ -469,11 +471,19 @@ window.__ModuleLoader__.load({
469
471
  const workspaces = plan.workspaces ?? [];
470
472
  const plugins = plan.plugins ?? [];
471
473
  const packages = Object.keys(plan.plugin_packages ?? {});
474
+ const pathIssues = Array.isArray(plan.path_issues) ? plan.path_issues : [];
475
+ const pendingIssues = pathIssues.filter((issue) => (pathMap[issue.source_path] ?? issue.target_path) === issue.target_path);
472
476
  return h('div', { className: 'tm-modalMask', role: 'dialog', 'aria-modal': 'true' },
473
477
  h('div', { className: 'tm-modal' }, [
474
478
  h('h3', { key: 'h' }, '确认还原到本机'),
475
479
  h('div', { key: 'src', className: 'tm-muted' }, `${formatTime(plan.point?.created_at)} · 来自 ${plan.point?.source_machine ?? '未知机器'} · ${formatBytes(plan.bytes)}`),
476
480
  plan.cross_platform ? h(Banner, { key: 'cross', kind: 'info', title: '跨平台还原', detail: '来源与当前系统不同,工作区路径需要映射;你可以在下面直接修改。' }) : null,
481
+ pendingIssues.length > 0 ? h(Banner, {
482
+ key: 'drive',
483
+ kind: 'error',
484
+ title: '本机没有该存储盘',
485
+ detail: `${pendingIssues.map((issue) => issue.message).join(';')} 请修改工作区文件夹后再确认还原。`,
486
+ }) : null,
477
487
  h('div', { key: 'grid', className: 'tm-grid' }, [
478
488
  h('div', { key: 's', className: 'tm-kv' }, [h('b', { key: 'n' }, String(will.sessions ?? 0)), h('span', { key: 'l' }, '会话')]),
479
489
  h('div', { key: 'a', className: 'tm-kv' }, [h('b', { key: 'n' }, String(will.attachments ?? 0)), h('span', { key: 'l' }, '附件')]),
@@ -482,15 +492,19 @@ window.__ModuleLoader__.load({
482
492
  ]),
483
493
  workspaces.length === 0 ? null : h('div', { key: 'ws' }, [
484
494
  h('div', { key: 't', style: { fontWeight: 600, marginBottom: 6 } }, '工作区将导入到'),
485
- ...workspaces.map((workspace, index) => h('div', { key: workspace.source_path ?? String(index), className: 'tm-row', style: { marginBottom: 6 } }, [
486
- h('span', { key: 'l', className: 'tm-muted', style: { minWidth: 120 } }, workspace.title ?? workspace.source_title ?? '工作区'),
487
- h('input', {
488
- key: 'i',
489
- className: 'tm-input tm-grow',
490
- value: pathMap[workspace.source_path] ?? workspace.target_path,
491
- onChange: (event) => setPathMap((current) => ({ ...current, [workspace.source_path]: event.target.value })),
492
- }),
493
- ])),
495
+ ...workspaces.map((workspace, index) => {
496
+ const invalid = pendingIssues.some((issue) => issue.source_path === workspace.source_path);
497
+ return h('div', { key: workspace.source_path ?? String(index), className: 'tm-row', style: { marginBottom: 6 } }, [
498
+ h('span', { key: 'l', className: 'tm-muted', style: { minWidth: 120 } }, workspace.title ?? workspace.source_title ?? '工作区'),
499
+ h('input', {
500
+ key: 'i',
501
+ className: `tm-input tm-grow${invalid ? ' tm-input-error' : ''}`,
502
+ 'aria-invalid': invalid ? 'true' : 'false',
503
+ value: pathMap[workspace.source_path] ?? workspace.target_path,
504
+ onChange: (event) => setPathMap((current) => ({ ...current, [workspace.source_path]: event.target.value })),
505
+ }),
506
+ ]);
507
+ }),
494
508
  ]),
495
509
  will.plugins > 0 ? h('label', { key: 'plugins', className: 'tm-check', style: { marginTop: 8, padding: '8px 10px' } }, [
496
510
  h('input', { type: 'checkbox', checked: installPlugins, disabled: busy, onChange: () => setInstallPlugins((value) => !value) }),
@@ -502,7 +516,7 @@ window.__ModuleLoader__.load({
502
516
  h('ul', { key: 'warn' }, (plan.warnings ?? []).map((text, index) => h('li', { key: String(index) }, text))),
503
517
  h('div', { key: 'actions', className: 'tm-row' }, [
504
518
  h('button', { key: 'cancel', type: 'button', className: 'tm-btn', disabled: busy, onClick: onCancel }, '取消'),
505
- h('button', { key: 'go', type: 'button', className: 'tm-btn danger', disabled: busy, onClick: onConfirm }, busy ? '还原中…' : '确认还原'),
519
+ h('button', { key: 'go', type: 'button', className: 'tm-btn danger', disabled: busy || pendingIssues.length > 0, onClick: onConfirm }, busy ? '还原中…' : '确认还原'),
506
520
  ]),
507
521
  ]),
508
522
  );
@@ -735,7 +749,15 @@ window.__ModuleLoader__.load({
735
749
  return null;
736
750
  }
737
751
  const imported = await request('/import', { method: 'POST', body: JSON.stringify({ file }) });
738
- setNotice({ kind: 'success', title: '还原点已导入', detail: imported.file });
752
+ if (Array.isArray(imported.path_issues) && imported.path_issues.length > 0) {
753
+ setNotice({
754
+ kind: 'error',
755
+ title: '还原点已导入,但本机没有该存储盘',
756
+ detail: `${imported.path_issues.map((issue) => issue.message).join(';')} 请在还原时修改工作区文件夹。`,
757
+ });
758
+ } else {
759
+ setNotice({ kind: 'success', title: '还原点已导入', detail: imported.file });
760
+ }
739
761
  setTab('imported');
740
762
  return imported;
741
763
  });
@@ -774,10 +796,28 @@ window.__ModuleLoader__.load({
774
796
  }),
775
797
  });
776
798
  setPlan(null);
799
+ const failedPlugins = result.plugins?.failed ?? [];
800
+ const incompatiblePlugins = (result.plugins?.skipped ?? []).filter((row) => row.reason_code === 'PLUGIN_DSH_INCOMPATIBLE');
801
+ const pluginWarnings = Array.isArray(result.plugin_warnings) ? result.plugin_warnings : [];
802
+ const warningDetail = [
803
+ ...(pluginWarnings.length > 0
804
+ ? pluginWarnings
805
+ : [
806
+ ...failedPlugins.map((row) => `${row.name}:安装失败,请自行手动安装!`),
807
+ ...incompatiblePlugins.map((row) => `${row.name}:${row.reason},已跳过安装。`),
808
+ ]),
809
+ result.display_hint,
810
+ ].filter((text) => typeof text === 'string' && text !== '').join(' ');
777
811
  setNotice({
778
- kind: result.live_registration?.ok === true ? 'success' : 'info',
779
- title: result.live_registration?.ok === true ? '还原完成,正在打开工作区' : '还原完成,需要重启 DSH',
780
- detail: result.display_hint ?? '请完全退出 DSH 客户端后重新启动。',
812
+ kind: (failedPlugins.length > 0 || incompatiblePlugins.length > 0 || pluginWarnings.length > 0) ? 'warn' : (result.live_registration?.ok === true ? 'success' : 'info'),
813
+ title: failedPlugins.length > 0
814
+ ? '安装失败,请自行手动安装!'
815
+ : incompatiblePlugins.length > 0
816
+ ? '部分第三方插件与当前 DSH 不兼容,已跳过'
817
+ : result.live_registration?.ok === true ? '还原完成,正在打开工作区' : '还原完成,需要重启 DSH',
818
+ detail: (failedPlugins.length > 0 || incompatiblePlugins.length > 0 || pluginWarnings.length > 0)
819
+ ? warningDetail
820
+ : (result.display_hint ?? '请完全退出 DSH 客户端后重新启动。'),
781
821
  });
782
822
  onDone?.(result);
783
823
  return result;
@@ -1021,7 +1061,15 @@ window.__ModuleLoader__.load({
1021
1061
  }),
1022
1062
  });
1023
1063
  setPlan(null);
1024
- setNote(result.live_registration?.ok === true ? '还原完成,正在打开工作区' : '还原完成,需要重启 DSH');
1064
+ const failedPlugins = result.plugins?.failed ?? [];
1065
+ const incompatiblePlugins = (result.plugins?.skipped ?? []).filter((row) => row.reason_code === 'PLUGIN_DSH_INCOMPATIBLE');
1066
+ const base = result.live_registration?.ok === true ? '还原完成,正在打开工作区' : '还原完成,需要重启 DSH';
1067
+ const failedText = failedPlugins.map((row) => `${row.name}:安装失败,请自行手动安装!`);
1068
+ const skippedText = incompatiblePlugins.map((row) => `${row.name}:${row.reason},已跳过安装。`);
1069
+ const prefix = failedText.length > 0
1070
+ ? '安装失败,请自行手动安装!'
1071
+ : skippedText.length > 0 ? '部分第三方插件与当前 DSH 不兼容,已跳过' : '';
1072
+ setNote(prefix === '' ? base : `${prefix} ${[...failedText, ...skippedText].join(' ')}`);
1025
1073
  await refresh();
1026
1074
  onRestoreDone?.(result);
1027
1075
  } catch (caught) {
@@ -1101,7 +1149,6 @@ window.__ModuleLoader__.load({
1101
1149
  let button = null;
1102
1150
  let observer = null;
1103
1151
  let timer = null;
1104
- let hideTimer = null;
1105
1152
 
1106
1153
  const stopWatching = () => {
1107
1154
  if (observer !== null) {
@@ -1114,25 +1161,7 @@ window.__ModuleLoader__.load({
1114
1161
  }
1115
1162
  };
1116
1163
 
1117
- const hide = () => {
1118
- hideTimer = null;
1119
- if (button !== null) {
1120
- try { button.remove(); } catch { /* already gone */ }
1121
- button = null;
1122
- }
1123
- stopWatching();
1124
- };
1125
-
1126
- const scheduleHide = () => {
1127
- if (typeof window.setTimeout !== 'function') return;
1128
- hideTimer = window.setTimeout(hide, CAPTION_AUTO_HIDE_MS);
1129
- };
1130
-
1131
1164
  const cleanup = () => {
1132
- if (hideTimer !== null) {
1133
- try { window.clearTimeout(hideTimer); } catch { /* already gone */ }
1134
- hideTimer = null;
1135
- }
1136
1165
  stopWatching();
1137
1166
  if (button !== null) {
1138
1167
  try { button.remove(); } catch { /* already gone */ }
@@ -1167,18 +1196,21 @@ window.__ModuleLoader__.load({
1167
1196
  return true;
1168
1197
  };
1169
1198
 
1170
- if (mount()) {
1171
- scheduleHide();
1172
- return cleanup;
1173
- }
1174
- scheduleHide();
1199
+ // The title-bar tag is intentionally persistent: it is the always-visible
1200
+ // entry when the native "应用" menu patch is not installed. Keep the
1201
+ // observer after the first mount so a title-bar re-render re-adds the tag;
1202
+ // only a UI that never has a title bar stops watching after the timeout.
1203
+ const mountedInitially = mount();
1175
1204
  try {
1176
1205
  observer = new MutationObserver(() => {
1177
- if (!mount()) return;
1178
- stopWatching();
1206
+ mount();
1179
1207
  });
1180
1208
  observer.observe(document.body ?? document.documentElement, { childList: true, subtree: true });
1181
- timer = window.setTimeout(stopWatching, CAPTION_AUTO_HIDE_MS);
1209
+ if (!mountedInitially) {
1210
+ timer = window.setTimeout(() => {
1211
+ if (button === null) stopWatching();
1212
+ }, CAPTION_DISCOVERY_MS);
1213
+ }
1182
1214
  } catch { /* no DOM observer in a test harness */ }
1183
1215
  return cleanup;
1184
1216
  }
@@ -1292,7 +1324,7 @@ window.__ModuleLoader__.load({
1292
1324
  exports.sidebarLabel = sidebarLabel;
1293
1325
  exports.panelTitle = panelTitle;
1294
1326
  exports.SIDEBAR_AUTO_HIDE_MS = SIDEBAR_AUTO_HIDE_MS;
1295
- exports.CAPTION_AUTO_HIDE_MS = CAPTION_AUTO_HIDE_MS;
1327
+ exports.CAPTION_DISCOVERY_MS = CAPTION_DISCOVERY_MS;
1296
1328
  exports.latestLocalPoint = latestLocalPoint;
1297
1329
  exports.allPointRows = allPointRows;
1298
1330
  exports.defaultFolderFile = defaultFolderFile;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@twinsearth/timemachine-dsh-plugin",
3
- "version": "0.2.3",
3
+ "version": "0.2.5",
4
4
  "description": "DSH 一键还原点:手动/自动双还原点、会话与工作区完整备份、第三方插件 latest 重装、配置迁移与一键还原、一键修复会话引导。",
5
5
  "type": "module",
6
6
  "icon": "./icon.png",
package/plugin.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "id": "timemachine",
3
3
  "name": "DeepSeekHarness:一键还原点",
4
- "version": "0.2.3",
4
+ "version": "0.2.5",
5
5
  "description": "DSH 一键还原点:手动/自动双还原点、会话与工作区完整备份、第三方插件 latest 重装、配置迁移与一键还原、一键修复会话引导。",
6
6
  "entry": "lib/index.js",
7
7
  "client": "lib/client.js",
@@ -38,6 +38,7 @@ const PATCHED_BLOCK = `\t\t{
38
38
  \t\t{
39
39
  \t\t\tid: "${MARKER}",
40
40
  \t\t\tlabel: "${LABEL}",
41
+ \t\t\tvisible: true,
41
42
  \t\t\tclick: () => {
42
43
  \t\t\t\tconst window = BrowserWindow.getFocusedWindow() ?? BrowserWindow.getAllWindows().find((candidate) => !candidate.isDestroyed());
43
44
  \t\t\t\tif (window === void 0) return;
@@ -0,0 +1,241 @@
1
+ /**
2
+ * DSH plugin compatibility checks used before a third-party install.
3
+ *
4
+ * DSH itself refuses to load a plugin whose `engines.dsh` (or DSH peer
5
+ * dependency) does not include the running runtime. A restore must not install
6
+ * such a plugin only for the next boot to reject it, so this module evaluates
7
+ * the same declaration before invoking the package manager.
8
+ */
9
+
10
+ import fs from 'node:fs';
11
+ import path from 'node:path';
12
+ import zlib from 'node:zlib';
13
+
14
+ import { readTar } from './archive/tar.mjs';
15
+
16
+ const SEMVER = /^v?(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/u;
17
+
18
+ /** Parse a complete semantic version, preserving prerelease identifiers. */
19
+ export function parseSemver(value) {
20
+ if (typeof value !== 'string') return null;
21
+ const match = SEMVER.exec(value.trim());
22
+ if (match === null) return null;
23
+ return {
24
+ major: Number(match[1]),
25
+ minor: Number(match[2]),
26
+ patch: Number(match[3]),
27
+ prerelease: match[4] === undefined ? [] : match[4].split('.'),
28
+ };
29
+ }
30
+
31
+ function compareIdentifier(left, right) {
32
+ const leftNumeric = /^\d+$/u.test(left);
33
+ const rightNumeric = /^\d+$/u.test(right);
34
+ if (leftNumeric && rightNumeric) return Number(left) - Number(right);
35
+ if (leftNumeric) return -1;
36
+ if (rightNumeric) return 1;
37
+ return left.localeCompare(right);
38
+ }
39
+
40
+ /** semver precedence, including prerelease ordering; build metadata is ignored. */
41
+ export function compareSemver(left, right) {
42
+ for (const key of ['major', 'minor', 'patch']) {
43
+ if (left[key] !== right[key]) return left[key] - right[key];
44
+ }
45
+ if (left.prerelease.length === 0 && right.prerelease.length === 0) return 0;
46
+ if (left.prerelease.length === 0) return 1;
47
+ if (right.prerelease.length === 0) return -1;
48
+ const length = Math.max(left.prerelease.length, right.prerelease.length);
49
+ for (let index = 0; index < length; index += 1) {
50
+ const a = left.prerelease[index];
51
+ const b = right.prerelease[index];
52
+ if (a === undefined) return -1;
53
+ if (b === undefined) return 1;
54
+ const compared = compareIdentifier(a, b);
55
+ if (compared !== 0) return compared;
56
+ }
57
+ return 0;
58
+ }
59
+
60
+ function partialVersion(value) {
61
+ const text = String(value ?? '').trim();
62
+ const match = /^v?(\d+)(?:\.(\d+|[xX*]))?(?:\.(\d+|[xX*]))?(?:-([0-9A-Za-z.-]+))?$/u.exec(text);
63
+ if (match === null) return null;
64
+ const minor = match[2] === undefined || /^[xX*]$/u.test(match[2]) ? null : Number(match[2]);
65
+ const patch = match[3] === undefined || /^[xX*]$/u.test(match[3]) ? null : Number(match[3]);
66
+ return {
67
+ major: Number(match[1]),
68
+ minor,
69
+ patch,
70
+ prerelease: match[4] === undefined ? [] : match[4].split('.'),
71
+ };
72
+ }
73
+
74
+ function floorVersion(parts) {
75
+ return { major: parts.major, minor: parts.minor ?? 0, patch: parts.patch ?? 0, prerelease: parts.prerelease };
76
+ }
77
+
78
+ function comparatorMatches(version, operator, parts) {
79
+ const base = floorVersion(parts);
80
+ const compared = compareSemver(version, base);
81
+ if (operator === '>=') return compared >= 0;
82
+ if (operator === '>') return compared > 0;
83
+ if (operator === '<=') return compared <= 0;
84
+ if (operator === '<') return compared < 0;
85
+ return compared === 0;
86
+ }
87
+
88
+ function caretRange(parts) {
89
+ const low = floorVersion(parts);
90
+ let high;
91
+ if (parts.minor === null) high = { major: parts.major + 1, minor: 0, patch: 0, prerelease: [] };
92
+ else if (parts.major > 0) high = { major: parts.major + 1, minor: 0, patch: 0, prerelease: [] };
93
+ else if (parts.minor > 0) high = { major: 0, minor: parts.minor + 1, patch: 0, prerelease: [] };
94
+ else if (parts.patch === null) high = { major: 0, minor: 1, patch: 0, prerelease: [] };
95
+ else high = { major: 0, minor: 0, patch: parts.patch + 1, prerelease: [] };
96
+ return { low, high };
97
+ }
98
+
99
+ function tildeRange(parts) {
100
+ const low = floorVersion(parts);
101
+ const high = parts.minor === null
102
+ ? { major: parts.major + 1, minor: 0, patch: 0, prerelease: [] }
103
+ : { major: parts.major, minor: parts.minor + 1, patch: 0, prerelease: [] };
104
+ return { low, high };
105
+ }
106
+
107
+ function matchesComparator(version, raw) {
108
+ const token = raw.trim();
109
+ if (token === '' || token === '*' || /^[xX]$/u.test(token)) return true;
110
+ const operatorMatch = /^(>=|<=|>|<|=|\^|~)?\s*(.+)$/u.exec(token);
111
+ if (operatorMatch === null) return false;
112
+ const operator = operatorMatch[1] ?? '';
113
+ const parts = partialVersion(operatorMatch[2]);
114
+ if (parts === null) return false;
115
+ if (operator === '^') {
116
+ const range = caretRange(parts);
117
+ return compareSemver(version, range.low) >= 0 && compareSemver(version, range.high) < 0;
118
+ }
119
+ if (operator === '~') {
120
+ const range = tildeRange(parts);
121
+ return compareSemver(version, range.low) >= 0 && compareSemver(version, range.high) < 0;
122
+ }
123
+ if (parts.minor === null || parts.patch === null) {
124
+ const low = floorVersion(parts);
125
+ const high = parts.minor === null
126
+ ? { major: parts.major + 1, minor: 0, patch: 0, prerelease: [] }
127
+ : { major: parts.major, minor: parts.minor + 1, patch: 0, prerelease: [] };
128
+ if (operator === '>=') return compareSemver(version, low) >= 0;
129
+ if (operator === '>') return compareSemver(version, high) >= 0;
130
+ if (operator === '<') return compareSemver(version, low) < 0;
131
+ if (operator === '<=') return compareSemver(version, high) < 0;
132
+ return compareSemver(version, low) >= 0 && compareSemver(version, high) < 0;
133
+ }
134
+ return comparatorMatches(version, operator === '' ? '=' : operator, parts);
135
+ }
136
+
137
+ /**
138
+ * A dependency-free subset of semver that covers every range shape used by DSH
139
+ * plugins: exact, comparators, `||`, caret, tilde, wildcards and hyphen ranges.
140
+ * Prereleases participate, matching DSH's `includePrerelease: true`.
141
+ */
142
+ export function satisfiesRange(version, range) {
143
+ const parsedVersion = parseSemver(version);
144
+ if (parsedVersion === null || typeof range !== 'string' || range.trim() === '') return false;
145
+ for (const alternative of range.split('||')) {
146
+ const text = alternative.trim().replace(/(>=|<=|>|<|=|\^|~)\s+/gu, '$1');
147
+ if (text === '') continue;
148
+ const hyphen = /^(\S+)\s+-\s+(\S+)$/u.exec(text);
149
+ if (hyphen !== null) {
150
+ const low = partialVersion(hyphen[1]);
151
+ const high = partialVersion(hyphen[2]);
152
+ if (low === null || high === null) continue;
153
+ const lowVersion = floorVersion(low);
154
+ const highVersion = floorVersion(high);
155
+ if (compareSemver(parsedVersion, lowVersion) >= 0 && compareSemver(parsedVersion, highVersion) <= 0) return true;
156
+ continue;
157
+ }
158
+ const comparators = text.split(/\s+/u).filter((token) => token !== '');
159
+ if (comparators.every((token) => matchesComparator(parsedVersion, token))) return true;
160
+ }
161
+ return false;
162
+ }
163
+
164
+ /**
165
+ * Return the DSH requirements a manifest does not satisfy. An own
166
+ * `engines.dsh` decides alone, matching DSH's app-boot behavior.
167
+ */
168
+ export function unmetDshRequirements(manifest, runtimeVersion) {
169
+ if (manifest === null || typeof manifest !== 'object') return {};
170
+ const engines = manifest.engines;
171
+ if (engines !== null && typeof engines === 'object' && Object.hasOwn(engines, 'dsh')) {
172
+ const range = engines.dsh;
173
+ if (typeof range !== 'string') return { 'engines.dsh': String(range) };
174
+ return satisfiesRange(runtimeVersion, range) ? {} : { 'engines.dsh': range };
175
+ }
176
+ const peers = manifest.peerDependencies;
177
+ if (peers === null || typeof peers !== 'object') return {};
178
+ const unmet = {};
179
+ for (const [name, range] of Object.entries(peers)) {
180
+ if (name !== '@deepseek-ai/dsh' && !name.startsWith('@deepseek-ai/dsh-')) continue;
181
+ if (typeof range !== 'string') {
182
+ unmet[name] = String(range);
183
+ continue;
184
+ }
185
+ const effective = ['workspace:^', 'workspace:~', 'workspace:*'].includes(range) ? runtimeVersion : range;
186
+ if (!satisfiesRange(runtimeVersion, effective)) unmet[name] = range;
187
+ }
188
+ return unmet;
189
+ }
190
+
191
+ /** Read `package/package.json` from an npm `.tgz` without spawning tar. */
192
+ export function readPackageManifestFromTarball(file) {
193
+ const archive = zlib.gunzipSync(fs.readFileSync(file));
194
+ for (const entry of readTar(archive)) {
195
+ if (entry.name === 'package/package.json' || entry.name.endsWith('/package/package.json')) {
196
+ return JSON.parse(entry.data.toString('utf8'));
197
+ }
198
+ }
199
+ throw new Error('the saved package has no package/package.json');
200
+ }
201
+
202
+ function runtimeVersionFromJson(file) {
203
+ try {
204
+ const raw = JSON.parse(fs.readFileSync(file, 'utf8'));
205
+ const value = typeof raw?.desktopVersion === 'string' ? raw.desktopVersion : raw?.version;
206
+ return parseSemver(value) === null ? null : value;
207
+ } catch {
208
+ return null;
209
+ }
210
+ }
211
+
212
+ /**
213
+ * Resolve the running DSH version. The desktop runtime writes it to
214
+ * `resources/runtime/primary-runtime/runtime.json`; tests and embedders can
215
+ * pass an explicit version. Returns `null` when no trustworthy version exists.
216
+ */
217
+ export function resolveDshRuntimeVersion(input = {}) {
218
+ const explicit = input.version ?? process.env.DSH_VERSION ?? process.env.DSH_CLIENT_VERSION;
219
+ if (parseSemver(explicit) !== null) return String(explicit).trim();
220
+ const execPath = input.execPath ?? process.execPath;
221
+ const dir = path.dirname(execPath);
222
+ const candidates = [
223
+ path.join(dir, 'resources', 'runtime', 'primary-runtime', 'runtime.json'),
224
+ path.join(dir, 'runtime', 'primary-runtime', 'runtime.json'),
225
+ // The DSH host may run the plugin under the bundled Node binary:
226
+ // resources/runtime/primary-runtime/node/node.exe -> ../runtime.json
227
+ path.join(dir, '..', 'runtime.json'),
228
+ path.join(dir, '..', '..', 'runtime', 'primary-runtime', 'runtime.json'),
229
+ ];
230
+ if (typeof input.profileDir === 'string' && input.profileDir !== '') {
231
+ candidates.push(
232
+ path.join(input.profileDir, 'node_modules', '@deepseek-ai', 'dsh', 'package.json'),
233
+ path.join(input.profileDir, 'node_modules', '@deepseek-ai', 'dsh-app-boot', 'package.json'),
234
+ );
235
+ }
236
+ for (const file of candidates) {
237
+ const version = runtimeVersionFromJson(file);
238
+ if (version !== null) return version;
239
+ }
240
+ return null;
241
+ }
package/src/plugins.mjs CHANGED
@@ -10,6 +10,8 @@ import fs from 'node:fs';
10
10
  import path from 'node:path';
11
11
  import { spawn } from 'node:child_process';
12
12
 
13
+ import { readPackageManifestFromTarball, resolveDshRuntimeVersion, unmetDshRequirements } from './plugin-compat.mjs';
14
+
13
15
  /** The package doing the restore must never reinstall itself while running. */
14
16
  export const SELF_PLUGIN = '@twinsearth/timemachine-dsh-plugin';
15
17
 
@@ -221,9 +223,15 @@ export function resolvePnpm(execPath = process.execPath) {
221
223
  /**
222
224
  * Install third-party plugins. pnpm is preferred; npm is a fallback that uses
223
225
  * `--no-save` so the archived package.json is not rewritten by an installer.
226
+ *
227
+ * One package failing must not abort the whole restore: every package is
228
+ * attempted, failures are collected for the yellow UI warning, and the caller
229
+ * continues with the file/config restore.
230
+ *
224
231
  * @param {{
225
232
  * profileDir: string, plugins: Array<{name: string, version?: string|null}>,
226
- * packages?: Record<string,string>, runner?: typeof runProcess,
233
+ * packages?: Record<string,string>, dshVersion?: string|null, manifests?: Record<string, object>,
234
+ * checkCompatibility?: boolean, runner?: typeof runProcess,
227
235
  * timeout_ms?: number, pnpmFile?: string|null, onProgress?: (event: object) => void,
228
236
  * }} input
229
237
  */
@@ -233,13 +241,15 @@ export async function reinstallPlugins(input) {
233
241
  const installed = [];
234
242
  const failed = [];
235
243
  const skipped = [];
244
+ const warnings = [];
236
245
  const plugins = Array.isArray(input.plugins) ? input.plugins : [];
237
- if (plugins.length === 0) return { ok: true, manager: 'none', installed, failed, skipped };
246
+ if (plugins.length === 0) return { ok: true, complete: true, manager: 'none', runtime_version: null, installed, failed, skipped, warnings };
238
247
  if (!fs.existsSync(input.profileDir)) {
239
- return { ok: false, reason_code: 'RESTORE_PROFILE_NOT_FOUND', detail: input.profileDir, manager: 'none', installed, failed, skipped };
248
+ return { ok: false, reason_code: 'RESTORE_PROFILE_NOT_FOUND', detail: input.profileDir, manager: 'none', installed, failed, skipped, warnings };
240
249
  }
241
250
  const pnpmFile = input.pnpmFile === undefined ? resolvePnpm() : input.pnpmFile;
242
251
  const manager = pnpmFile !== null && pnpmFile !== undefined ? 'pnpm' : 'npm';
252
+ const runtimeVersion = input.dshVersion ?? resolveDshRuntimeVersion({ profileDir: input.profileDir });
243
253
  for (const plugin of plugins) {
244
254
  const name = plugin?.name;
245
255
  if (!isSafePackageName(name)) {
@@ -252,16 +262,61 @@ export async function reinstallPlugins(input) {
252
262
  }
253
263
  const tarball = packages[name];
254
264
  const spec = typeof tarball === 'string' && tarball !== '' ? `file:${tarball}` : `${name}@latest`;
265
+
266
+ if (input.checkCompatibility !== false) {
267
+ let manifest = input.manifests?.[name];
268
+ if (manifest === undefined && typeof tarball === 'string' && tarball !== '') {
269
+ try {
270
+ manifest = readPackageManifestFromTarball(tarball);
271
+ } catch (error) {
272
+ warnings.push(`${name}:无法读取离线安装包的版本要求(${error instanceof Error ? error.message : String(error)}),继续安装。`);
273
+ }
274
+ }
275
+ if (manifest === undefined && (typeof tarball !== 'string' || tarball === '')) {
276
+ const viewed = await readRegistryManifest(runner, input.profileDir, name, input.timeout_ms);
277
+ if (viewed.ok) manifest = viewed.manifest;
278
+ else warnings.push(`${name}:无法读取 npm 版本要求(${viewed.detail}),继续安装。`);
279
+ }
280
+ if (manifest !== undefined && manifest !== null) {
281
+ if (runtimeVersion === null) {
282
+ warnings.push(`${name}:无法确认当前 DSH 客户端版本,未做兼容性检查。`);
283
+ } else {
284
+ const unmet = unmetDshRequirements(manifest, runtimeVersion);
285
+ if (Object.keys(unmet).length > 0) {
286
+ const requirement = Object.entries(unmet).map(([field, range]) => `${field} ${range}`).join('、');
287
+ const detail = `要求 ${requirement},当前 DSH ${runtimeVersion}`;
288
+ skipped.push({
289
+ name,
290
+ spec,
291
+ reason_code: 'PLUGIN_DSH_INCOMPATIBLE',
292
+ reason: detail,
293
+ manifest_version: typeof manifest.version === 'string' ? manifest.version : null,
294
+ requirements: unmet,
295
+ runtime_version: runtimeVersion,
296
+ });
297
+ warnings.push(`${name}:与当前 DSH 不兼容(${detail}),已跳过安装。`);
298
+ continue;
299
+ }
300
+ }
301
+ }
302
+ }
303
+
255
304
  const args = manager === 'pnpm'
256
305
  ? ['--dir', input.profileDir, 'add', spec, '--reporter=append-only', '--prefer-online']
257
306
  : ['install', '--no-save', '--package-lock=false', '--omit=dev', '--prefer-online', spec];
258
307
  const command = manager === 'pnpm' ? process.execPath : npmCommand();
259
308
  const argv = manager === 'pnpm' ? [pnpmFile, ...args] : args;
260
309
  input.onProgress?.({ phase: 'install', name, spec, manager });
261
- const result = await runner(command, argv, {
262
- cwd: input.profileDir,
263
- timeout_ms: input.timeout_ms ?? 240_000,
264
- });
310
+ let result;
311
+ try {
312
+ result = await runner(command, argv, {
313
+ cwd: input.profileDir,
314
+ timeout_ms: input.timeout_ms ?? 240_000,
315
+ });
316
+ } catch (error) {
317
+ result = { code: null, stdout: '', stderr: '', error: error instanceof Error ? error.message : String(error) };
318
+ }
319
+ result = result ?? { code: null, stdout: '', stderr: '' };
265
320
  const row = {
266
321
  name,
267
322
  spec,
@@ -275,15 +330,7 @@ export async function reinstallPlugins(input) {
275
330
  installed.push(row);
276
331
  } else {
277
332
  failed.push({ ...row, error: result.error ?? null });
278
- return {
279
- ok: false,
280
- reason_code: 'RESTORE_PLUGIN_INSTALL_FAILED',
281
- detail: `${name}: ${manager} exited ${String(result.code)}${result.timed_out === true ? ' (timeout)' : ''}`,
282
- manager,
283
- installed,
284
- failed,
285
- skipped,
286
- };
333
+ warnings.push(`${name}:安装失败,请自行手动安装!`);
287
334
  }
288
335
  }
289
336
  if (manager === 'npm') {
@@ -303,7 +350,30 @@ export async function reinstallPlugins(input) {
303
350
  fs.writeFileSync(pkgFile, `${JSON.stringify(pkg, null, 2)}\n`, 'utf8');
304
351
  } catch { /* a package.json write failure is reported by the next status, not here */ }
305
352
  }
306
- return { ok: true, manager, installed, failed, skipped };
353
+ return { ok: true, complete: failed.length === 0, manager, runtime_version: runtimeVersion, installed, failed, skipped, warnings };
354
+ }
355
+
356
+ async function readRegistryManifest(runner, cwd, name, timeoutMs) {
357
+ let result;
358
+ try {
359
+ result = await runner(npmCommand(), ['view', `${name}@latest`, 'version', 'engines', 'peerDependencies', '--json'], {
360
+ cwd,
361
+ timeout_ms: Math.min(timeoutMs ?? 60_000, 60_000),
362
+ });
363
+ } catch (error) {
364
+ return { ok: false, detail: `npm view failed: ${error instanceof Error ? error.message : String(error)}` };
365
+ }
366
+ if (result?.code !== 0) {
367
+ return { ok: false, detail: `npm view exited ${String(result?.code)}${result?.timed_out === true ? ' (timeout)' : ''}` };
368
+ }
369
+ try {
370
+ const parsed = JSON.parse(String(result.stdout ?? '').trim());
371
+ const manifest = Array.isArray(parsed) ? parsed[0] : parsed;
372
+ if (manifest === null || typeof manifest !== 'object') return { ok: false, detail: 'npm view returned no manifest' };
373
+ return { ok: true, manifest };
374
+ } catch {
375
+ return { ok: false, detail: 'npm view returned invalid JSON' };
376
+ }
307
377
  }
308
378
 
309
379
  /**
package/src/point.mjs CHANGED
@@ -29,7 +29,7 @@ import { scanExclusions, scanHome } from './scan.mjs';
29
29
  import { packPluginTarballs, readProfilePlugins, SELF_PLUGIN } from './plugins.mjs';
30
30
  import { buildPointTree } from './tree.mjs';
31
31
  import { atomicWriteFile, ensureDir, formatBytes, isSafeArchiveName, readJson, sha256, stamp } from './util/fs.mjs';
32
- import { encodeSegment, profileDir, projectKey, resolveDshHome } from './util/paths.mjs';
32
+ import { encodeSegment, missingDriveForPath, profileDir, projectKey, resolveDshHome } from './util/paths.mjs';
33
33
 
34
34
  export const POINT_SCHEMA = 'twinsearth-timemachine-point/1';
35
35
  export const MANIFEST_SCHEMA = 'twinsearth-timemachine-manifest/1';
@@ -633,6 +633,21 @@ export function importRestorePoint(input) {
633
633
  if (source.startsWith(`${path.resolve(root)}${path.sep}`)) {
634
634
  return { ok: false, reason_code: CODES.IMPORT_FAILED, detail: 'the source file is already inside the restore-point root' };
635
635
  }
636
+ const pathIssues = [];
637
+ const seenDrives = new Set();
638
+ for (const workspace of row.point?.workspaces ?? []) {
639
+ const workspacePath = typeof workspace?.path === 'string' ? workspace.path : '';
640
+ const drive = missingDriveForPath(workspacePath);
641
+ if (drive === null || seenDrives.has(`${drive}|${workspacePath}`)) continue;
642
+ seenDrives.add(`${drive}|${workspacePath}`);
643
+ pathIssues.push({
644
+ code: 'TIMEMACHINE_PATH_DRIVE_MISSING',
645
+ drive,
646
+ source_path: workspacePath,
647
+ target_path: workspacePath,
648
+ message: `本机没有 ${drive} 盘,还原点中的工作区“${workspace.title ?? workspacePath}”无法直接落到 ${workspacePath};请修改工作区文件夹。`,
649
+ });
650
+ }
636
651
  const writable = ensureWritableRoot(root);
637
652
  if (writable !== null) return { ok: false, reason_code: CODES.ROOT_UNWRITABLE, detail: writable };
638
653
  const folder = categoryDir(root, 'imported');
@@ -648,7 +663,16 @@ export function importRestorePoint(input) {
648
663
  } catch (error) {
649
664
  return { ok: false, reason_code: CODES.IMPORT_FAILED, detail: error instanceof Error ? error.message : String(error) };
650
665
  }
651
- return { ok: true, file: target, source, point: row.point, bytes: row.bytes, sha256: row.sha256 };
666
+ return {
667
+ ok: true,
668
+ file: target,
669
+ source,
670
+ point: row.point,
671
+ bytes: row.bytes,
672
+ sha256: row.sha256,
673
+ path_issues: pathIssues,
674
+ warnings: pathIssues.map((issue) => issue.message),
675
+ };
652
676
  }
653
677
 
654
678
  /** Estimate what a point will contain, without writing. */
package/src/restore.mjs CHANGED
@@ -18,12 +18,13 @@ import { inspectSessionBuffer, isV4Header, remapSessionCwd } from './session-log
18
18
  import { normalizeRegistry } from './scan.mjs';
19
19
  import { reinstallPlugins, SELF_PLUGIN } from './plugins.mjs';
20
20
  import { atomicWriteFile, atomicWriteJson, copyFileDurable, ensureDir, isInside, readJson, safeSegment, sha256, stamp } from './util/fs.mjs';
21
- import { encodeSegment, projectKey, profileDir, resolveDshHome, sessionDir } from './util/paths.mjs';
21
+ import { encodeSegment, missingDriveForPath, projectKey, profileDir, resolveDshHome, sessionDir } from './util/paths.mjs';
22
22
 
23
23
  export const RESTORE_CODES = Object.freeze({
24
24
  SESSION_INVALID: 'TIMEMACHINE_SESSION_INVALID',
25
25
  SESSION_MISSING: 'TIMEMACHINE_SESSION_MISSING',
26
26
  PATH_INVALID: 'TIMEMACHINE_PATH_INVALID',
27
+ PATH_DRIVE_MISSING: 'TIMEMACHINE_PATH_DRIVE_MISSING',
27
28
  VERIFY_FAILED: 'TIMEMACHINE_VERIFY_FAILED',
28
29
  APPLY_FAILED: 'TIMEMACHINE_APPLY_FAILED',
29
30
  PLUGIN_INSTALL_FAILED: 'TIMEMACHINE_PLUGIN_INSTALL_FAILED',
@@ -104,6 +105,7 @@ export function planRestore(input) {
104
105
  const targetDocument = registryDocument(targetRegistryRaw);
105
106
 
106
107
  const warnings = [];
108
+ const pathIssues = [];
107
109
  if (point.source_platform !== undefined && point.source_platform !== process.platform) {
108
110
  warnings.push(`还原点来自 ${point.source_platform},本机是 ${process.platform};工作区路径必须重新映射。`);
109
111
  }
@@ -204,6 +206,18 @@ export function planRestore(input) {
204
206
  const existing = targetDocument.tables.workspaces[targetId];
205
207
  const targetPathExists = fs.existsSync(workspace.target_path);
206
208
  if (!targetPathExists) warnings.push(`工作区目录不存在,将按映射路径创建:${workspace.target_path}`);
209
+ const missingDrive = missingDriveForPath(workspace.target_path);
210
+ if (missingDrive !== null) {
211
+ const message = `本机没有 ${missingDrive} 盘,无法还原工作区“${workspace.source_title}”到 ${workspace.target_path};请修改工作区文件夹。`;
212
+ pathIssues.push({
213
+ code: RESTORE_CODES.PATH_DRIVE_MISSING,
214
+ drive: missingDrive,
215
+ source_path: workspace.source_path,
216
+ target_path: workspace.target_path,
217
+ message,
218
+ });
219
+ warnings.push(message);
220
+ }
207
221
  workspacePlan.push({
208
222
  source_id: workspace.source_id,
209
223
  source_path: workspace.source_path,
@@ -319,6 +333,7 @@ export function planRestore(input) {
319
333
  added_sessions: merged.added_sessions,
320
334
  },
321
335
  workspaces: workspacePlan,
336
+ path_issues: pathIssues,
322
337
  plugins,
323
338
  plugin_packages: pluginPackages,
324
339
  will: {
@@ -376,6 +391,14 @@ function backupExisting(target, rel, backupDir) {
376
391
  */
377
392
  export function applyRestore(plan, options = {}) {
378
393
  if (!plan?.ok) return plan;
394
+ if (Array.isArray(plan.path_issues) && plan.path_issues.length > 0) {
395
+ return {
396
+ ok: false,
397
+ reason_code: RESTORE_CODES.PATH_DRIVE_MISSING,
398
+ detail: plan.path_issues.map((row) => row.message).join(';'),
399
+ path_issues: plan.path_issues,
400
+ };
401
+ }
379
402
  // plan carries absolute targets; resolve the live home from the registry file.
380
403
  const home = path.dirname(path.dirname(plan.registry.target_file));
381
404
  const backupDir = options.backupDir ?? backupDirFor(home);
@@ -659,6 +682,16 @@ export async function registerRestoredWorkspaces(workspaceRegistry, plan) {
659
682
  export async function restorePoint(input) {
660
683
  const plan = planRestore(input);
661
684
  if (!plan.ok) return plan;
685
+ if (Array.isArray(plan.path_issues) && plan.path_issues.length > 0) {
686
+ return {
687
+ ok: false,
688
+ reason_code: RESTORE_CODES.PATH_DRIVE_MISSING,
689
+ detail: plan.path_issues.map((row) => row.message).join(';'),
690
+ stage: 'preflight',
691
+ path_issues: plan.path_issues,
692
+ plan_ready: true,
693
+ };
694
+ }
662
695
  const dshHome = dshHomeForPlan(plan);
663
696
  const profile = typeof input.profile === 'string' && input.profile !== '' ? input.profile : plan.point.profile;
664
697
  const profilePath = profileDir(dshHome, profile);
@@ -688,6 +721,9 @@ export async function restorePoint(input) {
688
721
  packages,
689
722
  runner: input.runner,
690
723
  pnpmFile: input.pnpmFile,
724
+ dshVersion: input.dshVersion,
725
+ manifests: input.manifests,
726
+ checkCompatibility: input.checkCompatibility,
691
727
  onProgress: input.onProgress,
692
728
  });
693
729
  } catch (error) {
@@ -747,7 +783,7 @@ export async function restorePoint(input) {
747
783
  backupDir,
748
784
  skipRegistry: liveRegistry !== null,
749
785
  });
750
- if (!applied.ok) return { ...applied, stage: 'file-restore', plugins: install };
786
+ if (!applied.ok) return { ...applied, stage: 'file-restore', plugins: install, plugin_warnings: Array.isArray(install?.warnings) ? install.warnings : [] };
751
787
 
752
788
  let live = null;
753
789
  if (liveRegistry !== null) {
@@ -759,6 +795,7 @@ export async function restorePoint(input) {
759
795
  point: plan.point,
760
796
  stage: 'restored',
761
797
  plugins: install,
798
+ plugin_warnings: Array.isArray(install?.warnings) ? install.warnings : [],
762
799
  restore: applied,
763
800
  workspaces: live?.workspaces ?? applied.workspaces,
764
801
  display: live?.display ?? null,
@@ -1,3 +1,4 @@
1
+ import fs from 'node:fs';
1
2
  import os from 'node:os';
2
3
  import path from 'node:path';
3
4
 
@@ -72,7 +73,28 @@ export function platformLabel(platform = process.platform) {
72
73
 
73
74
  /** True when a path is a Windows drive path (imported from a Windows machine). */
74
75
  export function isWindowsPath(value) {
75
- return typeof value === 'string' && (/^[A-Za-z]:[\\/]/u.test(value) || value.startsWith('\\\\'));
76
+ return typeof value === 'string' && (/^[A-Za-z]:[\\/]/u.test(value) || value.startsWith('\\\\') || value.startsWith('//'));
77
+ }
78
+
79
+ /**
80
+ * Return `D:` when a Windows path points at a drive that is not mounted on
81
+ * this machine. Non-Windows platforms and relative paths never report a
82
+ * missing drive. The injectable `exists`/`platform` pair keeps this testable
83
+ * on every CI runner.
84
+ */
85
+ export function missingDriveForPath(value, options = {}) {
86
+ if (typeof value !== 'string') return null;
87
+ const platform = options.platform ?? process.platform;
88
+ if (platform !== 'win32') return null;
89
+ const match = /^([A-Za-z]):(?:[\\/]|$)/u.exec(value.trim());
90
+ if (match === null) return null;
91
+ const drive = `${match[1].toUpperCase()}:`;
92
+ const exists = options.exists ?? fs.existsSync;
93
+ try {
94
+ return exists(`${drive}\\`) ? null : drive;
95
+ } catch {
96
+ return drive;
97
+ }
76
98
  }
77
99
 
78
100
  /** Normalize a user-entered path for comparisons; case-insensitive on Windows. */
package/src/version.mjs CHANGED
@@ -1,2 +1,2 @@
1
1
  /** Single source for the version shown in the panel header and health routes. */
2
- export const PLUGIN_VERSION = '0.2.3';
2
+ export const PLUGIN_VERSION = '0.2.5';