Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -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托我带句话】」前缀 —— 收件人看得见是谁托的,她没法匿名传话。
Expand Down
16 changes: 16 additions & 0 deletions lib/client.js
Original file line number Diff line number Diff line change
Expand Up @@ -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")
Expand All @@ -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: "自动检查更新" })));
}
Expand Down
1 change: 1 addition & 0 deletions lib/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
22 changes: 18 additions & 4 deletions lib/routes-update.js
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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;
Expand All @@ -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') {
Expand All @@ -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;
Expand Down
5 changes: 5 additions & 0 deletions lib/routes.js
Original file line number Diff line number Diff line change
Expand Up @@ -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站扫码(密钥只留在服务端) */
Expand Down
21 changes: 18 additions & 3 deletions lib/self-update.js
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}
Expand Down
95 changes: 89 additions & 6 deletions lib/update-check.js
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand All @@ -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;
Expand All @@ -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/<profile>/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());
Expand Down Expand Up @@ -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() {
Expand All @@ -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(); }
Expand All @@ -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;
}
Expand Down Expand Up @@ -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;
Expand All @@ -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
};
}
}
13 changes: 13 additions & 0 deletions test/self-update.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -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 }),
Expand Down
Loading
Loading