| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145 |
- "use strict";
- /**
- * Upgrade steward for @deepseek-ai/dsh.
- *
- * Discovery, install, and rollback all go through npm — the same channel the
- * user installed dsh with — so the desktop shell never forks official code:
- *
- * 1. watch `npm view @deepseek-ai/dsh dist-tags` (startup + interval + manual)
- * 2. one-click upgrade: `npm install -g @deepseek-ai/dsh@<version>`
- * 3. graceful service restart, then a readiness smoke check
- * 4. if the upgraded service never comes up (rc breaking changes, plugin
- * incompatibilities), reinstall the previous version and restart again
- *
- * npm runs with an isolated --cache directory so a broken ~/.npm (root-owned
- * files) can never block upgrades.
- */
- const { spawn } = require("node:child_process");
- const { NPM_BIN, childEnv } = require("./env");
- const PKG = "@deepseek-ai/dsh";
- const IS_WIN = process.platform === "win32";
- /** Run npm with an isolated cache; never rejects, always reports ok + output. */
- function runNpm(args, cacheDir, timeoutMs = 300_000) {
- return new Promise((resolve) => {
- // On Windows npm is a .cmd shim — run via cmd.exe (shell:true) using the
- // bare name so the augmented PATH resolves it (spaces-safe).
- const bin = IS_WIN ? "npm" : NPM_BIN;
- const child = spawn(bin, [...args, "--cache", cacheDir, "--no-audit", "--no-fund"], {
- stdio: ["ignore", "pipe", "pipe"],
- env: childEnv(),
- shell: IS_WIN,
- windowsHide: true,
- });
- let out = "";
- const eat = (chunk) => { out += chunk.toString(); };
- child.stdout.on("data", eat);
- child.stderr.on("data", eat);
- const timer = setTimeout(() => {
- if (IS_WIN) {
- try { const { execFileSync } = require("node:child_process"); execFileSync("taskkill", ["/PID", String(child.pid), "/T", "/F"], { stdio: "ignore" }); } catch { /* gone */ }
- } else {
- try { child.kill("SIGKILL"); } catch { /* gone */ }
- }
- }, timeoutMs);
- child.on("error", (err) => { clearTimeout(timer); resolve({ ok: false, error: err.message, out }); });
- child.on("exit", (code) => { clearTimeout(timer); resolve({ ok: code === 0, code, out }); });
- });
- }
- function waitReady(service, timeoutMs) {
- return new Promise((resolve) => {
- const startedAt = Date.now();
- const iv = setInterval(() => {
- if (service.running) { clearInterval(iv); resolve(true); }
- else if (Date.now() - startedAt > timeoutMs) { clearInterval(iv); resolve(false); }
- }, 500);
- });
- }
- class Updater {
- constructor({ service, cacheDir, log, notify }) {
- this.service = service;
- this.cacheDir = cacheDir;
- this.log = log || (() => {});
- this.notify = notify || (() => {});
- this.available = null; // { tag, version } once a newer release is found
- this.current = null;
- this.busy = false;
- this.channel = "latest";
- }
- /** Startup check after a short delay, then on an interval. */
- start(intervalMs = 6 * 3600_000) {
- setTimeout(() => { this.checkNow(false).catch(() => {}); }, 20_000);
- setInterval(() => { this.checkNow(false).catch(() => {}); }, intervalMs);
- }
- async fetchTags() {
- const res = await runNpm(["view", PKG, "dist-tags", "--json"], this.cacheDir, 30_000);
- if (!res.ok) throw new Error(`npm view 失败: ${(res.error || res.out || "").slice(-300)}`);
- const tags = JSON.parse(res.out);
- const version = tags[this.channel] || tags.latest;
- if (!version) throw new Error("dist-tags 中没有可用版本");
- return { tags, version };
- }
- async checkNow(manual = true) {
- if (this.busy) return null;
- this.current = this.service.version();
- let latest;
- try {
- latest = await this.fetchTags();
- } catch (err) {
- this.log(`[updater] ${err.message}`);
- if (manual) this.notify("检查更新失败", String(err.message));
- return null;
- }
- const newer = Boolean(this.current && latest.version && latest.version !== this.current);
- this.available = newer ? { tag: this.channel, version: latest.version } : null;
- this.log(`[updater] current=${this.current} ${this.channel}=${latest.version}`);
- if (newer) this.notify(`发现新版本 ${latest.version}`, `当前 ${this.current} · 托盘菜单点击“升级”`);
- else if (manual) this.notify("已是最新版本", `当前 ${this.current}(${this.channel})`);
- return { current: this.current, latest: latest.version };
- }
- async upgrade() {
- if (!this.available || this.busy) return false;
- const from = this.current || this.service.version();
- const to = this.available.version;
- this.busy = true;
- this.service.upgrading = true;
- try {
- this.notify(`正在升级到 ${to}`, "npm 安装中,服务会短暂中断…");
- this.log(`[updater] installing ${PKG}@${to}`);
- const res = await runNpm(["install", "-g", `${PKG}@${to}`], this.cacheDir);
- if (!res.ok) throw new Error((res.error || res.out || "npm install 失败").slice(-600));
- this.log("[updater] installed; restarting service");
- await this.service.restart();
- if (!(await waitReady(this.service, 90_000))) throw new Error("升级后服务未能就绪");
- this.current = to;
- this.available = null;
- this.notify(`已升级到 ${to}`, `原版本 ${from} · 服务已重启`);
- return true;
- } catch (err) {
- this.log(`[updater] upgrade failed: ${err.message}; rolling back to ${from}`);
- this.notify(`升级失败,回滚到 ${from}`, String(err.message).slice(0, 120));
- try {
- await runNpm(["install", "-g", `${PKG}@${from}`], this.cacheDir);
- await this.service.restart();
- await waitReady(this.service, 90_000);
- this.notify(`已回滚到 ${from}`, "rc 版本间可能存在破坏性变更");
- } catch (err2) {
- this.notify("回滚失败", `请手动执行: npm install -g ${PKG}@${from}`);
- this.log(`[updater] rollback failed: ${err2.message}`);
- }
- return false;
- } finally {
- this.service.upgrading = false;
- this.busy = false;
- }
- }
- }
- module.exports = { Updater, runNpm, PKG };
|