@marktrue/dsh-mobile-remote 3.2.4-alpha.7 → 3.2.4-alpha.8

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,37 @@
1
1
  # Changelog
2
2
 
3
+ ## v3.2.4-alpha.8(build 40,issues #61 / #62)— 免重启插件更新与轮次 UI 收尾
4
+
5
+ > 插件 `3.2.4-alpha.8` / App `3.2.4+40` / 载体 `3.2.4-alpha.8-app`。
6
+
7
+ ### 插件:宿主原生插件管理器通道(DSH 0.2.2+,免重启更新)
8
+
9
+ - 新增 `lib/host-update-capabilities.js`:按**能力**探测宿主 `pluginManager` 与 `hmr`(不看宿主版本号,沿用 ADR 0017),给出通道选择 `host-manager > restart > guidance`。
10
+ - 新增 `lib/host-manager-update.js`:委托宿主 `pluginManager.updateBundle()` 执行进程内更新;把宿主 `ChangeResult` 压成稳定原因码,**不透传** diagnostic 原文(可能含路径/凭据),失败/取消/需重启分别归因。
11
+ - bootstrap / diagnostics 新增 `updateChannel`、`updateChannelDescription`、`canRestartHost`、`hostManager`;`services` 暴露 `pluginManager`、`hmr`。
12
+ - `plugin-update-controller` 新增 host-manager 提交分支,与重启通道共用同一 opId/租约/事务日志,两通道互斥、不并发。
13
+ - `detectRestartForm` 增加命令行证据(`dsh web ...` → web-foreground);前台 respawn 复用原命令行,`--port` 等参数不再丢失。
14
+ - 桌面连接页显示实际更新通道与「连接是否中断」;App 解析通道字段并提供「是否需要重启」的展示。
15
+
16
+ ### App:轮次过程 UI 收尾(issue #61,alpha.7 真机反馈)
17
+
18
+ - 展开态摘要去重:摘要行只作折叠态的展开入口;展开后改为过程块末尾行内「收起过程」,强制展开(运行中/插话/异常结束)不提供收起控件。
19
+ - 协议生命周期事件归调试可见:`job/*`、`session/jobs`、`question/*`、`approval/*` 等不再在普通模式渲染裸协议卡(待答/审批卡仍来自 store 与 `mobile/frame`)。
20
+ - 工具名兜底:新增 session 级 callId→toolName 映射(跨加载重建保留、换会话清空);仍无名称时标题为「工具调用」,折叠行给出参数/结果首行摘要(≤80 字)。
21
+ - 修复「正在调用工具…」常驻:抬头运行态只信 `group.running && !process.ended`,轮次结束后不再显示 running。
22
+ - 新增 `issue61_ui_polish_test.dart`(15 项)覆盖上述四类行为。
23
+
24
+ ### 宿主兼容性 canary 增强(#62)
25
+
26
+ - 安装阶段预检插件依赖解析,归因到具体缺失依赖包(`install`/`runtime` 阶段各自归因);安装保留 peer 解析、npm pack 时打包 bundled 运行时依赖并创建目标目录。
27
+ - 启动失败诊断可归因性增强;runtime 阶段自检插件可加载性;install worker 注入缺失依赖白名单。
28
+ - `tools/worktree.sh`:refresh-baseline 支持授权后刷新任务基线(写入/归属/授权收紧、注入写前拒绝、摘要级失败判定、自证断言),门禁自测同步扩充。
29
+
30
+ ### 文档与验证
31
+
32
+ - `docs/10-release.md` 与当前 npm 发布链对齐:移除「GitHub Release 三资产」表述,改为 npm 载体一致性校验(本链路通过 `-app` 载体分发 APK,不创建 GitHub Release)。
33
+ - 补跑 alpha.7 全新安装冒烟(隔离 HOME `pnpm add`):插件/载体版本与精确别名正确,APK `87,796,802 B` sha256=`5455b78f…` 与载体清单一致,主插件 tarball sha256 与清单一致。
34
+
3
35
  ## v3.2.4-alpha.7(build 39,issues #52 / #53 / #54)— 轮末两卡与工具卡结构化
4
36
 
5
37
  > 插件 `3.2.4-alpha.7` / App `3.2.4+39` / 载体 `3.2.4-alpha.7-app`。
@@ -25,11 +25,20 @@
25
25
  | 桌面宠物前台联动(build 27) | `MainActivity.onStart/onStop` → 服务根视图 `GONE`:App 在前台时收起宠物与状态气泡/迷你面板;`设置 → 桌面宠物 → App 在前台时收起` 可关。旧系统不涉及(仅原生层行为) |
26
26
  | 图标主题化与圆形图标 | **已知缺口**:`mipmap-anydpi-v26` 未提供 `<monochrome>` 层,Android 13 主题图标不生效;未声明 `android:roundIcon`,圆形图标机型退化为方形。计划在后续版本补齐,不影响功能 |
27
27
  | Flutter 构建环境 | Flutter 3.35+(Dart SDK ^3.13) |
28
+ | 插件自更新通道(v3.5) | 按**能力**分两条通道,不按宿主版本号门禁:宿主提供 `pluginManager.updateBundle` 且本插件可被它更新 → **`host-manager`**(进程内热更新,**不重启宿主**;HMR 可用时立即生效,否则装完需重启);否则退回传统通道(改依赖 → pnpm install → 重启 → 健康确认),再不行给人工指引。`0.2.2` 之前的宿主没有该服务,自动走传统通道,行为与旧版一致 |
28
29
 
29
30
  **声明式兼容范围(`peerDependencies`)**:`@deepseek-ai/dsh-{credentials,llm,sandbox-policy,scope}` 声明 `>=0.1.0-rc.6 <=0.2.2 || >=0.2.0-0 <0.2.0 || >=0.2.1-0 <0.2.1 || >=0.2.2-0 <0.2.2`。稳定版上限为 `0.2.2`;三个显式预发布分支分别纳入已发布的 `0.2.0-rc.*`、`0.2.1-rc.*`、`0.2.2-alpha/rc.*` 系列(npm 默认 semver 语义不会把裸 `<=0.2.2` 认作覆盖预发布版本)。`0.2.3+` 与 `0.3.0+` 会被判为不兼容。
30
31
 
31
32
  注意两条判定通道语义不同:宿主 `@deepseek-ai/dsh-app-boot` 的 `evaluatePluginCompatibility()` 用 `semver.satisfies(runtimeVersion, range, { includePrerelease: true })`(运行时放行预发布);npm / pnpm 安装期的 peer 解析用默认语义,所以预发布宿主必须在范围里显式出现。上界**只用于声明可安装边界**,功能路径仍按能力探测(ADR 0017),不按版本号做功能门禁。
32
33
 
34
+ **更新通道路由(v3.5,DSH 0.2.2+)**:`/m/api/bootstrap` 的 `pluginUpdate.updateChannel` 给出本机实际使用的通道,`updateChannelDescription` 是给用户的一句话说明(两端共用同一文案):
35
+
36
+ - `host-manager`:宿主原生插件管理器在进程内卸载旧版、安装新版。HMR 可用时**连接不中断**;`pluginUpdate.hostManager.hmrAvailable` 表示这一点。失败时宿主会自己把旧版本装回,并把结果如实报出。
37
+ - `restart`:传统通道(`<0.2.2` 或宿主管理器不可用时)。安装后重启宿主,重启形态由 `restartForm` 给出(`web-systemd` / `web-foreground`);前台 web 形态的 respawn **复用本进程原命令行**,因此 `--port` 等参数不会丢。
38
+ - `guidance`:两条通道都不可用,只能给人工指引。
39
+
40
+ `services` 一节同时新增 `pluginManager` / `hmr` 两项,可直接看到宿主是否提供这两项能力。
41
+
33
42
  **快速自检**:手机 App → 设置 → 环境诊断。`services` 一节列出每个内核服务是否存在;**v3.1.3+ 看 `checks.approvalMode`**(生效策略)与 **`checks.remoteEvents`**(`true` = `$events` 双端呈现通道就绪,`false` = both 降级 mobile 或配置即 mobile/desktop);`notes` 说明当前审批策略实际语义与**任何非全绿的宿主能力**。
34
43
 
