updater.js 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145
  1. "use strict";
  2. /**
  3. * Upgrade steward for @deepseek-ai/dsh.
  4. *
  5. * Discovery, install, and rollback all go through npm — the same channel the
  6. * user installed dsh with — so the desktop shell never forks official code:
  7. *
  8. * 1. watch `npm view @deepseek-ai/dsh dist-tags` (startup + interval + manual)
  9. * 2. one-click upgrade: `npm install -g @deepseek-ai/dsh@<version>`
  10. * 3. graceful service restart, then a readiness smoke check
  11. * 4. if the upgraded service never comes up (rc breaking changes, plugin
  12. * incompatibilities), reinstall the previous version and restart again
  13. *
  14. * npm runs with an isolated --cache directory so a broken ~/.npm (root-owned
  15. * files) can never block upgrades.
  16. */
  17. const { spawn } = require("node:child_process");
  18. const { NPM_BIN, childEnv } = require("./env");
  19. const PKG = "@deepseek-ai/dsh";
  20. const IS_WIN = process.platform === "win32";
  21. /** Run npm with an isolated cache; never rejects, always reports ok + output. */
  22. function runNpm(args, cacheDir, timeoutMs = 300_000) {
  23. return new Promise((resolve) => {
  24. // On Windows npm is a .cmd shim — run via cmd.exe (shell:true) using the
  25. // bare name so the augmented PATH resolves it (spaces-safe).
  26. const bin = IS_WIN ? "npm" : NPM_BIN;
  27. const child = spawn(bin, [...args, "--cache", cacheDir, "--no-audit", "--no-fund"], {
  28. stdio: ["ignore", "pipe", "pipe"],
  29. env: childEnv(),
  30. shell: IS_WIN,
  31. windowsHide: true,
  32. });
  33. let out = "";
  34. const eat = (chunk) => { out += chunk.toString(); };
  35. child.stdout.on("data", eat);
  36. child.stderr.on("data", eat);
  37. const timer = setTimeout(() => {
  38. if (IS_WIN) {
  39. try { const { execFileSync } = require("node:child_process"); execFileSync("taskkill", ["/PID", String(child.pid), "/T", "/F"], { stdio: "ignore" }); } catch { /* gone */ }
  40. } else {
  41. try { child.kill("SIGKILL"); } catch { /* gone */ }
  42. }
  43. }, timeoutMs);
  44. child.on("error", (err) => { clearTimeout(timer); resolve({ ok: false, error: err.message, out }); });
  45. child.on("exit", (code) => { clearTimeout(timer); resolve({ ok: code === 0, code, out }); });
  46. });
  47. }
  48. function waitReady(service, timeoutMs) {
  49. return new Promise((resolve) => {
  50. const startedAt = Date.now();
  51. const iv = setInterval(() => {
  52. if (service.running) { clearInterval(iv); resolve(true); }
  53. else if (Date.now() - startedAt > timeoutMs) { clearInterval(iv); resolve(false); }
  54. }, 500);
  55. });
  56. }
  57. class Updater {
  58. constructor({ service, cacheDir, log, notify }) {
  59. this.service = service;
  60. this.cacheDir = cacheDir;
  61. this.log = log || (() => {});
  62. this.notify = notify || (() => {});
  63. this.available = null; // { tag, version } once a newer release is found
  64. this.current = null;
  65. this.busy = false;
  66. this.channel = "latest";
  67. }
  68. /** Startup check after a short delay, then on an interval. */
  69. start(intervalMs = 6 * 3600_000) {
  70. setTimeout(() => { this.checkNow(false).catch(() => {}); }, 20_000);
  71. setInterval(() => { this.checkNow(false).catch(() => {}); }, intervalMs);
  72. }
  73. async fetchTags() {
  74. const res = await runNpm(["view", PKG, "dist-tags", "--json"], this.cacheDir, 30_000);
  75. if (!res.ok) throw new Error(`npm view 失败: ${(res.error || res.out || "").slice(-300)}`);
  76. const tags = JSON.parse(res.out);
  77. const version = tags[this.channel] || tags.latest;
  78. if (!version) throw new Error("dist-tags 中没有可用版本");
  79. return { tags, version };
  80. }
  81. async checkNow(manual = true) {
  82. if (this.busy) return null;
  83. this.current = this.service.version();
  84. let latest;
  85. try {
  86. latest = await this.fetchTags();
  87. } catch (err) {
  88. this.log(`[updater] ${err.message}`);
  89. if (manual) this.notify("检查更新失败", String(err.message));
  90. return null;
  91. }
  92. const newer = Boolean(this.current && latest.version && latest.version !== this.current);
  93. this.available = newer ? { tag: this.channel, version: latest.version } : null;
  94. this.log(`[updater] current=${this.current} ${this.channel}=${latest.version}`);
  95. if (newer) this.notify(`发现新版本 ${latest.version}`, `当前 ${this.current} · 托盘菜单点击“升级”`);
  96. else if (manual) this.notify("已是最新版本", `当前 ${this.current}(${this.channel})`);
  97. return { current: this.current, latest: latest.version };
  98. }
  99. async upgrade() {
  100. if (!this.available || this.busy) return false;
  101. const from = this.current || this.service.version();
  102. const to = this.available.version;
  103. this.busy = true;
  104. this.service.upgrading = true;
  105. try {
  106. this.notify(`正在升级到 ${to}`, "npm 安装中,服务会短暂中断…");
  107. this.log(`[updater] installing ${PKG}@${to}`);
  108. const res = await runNpm(["install", "-g", `${PKG}@${to}`], this.cacheDir);
  109. if (!res.ok) throw new Error((res.error || res.out || "npm install 失败").slice(-600));
  110. this.log("[updater] installed; restarting service");
  111. await this.service.restart();
  112. if (!(await waitReady(this.service, 90_000))) throw new Error("升级后服务未能就绪");
  113. this.current = to;
  114. this.available = null;
  115. this.notify(`已升级到 ${to}`, `原版本 ${from} · 服务已重启`);
  116. return true;
  117. } catch (err) {
  118. this.log(`[updater] upgrade failed: ${err.message}; rolling back to ${from}`);
  119. this.notify(`升级失败,回滚到 ${from}`, String(err.message).slice(0, 120));
  120. try {
  121. await runNpm(["install", "-g", `${PKG}@${from}`], this.cacheDir);
  122. await this.service.restart();
  123. await waitReady(this.service, 90_000);
  124. this.notify(`已回滚到 ${from}`, "rc 版本间可能存在破坏性变更");
  125. } catch (err2) {
  126. this.notify("回滚失败", `请手动执行: npm install -g ${PKG}@${from}`);
  127. this.log(`[updater] rollback failed: ${err2.message}`);
  128. }
  129. return false;
  130. } finally {
  131. this.service.upgrading = false;
  132. this.busy = false;
  133. }
  134. }
  135. }
  136. module.exports = { Updater, runNpm, PKG };