updater.js 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133
  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. /** Run npm with an isolated cache; never rejects, always reports ok + output. */
  21. function runNpm(args, cacheDir, timeoutMs = 300_000) {
  22. return new Promise((resolve) => {
  23. const child = spawn(NPM_BIN, [...args, "--cache", cacheDir, "--no-audit", "--no-fund"], {
  24. stdio: ["ignore", "pipe", "pipe"],
  25. env: childEnv(),
  26. });
  27. let out = "";
  28. const eat = (chunk) => { out += chunk.toString(); };
  29. child.stdout.on("data", eat);
  30. child.stderr.on("data", eat);
  31. const timer = setTimeout(() => { try { child.kill("SIGKILL"); } catch { /* gone */ } }, timeoutMs);
  32. child.on("error", (err) => { clearTimeout(timer); resolve({ ok: false, error: err.message, out }); });
  33. child.on("exit", (code) => { clearTimeout(timer); resolve({ ok: code === 0, code, out }); });
  34. });
  35. }
  36. function waitReady(service, timeoutMs) {
  37. return new Promise((resolve) => {
  38. const startedAt = Date.now();
  39. const iv = setInterval(() => {
  40. if (service.running) { clearInterval(iv); resolve(true); }
  41. else if (Date.now() - startedAt > timeoutMs) { clearInterval(iv); resolve(false); }
  42. }, 500);
  43. });
  44. }
  45. class Updater {
  46. constructor({ service, cacheDir, log, notify }) {
  47. this.service = service;
  48. this.cacheDir = cacheDir;
  49. this.log = log || (() => {});
  50. this.notify = notify || (() => {});
  51. this.available = null; // { tag, version } once a newer release is found
  52. this.current = null;
  53. this.busy = false;
  54. this.channel = "latest";
  55. }
  56. /** Startup check after a short delay, then on an interval. */
  57. start(intervalMs = 6 * 3600_000) {
  58. setTimeout(() => { this.checkNow(false).catch(() => {}); }, 20_000);
  59. setInterval(() => { this.checkNow(false).catch(() => {}); }, intervalMs);
  60. }
  61. async fetchTags() {
  62. const res = await runNpm(["view", PKG, "dist-tags", "--json"], this.cacheDir, 30_000);
  63. if (!res.ok) throw new Error(`npm view 失败: ${(res.error || res.out || "").slice(-300)}`);
  64. const tags = JSON.parse(res.out);
  65. const version = tags[this.channel] || tags.latest;
  66. if (!version) throw new Error("dist-tags 中没有可用版本");
  67. return { tags, version };
  68. }
  69. async checkNow(manual = true) {
  70. if (this.busy) return null;
  71. this.current = this.service.version();
  72. let latest;
  73. try {
  74. latest = await this.fetchTags();
  75. } catch (err) {
  76. this.log(`[updater] ${err.message}`);
  77. if (manual) this.notify("检查更新失败", String(err.message));
  78. return null;
  79. }
  80. const newer = Boolean(this.current && latest.version && latest.version !== this.current);
  81. this.available = newer ? { tag: this.channel, version: latest.version } : null;
  82. this.log(`[updater] current=${this.current} ${this.channel}=${latest.version}`);
  83. if (newer) this.notify(`发现新版本 ${latest.version}`, `当前 ${this.current} · 托盘菜单点击“升级”`);
  84. else if (manual) this.notify("已是最新版本", `当前 ${this.current}(${this.channel})`);
  85. return { current: this.current, latest: latest.version };
  86. }
  87. async upgrade() {
  88. if (!this.available || this.busy) return false;
  89. const from = this.current || this.service.version();
  90. const to = this.available.version;
  91. this.busy = true;
  92. this.service.upgrading = true;
  93. try {
  94. this.notify(`正在升级到 ${to}`, "npm 安装中,服务会短暂中断…");
  95. this.log(`[updater] installing ${PKG}@${to}`);
  96. const res = await runNpm(["install", "-g", `${PKG}@${to}`], this.cacheDir);
  97. if (!res.ok) throw new Error((res.error || res.out || "npm install 失败").slice(-600));
  98. this.log("[updater] installed; restarting service");
  99. await this.service.restart();
  100. if (!(await waitReady(this.service, 90_000))) throw new Error("升级后服务未能就绪");
  101. this.current = to;
  102. this.available = null;
  103. this.notify(`已升级到 ${to}`, `原版本 ${from} · 服务已重启`);
  104. return true;
  105. } catch (err) {
  106. this.log(`[updater] upgrade failed: ${err.message}; rolling back to ${from}`);
  107. this.notify(`升级失败,回滚到 ${from}`, String(err.message).slice(0, 120));
  108. try {
  109. await runNpm(["install", "-g", `${PKG}@${from}`], this.cacheDir);
  110. await this.service.restart();
  111. await waitReady(this.service, 90_000);
  112. this.notify(`已回滚到 ${from}`, "rc 版本间可能存在破坏性变更");
  113. } catch (err2) {
  114. this.notify("回滚失败", `请手动执行: npm install -g ${PKG}@${from}`);
  115. this.log(`[updater] rollback failed: ${err2.message}`);
  116. }
  117. return false;
  118. } finally {
  119. this.service.upgrading = false;
  120. this.busy = false;
  121. }
  122. }
  123. }
  124. module.exports = { Updater, runNpm, PKG };