diff --git a/CHANGELOG.md b/CHANGELOG.md index 5e1eaa9..33f3f8c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,11 @@ # dsh-fish-soul 变更记录 +- 未发布:设置页的「更新」修好了 —— 一键更新按钮以前**从来没渲染过**。 + - **根因**:`/update/` 那组路由要靠宿主的 plugin-manager 服务才知道能不能一键更新,但宿主上下文压根没被传进路由(`deps.ctx` 恒是空)⇒ 面板永远判定「不能一键更新」⇒ 按钮不渲染。顺带还有:`pluginManagerOf` 只按属性取服务(cordis 也能用 `ctx.get()` 拿)、两个路由的响应漏了 `canApply`(点一下「检查更新」按钮就凭空消失)、面板上的版本号是七八小时前的旧缓存(显示「已是最新」是假的)。 + - **现在**:按钮按宿主说了算(宿主拒绝时会把原因原样带回来),查到的版本号不会再过期到误导人。 + - **开发目录安装(link)的人**:面板会明说「npm 上的新版本不会覆盖这个目录」,并给一条 `git pull` 的命令 —— 这种情况一键更新本来就不该有(一键更新 = 用 npm 那份覆盖你正在改的代码)。 + - **验证范围**:新增接线测试(走真实的路由注册,确认宿主上下文真的传下去了)+ 安装方式判据的行为测试(6 个合成路径,含 pnpm 软链与「开发仓恰好在 node_modules 下」这两种容易判错的)。逐条撤掉验证全部真红。**未验证**:真机上点一次「更新到」(这台机器是 link 装,宿主会按设计拒绝 —— 那正是期望行为)。 + - v0.18.7:白名单里的熟人可以托她给另一个熟人带一句话了(默认关)。 - **能做什么**:设置页「日常 → 熟人传话」里配一份白名单(平台 uid,一行一个),打开开关后,白名单里的人可以说「帮我跟 xx 说一声……」,她就替这人给对方带一句。适合「手机没电帮传个话」「不在电脑前让朋友转达」这类场景。 - **为什么不是「白名单里的人随便指定谁都行」**:只判发起人挡不住三件事。一来对方没同意收,骚扰话术照样能出去,最后被封的是你这个 bot 号;二来「xx 是谁」如果按昵称解析,改个名就能冒充(这个仓库被昵称冒充坑过好几次);三来出了事查不到是谁让发的。所以这里设了四道闸:开关默认关、发起人和收件人都得在白名单里、按发起人每天限条数、发出的消息强制带「【xx托我带句话】」前缀 —— 收件人看得见是谁托的,她没法匿名传话。 diff --git a/lib/client.js b/lib/client.js index fcfdee6..a63a5a4 100644 --- a/lib/client.js +++ b/lib/client.js @@ -954,6 +954,13 @@ window.__ModuleLoader__.load({ if (r?.ok) { setData(r); notify(`已更新到 v${r.to},重启 DSH 生效`); } else notify(r?.error ?? "没更新成"); } + // 开发目录(link)安装:更新 = 在那个目录里 git pull + 重启 DSH,不是 pnpm add。 + // 用真实的开发目录路径,别给占位符(复制过去直接报错,等于没给命令)。 + const devPath = String(data.installPath ?? ""); + const devCommand = devPath === "" ? "在开发目录里 git pull,然后重启 DSH" : `git -C "${devPath}" pull && 重启 DSH`; + async function copyDev() { + try { await navigator.clipboard.writeText(devCommand); notify("已复制更新命令"); } catch { notify("复制失败,手动选中复制"); } + } const when = data.checkedAt ? new Date(data.checkedAt).toLocaleString("zh-CN", { hour12: false }) : ""; const status = data.hasUpdate ? Tag(`有新版本 v${data.latest}`, "warning") : data.latest ? Tag("已是最新", "success") @@ -964,11 +971,20 @@ window.__ModuleLoader__.load({ Row({ title: status, meta: when ? `${when}${data.source ? ` · ${data.source}` : ""}` : undefined, desc: "每 12 小时自动看一次 npm / GitHub" }, Button({ onClick: check, disabled: busy || data.checking }, busy || data.checking ? "检查中…" : "检查更新"), data.hasUpdate ? Button({ onClick: () => window.open(data.notesUrl, "_blank", "noopener") }, "更新说明") : null, + // ⚠️ 按钮的显隐由 **canApply**(宿主有没有插件管理服务)决定, + // 不是由 installMode 决定 —— 宿主才是唯一权威(updateBundle 自己会拒 + // link 装并给出明确理由)。插件拿自己的启发式去藏按钮, + // 等于把「判据可能出错」从「多一句废话」升级成「功能直接没了」。 data.hasUpdate && data.canApply ? Button({ variant: "primary", onClick: apply, disabled: busy }, busy ? "更新中…" : `更新到 v${data.latest}`) : null, data.hasUpdate && data.command ? Button({ variant: data.canApply ? "ghost" : "primary", onClick: copy, title: data.command }, "复制更新命令") : null), data.hasUpdate ? (data.notes ? h("pre", { className: "fs-report" }, data.notes) : h("p", { className: "fs-row-meta" }, h("a", { href: data.notesUrl, target: "_blank", rel: "noopener noreferrer" }, "GitHub Releases"))) : null, + // 开发目录(link)安装:npm 版不会覆盖它 ⇒ 这里的「更新」是 git pull + 重启。 + // 只是**追加一句说明**,不去替代上面那个按钮(宿主说行就行)。 + data.installMode === "dev" ? Row({ title: "开发目录安装", desc: "npm 上的新版本不会覆盖这个目录,要更新在这里 git pull 之后重启 DSH" }, + Button({ variant: "ghost", onClick: copyDev, title: devCommand }, "复制 git pull 命令"), + devPath === "" ? null : Muted(devPath)) : null, Row({ title: "自动检查更新", desc: "只提示,不会自动安装;点「更新到」才装,装完重启 DSH 生效" }, h(Switch, { checked: data.autoCheck !== false, onChange: toggle, label: "自动检查更新" }))); } diff --git a/lib/index.js b/lib/index.js index a3e7085..cc7a2dc 100644 --- a/lib/index.js +++ b/lib/index.js @@ -1206,6 +1206,7 @@ async function startup(ctx, config, { log, gate }) { step(STARTUP_STEPS[14]); registerRoutes(ctx, { gate, + ctx, // /update/ 那组路由要靠它找宿主的 plugin-manager 服务(一键更新) db, clock, embedder, embeddingCfg, worker, life, getConfig, saveConfig, log, gateway, channel, bili, biliClient, browser, biliSocial, douyinSocial, douyin, douyinHost, douyinBrowser, backup, historyImporter, updater, worldBooks, llmRouter, voice, stickers, slang, persona, reloadPersona, webConfig, hasWebTools, webUsedToday, hostWebAvailable, hostWebState, runWebSearch, diff --git a/lib/routes-update.js b/lib/routes-update.js index 4cab39f..0955a25 100644 --- a/lib/routes-update.js +++ b/lib/routes-update.js @@ -5,7 +5,7 @@ * POST /update/config { autoCheck } 自动检查开关 * POST /update/apply 一键更新到上次检查到的最新版(走宿主 plugin-manager,失败它自己回滚) */ -import { pluginVersion } from './update-check.js'; +import { pluginVersion, installInfo } from './update-check.js'; import { applyUpdate, pluginManagerOf } from './self-update.js'; const BODY_MAX = 4 * 1024; @@ -14,7 +14,14 @@ export async function handleUpdateRoute({ method, path, req, send, readBody, sam if (!path.startsWith('/update/')) return false; const { updater, saveConfig } = deps; const guard = () => { if (!sameOrigin(req)) { send(403, { ok: false, error: 'forbidden' }); return false; } return true; }; - const fallback = () => ({ ok: true, current: pluginVersion(), latest: null, hasUpdate: false, checkedAt: null, checking: false, autoCheck: true, canApply: pluginManagerOf(deps.ctx) !== null }); + // ⚠️ fallback 的字段集要和正常路径**完全一致**(少一个字段,面板就少一块东西)。 + // 这次修的就是「漏字段导致按钮消失」,同一个坑不能留半个。 + const fallback = () => ({ + ok: true, current: pluginVersion(), latest: null, hasUpdate: false, checkedAt: null, + checking: false, autoCheck: true, source: '', notes: '', notesUrl: '', publishedAt: null, error: '', command: '', + canApply: pluginManagerOf(deps.ctx) !== null, + installMode: installInfo().mode, installPath: installInfo().path + }); if (method === 'GET' && path === '/update/state') { if (!guard()) return true; @@ -32,7 +39,9 @@ export async function handleUpdateRoute({ method, path, req, send, readBody, sam if (!guard()) return true; if (!updater) { send(200, { ...fallback(), ok: false, error: '更新检查没起来' }); return true; } await updater.check(); - send(200, updater.state()); + // ⚠️ 别漏 canApply:面板把整个响应换进 data,漏了它「一键更新」按钮就没了 + // (点一下「检查更新」,按钮凭空消失 —— 主人会以为功能坏了)。 + send(200, { ...updater.state(), canApply: pluginManagerOf(deps.ctx) !== null }); return true; } if (method === 'POST' && path === '/update/config') { @@ -42,7 +51,12 @@ export async function handleUpdateRoute({ method, path, req, send, readBody, sam const b = JSON.parse(raw || '{}'); if (typeof b.autoCheck !== 'boolean') { send(400, { ok: false, error: 'autoCheck 要是 true / false' }); return true; } await saveConfig({ update: { autoCheck: b.autoCheck } }); - send(200, updater ? { ...updater.state(), autoCheck: b.autoCheck } : { ...fallback(), autoCheck: b.autoCheck }); + // ⚠️ 刚打开自动检查就查一次:否则那 30 秒的启动机会早就被 autoCheck=false 时烧掉了, + // 打开开关后要等十几个小时才有下一次 —— 面板继续显示旧结果(正是要消灭的那种陈旧)。 + if (b.autoCheck && updater) { try { await updater.check(); } catch { /* 查不到不影响保存 */ } } + send(200, updater + ? { ...updater.state(), autoCheck: b.autoCheck, canApply: pluginManagerOf(deps.ctx) !== null } + : { ...fallback(), autoCheck: b.autoCheck }); return true; } return false; diff --git a/lib/routes.js b/lib/routes.js index 98bd4ce..6024a83 100644 --- a/lib/routes.js +++ b/lib/routes.js @@ -104,6 +104,11 @@ export function maskKey(key) { * @param {import('./douyin-browse.js').DouyinBrowser} [deps.douyinBrowser] */ export function registerRoutes(ctx, deps) { + // 🔴 **ctx 必须进 deps**:/update/ 那组路由要靠 `deps.ctx` 找宿主的 plugin-manager 服务 + // (一键更新全靠它)。以前 deps 里没有 ctx ⇒ `deps.ctx` 恒 undefined ⇒ + // canApply 恒 false ⇒ 面板上「更新到」按钮**从来没渲染过**。 + // 放在这里而不是各个调用方,是为了以后新增路由不用再记得传一遍。 + deps.ctx ??= ctx; const { db, clock, embedder, worker, life, getConfig, saveConfig, log, gateway, channel, bili, biliClient, browser, biliSocial } = deps; const logger = log ?? (() => {}); /** 进行中的 B站扫码(密钥只留在服务端) */ diff --git a/lib/self-update.js b/lib/self-update.js index eb72c40..267dae1 100644 --- a/lib/self-update.js +++ b/lib/self-update.js @@ -12,11 +12,26 @@ * 等于覆盖开发目录,拒绝是对的,面板继续给「复制更新命令」。 */ -/** @param {object} ctx @returns {object | null} */ +/** + * 找宿主的插件管理服务。 + * + * ⚠️ **两条路都得试**:cordis 的服务既能通过 `ctx.get(name)` 拿到,也能作为属性挂在 ctx 上。 + * 仓库里其他服务都走 `service(ctx, name)`(先 get 再取属性),只做属性访问的话 + * 一键更新会永远拿不到服务 ⇒ `canApply: false` ⇒ 面板上根本不渲染「更新到」按钮。 + * + * @param {object} ctx + * @returns {object | null} + */ export function pluginManagerOf(ctx) { + const has = (v) => v && typeof v.updateBundle === 'function' ? v : null; + try { + if (typeof ctx?.get === 'function') { + const v = has(ctx.get('plugin-manager')); + if (v !== null) return v; + } + } catch { /* 往下走属性那条 */ } try { - const v = ctx?.['plugin-manager']; - return v && typeof v.updateBundle === 'function' ? v : null; + return has(ctx?.['plugin-manager']); } catch { return null; } diff --git a/lib/update-check.js b/lib/update-check.js index e8802a1..8626e3d 100644 --- a/lib/update-check.js +++ b/lib/update-check.js @@ -9,8 +9,10 @@ * - 只检查、不自动安装:装插件要动宿主的 profile,交给主人用设置页给的命令去装。 * - 只发 GET,不带任何本机信息。 */ -import { readFileSync } from 'node:fs'; -import { getKv, setKv } from './db.js'; +import { readFileSync, realpathSync } from 'node:fs'; +import { dirname, isAbsolute, relative, resolve } from 'node:path'; +import { fileURLToPath } from 'node:url'; +import { dshHome, getKv, setKv } from './db.js'; export const PACKAGE_NAME = 'dsh-fish-soul'; export const REPO = 'Britneycode/dsh-fish-soul'; @@ -19,6 +21,8 @@ const GH_URL = `https://api.github.com/repos/${REPO}/releases/latest`; const FIRST_DELAY_MS = 30_000; const INTERVAL_MS = 12 * 3600_000; const TIMEOUT_MS = 8000; +// 面板上的「上次检查结果」超过这个时长就算旧(会误导人),进程刚启动时补查一次。 +const STALE_MS = 3600_000; const KV_KEY = 'update.last'; let cachedVersion = null; @@ -37,6 +41,54 @@ export function pluginVersion() { return cachedVersion; } +/** +/** + * 这个插件是怎么装的: + * 'dev' —— 开发目录软链(link)。宿主 profile 里 `node_modules/dsh-fish-soul` + * 是个指向开发仓的符号链接。**npm 上的新版本不会覆盖它** + * (覆盖 = 把主人正在改的代码冲掉),所以一键更新在这台机器上不存在 —— + * 宿主会明确拒绝,面板要提前说清楚,不能让人以为「点了没反应」。 + * 'registry' —— 宿主自己装的(npm / pnpm),落在 DSH 的目录下面,一键更新才有意义。 + * + * ⚠️ 判据不能用「路径里有没有 node_modules」:主人把开发仓 clone 进某个项目的 + * `node_modules/` 里开发时,那条路径也含 node_modules ⇒ 会被误判成 registry ⇒ + * 面板对 dev 装的用户说「已是最���」,症状原样复发。 + * 「在不在 DSH 目录里」才是真的分界:宿主装的必然在 `~/.dsh/profiles//node_modules/…`, + * 开发仓在别处。pnpm 的虚拟 store(`.pnpm/xxx/node_modules/…`)也在 profiles 下 ⇒ 判成 registry,对。 + * + * @param {string} dir 插件自己的真实目录 + * @param {string} home DSH 的 home(`~/.dsh`) + * @returns {'dev'|'registry'|'unknown'} + */ +export function modeFromPath(dir, home) { + try { + const rel = relative(resolve(home), resolve(dir)); + // 在 home 之下(rel 不是以 .. 开头、也不是绝对路径)⇒ 宿主装的 + if (rel !== '' && !rel.startsWith('..') && !isAbsolute(rel)) return 'registry'; + if (rel === '') return 'unknown'; // 就是 home 本身,判断不了 + return 'dev'; + } catch { + return 'unknown'; + } +} + +/** + * @returns {{mode: 'dev'|'registry'|'unknown', path: string}} + */ +export function installInfo() { + try { + const self = realpathSync(fileURLToPath(new URL('../package.json', import.meta.url))); + const dir = dirname(self); + return { mode: modeFromPath(dir, dshHome()), path: dir }; + } catch { + return { mode: 'unknown', path: '' }; + } +} + +export function installMode() { + return installInfo().mode; +} + /** "v1.2.3-rc.1" → { nums:[1,2,3], pre:['rc',1] };看不懂返回 null。 */ function parse(v) { const m = /^v?(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?/.exec(String(v ?? '').trim()); @@ -88,6 +140,9 @@ export class UpdateChecker { this.random = random ?? Math.random; this.timer = null; this.running = null; + // 「本进程还没查过」—— 放构造函数而不是 start(): + // start(); stop(); start()(插件热重载)不该把它又置回 true 而多问一次。 + this.freshProcess = true; } autoCheck() { @@ -105,11 +160,33 @@ export class UpdateChecker { return Math.max(FIRST_DELAY_MS, Math.min(jitter, last + jitter - this.now())); } + /** + * 上次查到的结果是不是已经旧到会误导人(超过 STALE_MS)。 + * 从没查过 ⇒ 算旧(要查)。 + */ + staleResult() { + const last = getKv(this.db, KV_KEY, null)?.checkedAt; + return typeof last !== 'number' || (this.now() - last) > STALE_MS; + } + start() { this.stop(); this.stopped = false; + // 🔴 **进程刚启动、且上次的结果已经旧到会误导人时,补查一次**(30 秒后)。 + // 以前 nextDelay() 只看 kv 里的 checkedAt ⇒ 宿主重启后可能要再等好几个小时 + // 才重查,面板于是显示着**上一次**的结果(这次就显示 latest=0.18.5, + // 而 npm 上早就是 0.18.7 了)—— 「已是最新」是假的,主人根本不知道出了新版。 + // + // ⚠️ 但**不能每次启动都问**:GitHub 未认证 API 是 60 次/小时/IP, + // 崩溃重启循环会直接吃满;而且 nextDelay() 的文档写着 + // 「重启频繁时也不会每次启动都去问」—— 那是一条被代码主动推翻的承诺。 + // 所以加了 STALE_MS 门槛:结果超过 1 小时才算「旧到会误导人」。 const tick = async () => { - try { if (this.autoCheck()) await this.check(); } + try { + // 自动检查开着才真的查。查过了才把「本进程已问过」记上 —— + // 否则自动检查关着时,那 30 秒的机会会被白白烧掉,之后又是十几个小时不查。 + if (this.autoCheck()) { await this.check(); this.freshProcess = false; } + } catch (e) { this.log('warn', `[fish-soul] 检查更新出错:${e instanceof Error ? e.message : e}`); } if (!this.stopped) { try { arm(); } @@ -118,8 +195,9 @@ export class UpdateChecker { }; const arm = () => { let delay; - try { delay = this.nextDelay(); } - catch (e) { + try { + delay = (this.freshProcess && this.staleResult()) ? FIRST_DELAY_MS : this.nextDelay(); + } catch (e) { this.log('warn', `[fish-soul] 读取更新检查间隔失败,按默认间隔重试:${e instanceof Error ? e.message : e}`); delay = INTERVAL_MS; } @@ -185,6 +263,7 @@ export class UpdateChecker { } state() { + const info = installInfo(); // 一次取值就够(realpathSync 是同步的,面板每 60 秒轮询一次) const last = getKv(this.db, KV_KEY, null); const latest = last?.latest ?? null; const hasUpdate = latest !== null && compareVersions(latest, this.current) > 0; @@ -201,7 +280,11 @@ export class UpdateChecker { publishedAt: last?.publishedAt ?? null, error: last?.error ?? '', autoCheck: this.autoCheck(), - command: hasUpdate ? updateCommand(latest) : '' + command: hasUpdate ? updateCommand(latest) : '', + // dev(link)安装:npm 版不会覆盖开发目录 ⇒ 一键更新在这台机器上不存在。 + // 带上真实路径:面板给的更新命令要用它,不能给占位符(复制过去直接报错)。 + installMode: info.mode, + installPath: info.path }; } } diff --git a/test/self-update.mjs b/test/self-update.mjs index 5918da6..56709fc 100644 --- a/test/self-update.mjs +++ b/test/self-update.mjs @@ -10,6 +10,19 @@ assert.equal(pluginManagerOf(null), null); assert.equal(pluginManagerOf({}), null); assert.equal(pluginManagerOf({ 'plugin-manager': {} }), null, '没有 updateBundle 不算'); +// ⚠️ cordis 的服务能通过 ctx.get(name) 拿到,也能作为属性挂在 ctx 上 —— 两条路都得试。 +// 只做属性访问的话,一键更新永远拿不到服务 ⇒ canApply 恒 false ⇒ 面板上 +// 「更新到」按钮**根本不渲染**(主人问「更新怎么不是一键的」,根因就在这)。 +{ + const pm = { updateBundle: async () => ({}) }; + assert.equal(pluginManagerOf({ get: () => pm }), pm, 'ctx.get 能拿到服务'); + assert.equal(pluginManagerOf({ 'plugin-manager': pm }), pm, 'ctx 上挂着服务'); + assert.equal(pluginManagerOf({ get: () => pm, 'plugin-manager': pm }), pm, '两条路都通'); + assert.equal(pluginManagerOf({ get: () => ({}) }), null, 'get 到的不是服务'); + assert.equal(pluginManagerOf({ get: () => { throw new Error('boom'); } }), null, 'get 抛错要兜住'); + assert.equal(pluginManagerOf({ get: () => pm, 'plugin-manager': {} }), pm, '属性那条没有也不该盖掉 get 那条'); +} + // 宿主没有服务 assert.deepEqual( await applyUpdate({ ctx: {}, state }), diff --git a/test/update-check.mjs b/test/update-check.mjs index 6e07000..903ee5b 100644 --- a/test/update-check.mjs +++ b/test/update-check.mjs @@ -2,7 +2,7 @@ import assert from 'node:assert/strict'; import { DatabaseSync } from 'node:sqlite'; import { readFileSync } from 'node:fs'; -import { UpdateChecker, compareVersions, pluginVersion, updateCommand } from '../lib/update-check.js'; +import { UpdateChecker, compareVersions, pluginVersion, updateCommand, installMode, installInfo, modeFromPath } from '../lib/update-check.js'; import { handleUpdateRoute } from '../lib/routes-update.js'; const pkg = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8')); @@ -97,6 +97,65 @@ assert.equal((await pending).checking, false); assert.equal(lo.nextDelay(), 12 * 3600_000 * 0.9); } +// 安装方式:判据是「解 symlink 后的路径在不在 DSH 目录下面」。 +// ⚠️ 断言要打**行为**(合成路径 → 期望模式),不能只打「我此刻跑在开发仓里」—— +// 后者测的是环境:主人把仓库 clone 进某个项目的 node_modules 下开发时就会红, +// 而功能其实是对的。判据本身(dev/registry 的分界)必须被真正执行到。 +{ + const HOME = 'C:/Users/x/.dsh'; + const cases = [ + // [目录, 期望] + ['D:/Demo/program/qq-bot/dsh-fish-soul', 'dev'], // 开发仓在别处 + ['C:/Users/x/.dsh/profiles/desktop/node_modules/dsh-fish-soul', 'registry'], // npm 装 + ['C:/Users/x/.dsh/profiles/desktop/node_modules/.pnpm/dsh-fish-soul@0.18.7/node_modules/dsh-fish-soul', 'registry'], // pnpm 装 + ['C:/someproject/node_modules/dsh-fish-soul', 'dev'], // 开发仓恰好在 node_modules 下 —— 不能误判成 registry + ['C:/Users/x/.dsh-other/x', 'dev'], // 只是前缀像 + ['C:/Users/x/.dsh', 'unknown'] + ]; + for (const [dir, want] of cases) { + assert.equal(modeFromPath(dir, HOME), want, `${dir} 应判成 ${want}`); + } + // 本机这条只留一条,且只作「环境恰好如此」的记录 + const info = installInfo(); + assert.ok(['dev', 'registry', 'unknown'].includes(info.mode), 'mode 要是三种之一'); + assert.equal(up.state().installMode, info.mode, 'state 要带上安装方式'); + assert.equal(up.state().installPath, info.path, 'state 要带上路径'); +} + +// 🔴 **进程刚启动时,结果旧到会误导人(> 1 小时)就补查一次**。 +// 以前 nextDelay() 只看 kv 里的 checkedAt ⇒ 宿主重启后可能要再等好几个小时才重查, +// 面板一直显示上一次的旧结果(实测 latest 停在 0.18.5,而 npm 上早就是 0.18.7 了)。 +// ⚠️ 但**不能每次启动都问**:GitHub 未认证 API 是 60 次/小时/IP,崩溃重启循环会吃满; +// 而且 nextDelay() 的文档写着「重启频繁时也不会每次启动都去问」—— 那是一条既有承诺。 +{ + const armOf = async (u) => { + let armed = null; + const realSetTimeout = globalThis.setTimeout; + globalThis.setTimeout = (fn, ms) => { armed = ms; return { unref() {} }; }; + try { u.start(); } finally { globalThis.setTimeout = realSetTimeout; } + return armed; + }; + // (a) 上次查的结果很旧(7 小时前)⇒ 补查(30 秒) + { + const db3 = new DatabaseSync(':memory:'); + db3.exec('CREATE TABLE kv (key TEXT PRIMARY KEY, value TEXT NOT NULL)'); + let t = 7 * 3600_000; + const u3 = new UpdateChecker({ db: db3, getConfig: () => ({}), fetchImpl, current: '0.11.2', now: () => t, random: () => 1 }); + await u3.check(); // 查一次(checkedAt = t) + t += 7 * 3600_000; // 又过了 7 小时 ⇒ 结果旧到会误导人 + assert.equal(await armOf(u3), 30_000, '结果超过 1 小时了 ⇒ 进程启动后补查(30 秒)'); + } + // (b) 上次刚查过 ⇒ 不补查,接着 12 小时的排程(别把 API 打满) + { + const db4 = new DatabaseSync(':memory:'); + db4.exec('CREATE TABLE kv (key TEXT PRIMARY KEY, value TEXT NOT NULL)'); + const u4 = new UpdateChecker({ db: db4, getConfig: () => ({}), fetchImpl, current: '0.11.2', now: () => 0, random: () => 1 }); + await u4.check(); // checkedAt = 0 + const armed = await armOf(u4); + assert.ok(armed > 30_000, `刚查过就不该补查(否则每次重启都打一遍 API),实际排程 ${armed}ms`); + } +} + // 自动检查开关 assert.equal(up.state().autoCheck, true); auto = false; @@ -105,7 +164,13 @@ up.start(); up.stop(); // 路由 const saved = []; -const deps = { updater: up, saveConfig: async (p) => { saved.push(p); auto = p.update.autoCheck; } }; +// 带一个宿主 plugin-manager 服务 ⇒ canApply 应为 true +const pm = { updateBundle: async () => ({}) }; +const deps = { + updater: up, + ctx: { get: () => pm }, + saveConfig: async (p) => { saved.push(p); auto = p.update.autoCheck; } +}; const run = async (method, path, body, origin = true) => { let out = null; const handled = await handleUpdateRoute({ @@ -122,8 +187,66 @@ r = await run('POST', '/update/check', '', false); assert.equal(r.code, 403); r = await run('POST', '/update/config', JSON.stringify({ autoCheck: true })); assert.equal(r.code, 200); assert.deepEqual(saved, [{ update: { autoCheck: true } }]); assert.equal(r.payload.autoCheck, true); + +// ⚠️ canApply 必须在**每个**响应里都在。 +// 面板把整个响应换进 data ⇒ 漏一个字段,那个字段就变 undefined ⇒ +// 点一下「检查更新」或切一下自动检查开关,「一键更新」按钮就凭空消失。 +for (const [method, path, body] of [['GET', '/update/state', ''], ['POST', '/update/check', ''], ['POST', '/update/config', JSON.stringify({ autoCheck: true })]]) { + const rr = await run(method, path, body); + assert.equal(rr.code, 200, path); + assert.equal(rr.payload.canApply, true, `${path} 的响应要带 canApply(否则面板上「更新到」按钮会消失)`); + assert.equal(rr.payload.installMode, installInfo().mode, `${path} 的响应要带 installMode(面板要据此说明为什么没有一键更新)`); +} r = await run('POST', '/update/config', JSON.stringify({ autoCheck: 'yes' })); assert.equal(r.code, 400); assert.equal((await run('GET', '/other')).handled, false); +// ── 接线测试:ctx 有没有真的传到路由里 ── +// ⚠️ 以前所有测试都是**手工构造 deps**(自己塞 ctx),从来不走真实的 registerRoutes 接线, +// 于是「deps 里压根没有 ctx」这件事谁都没发现 —— 一键更新按钮在真机上从来没渲染过。 +{ + const { registerRoutes } = await import('../lib/routes.js'); + let handler = null; + const pm2 = { updateBundle: async () => ({}) }; + const hostCtx = { effect: (fn) => { fn(); }, webServer: { register: (o) => { handler = o.handler; } }, get: () => pm2 }; + // 生产形态的 deps:**没有 ctx**(就像 lib/index.js 里以前那样) + const prodDeps = { updater: up, saveConfig: async () => {}, db, clock: { getRoleDateParts: () => ({ dateStr: '2030-01-01' }) } }; + registerRoutes(hostCtx, prodDeps); + assert.equal(prodDeps.ctx, hostCtx, 'registerRoutes 必须把 ctx 放进 deps(否则 /update/ 拿不到宿主的 plugin-manager 服务)'); + const req = new (await import('node:stream')).Readable({ read() { this.push(null); } }); + req.url = '/api/plugins/fish-soul/update/state'; + req.method = 'GET'; + req.headers = {}; + let out = ''; + const res = { writeHead: () => {}, end: (t) => { out = t; } }; + await handler(req, res); + const payload = JSON.parse(out); + assert.equal(payload.ok, true); + assert.equal(payload.canApply, true, '宿主有 plugin-manager 服务时 canApply 要是 true(否则面板上没有「更新到」按钮)'); + assert.ok(payload.installMode !== undefined, '响应要带 installMode'); +} + +// ── fallback 路径(updater 没起来时)的字段集必须和正常路径一致 ── +// 少一个字段,面板就少一块东西 —— 这次修的正是「漏字段导致按钮消失」,同一个坑不能留半个。 +{ + const { registerRoutes } = await import('../lib/routes.js'); + let handler = null; + const hostCtx2 = { effect: (fn) => { fn(); }, webServer: { register: (o) => { handler = o.handler; } }, get: () => ({ updateBundle: async () => ({}) }) }; + // **没有 updater** —— 走 fallback 分支 + registerRoutes(hostCtx2, { saveConfig: async () => {} }); + const req = new (await import('node:stream')).Readable({ read() { this.push(null); } }); + req.url = '/api/plugins/fish-soul/update/state'; + req.method = 'GET'; + req.headers = {}; + let out = ''; + const res = { writeHead: () => {}, end: (t) => { out = t; } }; + await handler(req, res); + const payload = JSON.parse(out); + assert.equal(payload.ok, true); + for (const k of ['current', 'latest', 'hasUpdate', 'checkedAt', 'checking', 'autoCheck', 'canApply', 'installMode', 'installPath', 'command', 'notes', 'notesUrl', 'error']) { + assert.ok(k in payload, `fallback 的响应也要有 ${k}(面板按这些字段渲染,少一个就少一块)`); + } + assert.equal(payload.installMode, installInfo().mode, 'fallback 也要带上安装方式'); +} + console.log('update-check ok');