35
44
  **v3.1.6+ 新增宿主能力自检**(ADR 0017;issue #30 起补原因码):
@@ -45,7 +45,7 @@
45
45
  | 发布清单 | `<dist>/manifest.json` | schema 1;`app` + `plugin` 两段 + 顶层兼容镜像 |
46
46
  | 载体 tarball | `<dist>/marktrue-dsh-mobile-remote-<X.Y.Z>-app.tgz` | 同包名 `X.Y.Z-app`;内含 APK + 清单 + 说明/许可;发布到 npm 的 `app` tag |
47
47
  | 构建记录 | `<dist>/app-carrier.json` | 载体 tarball 的体积/哈希与两段身份;本地证据,不上传 |
48
- | Release 三资产 | GitHub Release | 上面的清单 + APK + 主插件 tarball(逐字节一致) |
48
+ | 发布交付 | npm registry(`alpha`/`rc`/`latest` 与 `app` 通道) | 主插件 tarball 与载体 tarball(`<X.Y.Z>-app`,内含 APK + 清单)分别发布到 npm;**本链路不创建 GitHub Release**,APK 通过 npm 载体分发(逐字节一致以 `dist.integrity` 校验) |
49
49
 
50
50
  ### 1.3 环境前置
51
51
 
@@ -456,7 +456,7 @@ NODE
456
456
  # 必须看到 alpha = 本次版本、app = 本次 carrier、latest 保持原值
457
457
  ```
458
458
 
459
- 4. **发布 Release 三资产**(同一清单、同一 APK、同一主插件 tgz;文件名/大小/哈希逐字节一致)。
459
+ 4. **分发与归档(无 GitHub Release)**:本链路不创建 GitHub Release —— 载体 tarball 已随第 2 步发布到 npm `app` tag、主插件 tarball 随第 3 步发布到对应 channel;人工兜底只需保证两次 `npm publish` 的产物与本地 `<dist>` 逐字节一致(sha256 / `dist.integrity`),并在发布记录中登记 registry URL。
460
460
  5. **记录结果**:两次发布各自的耗时/结果/公开 URL;失败与部分成功按 §10 处理。
461
461
 
462
462
  > 人工发布会话同样必须先把发布意图写入 release-meta(`node tools/release-gate.mjs record-intent ...`),发布后标记 published/failed;无法确认可见性时标记 unknown 并停止。
@@ -484,7 +484,7 @@ NODE
484
484
  3. **发布意图状态**:`git show origin/release-meta:build-policy.json` 中本次 tag 的意图应为 `published`,且没有为其它 tag 的未关闭 `submitted`/`unknown` 意图;未知状态按 §10.3 人工恢复。
485
485
  4. **镜像可取性**:在有代表性的镜像/网络环境重试上述查询与下载(记录耗时)。
486
486
  5. **全新安装冒烟**:在隔离 HOME/新目录 `pnpm add @marktrue/dsh-mobile-remote@<本次插件版本>`,确认精确别名目录存在且版本为 `<本次插件版本>-app`、APK 哈希与清单一致。
487
- 6. **Release 三资产**:GitHub Release 的清单/APK/插件 tgz 与本地 dist 逐字节一致(sha256)。
487
+ 6. **载体产物一致性(npm 分发,无 GitHub Release)**:下载本次 carrier tarball(`npm pack @marktrue/dsh-mobile-remote@<本次载体版本>`,或按 `npm view … dist.tarball` 直接下载),解包核对其中 APK 与清单和本地 `<dist>` 产物的 sha256 / 大小逐字节一致;主插件 tarball 用 `npm view @marktrue/dsh-mobile-remote@<本次插件版本> dist.integrity` 与本地 tgz 的 sha512 对照。**当前发布链不创建 GitHub Release。**
488
488
  7. **宿主更新目录**:如使用 `UPDATE_DIR`,确认清单/APK/tgz 已落位且 `manifest.json` 可解析;宿主重启后更新入口可用。
489
489
  8. **真机**:按 `docs/06-install-run.md` 手工验证 App 更新/首装(本手册不自动化真机),记录机型、网络与结果。
490
490
  9. **回滚预案**:确认上一版本插件 tgz/载体/APK 仍可取得(本地 dist 与 Release 记录),并知道回滚操作(§10)。
package/lib/client.js CHANGED
@@ -340,12 +340,27 @@ window.__ModuleLoader__.load({
340
340
  var state = String(value.state || "unknown");
341
341
  var transaction = value.transaction && typeof value.transaction === "object" ? value.transaction : null;
342
342
  var appVersion = String(carrier.appVersion || transaction?.targetAppVersion || "");
343
+ var hostManager = value.hostManager && typeof value.hostManager === "object" ? value.hostManager : null;
344
+ var updateChannel = String(value.updateChannel || "");
343
345
  return {
344
346
  state: state,
345
347
  reason: String(value.reason || ""),
346
348
  candidate: candidate,
347
349
  hasUpdate: state === "update-available" && Boolean(plugin.version),
348
350
  canSelfUpdate: value.canSelfUpdate === true,
351
+ // 通道(v3.5):host-manager = 进程内更新不重启;restart = 装完要重启宿主。
352
+ updateChannel: updateChannel,
353
+ updateChannelDescription: String(value.updateChannelDescription || ""),
354
+ canRestartHost: value.canRestartHost === true,
355
+ // 是否由宿主管理器在进程内完成(界面据此选择"不中断"措辞)。
356
+ usesHostManager: updateChannel === "host-manager",
357
+ hostManagerHmrAvailable: hostManager ? hostManager.hmrAvailable === true : null,
358
+ // 本次更新是否会让连接短暂断开(决定要不要提前预告)。
359
+ updateRestartsHost: updateChannel === "host-manager"
360
+ ? (hostManager ? hostManager.hmrAvailable === false : false)
361
+ : updateChannel === "restart"
362
+ ? true
363
+ : (updateChannel === "" && value.canSelfUpdate === true),
349
364
  pluginVersion: String(plugin.version || transaction?.targetVersion || ""),
350
365
  appVersion: appVersion,
351
366
  needsPreparation: state === "update-available" && !appVersion,
@@ -817,11 +832,18 @@ window.__ModuleLoader__.load({
817
832
  jsxRuntime.jsx("div", { style: { fontSize: "12.5px", color: "var(--dsw-alias-label-secondary, #888)" }, children: statusText }),
818
833
  progressBox,
819
834
  model.hasUpdate ? jsxRuntime.jsx("div", { style: { fontSize: "12.5px", lineHeight: "1.6" }, children: "插件 v" + pluginVersion + (appVersion ? " · App build " + appVersion : " · App build 将在准备后核验") }) : null,
835
+ // v3.5:把实际更新通道讲清楚——「不重启」与「会重启」对用户是完全不同的体验,
836
+ // 不能只在出错时才让用户猜。
837
+ model.hasUpdate && model.updateChannelDescription
838
+ ? jsxRuntime.jsx("div", { style: { fontSize: "12px", lineHeight: "1.6", color: "var(--dsw-alias-label-secondary, #888)" },
839
+ children: model.updateChannelDescription + (model.updateRestartsHost ? ";期间连接会短暂断开,重连后自动接续。" : ";连接不会中断。") })
840
+ : null,
820
841
  operationTarget,
821
842
  model.hasUpdate && !model.canSelfUpdate ? jsxRuntime.jsx("div", { style: { fontSize: "12px", color: "var(--dsw-alias-label-secondary, #888)" }, children: model.guidance?.summary || "当前安装形态需要按电脑端指引更新。" }) : null,
822
843
  workflow.status === "preparing" ? jsxRuntime.jsx("div", { style: { fontSize: "12px" }, children: "正在从主机 NPM 源准备并校验 carrier;profile 尚未修改…" }) : null,
844
+ workflow.status === "submitting" && model.usesHostManager ? jsxRuntime.jsx("div", { style: { fontSize: "12px" }, children: "正在交给宿主插件管理器处理…" }) : null,
823
845
  workflow.status === "submitting" ? jsxRuntime.jsx("div", { style: { fontSize: "12px" }, children: "正在提交安装事务…" }) : null,
824
- workflow.status === "running" ? jsxRuntime.jsx("div", { style: { fontSize: "12px" }, children: "pnpm 安装/重启进行中;输出会保留并可在重连后继续查看。" }) : null,
846
+ workflow.status === "running" ? jsxRuntime.jsx("div", { style: { fontSize: "12px" }, children: model.updateRestartsHost ? "安装/重启进行中;输出会保留并可在重连后继续查看。" : "宿主插件管理器正在进程内更新;连接不会中断,输出会保留。" }) : null,
825
847
  workflow.message ? jsxRuntime.jsx("div", { style: { fontSize: "12px", color: workflow.status === "failed" ? "var(--dsw-alias-text-danger, #e5484d)" : "inherit" }, children: workflow.message }) : null,
826
848
  detailsPanel,
827
849
  actionButton,
@@ -0,0 +1,178 @@
1
+ // 通过宿主原生插件管理器执行更新(DSH 0.2.2+):不重启宿主。
2
+ //
3
+ // 与 `plugin-self-update.js` 那条「改依赖 → pnpm install → 重启 → 健康确认」的传统
4
+ // 通道并列;本模块只在宿主提供 `pluginManager.updateBundle()` 时使用。
5
+ //
6
+ // 为什么优先用它:
7
+ // 1. **不重启**:宿主在 HMR 可用时移除旧版本、装新版本并在进程内重新组合 profile,
8
+ // 插件被重新加载而宿主进程不变——手机与桌面都不掉连接。
9
+ // 2. **判定权交给宿主**:registry 选择、pnpm 配置、凭据、兼容性豁免、构建脚本批准
10
+ // 全部由宿主那一套既有实现决定,我们不重复实现、也不绕过它的安全检查。
11
+ // 3. **失败即回滚**:宿主在装新版本失败/取消时会把旧版本装回去,并把结果如实报出来。
12
+ //
13
+ // 本模块不做的事:不自己跑 pnpm、不改 profile 文件、不做健康判定(宿主的
14
+ // `application` 字段就是结论)。
15
+ import { compareVersion, parseVersion } from "./plugin-update.js";
16
+ import { HOST_MANAGER_REASON, UPDATE_CHANNEL } from "./host-update-capabilities.js";
17
+
18
+ /** 宿主更新失败的稳定原因码(对外只暴露这一类,不含宿主异常原文)。 */
19
+ export const HOST_MANAGER_ERROR = {
20
+ /** 探测阶段就不可用。 */
21
+ UNAVAILABLE: "host-manager-unavailable",
22
+ /** 目标版本不是合法 semver。 */
23
+ VERSION_INVALID: "host-manager-version-invalid",
24
+ /** 目标版本不高于已安装版本(宿主会拒绝,这里提前挡)。 */
25
+ VERSION_NOT_NEWER: "host-manager-version-not-newer",
26
+ /** 宿主拒绝(`ChangeResult.application === 'failed'`)。 */
27
+ REJECTED: "host-manager-rejected",
28
+ /** 用户/调用方取消。 */
29
+ CANCELLED: "host-manager-cancelled",
30
+ /** 装上了但需要重启才生效。 */
31
+ RESTART_REQUIRED: "host-manager-restart-required",
32
+ /** 调用 itself 抛错。 */
33
+ CALL_FAILED: "host-manager-call-failed",
34
+ /** 被替代/覆盖(同一插件条目上有更高优先级的覆盖)。 */
35
+ OVERRIDDEN: "host-manager-overridden",
36
+ };
37
+
38
+ /**
39
+ * 把宿主的 `ChangeResult`(以及 `updateBundle` 外层结果)压成我们自己的稳定结论。
40
+ *
41
+ * 宿主字段语义(见 dsh-plugin-manager 的 `ChangeResult` / `PluginUpdateResult`):
42
+ * - `application: 'applied'` → 已生效,无需重启;
43
+ * - `application: 'restart-required'` → 装了但下次启动才生效;
44
+ * - `application: 'failed' | 'cancelled'` → 未生效(`restore` 存在时表示旧版本已装回);
45
+ * - `application: 'overridden'` → 被其它条目覆盖。
46
+ *
47
+ * @param {object|undefined} outcome - `updateBundle()` 的返回值。
48
+ * @returns {{ok: boolean, reason: string, restored: boolean, from: string, to: string, step: string, detail: string}}
49
+ */
50
+ export function interpretHostManagerUpdate(outcome) {
51
+ const from = typeof outcome?.from === "string" ? outcome.from : "";
52
+ const to = typeof outcome?.to === "string" ? outcome.to : "";
53
+ const step = typeof outcome?.step === "string" ? outcome.step : "";
54
+ const base = { from, to, step, restored: Boolean(outcome?.restore) };
55
+ // `updateBundle` 在「检查阶段就拒绝」时也可能没有 result。
56
+ const result = outcome?.result;
57
+ if (!result || typeof result !== "object") {
58
+ const reason = typeof result === "string" ? result : "";
59
+ return { ...base, ok: false, reason: HOST_MANAGER_ERROR.REJECTED, detail: reason };
60
+ }
61
+ switch (result.application) {
62
+ case "applied":
63
+ return { ...base, ok: true, reason: "", detail: "" };
64
+ case "restart-required":
65
+ return { ...base, ok: false, reason: HOST_MANAGER_ERROR.RESTART_REQUIRED, detail: String(result.restartReason ?? "") };
66
+ case "cancelled":
67
+ return { ...base, ok: false, reason: HOST_MANAGER_ERROR.CANCELLED, detail: "" };
68
+ case "overridden":
69
+ return { ...base, ok: false, reason: HOST_MANAGER_ERROR.OVERRIDDEN, detail: "" };
70
+ case "failed":
71
+ default: {
72
+ // 宿主的 error 是结构化对象(code/diagnostic);只取 code,绝不透传 diagnostic 原文
73
+ // (可能含 registry URL、凭据或缺路径)。
74
+ const code = typeof result.error?.code === "string" ? result.error.code : "";
75
+ return { ...base, ok: false, reason: HOST_MANAGER_ERROR.REJECTED, detail: code };
76
+ }
77
+ }
78
+ }
79
+
80
+ /**
81
+ * 校验目标版本可以交给宿主更新。
82
+ *
83
+ * 宿主自己也会校验(`semver.gt`),这里提前挡是为了给出**我们自己的稳定原因码**,
84
+ * 而不是把宿主的英文 diagnostic 抛给手机。
85
+ *
86
+ * @param {object} input
87
+ * @param {string} input.targetVersion - 目标版本。
88
+ * @param {string} input.installedVersion - 当前已安装版本。
89
+ * @returns {{ok: boolean, reason: string}}
90
+ */
91
+ export function validateHostManagerTarget({ targetVersion, installedVersion } = {}) {
92
+ if (!parseVersion(targetVersion)) return { ok: false, reason: HOST_MANAGER_ERROR.VERSION_INVALID };
93
+ if (installedVersion) {
94
+ const comparison = compareVersion(targetVersion, installedVersion);
95
+ // 比较不出来时放行给宿主判定:我们的比较器只认 `X.Y.Z[-pre][+N]`,
96
+ // 而宿主用的是完整 semver——不因为我们的解析面更窄就误拒。
97
+ if (comparison !== null && comparison <= 0) {
98
+ return { ok: false, reason: HOST_MANAGER_ERROR.VERSION_NOT_NEWER };
99
+ }
100
+ }
101
+ return { ok: true, reason: "" };
102
+ }
103
+
104
+ /**
105
+ * 通过宿主插件管理器更新本插件。
106
+ *
107
+ * 执行顺序刻意固定:
108
+ * 1. 探测结论必须可用(`probe.channel === host-manager`),否则直接拒绝;
109
+ * 2. 校验目标版本;
110
+ * 3. 调 `updateBundle(name, version, { registry?, requestId? })`;
111
+ * 4. 把结果压成稳定结论。
112
+ *
113
+ * 不在这里做重试:宿主的 `updateBundle` 内部已经处理了 registry 回退与失败回滚,
114
+ * 我们外加一层重试只会让「已经回滚过的事」再发生一次。
115
+ *
116
+ * @param {object} input
117
+ * @param {object} input.service - `pluginManager` 服务实例。
118
+ * @param {string} input.packageName - 本插件包名。
119
+ * @param {string} input.targetVersion - 目标版本。
120
+ * @param {string} [input.installedVersion] - 当前版本(用于提前挡降级)。
121
+ * @param {string} [input.registry] - 指定 registry;缺省由宿主按配置决定。
122
+ * @param {string} [input.requestId] - 宿主用它关联进度与日志。
123
+ * @param {(progress: object) => void} [input.onProgress] - 宿主 `update-state` 事件的转发。
124
+ * @param {object} [input.log] - 结构化日志(注入以便测试)。
125
+ * @returns {Promise<object>} 稳定结论。
126
+ */
127
+ export async function runHostManagerUpdate({
128
+ service,
129
+ packageName,
130
+ targetVersion,
131
+ installedVersion = "",
132
+ registry,
133
+ requestId,
134
+ onProgress,
135
+ log = {},
136
+ } = {}) {
137
+ if (!service || typeof service.updateBundle !== "function") {
138
+ return { ok: false, channel: UPDATE_CHANNEL.HOST_MANAGER, reason: HOST_MANAGER_REASON.SERVICE_MISSING, from: "", to: String(targetVersion ?? ""), step: "", restored: false };
139
+ }
140
+ if (typeof packageName !== "string" || packageName === "") {
141
+ return { ok: false, channel: UPDATE_CHANNEL.HOST_MANAGER, reason: HOST_MANAGER_REASON.NOT_UPDATABLE, from: "", to: String(targetVersion ?? ""), step: "", restored: false };
142
+ }
143
+ const validated = validateHostManagerTarget({ targetVersion, installedVersion });
144
+ if (!validated.ok) {
145
+ return { ok: false, channel: UPDATE_CHANNEL.HOST_MANAGER, reason: validated.reason, from: String(installedVersion ?? ""), to: String(targetVersion ?? ""), step: "check", restored: false };
146
+ }
147
+ const options = {};
148
+ // 只在调用方明确给了 registry 时才传:缺省要比「传 undefined」更明确地走宿主配置。
149
+ if (typeof registry === "string" && registry !== "") options.registry = registry;
150
+ if (typeof requestId === "string" && requestId !== "") options.requestId = requestId;
151
+ let outcome;
152
+ try {
153
+ log.stage?.("host-manager", `Updating ${packageName} to ${targetVersion} through the host plugin manager`);
154
+ outcome = await service.updateBundle(packageName, targetVersion, Object.keys(options).length > 0 ? options : undefined);
155
+ } catch (error) {
156
+ // 宿主在锁超时/服务销毁时是 reject 而不是返回失败结果;这仍然是一次失败结论。
157
+ log.fail?.("host-manager", "Host plugin manager update call rejected");
158
+ return {
159
+ ok: false,
160
+ channel: UPDATE_CHANNEL.HOST_MANAGER,
161
+ reason: HOST_MANAGER_ERROR.CALL_FAILED,
162
+ from: String(installedVersion ?? ""),
163
+ to: String(targetVersion ?? ""),
164
+ step: "",
165
+ restored: false,
166
+ detail: typeof error?.code === "string" ? error.code : "",
167
+ };
168
+ }
169
+ const interpreted = interpretHostManagerUpdate(outcome);
170
+ if (typeof onProgress === "function") {
171
+ try {
172
+ onProgress({ step: interpreted.step, from: interpreted.from, to: interpreted.to });
173
+ } catch {
174
+ // 进度回调不应影响更新结论
175
+ }
176
+ }
177
+ return { ...interpreted, channel: UPDATE_CHANNEL.HOST_MANAGER };
178
+ }
@@ -0,0 +1,203 @@
1
+ // 宿主「原生插件更新」能力探测(DSH 0.2.2+ 的 `pluginManager` 服务)。
2
+ //
3
+ // 背景:0.2.2 起 DSH 自带插件管理器(`@deepseek-ai/dsh-plugin-manager`),它把
4
+ // 「装/删/更新插件」做成了宿主内的服务方法,并且 **在 HMR 可用时不重启宿主**:
5
+ // `updateBundle()` 会先移除旧版本、再装新版本,由 `hmr.reconcileProfile()` 在进程内
6
+ // 重新组合 profile——插件被卸载并重新加载,宿主进程不变。
7
+ //
8
+ // 我们的自更新原先只会「改 profile 依赖 → pnpm install → 重启宿主」这一条路;当宿主
9
+ // 形态判断不出可重启方式(例如容器里没有 systemd、进程环境没有 DSH_PROFILE)时,
10
+ // 就整条降级成「请到电脑上运行 pnpm install」的手工指引。有了宿主原生能力后,
11
+ // 那种情形可以直接委托给宿主,彻底不需要重启,也不需要用户碰命令行。
12
+ //
13
+ // 本模块只做**探测**与**能力描述**,不执行更新(执行在 plugin-self-update.js)。
14
+
15
+ /** 更新执行通道。 */
16
+ export const UPDATE_CHANNEL = {
17
+ /** 委托宿主 `pluginManager.updateBundle()`:进程内热更新,不重启。 */
18
+ HOST_MANAGER: "host-manager",
19
+ /** 传统通道:改 profile 依赖 → pnpm install → 重启宿主并做健康确认。 */
20
+ RESTART: "restart",
21
+ /** 两者都不可用,只能给人工指引。 */
22
+ GUIDANCE: "guidance",
23
+ };
24
+
25
+ /** 宿主管理器不可用的稳定原因码(对外只暴露这几类,不含内部异常原文)。 */
26
+ export const HOST_MANAGER_REASON = {
27
+ /** 宿主没有 `pluginManager` 服务(0.2.2 之前,或该 bundle 未启用)。 */
28
+ SERVICE_MISSING: "host-manager-service-missing",
29
+ /** 服务存在但没有 `updateBundle` 方法(接口被裁剪/版本不符)。 */
30
+ METHOD_MISSING: "host-manager-method-missing",
31
+ /** 宿主没报告 HMR:更新仍可安装,但结果要重启才生效。 */
32
+ HMR_MISSING: "host-manager-hmr-missing",
33
+ /** 当前安装不是「以自身包名从 registry 装的 profile 依赖」,宿主会拒绝更新。 */
34
+ NOT_UPDATABLE: "host-manager-not-updatable",
35
+ /** 探测过程抛错。 */
36
+ PROBE_FAILED: "host-manager-probe-failed",
37
+ };
38
+
39
+ /** 探测结果的稳定状态。 */
40
+ export const HOST_MANAGER_STATE = {
41
+ /** 可用且能免重启生效。 */
42
+ READY: "ready",
43
+ /** 可用,但生效需要重启(无 HMR)。 */
44
+ RESTART_REQUIRED: "restart-required",
45
+ /** 不可用。 */
46
+ UNSUPPORTED: "unsupported",
47
+ };
48
+
49
+ /**
50
+ * 读 `pluginManager` 服务。
51
+ *
52
+ * 探测顺序刻意保守:先拿服务(`ctx.get('pluginManager')`),再确认 `updateBundle`
53
+ * 是可调用函数。**不看版本号**——版本号无法证明该服务真的挂在当前 profile 上
54
+ * (ADR 0017:能力看声明,不看版本号)。任何异常都收敛成 unsupported,不向上抛。
55
+ *
56
+ * @param {object} ctx - cordis 上下文。
57
+ * @returns {{available: boolean, reason: string, service: object|null}}
58
+ */
59
+ export function probeHostPluginManager(ctx) {
60
+ let service;
61
+ try {
62
+ service = ctx?.get?.("pluginManager");
63
+ } catch {
64
+ return { available: false, reason: HOST_MANAGER_REASON.PROBE_FAILED, service: null };
65
+ }
66
+ if (!service || typeof service !== "object") {
67
+ return { available: false, reason: HOST_MANAGER_REASON.SERVICE_MISSING, service: null };
68
+ }
69
+ if (typeof service.updateBundle !== "function") {
70
+ return { available: false, reason: HOST_MANAGER_REASON.METHOD_MISSING, service };
71
+ }
72
+ return { available: true, reason: "", service };
73
+ }
74
+
75
+ /**
76
+ * 宿主是否报告 HMR(决定更新结果能否免重启生效)。
77
+ *
78
+ * `pluginManager.updateBundle` 在没有 HMR 时照样能装,只是返回
79
+ * `application: 'restart-required'`。这里单独探测,是为了在**开始更新之前**
80
+ * 就告诉用户「这次会重启」还是「这次不重启」,而不是等装完再报。
81
+ *
82
+ * @param {object} ctx - cordis 上下文。
83
+ * @returns {{available: boolean, reason: string}}
84
+ */
85
+ export function probeHostHmr(ctx) {
86
+ let hmr;
87
+ try {
88
+ hmr = ctx?.get?.("hmr");
89
+ } catch {
90
+ return { available: false, reason: HOST_MANAGER_REASON.PROBE_FAILED };
91
+ }
92
+ if (!hmr || typeof hmr !== "object" || typeof hmr.reconcileProfile !== "function") {
93
+ return { available: false, reason: HOST_MANAGER_REASON.HMR_MISSING };
94
+ }
95
+ return { available: true, reason: "" };
96
+ }
97
+
98
+ /**
99
+ * 由 bundle 视图判断宿主会不会接受这次更新。
100
+ *
101
+ * `updateBundle` 的准入是(见 dsh-plugin-manager 的 `updateRefusal`):
102
+ * 必须是 profile 里的第三方依赖、从 registry 以**自身包名**安装、声明 semver 版本、
103
+ * 不带插件管理职责。`listBundles()` 已经把结论投影成 `updatable` 与
104
+ * `readOnlyReason`,这里直接采信,不重复实现那套判据。
105
+ *
106
+ * @param {object|undefined} bundle - `listBundles()` 里对应本插件的一行。
107
+ * @returns {{ok: boolean, reason: string}}
108
+ */
109
+ export function hostManagerAcceptsBundle(bundle) {
110
+ if (!bundle || typeof bundle !== "object") {
111
+ return { ok: false, reason: HOST_MANAGER_REASON.NOT_UPDATABLE };
112
+ }
113
+ if (bundle.updatable !== true) {
114
+ return { ok: false, reason: HOST_MANAGER_REASON.NOT_UPDATABLE };
115
+ }
116
+ if (bundle.readOnlyReason !== undefined) {
117
+ return { ok: false, reason: HOST_MANAGER_REASON.NOT_UPDATABLE };
118
+ }
119
+ return { ok: true, reason: "" };
120
+ }
121
+
122
+ /**
123
+ * 汇总一次探测的结果:宿主管理器可用性 + HMR + 本插件是否可被它更新。
124
+ *
125
+ * 返回的 `channel` 是本进程**应该优先使用**的更新通道;调用方还要结合传统重启通道
126
+ * 是否可用再决定最终通道(见 {@link chooseUpdateChannel})。
127
+ *
128
+ * @param {object} input
129
+ * @param {object} input.ctx - cordis 上下文。
130
+ * @param {string} input.packageName - 本插件包名。
131
+ * @param {(name: string) => Promise<object[]>} [input.listBundles] - 宿主 `listBundles()`;缺省用服务自己的方法。
132
+ * @returns {Promise<object>} 探测结果(稳定字段,可直接进 bootstrap)。
133
+ */
134
+ export async function detectHostUpdateCapabilities({ ctx, packageName, listBundles } = {}) {
135
+ const manager = probeHostPluginManager(ctx);
136
+ const hmr = probeHostHmr(ctx);
137
+ const base = {
138
+ packageName: typeof packageName === "string" ? packageName : "",
139
+ managerAvailable: manager.available,
140
+ managerReason: manager.reason,
141
+ hmrAvailable: hmr.available,
142
+ hmrReason: hmr.reason,
143
+ updatable: false,
144
+ state: HOST_MANAGER_STATE.UNSUPPORTED,
145
+ channel: UPDATE_CHANNEL.GUIDANCE,
146
+ };
147
+ if (!manager.available) return base;
148
+ const service = manager.service;
149
+ let bundle;
150
+ try {
151
+ const list = typeof listBundles === "function" ? listBundles : service.listBundles;
152
+ const bundles = await list.call(service);
153
+ bundle = Array.isArray(bundles) ? bundles.find((item) => item?.name === base.packageName) : undefined;
154
+ } catch {
155
+ return { ...base, managerReason: HOST_MANAGER_REASON.PROBE_FAILED };
156
+ }
157
+ const accepts = hostManagerAcceptsBundle(bundle);
158
+ if (!accepts.ok) {
159
+ return { ...base, managerReason: accepts.reason, installedVersion: bundle?.version ?? "" };
160
+ }
161
+ return {
162
+ ...base,
163
+ updatable: true,
164
+ state: hmr.available ? HOST_MANAGER_STATE.READY : HOST_MANAGER_STATE.RESTART_REQUIRED,
165
+ channel: UPDATE_CHANNEL.HOST_MANAGER,
166
+ installedVersion: bundle?.version ?? "",
167
+ };
168
+ }
169
+
170
+ /**
171
+ * 在「宿主原生免重启更新」与「传统重启更新」之间选通道。
172
+ *
173
+ * 规则(顺序即优先级):
174
+ * 1. 宿主管理器可用 → 用它(免重启,且不依赖我们能重启宿主)。
175
+ * 2. 否则传统重启通道可用(systemd / 前台 web)→ 用重启。
176
+ * 3. 都不行 → 人工指引。
177
+ *
178
+ * 注意第 1 条**不看** `hmrAvailable`:没有 HMR 时宿主管理器仍会把包装好,
179
+ * 只是返回 `restart-required`。这种情形仍优先走管理器——它至少保证了
180
+ * 「依赖真的被装上了」,比我们自己 `pnpm install` 更可靠;重启由宿主报告为准。
181
+ *
182
+ * @param {object} input
183
+ * @param {boolean} input.hostManagerAvailable - 宿主管理器是否可用(且本插件可被它更新)。
184
+ * @param {boolean} input.canRestart - 传统重启通道是否可用。
185
+ * @returns {{channel: string, reason: string}}
186
+ */
187
+ export function chooseUpdateChannel({ hostManagerAvailable = false, canRestart = false } = {}) {
188
+ if (hostManagerAvailable) return { channel: UPDATE_CHANNEL.HOST_MANAGER, reason: "" };
189
+ if (canRestart) return { channel: UPDATE_CHANNEL.RESTART, reason: "" };
190
+ return { channel: UPDATE_CHANNEL.GUIDANCE, reason: "no-update-channel" };
191
+ }
192
+
193
+ /** 通道 → 面向用户的一句话说明(手机与桌面共用,避免两端文案漂移)。 */
194
+ export function describeUpdateChannel(channel) {
195
+ switch (channel) {
196
+ case UPDATE_CHANNEL.HOST_MANAGER:
197
+ return "由 DSH 插件管理器在进程内更新,无需重启宿主";
198
+ case UPDATE_CHANNEL.RESTART:
199
+ return "安装新版本后重启宿主使插件生效";
200
+ default:
201
+ return "当前形态无法自动更新,需要人工处理";
202
+ }
203
+ }
package/lib/index.js CHANGED
@@ -51,6 +51,16 @@ import {
51
51
  selectBridgeEndpoint,
52
52
  } from "./desktop-form.js";
53
53
  import { detectInstallShape } from "./plugin-update.js";
54
+ import {
55
+ chooseUpdateChannel,
56
+ describeUpdateChannel,
57
+ detectHostUpdateCapabilities,
58
+ HOST_MANAGER_REASON,
59
+ HOST_MANAGER_STATE,
60
+ probeHostPluginManager,
61
+ UPDATE_CHANNEL,
62
+ } from "./host-update-capabilities.js";
63
+ import { runHostManagerUpdate } from "./host-manager-update.js";
54
64
  import {
55
65
  TRANSACTION_PHASE,
56
66
  checkForUpdate,
@@ -61,6 +71,7 @@ import {
61
71
  resolvePluginUpdateSource,
62
72
  resolvePluginUrl,
63
73
  restartPlan,
74
+ respawnCommandOf,
64
75
  runRestart,
65
76
  runSelfUpdate,
66
77
  UPDATE_SOURCE_KIND,
@@ -2817,12 +2828,17 @@ export function apply(ctx, config, runtime = {}) {
2817
2828
  const pluginUpdateStatus = { state: "unknown", reason: "not-checked" };
2818
2829
  // 是否由 systemd 托管:决定"终止宿主后有没有人把它拉起来"。INVOCATION_ID 只有服务单元里才有。
2819
2830
  const systemdManaged = () => existsSync("/run/systemd/system") && Boolean(process.env.INVOCATION_ID);
2820
- const restartFormOf = runtime.pluginUpdates?.restartForm ?? (() => detectRestartForm({ hasSystemdUnit: systemdManaged }));
2831
+ // 前台 web 形态的重启必须复用**本进程原命令行**:容器/自定义启动常见 `dsh web --port 3082`,
2832
+ // 拼一个默认的 `dsh web --profile web` 会丢掉端口等参数(重启后监听面就变了)。
2833
+ const respawnCommand = respawnCommandOf(process.argv);
2834
+ const restartFormOf = runtime.pluginUpdates?.restartForm
2835
+ ?? (() => detectRestartForm({ hasSystemdUnit: systemdManaged, commandLine: process.argv }));
2821
2836
  const restartContext = () => ({
2822
2837
  plan: restartPlan({
2823
2838
  form: restartFormOf(),
2824
2839
  pid: process.pid,
2825
2840
  profile: process.env.DSH_PROFILE || "web",
2841
+ respawnCommand,
2826
2842
  }),
2827
2843
  pid: process.pid,
2828
2844
  });
@@ -2858,20 +2874,101 @@ export function apply(ctx, config, runtime = {}) {
2858
2874
  .catch((e) => Object.assign(pluginUpdateStatus, { state: "unavailable", reason: String(e?.message ?? e) }));
2859
2875
  };
2860
2876
  // 自更新能力与降级指引:内容状态驱动"能不能一键",版本号只管文案(评审 R11)。
2877
+ //
2878
+ // 通道选择(v3.5 / DSH 0.2.2+):宿主若提供 `pluginManager.updateBundle()`,就优先
2879
+ // 委托它在**进程内**更新——不重启宿主,也不依赖我们能否重启。传统「改依赖 →
2880
+ // pnpm install → 重启 → 健康确认」通道保留给旧宿主(<0.2.2)以及宿主管理器不可用的
2881
+ // 形态。两条通道都不可用时才退回人工指引。
2882
+ const hostUpdateState = {
2883
+ // 探测结果缓存:`listBundles()` 会读 profile 清单,不必每次请求都跑一遍。
2884
+ at: 0,
2885
+ result: null,
2886
+ // 探测失败/不可用时也为 true,避免每个请求都重试。
2887
+ settled: false,
2888
+ };
2889
+ const hostUpdateCacheMs = Number.isFinite(runtime.pluginUpdates?.hostCapabilityTtlMs)
2890
+ ? runtime.pluginUpdates.hostCapabilityTtlMs
2891
+ : 30_000;
2892
+ /**
2893
+ * 探测宿主原生更新能力(同步读缓存,异步刷新)。
2894
+ *
2895
+ * 首次调用返回「尚未探测」的中性结论,同时排一次探测;下一次请求就能拿到结论。
2896
+ * 这样 bootstrap 路径不会被 `listBundles()`(可能读盘、可能等锁)拖慢。
2897
+ */
2898
+ function hostUpdateCapabilities() {
2899
+ // 测试/定制注入优先:给了结论就不再去探测(生产不传)。
2900
+ if (runtime.pluginUpdates?.hostCapabilities !== undefined) {
2901
+ return runtime.pluginUpdates.hostCapabilities;
2902
+ }
2903
+ const cached = hostUpdateState.result;
2904
+ const fresh = cached && Date.now() - hostUpdateState.at < hostUpdateCacheMs;
2905
+ if (!fresh) {
2906
+ detectHostUpdateCapabilities({
2907
+ ctx,
2908
+ packageName: pluginPackageName,
2909
+ // 探测失败一律收敛成 unavailable,绝不向上抛;结论只影响通道选择。
2910
+ }).then((r) => {
2911
+ hostUpdateState.result = r;
2912
+ hostUpdateState.at = Date.now();
2913
+ hostUpdateState.settled = true;
2914
+ return r;
2915
+ }).catch(() => {
2916
+ hostUpdateState.result = {
2917
+ packageName: pluginPackageName, managerAvailable: false, managerReason: HOST_MANAGER_REASON.PROBE_FAILED,
2918
+ hmrAvailable: false, hmrReason: "", updatable: false,
2919
+ state: HOST_MANAGER_STATE.UNSUPPORTED, channel: UPDATE_CHANNEL.GUIDANCE, installedVersion: "",
2920
+ };
2921
+ hostUpdateState.at = Date.now();
2922
+ hostUpdateState.settled = true;
2923
+ return hostUpdateState.result;
2924
+ });
2925
+ }
2926
+ return hostUpdateState.result;
2927
+ }
2928
+ /** 宿主管理器当前是否可用于本插件(探测结论 + 目标可被它更新)。 */
2929
+ function hostManagerUsable() {
2930
+ const caps = hostUpdateCapabilities();
2931
+ return Boolean(caps && caps.managerAvailable && caps.updatable);
2932
+ }
2861
2933
  function pluginUpdateCapabilities() {
2862
2934
  const form = restartFormOf();
2863
2935
  const specifier = profileSpecifierOf(pluginProfileDir, { keys: pluginDependencyKeys });
2864
2936
  const specPath = specifier.startsWith("file:") ? specifier.slice("file:".length) : "";
2865
2937
  const isGitRepo = specPath !== "" && existsSync(join(specPath, ".git"));
2866
2938
  const installShape = detectInstallShape({ specifier, dirPath: specPath, isGitRepo: () => isGitRepo });
2867
- const canSelfUpdate = Boolean(pluginProfileDir) && form !== "unsupported";
2939
+ // 「能自动完成」由**通道**决定,不再只由重启形态决定:宿主管理器可用时,
2940
+ // 即使我们判断不出重启方式(容器、无 systemd、进程无 DSH_PROFILE)也能自动更新。
2941
+ const canRestart = Boolean(pluginProfileDir) && form !== "unsupported";
2942
+ const hostCaps = hostUpdateCapabilities();
2943
+ const channel = chooseUpdateChannel({
2944
+ hostManagerAvailable: hostManagerUsable(),
2945
+ canRestart,
2946
+ });
2947
+ const canSelfUpdate = channel.channel !== UPDATE_CHANNEL.GUIDANCE;
2868
2948
  const plan = planForShape(installShape, {
2869
2949
  specifier,
2870
2950
  dirPath: specPath,
2871
2951
  canSelfUpdate,
2872
2952
  reason: canSelfUpdate ? "" : pluginProfileDir ? `restart-form-${form}` : "profile-not-found",
2953
+ channel: channel.channel,
2873
2954
  });
2874
- return { installShape, canSelfUpdate, restartForm: form, guidance: plan };
2955
+ return {
2956
+ installShape,
2957
+ canSelfUpdate,
2958
+ restartForm: form,
2959
+ guidance: plan,
2960
+ // 通道与宿主动更能力(手机/桌面据此显示「不重启更新」还是「会重启」)。
2961
+ updateChannel: channel.channel,
2962
+ updateChannelDescription: describeUpdateChannel(channel.channel),
2963
+ hostManager: hostCaps ? {
2964
+ available: Boolean(hostCaps.managerAvailable && hostCaps.updatable),
2965
+ state: hostCaps.state,
2966
+ reason: hostCaps.managerReason || "",
2967
+ hmrAvailable: Boolean(hostCaps.hmrAvailable),
2968
+ } : null,
2969
+ // 兼容旧字段语义:`canSelfUpdate` 曾经等价于「能重启」,现在由通道决定。
2970
+ canRestartHost: canRestart,
2971
+ };
2875
2972
  }
2876
2973
  /** 客户端视图参数:公开基址只取 actual endpoint 视图(W1;Host/trustedHosts 不能证明监听)。 */
2877
2974
  function clientViewFor(_req) {
@@ -2907,6 +3004,17 @@ export function apply(ctx, config, runtime = {}) {
2907
3004
  workerOptions: { installedRoot: pluginRootDir, pluginRoot: pluginRootDir, needsEscape: systemdManaged(),
2908
3005
  restartForm: restartFormOf(), hostPid: process.pid, port: ctx.webServer.port, basePath,
2909
3006
  token: authToken, profile: process.env.DSH_PROFILE || "web", dshCommand: process.env.DSH_BIN || "dsh" },
3007
+ // DSH 0.2.2+:宿主原生插件管理器可用时,更新走「进程内卸载→安装」,不重启宿主。
3008
+ // 不提供该执行器的宿主(<0.2.2 或服务未挂载)自动回落到下面的重启通道。
3009
+ runHostUpdate: ({ targetVersion, installedVersion, onStep, log }) => runHostManagerUpdate({
3010
+ service: probeHostPluginManager(ctx).service,
3011
+ packageName: pluginPackageName,
3012
+ targetVersion,
3013
+ installedVersion,
3014
+ requestId: `mobile-remote-${targetVersion}`,
3015
+ onProgress: (progress) => onStep?.(progress.step === 'installing' ? 'installing' : 'staging'),
3016
+ log: { stage: (stage, message) => { onStep?.(stage); log?.(message); } },
3017
+ }),
2910
3018
  ...runtime.pluginUpdates,
2911
3019
  });
2912
3020
  // 实际监听成功才算可用(绑定失败时 QR/地址回退回环,不指向死端口)
@@ -8148,6 +8256,9 @@ export function apply(ctx, config, runtime = {}) {
8148
8256
  credentials: probe("credentials"),
8149
8257
  messageFeedback: probe("messageFeedback"),
8150
8258
  userQuestions: probe("userQuestions"),
8259
+ // DSH 0.2.2+:宿主原生插件管理能力(决定更新是否免重启)。能力看声明,不看版本号。
8260
+ pluginManager: probe("pluginManager"),
8261
+ hmr: probe("hmr"),
8151
8262
  };
8152
8263
  const checks = { modelsRpc: false, sessionsList: false, directories: false, workspaces: false, notifications: false, actions: false };
8153
8264
  try {
@@ -288,7 +288,7 @@ export function isAllowedDownloadUrl(url) {
288
288
  * 该形态下如何更新;不能自更新时给出**与实际安装方式对应的那一条**降级指引(R11)。
289
289
  * `canSelfUpdate` 由调用方按宿主运行形态判定后传入。
290
290
  */
291
- export function planForShape(shape, { specifier = "", dirPath = "", canSelfUpdate = true, reason = "" } = {}) {
291
+ export function planForShape(shape, { specifier = "", dirPath = "", canSelfUpdate = true, reason = "", channel = "" } = {}) {
292
292
  const installCmd = "pnpm install";
293
293
  const base = (() => {
294
294
  switch (shape) {
@@ -330,7 +330,20 @@ export function planForShape(shape, { specifier = "", dirPath = "", canSelfUpdat
330
330
  };
331
331
  }
332
332
  })();
333
- return { ...base, shape, mode: canSelfUpdate ? "auto" : "guidance", reason };
333
+ // 通道优先:能走宿主原生管理器时,指引要描述**实际会发生什么**,而不是让用户去跑
334
+ // pnpm install(旧实现只按「能不能重启」决定 auto/guidance,容器里就永远给手工指引)。
335
+ if (channel === "host-manager") {
336
+ return {
337
+ summary: "由 DSH 插件管理器在进程内更新,无需重启宿主",
338
+ steps: ["确认目标版本", "宿主移除旧版本并安装新版本", "插件在进程内重新加载(连接不中断)"],
339
+ commands: [],
340
+ shape,
341
+ mode: "auto",
342
+ reason,
343
+ channel,
344
+ };
345
+ }
346
+ return { ...base, shape, mode: canSelfUpdate ? "auto" : "guidance", reason, channel };
334
347
  }
335
348
 
336
349
  /** 检查是否有新版(**不下载、不改动任何东西**)。 */
@@ -639,7 +652,7 @@ function writeJsonFile(file, doc) {
639
652
 
640
653
  // ── 重启 ──────────────────────────────────────────────────────────────────
641
654
 
642
- export function restartPlan({ form, pid = null, profile = "web", dshCommand = "dsh" } = {}) {
655
+ export function restartPlan({ form, pid = null, profile = "web", dshCommand = "dsh", respawnCommand = "" } = {}) {
643
656
  switch (form) {
644
657
  case "web-systemd":
645
658
  return {
@@ -648,11 +661,16 @@ export function restartPlan({ form, pid = null, profile = "web", dshCommand = "d
648
661
  commands: pid ? [`kill -TERM ${pid}`] : ["systemctl --user restart dsh-web.service"],
649
662
  };
650
663
  case "web-foreground":
651
- return {
652
- mode: "respawn",
653
- steps: ["终止当前宿主进程", "由分离脚本重新拉起 dsh web"],
654
- commands: pid ? [`kill -TERM ${pid}`, `${dshCommand} web --profile ${profile}`] : [`${dshCommand} web --profile ${profile}`],
655
- };
664
+ // 优先复用**本进程原样的命令行**(含 --port / --no-open 等参数):容器与自定义启动
665
+ // 方式下拼一个 `dsh web --profile x` 会丢掉这些参数,重启后端口就变了。
666
+ {
667
+ const respawn = respawnCommand !== "" ? respawnCommand : `${dshCommand} web --profile ${profile}`;
668
+ return {
669
+ mode: "respawn",
670
+ steps: ["终止当前宿主进程", "由分离脚本用原命令行重新拉起 dsh web"],
671
+ commands: pid ? [`kill -TERM ${pid}`, respawn] : [respawn],
672
+ };
673
+ }
656
674
  default:
657
675
  return {
658
676
  mode: "unsupported",
@@ -666,13 +684,96 @@ export function restartPlan({ form, pid = null, profile = "web", dshCommand = "d
666
684
  * 识别本机可自动重启的形态。
667
685
  * **默认读真实 `process.env`**——生产调用漏传 env 会让前台 web 永远探测不到(评审 R12)。
668
686
  */
669
- export function detectRestartForm({ env = process.env, platform = process.platform, hasSystemdUnit = () => false } = {}) {
687
+ export function detectRestartForm({ env = process.env, platform = process.platform, hasSystemdUnit = () => false, commandLine = null } = {}) {
670
688
  if (platform === "win32" || platform === "darwin") return "unsupported";
671
689
  if (hasSystemdUnit()) return "web-systemd";
690
+ // 显式标记:启动脚本/服务单元自己声明了这是可重启的前台 web。
672
691
  if (env?.DSH_PROFILE || env?.DSH_WEB_FOREGROUND === "1") return "web-foreground";
692
+ // 退一步看**实际命令行**:`dsh web ...` 本身就是前台 web 形态,与原命令行重启就能生效。
693
+ // 旧实现只看两个环境变量,于是容器/自定义启动(`dsh web --port 3082`,无 DSH_PROFILE)
694
+ // 被误判成 unsupported,整条自更新降级成「请到电脑上运行 pnpm install」。
695
+ // 命令行证据是**本进程自己的**,不依赖外部约定,因此可以作为该判定的依据。
696
+ if (Array.isArray(commandLine) && isDshWebCommandLine(commandLine)) return "web-foreground";
673
697
  return "unsupported";
674
698
  }
675
699
 
700
+ /**
701
+ * 判断命令行是否是前台 `dsh web` 调用。
702
+ *
703
+ * 只认「结尾是 dsh 入口 + `web` 子命令」的形状(兼容 `node <path>/dsh web ...`),
704
+ * 不猜其它形状——误判会让重启脚本执行错误的命令。
705
+ *
706
+ * @param {string[]} commandLine - 完整命令行(`process.argv` 形状)。
707
+ * @returns {boolean}
708
+ */
709
+ export function isDshWebCommandLine(commandLine) {
710
+ if (!Array.isArray(commandLine) || commandLine.length < 2) return false;
711
+ // 第一个参数是 node(或执行器),从第二个开始找 dsh 入口;允许前面有 `--flag`。
712
+ const rest = commandLine.slice(1);
713
+ const dshIndex = rest.findIndex((arg) => typeof arg === "string" && /(^|\/)dsh$/i.test(arg));
714
+ if (dshIndex === -1) return false;
715
+ // dsh 之后第一个**位置参数**必须是 `web`。
716
+ // 注意不能简单地「跳过所有 - 开头的参数再取第一个」:`--profile web` 的取值
717
+ // `web` 会被误当成子命令,而 `--profile web` 实际是「启动名为 web 的 profile」。
718
+ // 因此这里按 dsh 自己的 CLI 选项表跳过取值。
719
+ return firstDshPositional(rest.slice(dshIndex + 1)) === "web";
720
+ }
721
+
722
+ /** dsh 顶层会吃掉一个取值的选项(见 `dsh --help`)。 */
723
+ const DSH_VALUE_OPTIONS = new Set([
724
+ "--profile",
725
+ "--from-default-profile",
726
+ "--patch",
727
+ ]);
728
+
729
+ /**
730
+ * 取 dsh 参数里第一个位置参数,跳过选项及其取值。
731
+ *
732
+ * `--profile web` 与 `--patch a.yml` 的取值不算位置参数;`--flag=value` 形式不占额外参数。
733
+ *
734
+ * @param {string[]} args - dsh 之后的参数。
735
+ * @returns {string} 第一个位置参数,没有则空串。
736
+ */
737
+ export function firstDshPositional(args) {
738
+ for (let i = 0; i < args.length; i++) {
739
+ const arg = args[i];
740
+ if (typeof arg !== "string" || arg === "") continue;
741
+ if (arg.startsWith("-")) {
742
+ // 已带 `=` 的形式(`--profile=web`)不再吃下一个参数。
743
+ if (arg.includes("=")) continue;
744
+ if (DSH_VALUE_OPTIONS.has(arg)) i++;
745
+ continue;
746
+ }
747
+ return arg;
748
+ }
749
+ return "";
750
+ }
751
+
752
+ /**
753
+ * 用本进程原命令行重建一条可执行的 respawn 命令(用于前台 web 形态的重启)。
754
+ *
755
+ * 重新执行的必须是**同一入口、同一参数**;拿不到可靠命令行时返回空串,
756
+ * 由调用方退回 `dsh web --profile <name>` 的保守写法。
757
+ *
758
+ * @param {string[]} commandLine - `process.argv`。
759
+ * @returns {string} 可直接交给 shell 的命令行,或空串。
760
+ */
761
+ export function respawnCommandOf(commandLine) {
762
+ if (!isDshWebCommandLine(commandLine)) return "";
763
+ const parts = commandLine.map((arg) => String(arg));
764
+ // `process.argv[0]` 是 node 可执行文件;用 process.execPath 更稳(argv[0] 可能是别名)。
765
+ if (parts.length > 0) parts[0] = process.execPath;
766
+ return parts.map(shellQuote).join(" ");
767
+ }
768
+
769
+ /** 最小 shell 引用:只给含空白/特殊字符的参数加引号,避免破坏正常路径。 */
770
+ function shellQuote(value) {
771
+ const text = String(value);
772
+ if (text === "") return "''";
773
+ if (/^[A-Za-z0-9_@%+=:,./-]+$/.test(text)) return text;
774
+ return `'${text.replace(/'/g, `'\\''`)}'`;
775
+ }
776
+
676
777
  export function buildRestartScript({ plan, pid = null, delayMs = 3000 } = {}) {
677
778
  const seconds = Math.max(0, Math.round(delayMs / 1000));
678
779
  if (plan?.mode === "supervised") {
@@ -41,7 +41,9 @@ export function createPluginUpdateController(options) {
41
41
  const { home = homedir(), configValue, profileDir, packageName = '', npmPackageView, capabilities, localVersion, localContentSha256,
42
42
  status, log = () => {}, fetchImpl = fetch, auth = {}, basePath = '/m', workerOptions = {},
43
43
  schedule = fn => setImmediate(fn), runSelfUpdate: runner = runSelfUpdate, prepareNpmArtifacts: prepareRunner = prepareNpmArtifacts,
44
- persist = writeOwnedTransaction } = options;
44
+ runHostUpdate: hostRunner, persist = writeOwnedTransaction } = options;
45
+ // 只有调用方显式提供宿主更新执行器时才启用该通道(旧宿主/测试不提供即自动关闭)。
46
+ const runHostUpdate = typeof hostRunner === 'function' ? hostRunner : null;
45
47
  const currentFile = transactionFile(home), lockPath = updateLockPath(home);
46
48
  const preparedUpdates = new Map();
47
49
  const preparedTtlMs = 30 * 60 * 1000;
@@ -160,6 +162,8 @@ export function createPluginUpdateController(options) {
160
162
  if (source.kind === UPDATE_SOURCE_KIND.OFF) return { status: 503, body: { error: 'update-source-off' } };
161
163
  if (source.kind === UPDATE_SOURCE_KIND.INVALID) return { status: 400, body: { error: 'update-source-invalid' } };
162
164
  if (!profileDir) return { status: 409, body: { error: 'profile-not-found' } };
165
+ // `canSelfUpdate` 现在由**通道**决定(宿主管理器或重启通道只要有一条可用即为真),
166
+ // 两条都不通才拒绝;原因码保留 `restart-unsupported` 以免旧 App 判断失效。
163
167
  if (!capabilities().canSelfUpdate) return { status: 409, body: { error: 'restart-unsupported' } };
164
168
  const view = clientView(clientOrigin);
165
169
  const old = readTransaction(currentFile);
@@ -176,6 +180,68 @@ export function createPluginUpdateController(options) {
176
180
  return { status: 200, body: { ok: true, action: 'none', check: { ...checked, release: clientReleaseView(checked.release, view) } } };
177
181
  }
178
182
  const opId = body.opId ?? newOperationId();
183
+ // ── 通道分派:宿主原生管理器可用时走它(进程内更新,不重启) ──────────────
184
+ // 这条路径与下面的「重启通道」互斥:同一时刻只有一个事务、同一把锁。
185
+ if (typeof runHostUpdate === 'function' && capabilities().updateChannel === 'host-manager') {
186
+ const hostTarget = checked.release?.plugin ?? checked.candidate?.plugin;
187
+ if (!hostTarget?.version) return { status: 503, body: { error: 'update-candidate-incomplete' } };
188
+ if (typeof body.targetVersion === 'string' && body.targetVersion !== hostTarget.version) {
189
+ return { status: 409, body: { error: 'candidate-changed', check: checked } };
190
+ }
191
+ const lock = acquireLock(lockPath, { opId, stateFile: currentFile });
192
+ if (!lock.ok) return { status: 409, body: { error: lock.error, transaction: publicTransaction(readTransaction(currentFile), view) } };
193
+ const lease = lock.lease, stateFile = serverOperationPath(home, lease.generation);
194
+ const operationLog = createOperationLog({ home, generation: lease.generation,
195
+ redactPaths: [home, profileDir, workerOptions.pluginRoot, workerOptions.installedRoot] });
196
+ operationLog.setStage('host-manager', 'Host plugin manager update accepted');
197
+ let tx;
198
+ try {
199
+ tx = persist(stateFile, { ...workerOptions, opId, phase: 'staging', startedAt: new Date().toISOString(),
200
+ profileDir, release: checked.release ?? null, hostManager: true,
201
+ manifestUrl: checked.release?.manifestUrl ?? '',
202
+ targetVersion: hostTarget.version, targetContentSha256: hostTarget.contentSha256 ?? '',
203
+ targetAppVersion: checked.release?.app?.version ?? null,
204
+ currentFile, lockPath, lease, attempts: 0 }, { lockPath, lease, currentFile });
205
+ } catch {
206
+ releaseLock(lockPath, lease, { stateFile: currentFile });
207
+ operationLog.setStage('failed', 'Could not persist host manager admission state.');
208
+ operationLog.flush();
209
+ log('host manager update admission state write failed');
210
+ return { status: 500, body: { error: 'update-state-write-failed' } };
211
+ }
212
+ schedule(async () => {
213
+ try {
214
+ const run = await runHostUpdate({ opId, targetVersion: hostTarget.version,
215
+ installedVersion: typeof localVersion === 'function' ? localVersion() : localVersion,
216
+ onStep: step => { operationLog.setStage(step); workerOptions.onStep?.(step); },
217
+ log: message => { operationLog.appendStatus(message, 'worker'); } });
218
+ if (run.ok) {
219
+ operationLog.setStage('finished', 'Host plugin manager applied the update without a restart.');
220
+ finishOwnedTerminal(stateFile, { phase: 'settled', result: { ok: true, matched: 'host-manager' } },
221
+ { lockPath, lease, currentFile });
222
+ Object.assign(status, { state: 'up-to-date', reason: 'host-manager-applied', opId });
223
+ } else {
224
+ const reason = safeUpdateReason(run.reason);
225
+ operationLog.setStage('failed', `Host plugin manager update failed: ${reason}`);
226
+ // `restart-required` 表示包装好了但要重启才生效:这不回滚,如实报告。
227
+ finishOwnedTerminal(stateFile, { phase: run.reason === 'host-manager-restart-required' ? 'settled' : 'failed',
228
+ rolledBack: false, result: { ok: false, reason } }, { lockPath, lease, currentFile });
229
+ Object.assign(status, { state: run.reason === 'host-manager-restart-required' ? 'restarting' : 'update-failed', reason, opId });
230
+ }
231
+ operationLog.flush();
232
+ } catch (e) {
233
+ const reason = safeUpdateReason(e?.message);
234
+ try { finishOwnedTerminal(stateFile, { phase: 'failed', result: { ok: false, reason } }, { lockPath, lease, currentFile }); }
235
+ catch { /* lost lease: never overwrite a newer operation */ }
236
+ operationLog.setStage('failed', `Host manager worker failed: ${reason}`);
237
+ operationLog.flush();
238
+ Object.assign(status, { state: 'update-failed', reason, opId });
239
+ log('host manager update worker failed');
240
+ }
241
+ });
242
+ return { status: 200, body: { ok: true, action: 'accepted', opId, channel: 'host-manager',
243
+ transaction: publicTransaction(tx, view), check: { ...checked, release: clientReleaseView(checked.release, view) } } };
244
+ }
179
245
  let effectiveCheck = checked;
180
246
  let npmCandidate = checked.candidate ?? null;
181
247
  let preparedNpmArtifacts = null;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@marktrue/dsh-mobile-remote",
3
- "version": "3.2.4-alpha.7",
3
+ "version": "3.2.4-alpha.8",
4
4
  "description": "DSH Mobile:把 DeepSeek Harness 变成随身控制台——手机远程发消息派活、看进度、收通知、审批决策、管理会话;配套 Flutter App(当前 Android 端,iOS 未开发)",
5
5
  "type": "module",
6
6
  "main": "lib/index.js",
@@ -52,7 +52,7 @@
52
52
  "qrcode"
53
53
  ],
54
54
  "optionalDependencies": {
55
- "@marktrue/dsh-mobile-remote-app": "npm:@marktrue/dsh-mobile-remote@3.2.4-alpha.7-app"
55
+ "@marktrue/dsh-mobile-remote-app": "npm:@marktrue/dsh-mobile-remote@3.2.4-alpha.8-app"
56
56
  },
57
57
  "peerDependencies": {
58
58
  "@deepseek-ai/dsh-credentials": ">=0.1.0-rc.6 <=0.2.2 || >=0.2.0-0 <0.2.0 || >=0.2.1-0 <0.2.1 || >=0.2.2-0 <0.2.2",