From 6c5ab25b2f5a2eeb014d67f0a5bb4f2423a5548f Mon Sep 17 00:00:00 2001 From: qinqiu <2186498057@qq.com> Date: Tue, 17 Nov 2026 23:08:48 +0800 Subject: [PATCH] =?UTF-8?q?feat(relay):=20=E5=88=B7=E5=88=B0=E5=B0=B1?= =?UTF-8?q?=E5=88=86=E4=BA=AB=E5=8A=A0=E5=85=9C=E5=BA=95=20+=20DSH=20?= =?UTF-8?q?=E5=8A=A8=E6=80=81=E6=98=BE=E7=A4=BA=E4=B8=BB=E4=BA=BA=E5=8F=91?= =?UTF-8?q?=E8=A8=80=EF=BC=88#133=20/=20#78=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## #133 B站不主动开口分享 真机库只读核实的现状: - 2026-11-17 她刷了 8 条以上 B站视频,**一条分享待办都没排** - 分享原本只靠模型在每条视频末尾标 `[分享]`,提示词里明说「大多数视频不用」 ⇒ 她几乎不标 ⇒ 排出来的待办长期为 0 - B站最近一次分享是 2026-11-07(10 天前) - `SHARE_TTL_VIRTUAL_MS` 原本 4 虚拟小时 ⇒ 11-12 排的那条下午刷的 晚上想发已经过期(status=expired),主人只看到「她没开口」 ## 改了什么 1. **兜底策略**:模型没标 `[分享]` 时,最近 N 天没分享过就主动挑一条(有感受、 没划走的)排上。`proactive.shareFallbackDays`(默认 2,0 = 关),面板可调。 2. **「上次分享」按送达算、按平台分**: - 入队就记的话,一条从没发出去的(failed / expired)会把兜底锁死两天 —— 等于把「排了没发出去」这个原 bug 原样复制一遍。改成送达时(deliverOne)才记。 - 分平台(`share.lastAt.B站` / `share.lastAt.抖音`):抖音天天分享不该把 B站的兜底也压掉 —— 主人报的就是 B站。 3. **TTL 4h → 12h**,但**不跨角色日**:12 小时窗口必然跨午夜,而待办正文写的是 「你刚在X刷到一个视频」,隔天早上发出去这话不成立。 4. **平台开关优先**:B站 / 抖音面板上关掉「刷到就分享」,兜底也不发 (之前兜底把用户的显式关闭反转了,比不修更糟)。 5. 补 `proactive.shareVideos` 到 schema(代码一直在读,schema 里没有)。 ## #78 DSH 桌面端动态只显示她的发言 主人 11-16 问「用DSH给她发消息时,动态里只有一条DSH,内容是她的发言,我的发言去哪了」。 真机库核实结论:**记忆整理不受影响**(他的发言经 beginTurn 的 speakers 进 journal, 记忆里确实有「later让我给他唱一首歌」这种双人的内容);缺的是动态页这一轮的上下文。 现在 `note('dsh')` 也带上主人这一轮说的话。 ## 审查轮抓到的问题(全是「测试全绿但功能是坏的」) | 级别 | 问题 | 后果 | |---|---|---| | P0 | 两个浏览器构造函数没接 `shareFallback` | **整个兜底是死代码**,一次都不会触发 | | P0 | 面板 POST body 漏了两个字段 | 改了存不进去(读回又是默认值,像保存失败但没报错);而且任何一次「自走与主动」保存都会把用户手写的 0(关掉兜底)改回 2 | | P1 | 兜底无视平台开关 | 用户显式关掉的开关被反转 | | P1 | `share.lastAt` 全局 | 抖音分享一次,B站兜底哑火两天 —— 正好打在主人报的 B站 上 | | P1 | `share.lastAt` 记「排上」不是「发出」 | 排了没发出去也锁死两天(原 bug 原样复制) | | P1 | TTL 12h 跨午夜 | 晚上排的分享第二天早上发出去(正是被删掉的那行注释担心的) | **P0-1 之所以漏网**:测试全是手搓的对象字面量,没用真实的浏览器实例。 现在补了一条用真 `BiliBrowser` 的断言。 ## 验证 - `test/share-fallback.mjs` 14 组断言(含真实浏览器实例 / 平台开关 / 跨平台 / 送达语义 / 过期判定 / 配额 / 门槛) - `test/smoke.mjs` 补路由断言:请求不带分享字段时不能把用户设的值冲掉 - 逐条撤掉验证 **11 处全部真红**,还原后全绿 - 全量 `npm test` **EXIT=0,527 项断言全绿** ## 未验证 真机上她真的主动分享出去一条(要跑一整轮自走层 + 真发消息给主人)。 ## 顺带 `douyin-adapter-plan.md` 是工作区方案文档(同 `DESIGN-fish-soul.md` 一类), 之前没在 .gitignore 里,会被 `git add -A` 带进提交 —— 已加进忽略清单,文件仍在磁盘上。 --- .gitignore | 1 + CHANGELOG.md | 8 + lib/browse.js | 29 +++- lib/client.js | 10 ++ lib/config-schema.js | 4 + lib/douyin-browse.js | 4 +- lib/gateway-util.js | 8 + lib/gateway.js | 14 +- lib/index.js | 4 +- lib/life.js | 105 ++++++++++++- lib/routes.js | 11 ++ package.json | 2 +- test/issue-78-diagnostic.mjs | 8 +- test/share-fallback.mjs | 280 +++++++++++++++++++++++++++++++++++ test/smoke-v05.mjs | 10 +- test/smoke.mjs | 15 +- 16 files changed, 494 insertions(+), 19 deletions(-) create mode 100644 test/share-fallback.mjs diff --git a/.gitignore b/.gitignore index 5d3c12d..ce06ea4 100644 --- a/.gitignore +++ b/.gitignore @@ -7,6 +7,7 @@ test/eval/reports/ DESIGN-fish-soul.md dsh_fish_soul_deepseek_harness.html dsh_fish_soul_ui_design.md +douyin-adapter-plan.md # 抖音抓包原始数据(解出来是真实 uid / sec_uid,别进仓库) probe-*/ diff --git a/CHANGELOG.md b/CHANGELOG.md index 33f3f8c..5ae5d07 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,13 @@ # dsh-fish-soul 变更记录 +- 未发布:她刷到想分享的视频会主动挑一条发给你了(#133);在 DSH 里聊的话,动态里能看到你说了什么(#78)。 + - **「刷到就分享」加了兜底**:以前分享只靠模型自己在每条视频末尾标 `[分享]`,而提示词里明说「大多数视频不用」⇒ 她几乎不标 ⇒ 分享待办长期为 0。真机库核对:2026-11-17 她刷了 8 条以上 B站视频,一条分享都没排;B站最近一次分享还是 11-07(10 天前)。现在:最近几天没分享过的话,她会主动从这轮刷到的里挑一条(有感受、没划走的)发给你。可以在设置页调「几天没分享就主动挑一条」(默认 2 天,设 0 = 回到「只发她自己想发的」)。 + - **「上次分享过」按送达算、按平台分**:只排上没发出去的(失败 / 过期)不算「分享过」—— 否则一条卡住的分享会连着两天什么都不做。抖音分享一次也不影响 B站的兜底(之前是全局一个键,抖音天天分享 B站就永远轮不上)。 + - **分享待办的时效从 4 小时放宽到 12 小时**:下午刷到的视频晚上想发,原来 4 小时一到就作废了(真机上 11-12 排的那条就是这么没发出去的)。但**不会跨天** —— 待办正文写的是「你刚刷到」,隔天早上发出去这话就不成立。 + - **平台开关优先**:你在 B站 / 抖音面板上关掉「刷到就分享」,兜底也不会发(之前兜底把你的显式关闭反转了,比不修更糟)。 + - **在 DSH 里聊,动态里能看到你说了什么**:以前那一轮只显示她的发言,你会以为自己的话丢了。记忆整理本身不受影响(你的话一直进聊天日志)。 + - **验证范围**:新增 `test/share-fallback.mjs`(14 组断言,含**真实浏览器实例**——上一版全是手搓对象,构造函数的参数漏接了导致整个兜底是死代码都没测出来)+ `test/smoke.mjs` 补路由断言(请求不带分享字段时不能把你手改的值冲掉)。逐条撤掉验证 11 处全部真红。**未验证**:真机上她真的主动分享出去一条(要跑一整轮自走层 + 真发消息给主人)。 + - 未发布:设置页的「更新」修好了 —— 一键更新按钮以前**从来没渲染过**。 - **根因**:`/update/` 那组路由要靠宿主的 plugin-manager 服务才知道能不能一键更新,但宿主上下文压根没被传进路由(`deps.ctx` 恒是空)⇒ 面板永远判定「不能一键更新」⇒ 按钮不渲染。顺带还有:`pluginManagerOf` 只按属性取服务(cordis 也能用 `ctx.get()` 拿)、两个路由的响应漏了 `canApply`(点一下「检查更新」按钮就凭空消失)、面板上的版本号是七八小时前的旧缓存(显示「已是最新」是假的)。 - **现在**:按钮按宿主说了算(宿主拒绝时会把原因原样带回来),查到的版本号不会再过期到误导人。 diff --git a/lib/browse.js b/lib/browse.js index 23d5120..a640071 100644 --- a/lib/browse.js +++ b/lib/browse.js @@ -35,7 +35,29 @@ export function afterRound(self, label, watched, pick) { }); } catch { /* 动态可缺 */ } const s = watched.find((w) => w.share); - if (!s || typeof self.share !== 'function') return; + // 模型这轮没标 [分享]:让自走层判断要不要主动挑一条(最近几天没分享过才挑,见 #133)。 + // 原来这里是直接 return ⇒ 她不标就一条都不排,主人看到的就是「刷了但从不分享」。 + if (!s) { + if (typeof self.shareFallback !== 'function') return; + // ⚠️ 用户在平台面板上明确关了「刷到就分享」⇒ 兜底也不许发。 + // 不看这个开关的话,兜底会把用户的显式关闭**反转**(比不修更糟)。 + if (typeof self.cfg === 'function' && self.cfg()?.share === false) return; + try { + const candidates = watched.map((w) => ({ ...pick(w), impression: w.impression, skipped: w.skipped, url: w.url })); + const r = self.shareFallback({ platform: label, candidates }); + if (r?.ok) { + // 用它返回的那条(挑的规则在自走层那边,自己重算可能挑到不一样的) + const one = r.chosen ?? candidates.find((c) => c.impression) ?? candidates[0]; + self.note?.('share', { title: label, reason: `最近没分享,主动挑一条《${String(one?.title ?? '').slice(0, 20)}》分享给你`, text: one?.url ?? '' }); + } else if (r?.error && !/最近 .* 天分享过了|没有值得分享|兜底关着|分享视频关着/.test(r.error)) { + self.note?.('browse', { title: label, reason: `想主动分享但没排上:${r.error}` }); + } + } catch (error) { + self.log('warn', `[fish-soul] 兜底分享失败:${String(error instanceof Error ? error.message : error)}`); + } + return; + } + if (typeof self.share !== 'function') return; try { const r = self.share({ platform: label, ...pick(s), url: s.url, impression: s.impression }); self.note?.(r?.ok ? 'share' : 'browse', { title: label, reason: r?.ok ? `想把《${String(pick(s).title ?? '').slice(0, 20)}》分享给你` : `想分享但没排上:${r?.error ?? '不知道为什么'}`, text: s.url }); @@ -57,8 +79,11 @@ export class BiliBrowser { * @param {(level: string, msg: string) => void} [deps.log] * @param {[number, number]} [deps.watchDelayMs] 两条视频之间"看"多久(真实毫秒) */ - constructor({ db, clock, client, getConfig, callLlm, persona, worker, log, watchDelayMs = [8000, 20000], share, note, frames }) { + constructor({ db, clock, client, getConfig, callLlm, persona, worker, log, watchDelayMs = [8000, 20000], share, shareFallback, note, frames }) { this.share = share ?? null; // 刷到特别想分享的:交给自走层排一条主动消息(带链接) + // #133:模型没标 [分享] 时的兜底(最近几天没分享过就主动挑一条)。 + // ⚠️ 漏了这个参数整个兜底就是死代码(afterRound 里 self.shareFallback 恒 undefined)。 + this.shareFallback = shareFallback ?? null; this.note = note ?? null; // 记一条动态 this.db = db; this.clock = clock; diff --git a/lib/client.js b/lib/client.js index a63a5a4..3ce26bb 100644 --- a/lib/client.js +++ b/lib/client.js @@ -437,6 +437,7 @@ window.__ModuleLoader__.load({ enabled: pc.enabled !== false, dailyMaxCount: pc.dailyMaxCount ?? 10, activeStart: pc.activeHours?.[0] ?? 8, activeEnd: pc.activeHours?.[1] ?? 24, idleTriggerHours: pc.idleTriggerHours ?? 6, idleRealGapMinutes: pc.idleRealGapMinutes ?? 30, scheduleEnabled: pc.scheduleEnabled !== false, + shareMaxPerDay: pc.shareMaxPerDay ?? 2, shareFallbackDays: pc.shareFallbackDays ?? 2, masterPrivateChannelId: targets.masterPrivateChannelId ?? "", selfGroupChannelIds: [...(targets.selfGroupChannelIds ?? [])] })); if (!data || !form) return null; @@ -456,6 +457,9 @@ window.__ModuleLoader__.load({ idleTriggerHours: next.idleTriggerHours, idleRealGapMinutes: next.idleRealGapMinutes, scheduleEnabled: next.scheduleEnabled, + // #133:这两个字段不进 body ⇒ 面板改了存不进去(读回又是默认值,像保存失败但没报错) + shareMaxPerDay: next.shareMaxPerDay, + shareFallbackDays: next.shareFallbackDays, targets: { masterCanonicalId: targets.masterCanonicalId ?? "user:master", masterPrivateChannelId: next.masterPrivateChannelId, selfGroupChannelIds: next.selfGroupChannelIds } }); if (res?.ok) refresh(); else notify(res?.error ?? "保存失败"); @@ -489,6 +493,12 @@ window.__ModuleLoader__.load({ form.enabled ? Row({ title: "空闲多久后" }, num("idleTriggerHours", "空闲多久后", 1, 48, 6), Muted("小时")) : null, form.enabled ? Row({ title: "刚聊完先等等" }, num("idleRealGapMinutes", "刚聊完先等等", 0, 1440, 30), Muted("分钟"), Muted("0 = 不等")) : null, form.enabled ? Row({ title: "自走日程" }, h(Switch, { label: "自走日程", checked: form.scheduleEnabled, onChange: (v) => save({ scheduleEnabled: v }) }), Muted("关掉就不排今天干什么")) : null, + form.enabled ? Row({ title: "分享视频", stack: true }, + num("shareMaxPerDay", "分享视频每天最多", 0, 20, 2), Muted("条/天"), + Muted("她刷到特别想分享的才会发")) : null, + form.enabled ? Row({ title: "几天没分享就主动挑一条", stack: true }, + num("shareFallbackDays", "几天没分享就主动挑一条", 0, 30, 2), Muted("天"), + Muted("0 = 不主动挑(只用她自己想分享的)")) : null, form.enabled ? Row({ title: "主人私聊" }, Input({ value: form.masterPrivateChannelId, placeholder: "private:主人 QQ", onChange: (e) => patch({ masterPrivateChannelId: e.target.value }), onBlur: () => save() })) : null, form.enabled ? Row({ title: "群聊", stack: true }, ...form.selfGroupChannelIds.map((cid) => Tag(cid, undefined, { key: cid }, diff --git a/lib/config-schema.js b/lib/config-schema.js index 7a33be5..2dce80a 100644 --- a/lib/config-schema.js +++ b/lib/config-schema.js @@ -176,6 +176,10 @@ export function fishSoulConfigSchema(z) { // #75:自走日程开关。关掉 = 不生成日程、不注入时段、不用忙/闲卡住主动与刷视频 scheduleEnabled: z.boolean().default(true), shareMaxPerDay: z.number().default(2), // 刷到想分享的视频,一天最多主动发几条 + shareVideos: z.boolean().default(true), // 分享视频总开关(以前代码读它但 schema 里没有 ⇒ 读不到,等于写不了) + // #133:最近 N 天没分享过就主动挑一条(0 = 关)。分享原本只靠模型标 [分享], + // 而提示词明说「大多数视频不用」⇒ 实测她几乎不标,分享待办长期为 0。 + shareFallbackDays: z.number().default(2), targets: z.object({ masterCanonicalId: z.string().default('user:master'), masterPrivateChannelId: z.string().default(''), diff --git a/lib/douyin-browse.js b/lib/douyin-browse.js index d4dd543..89fa26b 100644 --- a/lib/douyin-browse.js +++ b/lib/douyin-browse.js @@ -105,8 +105,10 @@ export class DouyinBrowser { * @param {import('./douyin-http.js').DouyinHttp} [deps.http] 纯 HTTP 客户端(http 模式用) * @param {object} [deps.timing] 页面操作的时间上限(eval / send / next 的总预算) */ - constructor({ db, clock, host, getConfig, callLlm, persona, worker, log, dwellMs = [5000, 20000], readDetail = detail, settleMs = 8000, fetchImpl, share, note, http, frames, timing = {} }) { + constructor({ db, clock, host, getConfig, callLlm, persona, worker, log, dwellMs = [5000, 20000], readDetail = detail, settleMs = 8000, fetchImpl, share, shareFallback, note, http, frames, timing = {} }) { this.share = share ?? null; + // #133:同上 —— 漏了这个参数兜底就是死代码。 + this.shareFallback = shareFallback ?? null; this.note = note ?? null; this.framesOf = frames ?? null; // 抽九宫格看画面(可缺:没有就只读文字) this.db = db; diff --git a/lib/gateway-util.js b/lib/gateway-util.js index a5db9ab..7fe23d1 100644 --- a/lib/gateway-util.js +++ b/lib/gateway-util.js @@ -144,6 +144,14 @@ export function parseRelayTarget(toRaw, platformRaw) { return { ok: false, error: `收件人「${raw}」看不出是哪个平台的号。要么给纯数字 + platform,要么写成 qq:123 / bili:123 / douyin:123。` }; } +/** 宿主 user/message 事件里的正文(content 可能是字符串,也可能是 block 数组)。 */ +export function textOfUserMessage(message) { + const content = message?.content; + if (typeof content === 'string') return content; + if (!Array.isArray(content)) return ''; + return content.filter((b) => b && b.type === 'text' && typeof b.text === 'string').map((b) => b.text).join('\n').trim(); +} + /** channel_id → 平台:bili: 是 B站私信,douyin:<名字> / douyin-group:<群名> 是抖音私信 / 群聊,其余(private:/group:)是 QQ。 */ export function platformOf(channelId) { const s = String(channelId ?? ''); diff --git a/lib/gateway.js b/lib/gateway.js index 0fb9779..d57c219 100644 --- a/lib/gateway.js +++ b/lib/gateway.js @@ -37,7 +37,7 @@ import { applyAttachments, attachmentConfig } from './attachments.js'; import { parseCollect } from './stickers.js'; import { UNHEARD } from './voice.js'; import { saveVoiceFile, voiceIncomingEpoch, audioExt } from './voice-files.js'; -import { typingDelayMs, interjectScore, interjectConfig, platformOf, splitChannelId, sessionChannelOf, isGroupChannelId, service, parseClosing, clampReplyWindow, normalizeRelayId } from './gateway-util.js'; +import { typingDelayMs, interjectScore, interjectConfig, platformOf, splitChannelId, sessionChannelOf, isGroupChannelId, service, parseClosing, clampReplyWindow, normalizeRelayId, textOfUserMessage } from './gateway-util.js'; import { mediaMethods } from './gateway-media.js'; import { Outbox, classifySendError } from './outbox.js'; import { safeDownload } from './safe-download.js'; @@ -1690,7 +1690,14 @@ export class ChatGateway { const pending = this.pendingVoicePaths?.get(String(msg?.id ?? '')); st.voicePaths = kind === SOURCE_QQ && pending?.sessionId === sessionId && Date.now() - pending.at <= 300_000 ? pending.paths : []; if (pending) this.pendingVoicePaths.delete(String(msg.id)); - } else if (kind === 'user') { st.fromUs = false; st.dshTyped = true; st.voicePaths = []; } // #78:DSH 桌面端打字,不外发但要记动态 + } else if (kind === 'user') { + st.fromUs = false; st.dshTyped = true; st.voicePaths = []; + // #78:主人自己打的字也记下来。动态页原来只显示她的发言 ⇒ 主人看到 + // 「动态里只有一条 DSH,内容是她的发言,我的发言去哪了」。 + // 记忆整理不受影响(他的发言经 beginTurn 的 speakers 进 journal), + // 缺的是动态页这一轮的上下文。 + st.userText = textOfUserMessage(msg); + } // 其他宿主上下文(runtime-context / model-selection 等):不动 fromUs —— // 它们不是我们发的消息,但也不是真人打字,重置会把 B站/抖音 的回复憋回去(smoke #13 守着) // 共享会话里一个会话对应多个通道(QQ + B站):这一轮从哪个通道进来的,来源里也带着 —— @@ -1766,6 +1773,9 @@ export class ChatGateway { this.note('dsh', { channelId: st.channelId ?? this.bound.get(sessionId)?.channel_id ?? '', text: String(st.text ?? '').slice(0, 60), + // 主人这一轮说了什么也带上(#78):动态页只显示她的发言, + // 主人会以为自己的话丢了。带上之后这一轮是完整的一问一答。 + who: String(st.userText ?? '').trim() === '' ? '' : '主人:' + String(st.userText).trim().slice(0, 40), reason: '在 DSH 里聊的,不外发', memories: recall.memories ?? [], recallAt: recall.at ?? 0, diff --git a/lib/index.js b/lib/index.js index cc7a2dc..5d8af4a 100644 --- a/lib/index.js +++ b/lib/index.js @@ -320,7 +320,7 @@ async function startup(ctx, config, { log, gate }) { }); const browser = new BiliBrowser({ db, clock, client: biliClient, getConfig: biliCfg, callLlm: llmRouter.bound('browse'), worker, log, - share: (x) => life.queueShare(x), note: (k, x) => gateway?.note(k, x), + share: (x) => life.queueShare(x), shareFallback: (x) => life.queueShareFallback(x), note: (k, x) => gateway?.note(k, x), persona: () => ({ name: persona.name, brief: personaBrief() }), // 抽帧看画面(bili.browse.frames 开才用):一条失败不影响她看完这条视频 // 超时 60s:CDN 卡住时 ffmpeg 永久挂起会拖死整轮 watch(),到点 kill 退回纯文字 @@ -380,7 +380,7 @@ async function startup(ctx, config, { log, gate }) { // 抽帧看画面(douyin.browse.frames 开才用):play_addr 直链 → ffmpeg 九宫格。 // 超时 90 秒(抖音 CDN 会挂);一条失败不影响她看完这条,照旧只看文字。 frames: (v) => douyinFrames(v.urls, { id: v.id, durationMs: v.durationMs, signal: AbortSignal.timeout(90_000) }), - share: (x) => life.queueShare(x), note: (k, x) => gateway?.note(k, x), + share: (x) => life.queueShare(x), shareFallback: (x) => life.queueShareFallback(x), note: (k, x) => gateway?.note(k, x), persona: () => ({ name: persona.name, brief: personaBrief() }) }); // 抖音自己发图文 / 回评论(默认都关;走专用浏览器,尽力而为) diff --git a/lib/life.js b/lib/life.js index 16f66f8..5e4fbf2 100644 --- a/lib/life.js +++ b/lib/life.js @@ -45,7 +45,12 @@ const PENDING_MAX_ATTEMPTS = PENDING_RETRY_STEPS_VIRTUAL_MS.length; const SURFACED_RECYCLE_VIRTUAL_MS = 6 * 3600_000; const RESTORE_INTERACTION_WINDOW_MS = 7 * 86_400_000; /** 刷到想分享的:排进待办,过了这么久(虚拟)还没发出去就算了(隔天再分享像翻旧账) */ -const SHARE_TTL_VIRTUAL_MS = 4 * 3600_000; +// 分享待办的时效:12 虚拟小时(以前 4 小时 —— 下午刷到的晚上想发已经过期了, +// 真机上 2026-11-12 排的那条就是这么变成 expired 的,主人只看到「她没开口」)。 +// ⚠️ 但**不能跨角色日**:12 小时窗口必然跨午夜(16:00 排的能发到次日 04:00), +// 而待办正文写的是「你刚在X刷到一个视频」—— 隔天早上发出去这话就不成立了。 +// 所以过期判定 = 「超过 TTL」或「不是同一个角色日」,两个条件满足其一就作废。 +const SHARE_TTL_VIRTUAL_MS = 12 * 3600_000; const SHARE_DEFAULT_PER_DAY = 2; /** 她自己起意的待办(占每日主动配额) */ const BOT_ORIGINS = new Set(['dream', 'share']); @@ -341,8 +346,12 @@ export class LifeEngine { */ async flushDue(p) { const nowVirtual = this.clock.now(); - // 分享过了时效就不发了(下午刷到的视频晚上再发像翻旧账) - this.db.prepare("UPDATE pending SET status = 'expired' WHERE character_id = 'feiyu' AND status = 'pending' AND origin = 'share' AND due_at < ?").run(nowVirtual - SHARE_TTL_VIRTUAL_MS); + // 分享过了时效就不发了(下午刷到的视频晚上再发像翻旧账;隔天更不行 —— 正文写的是「你刚刷到」) + this.db.prepare("UPDATE pending SET status = 'expired' WHERE character_id = 'feiyu' AND status = 'pending' AND origin = 'share' AND (due_at < ? OR created_at < ?)").run( + nowVirtual - SHARE_TTL_VIRTUAL_MS, + // 当天 00:00(角色时区)之前的排的都作废 + this.roleDayStartMs(nowVirtual) + ); // 顺口提起过、对方没接着聊:过一阵退回 pending 重来,别让提醒就这么没了(#80) this.db.prepare(` UPDATE pending SET status = 'pending', due_at = ?, surfaced_at = NULL @@ -371,7 +380,7 @@ export class LifeEngine { (day.last_proactive_at === null || day.last_proactive_at === undefined || nowVirtual - day.last_proactive_at >= PROACTIVE_MIN_GAP_VIRTUAL_MS); if (!botAllowed) return false; - const bot = rows.find((d) => BOT_ORIGINS.has(d.origin) && !(d.origin === 'share' && d.due_at < nowVirtual - SHARE_TTL_VIRTUAL_MS)); + const bot = rows.find((d) => BOT_ORIGINS.has(d.origin) && !(d.origin === 'share' && this.shareExpired(d, nowVirtual))); if (bot === undefined) return false; await this.deliverOne(bot, nowVirtual); return true; @@ -400,6 +409,9 @@ export class LifeEngine { this.lastProactiveReal.set(platform, Date.now()); if (ok) { this.db.prepare("UPDATE pending SET status = 'done' WHERE id = ?").run(d.id); + // #133:分享**真的发出去了**才记「上次分享」(分平台)。 + // 分平台是因为抖音分享一次不该把 B站的兜底也压掉 —— 主人报的就是 B站。 + if (d.origin === 'share') this.recordShareSent(d.id, nowVirtual); if (botInitiated) { this.db.prepare(` UPDATE day SET proactive_count = proactive_count + 1, last_proactive_at = ? @@ -480,7 +492,7 @@ export class LifeEngine { `).all(); for (const r of rows) { if (!this.isWhitelisted(r.channel_id, p, r.origin)) continue; - if (r.origin === 'share' && r.due_at < nowVirtual - SHARE_TTL_VIRTUAL_MS) continue; + if (r.origin === 'share' && this.shareExpired(r, nowVirtual)) continue; return Math.max(0, r.due_at - nowVirtual); } return null; @@ -590,6 +602,40 @@ export class LifeEngine { this.note('browse', { title: '抖音', reason: '想刷抖音,但抖音浏览器没开或没登录,这次先刷 B站' }); } + /** + * 角色时区(UTC+8)当天 00:00 对应的虚拟毫秒。 + * 角色日 = (atMs + 8h) 的 UTC 日期,所以那天的 00:00 往前推 8 小时就是 UTC 起点。 + */ + roleDayStartMs(atMs) { + const parts = this.clock.getRoleDateParts(atMs); + const d = String(parts?.dateStr ?? ''); + if (!/^\d{4}-\d{2}-\d{2}$/.test(d)) return 0; + const utc = Date.UTC(Number(d.slice(0, 4)), Number(d.slice(5, 7)) - 1, Number(d.slice(8, 10))); + return utc - 8 * 3600_000; + } + + /** + * 一条分享待办是不是已经「过时」了。 + * 两个条件满足其一就作废:① 超过 TTL;② 不是同一个角色日(跨夜了 —— + * 待办正文写的是「你刚在X刷到」,隔天发出去这话就不成立)。 + */ + shareExpired(row, nowVirtual) { + if (Number(row?.due_at ?? 0) < nowVirtual - SHARE_TTL_VIRTUAL_MS) return true; + const dayStart = this.roleDayStartMs(nowVirtual); + return dayStart > 0 && Number(row?.created_at ?? 0) < dayStart; + } + + /** + * 一条分享待办真的发出去了 ⇒ 记「这个平台上次分享是在什么时候」。 + * @param {number|string} pendingId + * @param {number} nowVirtual + */ + recordShareSent(pendingId, nowVirtual) { + const plat = String(getKv(this.db, `share.platform.${pendingId}`, '') ?? ''); + if (plat === '') return; + setKv(this.db, `share.lastAt.${plat}`, nowVirtual); + } + /** * 刷到特别想分享的视频:排一条给主人的主动消息(带链接 + 感受)。 * 走主动开口的所有限制(活跃时段、白名单、每日配额、两条之间的间隔),一天最多 proactive.shareMaxPerDay 条(默认 2)。 @@ -632,10 +678,59 @@ export class LifeEngine { // 它漏抄链接、或者干脆回个 [不回],卡片该发还是要发。 if (dyChannel !== '') setKv(this.db, `share.intent.${id}`, { videoId, caption: clean(impression, 120), title: clean(title, 60) }); setKv(this.db, 'share.day', { date: dateStr, count: count + 1 }); + // 🔴 **「上次分享」记在送达时,不是入队时**(#133 审查): + // 入队就记的话,一条从没发出去的分享(failed / expired)会把兜底锁死两天 —— + // 等于把「排了没发出去」这个原 bug 原样复制了一遍。 + // 这里只记「这条待办是哪个平台的」,送达时(deliverOne)才写 lastAt。 + setKv(this.db, `share.platform.${id}`, platform); this.armPendingAlarm(); return { ok: true, id }; } + /** + * 兜底:模型这轮没标 [分享],但好几天没分享过了 —— 主动挑一条排上。 + * + * 为什么要有这条(#133):分享原本只靠模型在每条视频末尾标 [分享], + * 而提示词里明说「大多数视频不用」⇒ 真机实测她几乎不标 ⇒ 分享待办长期为 0, + * 主人看到的就是「她刷了一堆视频,但从不开腔分享」。 + * + * 门槛是「最近 N 天没分享过」(`proactive.shareFallbackDays`,默认 2,0 = 关): + * 不设门槛的话每轮都分享,那就成刷屏了。 + * + * @param {{platform: string, candidates: Array}} input + * @returns {{ok: boolean, error?: string, id?: number}} + */ + queueShareFallback({ platform, candidates }) { + const p = this.getConfig().proactive ?? {}; + const days = Math.floor(Number(p.shareFallbackDays ?? 2)) || 0; + if (days <= 0) return { ok: false, error: '分享兜底关着' }; + if (p.shareVideos === false) return { ok: false, error: '分享视频关着' }; + const now = this.clock.now(); + // ⚠️ **分平台**:抖音分享一次不该把 B站的兜底也压掉(主人报的就是 B站)。 + // 每日配额 share.day 仍���全局的 —— 那道是「别刷屏」的总闸,跨平台共享是对的。 + const lastAt = Number(getKv(this.db, `share.lastAt.${platform}`, 0) ?? 0); + // 时钟被回拨 / 从旧备份恢复时 now < lastAt ⇒ 负 delta 会把兜底永久锁死。 + // 这里夹到 0(当成「没分享过」)而不是让负数小于阈值。 + const since = lastAt > 0 ? Math.max(0, now - lastAt) : Number.POSITIVE_INFINITY; + if (lastAt > 0 && since < days * 24 * 3600_000) { + return { ok: false, error: `最近 ${days} 天分享过了,不主动补` }; + } + const list = Array.isArray(candidates) ? candidates : []; + // 只挑「有感受、没划走」的:没印象的分享出去只是一条链接,主人在 DSH 里点开也没话说 + const chosen = list.find((c) => c && c.skipped !== true && String(c.impression ?? '').trim() !== ''); + if (chosen === undefined) return { ok: false, error: '这轮没有值得分享的' }; + const r = this.queueShare({ + platform, + title: chosen.title, + author: chosen.owner ?? chosen.author ?? '', + url: chosen.url, + impression: chosen.impression + }); + // 把挑中的那条带回去(#133 审查):调用方记动态时要用它, + // 自己重算一遍挑的规则可能不一样(印象为空 / 划走),记出来的书名就跟实际发的不一样。 + return { ...r, chosen }; + } + /** 空闲时段自己刷 B站 / 抖音(一次只刷一个):后台跑,不阻塞 tick;失败只记日志。 */ maybeBrowse(day, parts) { if ((this.browse === null && this.douyinBrowse === null) || this.isBrowsing) return; diff --git a/lib/routes.js b/lib/routes.js index 6024a83..1e2319b 100644 --- a/lib/routes.js +++ b/lib/routes.js @@ -371,6 +371,15 @@ export function registerRoutes(ctx, deps) { const idleRealGapMinutes = Number.isFinite(rawRealGap) ? Math.min(1440, Math.max(0, Math.floor(rawRealGap))) : DEFAULT_IDLE_REAL_GAP_MIN; const rawIdleHours = Number(body.idleTriggerHours ?? 6); const idleTriggerHours = Number.isFinite(rawIdleHours) ? Math.min(168, Math.max(0, Math.floor(rawIdleHours))) : 6; + // 分享相关(#133):每天最多几条 + 几天没分享就主动挑一条(0 = 关) + // ⚠️ **字段缺失就沿用配置里的现值**,不能拿默认值覆盖 —— + // 否则任何一次没带这两个字段的保存(比如旧客户端、别的调用方) + // 都会把主人手写的 0(关掉兜底)悄悄改回 2。 + const curProactive = getConfig().proactive ?? {}; + const rawShareMax = body.shareMaxPerDay === undefined ? curProactive.shareMaxPerDay : Number(body.shareMaxPerDay); + const shareMaxPerDay = Number.isFinite(Number(rawShareMax)) ? Math.min(20, Math.max(0, Math.floor(Number(rawShareMax)))) : 2; + const rawFallbackDays = body.shareFallbackDays === undefined ? curProactive.shareFallbackDays : Number(body.shareFallbackDays); + const shareFallbackDays = Number.isFinite(Number(rawFallbackDays)) ? Math.min(30, Math.max(0, Math.floor(Number(rawFallbackDays)))) : 2; saveConfig({ proactive: { enabled: body.enabled !== false, @@ -379,6 +388,8 @@ export function registerRoutes(ctx, deps) { idleTriggerHours, idleRealGapMinutes, scheduleEnabled: body.scheduleEnabled !== false, + shareMaxPerDay, + shareFallbackDays, targets: { masterCanonicalId: body.targets?.masterCanonicalId ?? 'user:master', masterPrivateChannelId: masterChannel, diff --git a/package.json b/package.json index 17c99da..ea9f770 100644 --- a/package.json +++ b/package.json @@ -64,6 +64,6 @@ } }, "scripts": { - "test": "node test/memory-bulk-move.mjs && node test/safe-download.mjs && node test/douyin-exact-id.mjs && node test/douyin-pb-init.mjs && node test/douyin-conversation.mjs && node test/douyin-inbox.mjs && node test/douyin-quarantine.mjs && node test/douyin-send-target.mjs && node test/douyin-send-exclusive.mjs && node test/douyin-gap-dedupe.mjs && node test/douyin-message-id-dedupe.mjs && node test/douyin-read-fail-retry.mjs && node test/douyin-read-cache.mjs && node test/douyin-dm-media-conv.mjs && node test/douyin-read-fail-retry-poll.mjs && node test/douyin-inbox-contract.mjs && node test/person-attribution.mjs && node test/memory-owner-reassign.mjs && node test/douyin-poll-and-timer-safety.mjs && node test/p2-limits.mjs && node test/resource-safety.mjs && node test/leftover-edge-cases.mjs && node test/douyin-master-person-merge.mjs && node test/douyin-master-uid.mjs && node test/douyin-identity-e2e.mjs && node test/douyin-post-jobs.mjs && node test/retrieval-filtered-vectors.mjs && node test/security-boundaries.mjs && node test/douyin-cdp-cursor.mjs && node test/douyin-nav-timeout.mjs && node test/persona-isolation.mjs && node test/smoke.mjs && node test/douyin-browser.mjs && node test/douyin-page-alive.mjs && node test/douyin-eval-timeout.mjs && node test/douyin-bridge-timeout.mjs && node test/douyin-goto-budget.mjs && node test/douyin-music.mjs && node test/startup-gate.mjs && node test/outbox.mjs && node test/import-coverage.mjs && node test/update-check.mjs && node test/issue-fixes.mjs && node test/import-resume.mjs && node test/maibot-extras.mjs && node test/worldinfo.mjs && node test/memory-bulk.mjs && node test/memory-tiers.mjs && node test/memory-weekly.mjs && node test/issue-98-self-archive.mjs && node test/issue-99-memory-order.mjs && node test/issue-115-memory-date.mjs && node test/issue-119-memory-page.mjs && node test/issue-125-memory-filter.mjs && node test/issue-78-diagnostic.mjs && node test/memory-storage.mjs && node test/memory-storage-restore.mjs && node test/backup-restore.mjs && node test/douyin-group.mjs && node test/review-fixes.mjs && node test/at-reads-video.mjs && node test/search-source.mjs && node test/followups.mjs && node test/detail-config.mjs && node test/qq-send-any-image.mjs && node test/qq-read-attachment.mjs && node test/qq-batch-window.mjs && node test/comment-video.mjs && node test/frames.mjs && node test/face-name.mjs && node test/comment-reply.mjs && node test/chat-comment.mjs && node test/at-target.mjs && node test/quota-caps.mjs && node test/client-lint.mjs && node test/client-panels.mjs && node test/dsh-desktop.mjs && node test/group-mention-only.mjs && node test/qq-private-allowlist.mjs && node test/issue-59-interject.mjs && node test/issue-59-diagnose.mjs && node test/sticker-backfill.mjs && node test/issue-118-sticker-diagnostics.mjs && node test/sticker-manage.mjs && node test/bili-emotes.mjs && node test/qq-outbound-sanitize.mjs && node test/person-delete.mjs && node test/qq-group-admin.mjs && node test/douyin-recovery.mjs && node test/session-preset.mjs && node test/qq-connect-error.mjs && node test/douyin-comment-bridge.mjs && node test/douyin-comment-write-unknown.mjs && node test/douyin-reply-verify-status.mjs && node test/bili-comment-emoji.mjs && node test/douyin-state-echo.mjs && node test/issue-75-proactive.mjs && node test/issue-76-capability.mjs && node test/douyin-http-browse.mjs && node test/douyin-verify-backoff.mjs && node test/douyin-digg-bridge.mjs && node test/memory-evidence-transcript.mjs && node test/chat-archive-default.mjs && node test/issue-113-desktop-archive.mjs && node test/dream-transcript-wire.mjs && node test/douyin-frames-collect.mjs && node test/master-qq-uin-rebind.mjs && node test/douyin-session-health.mjs && node test/douyin-delivered.mjs && node test/douyin-card-share.mjs && node test/douyin-push-drop.mjs && node test/douyin-stranger-dm.mjs && node test/douyin-uid-binding.mjs && node test/image-webp-fallback.mjs && node test/douyin-emoji-fallback.mjs && node test/relay-other-platform.mjs && node test/relay-to-friend.mjs && node test/relay-config-route.mjs && node test/issue-101-voice-files.mjs && node test/voice-volcengine.mjs && node test/voice-minimax-dashscope.mjs && node test/bili-switch-persist.mjs && node test/cross-channel-context.mjs && node test/reply-target.mjs && node test/shared-session.mjs && node test/memory-source-label.mjs && node test/pending-delivery.mjs && node test/recall-window-78.mjs && node test/memory-recall-recent-78.mjs && node test/client-syntax.mjs && node test/diag-log.mjs && node test/check-rings.mjs && node test/release-workflow.mjs && node test/sticker-import-gif.mjs && node test/sticker-real-gif.mjs && node test/sticker-upload-binary.mjs && node test/sticker-vision-tags.mjs && node test/sticker-manual-tags.mjs && node test/sticker-auto-name.mjs && node test/self-update.mjs && node test/group-list.mjs && node test/douyin-inbox-noise.mjs && node test/douyin-inbox-diag.mjs && node test/douyin-inbox-stuck.mjs && node test/reply-window.mjs && node test/douyin-sticker-heuristic.mjs && node test/douyin-image-boundary.mjs && node test/media-image-boundary.mjs && node test/douyin-comment-identity-cid.mjs && node test/qq-mention-only-echo.mjs && node test/bili-panel-pagination.mjs && node test/bili-allowlist.mjs && node test/douyin-master-uid-mismatch.mjs && node test/check-test-chain.mjs && node test/check-route-guard.mjs && node test/check-client-imports.mjs && node test/check-secrets.mjs" + "test": "node test/memory-bulk-move.mjs && node test/safe-download.mjs && node test/douyin-exact-id.mjs && node test/douyin-pb-init.mjs && node test/douyin-conversation.mjs && node test/douyin-inbox.mjs && node test/douyin-quarantine.mjs && node test/douyin-send-target.mjs && node test/douyin-send-exclusive.mjs && node test/douyin-gap-dedupe.mjs && node test/douyin-message-id-dedupe.mjs && node test/douyin-read-fail-retry.mjs && node test/douyin-read-cache.mjs && node test/douyin-dm-media-conv.mjs && node test/douyin-read-fail-retry-poll.mjs && node test/douyin-inbox-contract.mjs && node test/person-attribution.mjs && node test/memory-owner-reassign.mjs && node test/douyin-poll-and-timer-safety.mjs && node test/p2-limits.mjs && node test/resource-safety.mjs && node test/leftover-edge-cases.mjs && node test/douyin-master-person-merge.mjs && node test/douyin-master-uid.mjs && node test/douyin-identity-e2e.mjs && node test/douyin-post-jobs.mjs && node test/retrieval-filtered-vectors.mjs && node test/security-boundaries.mjs && node test/douyin-cdp-cursor.mjs && node test/douyin-nav-timeout.mjs && node test/persona-isolation.mjs && node test/smoke.mjs && node test/douyin-browser.mjs && node test/douyin-page-alive.mjs && node test/douyin-eval-timeout.mjs && node test/douyin-bridge-timeout.mjs && node test/douyin-goto-budget.mjs && node test/douyin-music.mjs && node test/startup-gate.mjs && node test/outbox.mjs && node test/import-coverage.mjs && node test/update-check.mjs && node test/issue-fixes.mjs && node test/import-resume.mjs && node test/maibot-extras.mjs && node test/worldinfo.mjs && node test/memory-bulk.mjs && node test/memory-tiers.mjs && node test/memory-weekly.mjs && node test/issue-98-self-archive.mjs && node test/issue-99-memory-order.mjs && node test/issue-115-memory-date.mjs && node test/issue-119-memory-page.mjs && node test/issue-125-memory-filter.mjs && node test/issue-78-diagnostic.mjs && node test/memory-storage.mjs && node test/memory-storage-restore.mjs && node test/backup-restore.mjs && node test/douyin-group.mjs && node test/review-fixes.mjs && node test/at-reads-video.mjs && node test/search-source.mjs && node test/followups.mjs && node test/detail-config.mjs && node test/qq-send-any-image.mjs && node test/qq-read-attachment.mjs && node test/qq-batch-window.mjs && node test/comment-video.mjs && node test/frames.mjs && node test/face-name.mjs && node test/comment-reply.mjs && node test/chat-comment.mjs && node test/at-target.mjs && node test/quota-caps.mjs && node test/client-lint.mjs && node test/client-panels.mjs && node test/dsh-desktop.mjs && node test/group-mention-only.mjs && node test/qq-private-allowlist.mjs && node test/issue-59-interject.mjs && node test/issue-59-diagnose.mjs && node test/sticker-backfill.mjs && node test/issue-118-sticker-diagnostics.mjs && node test/sticker-manage.mjs && node test/bili-emotes.mjs && node test/qq-outbound-sanitize.mjs && node test/person-delete.mjs && node test/qq-group-admin.mjs && node test/douyin-recovery.mjs && node test/session-preset.mjs && node test/qq-connect-error.mjs && node test/douyin-comment-bridge.mjs && node test/douyin-comment-write-unknown.mjs && node test/douyin-reply-verify-status.mjs && node test/bili-comment-emoji.mjs && node test/douyin-state-echo.mjs && node test/issue-75-proactive.mjs && node test/issue-76-capability.mjs && node test/douyin-http-browse.mjs && node test/douyin-verify-backoff.mjs && node test/douyin-digg-bridge.mjs && node test/memory-evidence-transcript.mjs && node test/chat-archive-default.mjs && node test/issue-113-desktop-archive.mjs && node test/dream-transcript-wire.mjs && node test/douyin-frames-collect.mjs && node test/master-qq-uin-rebind.mjs && node test/douyin-session-health.mjs && node test/douyin-delivered.mjs && node test/douyin-card-share.mjs && node test/douyin-push-drop.mjs && node test/douyin-stranger-dm.mjs && node test/douyin-uid-binding.mjs && node test/image-webp-fallback.mjs && node test/douyin-emoji-fallback.mjs && node test/relay-other-platform.mjs && node test/relay-to-friend.mjs && node test/relay-config-route.mjs && node test/share-fallback.mjs && node test/issue-101-voice-files.mjs && node test/voice-volcengine.mjs && node test/voice-minimax-dashscope.mjs && node test/bili-switch-persist.mjs && node test/cross-channel-context.mjs && node test/reply-target.mjs && node test/shared-session.mjs && node test/memory-source-label.mjs && node test/pending-delivery.mjs && node test/recall-window-78.mjs && node test/memory-recall-recent-78.mjs && node test/client-syntax.mjs && node test/diag-log.mjs && node test/check-rings.mjs && node test/release-workflow.mjs && node test/sticker-import-gif.mjs && node test/sticker-real-gif.mjs && node test/sticker-upload-binary.mjs && node test/sticker-vision-tags.mjs && node test/sticker-manual-tags.mjs && node test/sticker-auto-name.mjs && node test/self-update.mjs && node test/group-list.mjs && node test/douyin-inbox-noise.mjs && node test/douyin-inbox-diag.mjs && node test/douyin-inbox-stuck.mjs && node test/reply-window.mjs && node test/douyin-sticker-heuristic.mjs && node test/douyin-image-boundary.mjs && node test/media-image-boundary.mjs && node test/douyin-comment-identity-cid.mjs && node test/qq-mention-only-echo.mjs && node test/bili-panel-pagination.mjs && node test/bili-allowlist.mjs && node test/douyin-master-uid-mismatch.mjs && node test/check-test-chain.mjs && node test/check-route-guard.mjs && node test/check-client-imports.mjs && node test/check-secrets.mjs" } } diff --git a/test/issue-78-diagnostic.mjs b/test/issue-78-diagnostic.mjs index b8b812a..5a39338 100644 --- a/test/issue-78-diagnostic.mjs +++ b/test/issue-78-diagnostic.mjs @@ -14,10 +14,16 @@ assert.equal(recallStatus({kind:'dsh',recallAt:10,memories:['一条']}).badge,' assert.equal(recallStatus({kind:'sent',recallAt:10,speakerUnknown:true}).badge,'认不出是谁'); const notes=[],entries=[]; const gw=Object.assign(Object.create(ChatGateway.prototype),{bound:new Map([['s',{channel_id:'private:1'}]]),turns:new Map(),waiters:new Map(),interjectTurns:new Set(),douyin:null,soul:{recallInfo:()=>({at:10,memories:['一条']})},note:(...a)=>notes.push(a),diag:{add:(...a)=>entries.push(a)},log:()=>{}}); -gw.onSessionEvent({id:'s'},{type:'user/message',data:{message:{source:{kind:'user'}}}}); +gw.onSessionEvent({id:'s'},{type:'user/message',data:{message:{source:{kind:'user'},content:'你的身体是桌宠吗'}}}); gw.onSessionEvent({id:'s'},{type:'assistant/message',data:{message:{content:[{type:'text',text:'好'}]}}}); gw.onSessionEvent({id:'s'},{type:'turn/end',data:{reason:{kind:'completed'}}}); assert(notes.some(([k])=>k==='dsh'));assert(!entries.some(([k])=>k.startsWith('turn-end-failed')),'正常桌面聊天不该记失败'); +// #78:动态里原来只有她的发言,主人会以为自己的话丢了。主人这一轮说的要带上。 +{ + const dshNote=notes.find(([k])=>k==='dsh'); + assert.ok(dshNote,'要有一条 dsh 动态'); + assert.match(dshNote[1].who??'',/主人:你的身体是桌宠吗/,'动态里要能看到主人这一轮说了什么'); +} const noteGw=Object.assign(Object.create(ChatGateway.prototype),{decisions:[],titleOf:()=>'',getConfig:()=>({})}); noteGw.note('reply',{text:'a'});assert.equal(noteGw.decisions[0].recallChecked,undefined); noteGw.note('sent',{recallAt:0});assert.equal(noteGw.decisions[0].recallChecked,true); diff --git a/test/share-fallback.mjs b/test/share-fallback.mjs new file mode 100644 index 0000000..b25f2a0 --- /dev/null +++ b/test/share-fallback.mjs @@ -0,0 +1,280 @@ +// 熟人传话之外的「刷到就分享」兜底(#133): +// 模型不标 [分享] 时,最近 N 天没分享过就主动挑一条排上。 +// +// 为什么要有:分享原本只靠模型在每条视频末尾标 [分享],而提示词里明说 +// 「大多数视频不用」⇒ 真机实测她几乎不标 ⇒ 分享待办长期为 0, +// 主人看到的就是「她刷了一堆视频,但从不开腔分享」(#133 的截图就是这个)。 +import assert from 'node:assert/strict'; +import { DatabaseSync } from 'node:sqlite'; +import { afterRound } from '../lib/browse.js'; + +const ok = (msg) => console.log(' ✓ ' + msg); + +// ── afterRound 的兜底行为 ── +{ + const notes = []; + const shared = []; + const self = { + note: (k, x) => notes.push([k, x]), + share: (x) => { shared.push(x); return { ok: true }; }, + shareFallback: (x) => { self._fb = x; return { ok: true }; } + }; + const watched = [ + { share: false, skipped: false, impression: '讲得挺清楚', title: 'A', owner: '甲', url: 'https://x/a' }, + { share: false, skipped: true, impression: '', title: 'B', owner: '乙', url: 'https://x/b' } + ]; + const pick = (w) => ({ title: w.title, owner: w.owner }); + afterRound(self, 'B站', watched, pick); + + assert.equal(shared.length, 0, '模型没标分享时不该走正常的 share 回调'); + assert.ok(self._fb, '应该调 shareFallback'); + assert.equal(self._fb.platform, 'B站'); + assert.equal(self._fb.candidates.length, 2, '兜底要把候选都交给自走层挑'); + assert.ok(notes.some(([k]) => k === 'share'), '排上了要记一条 share 动态'); + ok('模型没标 [分享] 时走兜底回调'); +} + +// ── 模型标了分享时,兜底不该被调用(别重复排两条)── +{ + let fbCalled = false; + const shared = []; + const self = { + note: () => {}, + share: (x) => { shared.push(x); return { ok: true }; }, + shareFallback: () => { fbCalled = true; return { ok: true }; } + }; + const watched = [{ share: true, skipped: false, impression: '有意思', title: 'A', owner: '甲', url: 'https://x/a' }]; + afterRound(self, 'B站', watched, (w) => ({ title: w.title, owner: w.owner })); + assert.equal(shared.length, 1, '模型标了就正常走 share'); + assert.equal(fbCalled, false, '模型标了就不该再兜底(否则一条视频排两次)'); + ok('模型标了 [分享] 时不重复兜底'); +} + +// ── 没有 shareFallback 回调时不能炸(旧调用方兼容)── +{ + const self = { note: () => {}, share: () => ({ ok: true }) }; + assert.doesNotThrow(() => { + afterRound(self, 'B站', [{ share: false, skipped: false, impression: 'x', title: 'A', owner: '甲', url: 'u' }], (w) => ({ title: w.title })); + }, '没有 shareFallback 回调时不能抛'); + ok('没有兜底回调时不抛异常'); +} + +// ── queueShareFallback 的门槛(用 life 的真实实现)── +{ + const { LifeEngine } = await import('../lib/life.js'); + const db = new DatabaseSync(':memory:'); + db.exec(`CREATE TABLE pending (id INTEGER PRIMARY KEY AUTOINCREMENT, character_id TEXT, owner_id TEXT, channel TEXT, channel_id TEXT, due_at INTEGER, reason TEXT, status TEXT, created_at INTEGER, origin TEXT, surfaced_at INTEGER); + CREATE TABLE kv (key TEXT PRIMARY KEY, value TEXT NOT NULL); + CREATE TABLE day (character_id TEXT, date TEXT, proactive_count INTEGER, last_proactive_at INTEGER, PRIMARY KEY (character_id, date));`); + // masterQqUin 要给:life 的 masterChannel() 从 config 推主人私聊通道(不是构造参数) + let cfg = { masterQqUin: '10001', proactive: { enabled: true, shareMaxPerDay: 2, shareFallbackDays: 2, targets: { masterCanonicalId: 'user:master' } } }; + let now = 1_000_000_000; + const life = new LifeEngine({ + db, + clock: { now: () => now, getRoleDateParts: () => ({ dateStr: '2026-11-17' }) }, + getConfig: () => cfg, + log: () => {}, + note: () => {}, + worker: { enqueueRealtime: () => {} }, + callLlm: async () => null, + armPendingAlarm: () => {} + }); + const candidates = [{ title: '高中数学', owner: '甲', url: 'https://bili/x1', impression: '讲得挺清楚', skipped: false }]; + + // (1) 从来没分享过 → 排上了 + { + const r = life.queueShareFallback({ platform: 'B站', candidates }); + assert.equal(r.ok, true, `应该排上,实际:${r.error}`); + const rows = db.prepare("SELECT * FROM pending WHERE origin='share'").all(); + assert.equal(rows.length, 1, '应该排了一条分享待办'); + assert.ok(String(rows[0].reason).includes('高中数学'), '待办里要带上视频标题'); + ok('从没分享过 → 主动挑一条排上'); + } + + // (2) 刚**送达**过 → 不排(lastAt 记在送达时,不是入队时) + { + const pid = Number(db.prepare("SELECT id FROM pending WHERE origin='share' ORDER BY id DESC LIMIT 1").get().id); + db.prepare("UPDATE pending SET status='done' WHERE id = ?").run(pid); + life.recordShareSent(pid, now); + const before = db.prepare("SELECT COUNT(*) c FROM pending WHERE origin='share'").get().c; + const r = life.queueShareFallback({ platform: 'B站', candidates }); + assert.equal(r.ok, false, '刚送达过不该再排'); + assert.match(r.error, /最近 2 天分享过了/); + assert.equal(db.prepare("SELECT COUNT(*) c FROM pending WHERE origin='share'").get().c, before, '没排新的'); + ok('刚送达过 → 不重复排'); + } + + // (3) 过了门槛 → 又可以排 + { + db.prepare("UPDATE pending SET status='done' WHERE origin='share'").run(); + now += 3 * 24 * 3600_000; // 3 天后 + const r = life.queueShareFallback({ platform: 'B站', candidates }); + assert.equal(r.ok, true, `过了门槛应该能排,实际:${r.error}`); + ok('过了「几天没分享」的门槛 → 又可以排'); + } + + // (4) 门槛关着(0)→ 永远不主动挑 + { + db.prepare("UPDATE pending SET status='done' WHERE origin='share'").run(); + cfg = { ...cfg, proactive: { ...cfg.proactive, shareFallbackDays: 0 } }; + const before = db.prepare("SELECT COUNT(*) c FROM pending WHERE origin='share'").get().c; + const r = life.queueShareFallback({ platform: 'B站', candidates }); + assert.equal(r.ok, false, '门槛关着就不该排'); + assert.match(r.error, /兜底关着/); + assert.equal(db.prepare("SELECT COUNT(*) c FROM pending WHERE origin='share'").get().c, before); + ok('门槛设为 0 → 不主动挑'); + } + + // (5) 候选里没有「有感受的」→ 不排一条没内容的链接 + { + db.prepare("UPDATE pending SET status='done' WHERE origin='share'").run(); + cfg = { ...cfg, proactive: { ...cfg.proactive, shareFallbackDays: 2 } }; + now += 5 * 24 * 3600_000; + const before = db.prepare("SELECT COUNT(*) c FROM pending WHERE origin='share'").get().c; + const r = life.queueShareFallback({ platform: 'B站', candidates: [{ title: 'X', url: 'u', impression: '', skipped: false }] }); + assert.equal(r.ok, false, '没感受的不该排'); + assert.match(r.error, /没有值得分享的/); + assert.equal(db.prepare("SELECT COUNT(*) c FROM pending WHERE origin='share'").get().c, before); + ok('没有「有感受的」候选 → 不排'); + } + + // (6) 划走的不挑 + { + db.prepare("UPDATE pending SET status='done' WHERE origin='share'").run(); + now += 5 * 24 * 3600_000; + const r = life.queueShareFallback({ platform: 'B站', candidates: [{ title: 'X', url: 'u', impression: '还行', skipped: true }] }); + assert.equal(r.ok, false, '划走的视频不该被挑中分享'); + ok('划走的不挑'); + } +} + +// ── 用**真实的 BiliBrowser 实例**跑一遍(#133 审查 P0-1 的教训)── +// 上一版测试全是手搓的对象字面量,所以「构造函数没接 shareFallback ⇒ 兜底是死代码」 +// 这类洞一个都测不出来。判据:真实实例上 shareFallback 要是函数,且 afterRound 真能触发它。 +{ + const { BiliBrowser } = await import('../lib/browse.js'); + let called = 0; + const browser = new BiliBrowser({ + db: { prepare: () => ({ all: () => [] }) }, + clock: { now: () => Date.now() }, + client: {}, + getConfig: () => ({ enabled: true, browse: { share: true } }), + callLlm: async () => null, + persona: () => ({ name: '肥鱼', brief: '' }), + share: () => ({ ok: true }), + shareFallback: () => { called++; return { ok: true, chosen: { title: 'X' } }; } + }); + assert.equal(typeof browser.shareFallback, 'function', '真实浏览器实例必须接住 shareFallback(否则兜底是死代码)'); + assert.equal(typeof browser.share, 'function', 'share 也要在'); + + // 真跑一轮:模型没标分享 → 兜底被调用 + called = 0; + afterRound(browser, 'B站', [{ share: false, skipped: false, impression: '有意思', title: 'A', owner: '甲', url: 'u' }], (w) => ({ title: w.title, owner: w.owner })); + assert.equal(called, 1, '真实实例上模型没标分享要触发兜底'); + + // 平台开关关着 → 兜底不许发(用户的显式关闭不能被反转) + called = 0; + browser.getConfig = () => ({ enabled: true, browse: { share: false } }); + afterRound(browser, 'B站', [{ share: false, skipped: false, impression: '有意思', title: 'A', owner: '甲', url: 'u' }], (w) => ({ title: w.title, owner: w.owner })); + assert.equal(called, 0, '平台开关关了就不该兜底(用户显式关掉的开关不能被反转)'); + ok('真实 BiliBrowser:兜底接得住、平台开关关着就不发'); +} + +// ── lastAt 是「送达时」才记的(#133 审查 P1-5)── +// 排了但没发出去(failed / expired)不该把兜底锁死两天。 +{ + const { LifeEngine } = await import('../lib/life.js'); + const db = new DatabaseSync(':memory:'); + db.exec(`CREATE TABLE pending (id INTEGER PRIMARY KEY AUTOINCREMENT, character_id TEXT, owner_id TEXT, channel TEXT, channel_id TEXT, due_at INTEGER, reason TEXT, status TEXT, created_at INTEGER, origin TEXT, surfaced_at INTEGER, attempts INTEGER DEFAULT 0); + CREATE TABLE kv (key TEXT PRIMARY KEY, value TEXT NOT NULL); + CREATE TABLE day (character_id TEXT, date TEXT, proactive_count INTEGER, last_proactive_at INTEGER, PRIMARY KEY (character_id, date));`); + const cfg = { masterQqUin: '10001', proactive: { enabled: true, shareMaxPerDay: 5, shareFallbackDays: 2, targets: { masterCanonicalId: 'user:master' } } }; + let now = 1_000_000_000; + const life = new LifeEngine({ + db, + clock: { now: () => now, getRoleDateParts: () => ({ dateStr: '2026-11-17' }) }, + getConfig: () => cfg, log: () => {}, note: () => {}, + worker: { enqueueRealtime: () => {} }, callLlm: async () => null, + armPendingAlarm: () => {} + }); + const candidates = [{ title: 'A', owner: '甲', url: 'u', impression: '有意思', skipped: false }]; + + // 排上了,但**没发出去**(模拟投递失败)⇒ 兜底不该被锁死 + const r1 = life.queueShareFallback({ platform: 'B站', candidates }); + assert.equal(r1.ok, true, '应该排上'); + db.prepare("UPDATE pending SET status='failed' WHERE origin='share'").run(); + const r2 = life.queueShareFallback({ platform: 'B站', candidates }); + assert.equal(r2.ok, true, `排了但没发出去不该把兜底锁死(实际:${r2.error})`); + ok('lastAt 记在送达时 —— 排了没发出去不会锁死兜底'); +} + +// ── lastAt 分平台(#133 审查 P1-4)── +// 抖音分享一次不该把 B站的兜底也压掉(主人报的就是 B站)。 +{ + const { LifeEngine } = await import('../lib/life.js'); + const db = new DatabaseSync(':memory:'); + db.exec(`CREATE TABLE pending (id INTEGER PRIMARY KEY AUTOINCREMENT, character_id TEXT, owner_id TEXT, channel TEXT, channel_id TEXT, due_at INTEGER, reason TEXT, status TEXT, created_at INTEGER, origin TEXT, surfaced_at INTEGER, attempts INTEGER DEFAULT 0); + CREATE TABLE kv (key TEXT PRIMARY KEY, value TEXT NOT NULL); + CREATE TABLE day (character_id TEXT, date TEXT, proactive_count INTEGER, last_proactive_at INTEGER, PRIMARY KEY (character_id, date));`); + const cfg = { masterQqUin: '10001', proactive: { enabled: true, shareMaxPerDay: 5, shareFallbackDays: 2, targets: { masterCanonicalId: 'user:master' } } }; + let now = 1_000_000_000; + const life = new LifeEngine({ + db, + clock: { now: () => now, getRoleDateParts: () => ({ dateStr: '2026-11-17' }) }, + getConfig: () => cfg, log: () => {}, note: () => {}, + worker: { enqueueRealtime: () => {} }, callLlm: async () => null, + armPendingAlarm: () => {} + }); + const candidates = [{ title: 'A', owner: '甲', url: 'u', impression: '有意思', skipped: false }]; + + // 抖音分享一次(并标记为已送达) + const r1 = life.queueShareFallback({ platform: '抖音', candidates }); + assert.equal(r1.ok, true, '抖音应该排上'); + const pid = Number(r1.id); + db.prepare("UPDATE pending SET status='done' WHERE id = ?").run(pid); + life.recordShareSent(pid, now); + // B站的兜底不该被抖音这次分享压掉 + db.prepare("UPDATE pending SET status='done' WHERE origin='share'").run(); + const r2 = life.queueShareFallback({ platform: 'B站', candidates }); + assert.equal(r2.ok, true, `抖音分享过不该压掉 B站的兜底(实际:${r2.error})`); + ok('lastAt 分平台 —— 抖音分享过,B站照样能兜底'); +} + +// ── 过期判定:跨角色日的分享要作废(#133 审查 P1-6)── +// TTL 放宽到 12 小时后,窗口必然跨午夜;待办正文写的是「你刚刷到」, +// 隔天早上发出去这话就不成立了。 +{ + const { LifeEngine } = await import('../lib/life.js'); + const db = new DatabaseSync(':memory:'); + db.exec(`CREATE TABLE pending (id INTEGER PRIMARY KEY AUTOINCREMENT, character_id TEXT, owner_id TEXT, channel TEXT, channel_id TEXT, due_at INTEGER, reason TEXT, status TEXT, created_at INTEGER, origin TEXT, surfaced_at INTEGER, attempts INTEGER DEFAULT 0); + CREATE TABLE kv (key TEXT PRIMARY KEY, value TEXT NOT NULL); + CREATE TABLE day (character_id TEXT, date TEXT, proactive_count INTEGER, last_proactive_at INTEGER, PRIMARY KEY (character_id, date));`); + // now 要和 dateStr 对得上(角色日 2026-11-17 的下午),否则 roleDayStart 算出来是未来 + const dayStart = Date.UTC(2026, 10, 17) - 8 * 3600_000; + const now = dayStart + 14 * 3600_000; // 当天 14:00(UTC+8) + const life = new LifeEngine({ + db, + clock: { now: () => now, getRoleDateParts: () => ({ dateStr: '2026-11-17' }) }, + getConfig: () => ({ masterQqUin: '10001', proactive: { enabled: true, shareMaxPerDay: 5, shareFallbackDays: 2 } }), + log: () => {}, note: () => {}, worker: { enqueueRealtime: () => {} }, callLlm: async () => null, + armPendingAlarm: () => {} + }); + // 当天排的 → 不过期 + assert.equal(life.shareExpired({ due_at: now, created_at: now }, now), false, '当天排的分享不该作废'); + // ⚠️ 「跨角色日」判定只在**距入队不到 12 小时**时才起作用 —— + // 超过 12 小时的话 TTL 条件先成立,撤掉跨日判定照样作废(测不出这一条)。 + // 所以判定时刻要贴着跨日点:昨天 23:00 入队,今天 01:00 判定。 + { + const justAfterMidnight = dayStart + 3600_000; // 今天 01:00 + const lateYesterday = dayStart - 3600_000; // 昨天 23:00 + assert.ok(justAfterMidnight - lateYesterday < 12 * 3600_000, + '这条用例的前提:距入队不到 12 小时(否则 TTL 条件先成立,测不出跨日判定)'); + assert.equal(life.shareExpired({ due_at: lateYesterday, created_at: lateYesterday }, justAfterMidnight), true, + '刚跨角色日就该作废(隔天发就说不了「你刚刷到」)'); + } + // 超过 TTL 的(同一天但排很久了)→ 作废 + assert.equal(life.shareExpired({ due_at: now - 13 * 3600_000, created_at: now - 13 * 3600_000 }, now), true, '超过 12 小时的要作废'); + ok('过期判定:超 TTL 或跨角色日都作废'); +} + +console.log('share-fallback: all assertions passed'); diff --git a/test/smoke-v05.mjs b/test/smoke-v05.mjs index f50ee4a..09f53bf 100644 --- a/test/smoke-v05.mjs +++ b/test/smoke-v05.mjs @@ -327,10 +327,16 @@ export async function run(t) { assert.equal(slife.queueShare({ ...share, title: '第二条' }).ok, true); sdb.prepare("UPDATE pending SET status = 'done' WHERE origin = 'share'").run(); assert.match(slife.queueShare({ ...share, title: '第三条' }).error, /今天已经分享过 2 条了/); - // 过了 4 个虚拟小时还没发出去的分享作废 - sdb.prepare("UPDATE pending SET status = 'pending', due_at = ? WHERE reason LIKE '%第二条%'").run(t - 5 * 3600_000); + // 过了 12 个虚拟小时还没发出去的分享作废(#133:原来 4 小时, + // 「下午刷到的晚上想发」就已经过期了 —— 真机上 2026-11-12 排的那条就是这么没发出去的) + sdb.prepare("UPDATE pending SET status = 'pending', due_at = ? WHERE reason LIKE '%第二条%'").run(t - 13 * 3600_000); t += 61 * 60_000; await slife.tick(); await sleep(5); assert.equal(sdb.prepare("SELECT status FROM pending WHERE reason LIKE '%第二条%'").get().status, 'expired'); + // ⚠️ 但 12 小时之内要还能发(别把「下午刷的晚上发」也作废掉) + sdb.prepare("UPDATE pending SET status = 'pending', due_at = ? WHERE reason LIKE '%第二条%'").run(t - 6 * 3600_000); + t += 61 * 60_000; await slife.tick(); await sleep(5); + assert.notEqual(sdb.prepare("SELECT status FROM pending WHERE reason LIKE '%第二条%'").get().status, 'expired', + '6 小时前排的分享不该作废(下午刷的晚上发是正常场景)'); cfg.proactive.enabled = false; assert.match(slife.queueShare(share).error, /主动开口关着/); sdb.close(); diff --git a/test/smoke.mjs b/test/smoke.mjs index bd53abb..f0b3da8 100644 --- a/test/smoke.mjs +++ b/test/smoke.mjs @@ -1,5 +1,5 @@ // 本地冒烟测试:模拟 DSH 宿主 ctx,验证会话隔离、零滞后召回、配置合并、导入、待办队列、向量索引。 -import { writeFileSync, mkdirSync } from 'node:fs'; +import { writeFileSync, mkdirSync, readFileSync } from 'node:fs'; import { join } from 'node:path'; import http from 'node:http'; import assert from 'node:assert/strict'; @@ -681,7 +681,16 @@ assert.ok(cs.json.sessions.chats.every((c) => c.workspacePath === join(home, 'ot p = await call('POST', '/life/proactive-config', { dailyMaxCount: 10, activeHours: [8, 24], targets: { masterPrivateChannelId: '', selfGroupChannelIds: [] } }); assert.equal(p.json.ok, true); assert.equal((await call('GET', '/life/state')).json.today.dailyMaxCount, 10); -ok('路由:连接状态、只能选已登记的工作区、一键迁移、每日上限不再被压成 2'); +// #133:分享相关字段**缺失时要沿用配置里的现值**,不能拿默认值覆盖 —— +// 否则主人手工关掉兜底(0)后,动一下「主动开口」就被悄悄改回 2。 +p = await call('POST', '/life/proactive-config', { dailyMaxCount: 10, activeHours: [8, 24], shareFallbackDays: 0, shareMaxPerDay: 4, targets: { masterPrivateChannelId: '', selfGroupChannelIds: [] } }); +assert.equal(p.json.ok, true); +const cfgFile = () => JSON.parse(readFileSync(join(home, 'fish-soul-config.json'), 'utf8')); +assert.equal(cfgFile().proactive.shareFallbackDays, 0, '显式设 0 要存进去(0 = 关掉兜底)'); +p = await call('POST', '/life/proactive-config', { dailyMaxCount: 10, activeHours: [8, 24], targets: { masterPrivateChannelId: '', selfGroupChannelIds: [] } }); +assert.equal(cfgFile().proactive.shareFallbackDays, 0, '请求没带这个字段时不能把用户设的 0 冲掉'); +assert.equal(cfgFile().proactive.shareMaxPerDay, 4, '请求没带这个字段时不能把用户设的值冲掉'); +ok('路由:连接状态、只能选已登记的工作区、一键迁移、每日上限不再被压成 2;分享字段缺失时沿用现值'); // 19 主动开口:恢复已有会话 → 递触发消息 → 轮次结束发出去才算成功 const { ChatGateway } = await import('../lib/gateway.js'); @@ -803,7 +812,7 @@ ok('主动配额:自发 ≤ 上限且间隔 ≥ 60 分钟;用户交代的提 const bl = await import('../lib/channels/bilibili.js'); const { encodeQr, qrSvg } = await import('../lib/channels/qrcode.js'); const { findVideoRefs, BiliBrowser } = await import('../lib/browse.js'); -const { statSync, readFileSync, existsSync } = await import('node:fs'); +const { statSync, existsSync } = await import('node:fs'); // 21 纯函数:WBI 签名(文档向量)、大整数、私信归一化、视频引用、二维码 assert.equal(bl.mixinKey('7cd084941338484aae1ad9425b84077c', '4932caff0ff746eab6f01bf08b70ac45'), MIXIN);