From f4adf0b52679d30cb294c79a698b5cae7d6becab Mon Sep 17 00:00:00 2001 From: AskaEth Date: Mon, 5 Oct 2026 19:47:54 +0800 Subject: [PATCH] =?UTF-8?q?feat(notify):=20IM=20=E8=B7=AF=E7=94=B1?= =?UTF-8?q?=E7=9A=84=E4=B8=BB=E5=8A=A8=E6=B6=88=E6=81=AF=E4=B9=9F=E5=9C=A8?= =?UTF-8?q?=E9=9D=9E=E5=89=8D=E5=8F=B0=E8=A1=A5=E6=B5=8F=E8=A7=88=E5=99=A8?= =?UTF-8?q?=E9=80=9A=E7=9F=A5=EF=BC=88=E5=A5=91=E7=BA=A6=20v0.74=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 主人裁定 C 的必然推论:她该不该提醒我,与后端走了哪条路由无关。P0 如实报回的缺口 = 通知只挂在 proactive_message 帧上,而 auto 提示在有已连接 IM 渠道时优先走 IM ⇒ 最常发生的路径恰恰不弹。 判据(先查现状、不猜):行字段**区分不出**主动推送与普通回复(已用真库证据排除 platform/adapterId/turnId 反推)⇒ 新增**结构化的正向声明**:帧顶 data.proactive === true,只由主动推送那条通道打(gateway.BroadcastProactivePersisted);普通路径永远传 false。 - 后端:channelbridge 抽出唯一写入口径 persistMain + 新增 proactive_notify 接缝;gateway 抽出 broadcastPersisted(msg, proactive) 两入口共用 - 前端:handlers/proactive-notice.ts 两条帧路共用同一套提醒运行时(有界去重 + 降级说明 + DOM/Notification 取值);message.ts 读到判据才走提醒 - 对照断言(必须有):普通 IM 回复/主人提问/显式 proactive:false ⇒ **0 通知、3 气泡**(不误伤) - 变异实测:去掉非主动保护 / 跨两路去重失效 / 前台也弹 / IM 不发判据帧 / 普通广播带判据 ⇒ 5 条全部打红 - 契约 v0.74(纯增量:message_persisted 新增可选 proactive:true) - 边界(如实):判据**不落库**(翻历史不弹提醒,也不得从行字段反推);落库失败时不发判据帧(无权威 id 的帧前端整帧丢弃) --- Docs/api-client.md | 35 +++- cmd/cyrene/wire_frontend.go | 5 + frontend/web/src/lib/ws/handlers/message.ts | 10 + .../src/lib/ws/handlers/proactive-notice.ts | 123 ++++++++++++ .../web/src/lib/ws/handlers/proactive.test.ts | 185 ++++++++++++++++++ frontend/web/src/lib/ws/handlers/proactive.ts | 117 ++--------- .../services/channelbridge/channelbridge.go | 9 +- internal/services/channelbridge/persist.go | 27 ++- internal/services/channelbridge/proactive.go | 41 +++- .../channelbridge/proactive_notify.go | 40 ++++ internal/services/gateway/broadcast.go | 18 +- internal/services/gateway/proactive.go | 18 ++ .../gateway/proactive_im_notify_test.go | 146 ++++++++++++++ 13 files changed, 652 insertions(+), 122 deletions(-) create mode 100644 frontend/web/src/lib/ws/handlers/proactive-notice.ts create mode 100644 internal/services/channelbridge/proactive_notify.go create mode 100644 internal/services/gateway/proactive_im_notify_test.go diff --git a/Docs/api-client.md b/Docs/api-client.md index 4f8bc0e..31d09af 100644 --- a/Docs/api-client.md +++ b/Docs/api-client.md @@ -1,6 +1,6 @@ # Cyrene v2 客户端 API 契约 -> **契约版本:`v0.73`**(上一版 `v0.72`,其条目见 §6;`v0.71` 及更早见本文件 §6,`v0.67` 及更早的基线已归档、只读:`Docs/archive/api-client.v0.65.md`)。 +> **契约版本:`v0.74`**(上一版 `v0.73`,其条目见 §6;`v0.72` / `v0.71` 及更早见本文件 §6,`v0.67` 及更早的基线已归档、只读:`Docs/archive/api-client.v0.65.md`)。 > **读者**:Web 前端 / 移动端原生客户端(含 Android)/ IM 桥接等**跨平台客户端开发者**。 > **唯一真源 = 当前代码**(`internal/services/gateway/*` 等)。本文档由代码逐条核对得出;与代码不符时**以代码为准**,并回改本文档。 > **旧的超详细版已归档、只读**:`Docs/archive/api-client.v0.65.md`(412 KB,含 v0.28→v0.65 全部历史条目)与 `Docs/archive/api-reference.v0.65.md`(170 KB,后端全量字段级文档)。归档的原因是**结构性臃肿 + 历史条目并列 + 长期漂移**;本文档**不复制**那段历史,需要考古时去归档。 @@ -16,6 +16,8 @@ > **v0.73 是链路图本地落盘版(已实现,纯增量)**:链路图从「只活在进程内存」变成**每轮一行落进本地库**(新表 `flow_graphs`,迁移 `0022`),`GET /api/v1/admin/flow/graph` 在 v0.71 之上**增量**:新增可选查询参数 `turnId`(省略 = 最近一轮;**先查内存 `LastGraph`,miss 才回退落盘**)、响应新增 `turnId` / `source` / `turns[]` 三键(**多轮历史回放**,`design/19 §4` 的 P3)。修的是主人 2026-10-05 追加要求的那句「链路流程应该有本地数据,不然每次重载之后页面就没数据了」—— v0.71 只覆盖「后端进程活着时的最近一轮」,后端一重启、或翻更早的轮次,仍然什么都查不到。**无破坏性变更**(旧键 `sessionId`/`graph` 形状语义不变,`graph_update` 帧、角色门、发布会话范围一字未改;老客户端不读新键即行为与 v0.71 相同)。落盘范围**只有**发布会话白名单内的会话(`flowSessionAllowed`),隔离渠道会话绝不入库。详见 **§2.2 B13 / §4.11**。 +> **v0.74 是 IM 路由主动消息的提醒版(已实现,纯增量)**:`message_persisted` 的 `data` 新增**可选**结构化判据 `proactive:true` —— IM 路由(`im_bridge`)的主动推送在落库之后**追加**一条带该键的同类帧,客户端据此在**非前台**补一发浏览器通知(此前通知只挂在 `proactive_message` 上,而 `auto` 提示在主人有已连接 IM 渠道时**优先走 IM** ⇒ 实际最可能发生的路径恰恰不弹)。判据是**结构化字段**(不是正文/提示词):普通消息(Web 回合 / IM 回复 / IM 镜像)的帧**永不**带该键 ⇒ 不可能被误判成主动消息。同一行仍照旧发一条**不带**该键的普通镜像帧(v0.72 起的行为逐字不变,两帧同 id ⇒ 客户端按 id 去重后仍是一个气泡、仍只提醒一次)。详见 **§3.4.4 后的「`message_persisted` 的 `proactive` 判据」**。 + --- ## 0. 基础约定 @@ -367,12 +369,19 @@ | type | 帧壳 | data | 说明 | |---|---|---|---| -| `message_persisted` | sessionId | `{message:}` | Web 主会话及 `web:*` 子会话的消息落库实时同步。**`thinking` 恒缺席**;**可能**带可选 `turnId`(v0.66,空则键省略) | +| `message_persisted` | sessionId | `{message:,proactive?:true}` | Web 主会话及 `web:*` 子会话的消息落库实时同步。**`thinking` 恒缺席**;**可能**带可选 `turnId`(v0.66,空则键省略);**可能**带可选结构化判据 `proactive:true`(v0.74,仅 IM 路由的主动推送 —— 见下方说明,普通消息永不带它) | | `channel_persisted` | sessionId | `{message:}` | 隔离渠道会话(`sess-*`)的消息落库,供 IM 日志页。**`thinking` 恒缺席**;**可能**带可选 `turnId`(v0.66) | | `message_edited` | sessionId | ``(**data 直接就是 DTO**) | 编辑单条消息。**`thinking` 恒缺席**;**可能**带可选 `turnId`(v0.66) | | `message_deleted` | sessionId | `{id}` | 删除单条消息 | > **`thinking` 可达性口径(v0.66 口径更正)**:消息 DTO 的 `thinking` 在**全部读取面**(`GET /sessions/{id}/messages`、`GET /admin/channels[/{platform}]/messages`、握手 `history` 回放、`message_persisted` / `channel_persisted` / `message_edited`)**恒为缺席**。原因不是「有意清空」,而是 `history.Message.Thinking` **全仓没有任何写入者**(`loop.Result` 没有该字段、Anthropic 流式收尾直接丢弃思考文本)⇒ 该键在线上**永远不会出现**。 + +> **`message_persisted` 的 `proactive` 判据(v0.74,纯增量)**:帧 `data` 里**可选**的布尔键 `proactive:true` 是「这条是她**主动**说的话」在线上**唯一**的结构化判据,由后端的主动推送通道打上(`gateway.BroadcastProactivePersisted`)。客户端读到它就应走与 `proactive_message` **同一套**提醒逻辑(页面不在前台时补一发浏览器通知、同一条只打扰一次),因此「她该不该提醒我」**与后端走了哪条路由无关**。 +> - **为什么需要它**:`auto` 提示在主人有已连接 IM 渠道时**优先走 IM**,而 IM 路由过去只发普通 `message_persisted` —— 浏览器通知挂在 `proactive_message` 上 ⇒ **实际最可能发生的路径恰恰不弹**。修的是这条边界(主人 2026-10-05 裁定「她说话该不该提醒我,与走哪条路由无关」)。 +> - **判据为什么不会误伤普通消息**:只有主动推送那条通道会调用带判据的广播入口;普通消息(Web 回合 / IM 回复 / IM 镜像)走的仍是原入口,那条路径**永不**往帧顶放该键。客户端只应做 `data.proactive === true` 的**严格相等**判断 —— 缺失、`false`、非布尔值都按「不是主动消息」处理。 +> - **去重键 = `message.id`**:主动推送镜像回主会话时,**同一条**消息会先发一条**不带**判据的普通帧(v0.72 起的行为,逐字不变,任何客户端都能渲染),随后追加一条带判据的帧。两帧同 `message.id` ⇒ 合并成一个气泡(消息 store 按 id 去重),提醒也只发一次(提醒去重表按同一个 id 记)。**`proactive_message` 与带判据的 `message_persisted` 同时到达时同样只提醒一次**。 +> - **落库失败时不发判据帧**:没有落库行就没有权威 `id`,而 `message_persisted` 的载荷要求非空 `id`(缺了客户端会整帧丢弃)⇒ 那种情况下只记 WARN、不弹通知(绝不发一条会被丢掉的帧假装提醒过)。 +> - **⚠️ 判据不落库**:它只活在**实时帧**上(写入那一刻才知道这条是不是主动推送),库里的行没有对应列(不改 schema)。因此刷新后从 `GET /sessions/web/messages` / 握手 `history` 回放读到的那一行**不带**该信息 —— 这是预期的:通知只对「实时到达」有意义,翻历史不该弹提醒。 > **思维链的唯一出口是实时帧**:§3.4.2 的 `thinking.start` / `thinking.delta` / `thinking.end`(owner/admin 档)。客户端**不要**为「从历史里读回思维链」写任何代码。 > ⚠️ 本行**更正**本文档 v0.65 及更早的写法(旧版称「历史思维链只有 `GET /sessions/{id}/messages`(owner/admin)返回」)—— **那是文档写错了**,与实现不符。见 §7.3。 > 另注:管理面板人格清单里的 `thinking` 是**人格旋钮**(`GET /admin/personas` 的 `thinking` 块),与消息 DTO 的 `thinking` 不是同一个字段。 @@ -405,7 +414,7 @@ > - 落库行:`sessionId="web"`、`role="assistant"`、`content` = 帧里的 `content`(后端已净化的同一份文本,系统元数据绝不进正文)、`platform` = 帧里的 `platform`、`mode="chat"`、`turn_id` **留空**(主动推送不属于任何一路回合)。因此 `GET /sessions/web/messages`、握手 `history` 回放、`message_persisted` 都能读到它。 > - **`id`/`createdAt` 随帧下发**,客户端应据此把实时气泡对齐到历史行(按 id 去重;刷新后由历史行接续,不是第二个气泡)。**落库失败时这两个键缺席**,但同时:帧照发(实时气泡不丢),后端记 WARN 并返回错误 ⇒ 后台思考记录里的 `route/detail` 会写明**未落库**(不会再说成「已推送」)。 > - **无在线 owner/admin 连接时也会落库**:推送器如实报告「没有活跃客户端」(`pushed=false`),这条话仍作为一条真实记录留在主会话里,下次打开就能看到。 -> - **IM 路由不需要客户端做任何事**:`im_bridge` 路由(IM 桥)本就把消息镜像回主会话并广播 `message_persisted`(逐条一条,**不双份**)。两条路由在一次推送里**互斥**(`web` 提示只走活跃客户端,其余先 IM、IM 投递失败才降级活跃客户端),因此同一条主动消息在主会话里**恰好一条**。 +> - **IM 路由(v0.74 起也提醒)**:`im_bridge` 路由本就把消息镜像回主会话并广播 `message_persisted`(逐条一条,**不双份**),v0.74 起在落库之后**追加**一条帧顶带 `proactive:true` 的同类帧 ⇒ 客户端走与 `proactive_message` 同一套提醒逻辑(见 §3.4.4 后的「`message_persisted` 的 `proactive` 判据」)。两条路由在一次推送里**互斥**(`web` 提示只走活跃客户端,其余先 IM、IM 投递失败才降级活跃客户端),因此同一条主动消息在主会话里**恰好一条**。 #### 3.4.6 定向帧(不经 `hub.broadcast`,只到指定连接) @@ -828,7 +837,21 @@ > 只保留最近若干版(**v0.60 起**);更早的全部历史见归档 `Docs/archive/api-client.v0.65.md` §5(v0.28 → v0.59)。 > 每版一句话 + 三档标注。**三档定义见 [§0.4](#04-三档标注惯例)。** -### v0.73(当前契约版本) +### v0.74(当前契约版本) + +**IM 路由的主动消息也补浏览器通知 —— `message_persisted` 新增可选结构化判据 `proactive:true`**(依据主人 2026-10-05 裁定 C 的必然推论「她说话该不该提醒我,与走哪条路由无关」;对齐 `design/12 §3` 的主动推送与 `design/16 §4.4` 的镜像口径)。 + +- **纯增量**: + ① **`message_persisted` 的 `data` 新增可选键 `proactive:true`**:IM 路由(`im_bridge`)的主动推送在落库之后**追加**一条带该键的同类帧 —— 帧类型、角色门、`message` DTO 形状**一字未改**,只多一个布尔键(**§3.4.4**)。 + ② 客户端据此走与 `proactive_message` **同一套**提醒逻辑(非前台补一发通知;去重键同为 `message.id`)。老客户端不读该键即行为与 v0.73 完全相同。 +- **修的是什么(根因)**:`auto` 提示在主人有已连接 IM 渠道时**优先走 IM**,而 IM 路由此前只发普通 `message_persisted` —— 浏览器通知挂在 `proactive_message` 上 ⇒ **实际最可能发生的路径恰恰不弹**。这就是 P0(v0.72)如实报回的边界。 +- **判据是结构化的**:主会话落库行的 `platform`/`adapter_id` **区分不出**主动推送与普通回复(主动推送写的是解析后的真实平台,例如 `weixin-ilink`,与普通回复行同一形状)⇒ 判据放在**落库那一刻的通知通道**上(`gateway.BroadcastProactivePersisted`),随帧顶到达客户端。**绝不**读正文关键词、**绝不**用提示词/模型判断(项目红线:身份与判定靠元数据)。 +- **不误伤**:普通消息(Web 回合 / IM 回复 / IM 镜像)走的仍是原入口 `BroadcastPersisted`,那条路径**永不**放该键 ⇒ 客户端不可能把普通消息误判成主动消息。客户端只应做 `data.proactive === true` 的严格相等判断。 +- **行为变更**:无(普通镜像帧照旧发一条;主会话里仍**恰好一条**行,P0 的「不双份」红线未动)。 +- **破坏性**:无。 +- ⚠️ **诚实边界**:① 判据**不落库**(不改 schema)⇒ 刷新后从历史读回的行不带它(预期:通知只对实时到达有意义)。② **落库失败时不发判据帧**:没有权威 `id` 的 `message_persisted` 会被客户端整帧丢弃,发它等于假装提醒过 —— 那种情况下只记 WARN。③ 「她主动说的话」在三类帧上到达的完整清单见 §3.4.4 与 §3.4.5。 + +### v0.73(上一版) **链路图本地落盘 + 多轮历史回放 —— 图从「只活在进程内存」变成每轮一行落进本地库,`GET /api/v1/admin/flow/graph` 增量支持按 `turnId` 取历史轮**(依据主人 2026-10-05 追加要求「链路流程应该有本地数据,不然每次重载之后页面就没数据了」;对齐 `design/19 §4` 的 **P3**「多轮历史回放」—— v0.71 只做了其中最小一步)。 @@ -1078,6 +1101,8 @@ 19. **(v0.71 登记 · v0.73 更新)图源是**进程内内存**,但**每轮收尾会落盘**(v0.73)**:`loop.FlowPublisher` 的每会话最近一图仍是**内存**(design/19 §1 的实时口径),但 `EndRound` 会把该轮写进 `flow_graphs`(迁移 `0022`)⇒ 后端重启后、该会话还没跑新轮次时,省略 `turnId` 的查询**回退落盘**即可拿到最近一轮(`source:"persisted"`),不再一律 `graph:null`。⚠️ **仍会 `graph:null` 的情形**:该会话本就在**发布会话白名单之外**(隔离渠道会话,从不建图也从不落盘)、或该会话**从未跑过带 span 的轮次**、或该轮已被**保留期 GC 回收**(默认 168h)。**登记既有裁决不改**:`graph_update` 的两路互顶(同会话并行两路时后发的那张图会顶掉先发的)仍**未修**,本版**不碰**它。 20. **(v0.73 登记)落盘只覆盖「保留期内」且只覆盖白名单会话**:`turns[]` 是**已落盘且未被 GC 回收**的轮次摘要,**不是全历史**(`FLOW_GRAPH_RETENTION` 默认 168h,`≤0` = 关闭 GC ⇒ 那时才会无限增长,属显式选择)。落盘范围与实时发布**同一白名单**(`flowSessionAllowed`:`web` / `web:` / `sess-backthink`)—— **群聊 / 陌生人会话永远不会出现在 `turns[]` 里**。此外**正在跑、尚未 `EndRound`** 的那一轮不会在 `turns[]` 中出现(它是内存里的「实时」那一轮,`source:"live"`),这是如实而非缺失。 +21. **(v0.74 登记)`message_persisted` 的 `proactive` 判据只活在实时帧上,不落库**:它是「这条是她主动说的话」在线上**唯一**的结构化判据(帧顶布尔键,由 `gateway.BroadcastProactivePersisted` 打上),**没有对应数据库列**(本片不动 schema)。因此 ① `GET /sessions/{id}/messages`、握手 `history` 回放、`GET /admin/channels/**` 读到的历史行**不带**它(预期:通知只对实时到达有意义);② 客户端**不得**从 `platform` / `adapterId` / `turnId` 等行字段反推「是不是主动消息」—— 主会话里主动推送写的是**解析后的真实平台**(例如 `weixin-ilink`),与普通回复行同一形状,反推必然误伤。**落库失败时不发该帧**(没有权威 `id` 的 `message_persisted` 会被客户端整帧丢弃)。 + --- -*本文件由「以代码为真源」维护(当前 `v0.73`;`v0.72` / `v0.71` / `v0.70` / `v0.69` / `v0.68` 见本文件 §6,`v0.67` 及更早见本文件 §6 与 `Docs/archive/`)。范围:`v0.73` 同步了 `internal/services/gateway/**`、`internal/runtime/loop/flow.go`、`internal/runtime/flowgraph/**`、`internal/db/migrations/0022_flow_graphs.*`、`frontend/web/src/**` 与本文件;`v0.72` 同步了 `internal/services/gateway/**`(`proactive*`)、`internal/services/backthink/**`、`frontend/web/src/**` 与本文件;`v0.71` 同步了 `internal/services/gateway/**`、`internal/runtime/loop/flow.go`、`frontend/web/src/**` 与本文件。* +*本文件由「以代码为真源」维护(当前 `v0.74`;`v0.73` / `v0.72` / `v0.71` / `v0.70` / `v0.69` / `v0.68` 见本文件 §6,`v0.67` 及更早见本文件 §6 与 `Docs/archive/`)。范围:`v0.74` 同步了 `internal/services/gateway/**`(`proactive.go` / `broadcast.go`)、`internal/services/channelbridge/**`(`proactive.go` / `persist.go` / `proactive_notify.go`)、`cmd/cyrene/wire_frontend.go`、`frontend/web/src/lib/ws/handlers/**` 与本文件;`v0.73` 同步了 `internal/services/gateway/**`、`internal/runtime/loop/flow.go`、`internal/runtime/flowgraph/**`、`internal/db/migrations/0022_flow_graphs.*`、`frontend/web/src/**` 与本文件;`v0.72` 同步了 `internal/services/gateway/**`(`proactive*`)、`internal/services/backthink/**`、`frontend/web/src/**` 与本文件;`v0.71` 同步了 `internal/services/gateway/**`、`internal/runtime/loop/flow.go`、`frontend/web/src/**` 与本文件。* diff --git a/cmd/cyrene/wire_frontend.go b/cmd/cyrene/wire_frontend.go index d967831..c6c1edc 100644 --- a/cmd/cyrene/wire_frontend.go +++ b/cmd/cyrene/wire_frontend.go @@ -116,6 +116,11 @@ func (a *app) wireFrontend() error { // `message_persisted` 广播,让 Web 客户端用同一套统一帧来镜像 IM 消息 // (design/16 §4.4)。 a.channelBridge.SetOnPersisted(a.gw.BroadcastPersisted) + // IM 路由的**主动推送**另走一条通知通道(切片 P0b):它落的也是主会话,但帧顶 + // 带结构化判据 `proactive:true`,客户端据此在非前台补一发浏览器通知。此前 IM + // 路由只有上面那条普通帧 ⇒ 走 IM 的主动消息一条都不弹(而 `auto` 提示在主 + // 人有已连接 IM 渠道时优先走 IM,恰恰是最常见的路径)。 + a.channelBridge.SetOnProactivePersisted(a.gw.BroadcastProactivePersisted) // design/16 §4.6 §6:被平台白/黑名单(allow/deny)丢弃的消息会记入网关审计 // 轨迹,这样即使它从未到达循环,这次拒绝也「audit 可查」。 a.channelBridge.SetOnRejected(func(msg adapter.UnifiedMessage, reason string) { diff --git a/frontend/web/src/lib/ws/handlers/message.ts b/frontend/web/src/lib/ws/handlers/message.ts index 585fdd1..3a37867 100644 --- a/frontend/web/src/lib/ws/handlers/message.ts +++ b/frontend/web/src/lib/ws/handlers/message.ts @@ -5,6 +5,8 @@ import { parsePersistedMessage, toRecord, } from "../../wsParse"; +import { noticeKey } from "./proactive"; +import { notifyProactiveMessage } from "./proactive-notice"; import { frameSessionId, type FrameEvent, type FramePayload, type StoreState } from "./shared"; /** The fields of a `message_edited` payload the chat needs: the edited message's @@ -75,6 +77,14 @@ export function handleMessageEvent(ev: FrameEvent, r: FramePayload, s: StoreStat if (msg.role === "assistant" && msg.turnId) { s.clearGrey(msg.turnId, msg.sessionId ?? s.activeSessionId); } + // 切片 P0b:帧顶的 `proactive:true` 是「这条是她**主动**说的话」的结构化判据 + // (IM 路由的主动推送由 gateway 的 BroadcastProactivePersisted 打上)。带它才走 + // 与 `proactive_message` **同一套**提醒逻辑 —— 非前台补一发通知、同一条只提醒 + // 一次(去重键同为落库行 id)。普通消息的帧**永远没有**这个键,因此不可能被 + // 误判成主动消息去弹通知。判据是结构化字段,绝不读正文/提示词(项目红线)。 + if (r?.proactive === true) { + notifyProactiveMessage(msg.content, noticeKey(msg.id, msg.createdAt, msg.content), s); + } } return true; } diff --git a/frontend/web/src/lib/ws/handlers/proactive-notice.ts b/frontend/web/src/lib/ws/handlers/proactive-notice.ts new file mode 100644 index 0000000..cbef4fe --- /dev/null +++ b/frontend/web/src/lib/ws/handlers/proactive-notice.ts @@ -0,0 +1,123 @@ +import { + createSeenNotices, + decideProactiveNotice, + type NotifyPermission, +} from "../../notify/proactive"; +import type { StoreState } from "./shared"; + +/** + * 主动消息的**通知运行时**(切片 P0b「IM 路由的主动消息也要在非前台补通知」)。 + * + * 为什么单独一个模块:主人在裁定 C 里说清了「她说话该不该提醒我,与走哪条路由无关」, + * 而后端有**两条**路把「她主动说的话」推到本端 —— + * + * ① `proactive_message` 帧(活跃客户端路由,见 `handlers/proactive.ts`); + * ② `message_persisted` 帧顶带 `proactive:true` 的帧(IM 路由,见 `handlers/message.ts`: + * `auto` 提示在主人有已连接 IM 渠道时优先走 IM,因此这条其实才是最常见的)。 + * + * 两条路必须走**同一套**提醒逻辑,否则「同一条既走实时帧、又被镜像回主会话」就会被 + * 打扰两次。因此「已提醒表」与降级说明都住在这里、由两条路共用;判定本身仍是 + * `lib/notify/proactive.ts` 的纯函数(不碰 DOM,可在纯 node 下逐条钉住)。 + * + * 判据是**结构化**的:只有后端主动推送那条通道会在帧顶放 `proactive:true`,普通消息 + * (Web 回合、IM 回复、IM 镜像)永远没有它 ⇒ 普通消息不可能被误判成主动消息。 + */ + +/** 本页存活期间的「已提醒」表:同一条消息只打扰一次(含同一条既走实时帧、又被 IM + * 镜像回主会话这种同时到达的情形)。气泡不参与去重 —— 那是消息 store 按 id 的事。 */ +const seenNotices = createSeenNotices(200); + +/** 最近一次已经说明过的降级状态:通知没开是**状态**,不是每次推送都要报告一遍的事故。 */ +let degradeNote: NotifyPermission | null = null; + +/** 按 `lib/notify/proactive.ts` 的裁定决定要不要补一发系统通知,并把「同一条只打扰 + * 一次」记进去重表。 + * + * `content` 是通知正文(= 她说的那句话),`key` 是这条消息的权威去重键(落库行 id)。 + * 两条帧路给出**同一个** key,因此同一条消息到达两次也只有一次提醒。 */ +export function notifyProactiveMessage(content: string, key: string, s: StoreState): void { + const permission = notifyPermission(); + const decision = decideProactiveNotice({ + seen: seenNotices.has(key), + visibility: documentVisibility(), + focused: documentFocused(), + permission, + }); + // 无论结论如何都记下「这条已经露过面」:前台看过、或提醒过,都不该被第二次打扰。 + seenNotices.add(key); + if (decision === "not-granted") { + noteDegrade(s, permission); + return; + } + if (decision !== "show") return; + if (!showSystemNotification(content, key)) { + // 构造通知本身失败(浏览器策略/权限收紧等)也算降级:留一句可见说明, + // 绝不让它冒泡进帧处理把气泡也带崩。 + noteDegrade(s, notifyPermission()); + } +} + +/** 通知没开时留一句**可见说明**(同一状态只说一次,不刷屏):让主人知道「不是她没说, + * 是浏览器通知没开」,而不是以为主动消息根本没来。 */ +function noteDegrade(s: StoreState, permission: NotifyPermission): void { + if (degradeNote === permission) return; + degradeNote = permission; + s.addDeviceUpdate( + permission === "denied" + ? "浏览器通知未授权(已拒绝):主动消息只出现在气泡里,可在本站的站点设置里允许通知。" + : "浏览器通知尚未授权:主动消息只出现在气泡里,可在本站允许通知。" + ); +} + +/** `Notification` 构造器(不存在时 null)。**调用时**才解引用全局,因此纯 node + * 测试可以安全导入本模块(模块加载期不碰 DOM)。 */ +type NotificationCtor = (new (title: string, options?: { body?: string; tag?: string }) => unknown) & { + permission?: string; +}; + +function notificationCtor(): NotificationCtor | null { + const g = globalThis as unknown as { Notification?: NotificationCtor }; + return typeof g.Notification === "function" ? g.Notification : null; +} + +/** 当前通知权限。运行时没有该 API ⇒ 归到 `"denied"`(拿不到通知就是没授权, + * 绝不假装已授权)。 */ +function notifyPermission(): NotifyPermission { + const ctor = notificationCtor(); + if (!ctor) return "denied"; + if (ctor.permission === "granted") return "granted"; + if (ctor.permission === "denied") return "denied"; + return "default"; +} + +/** `document.visibilityState`;取不到时按 `"visible"`(= 不去打扰)。 */ +function documentVisibility(): string { + const g = globalThis as unknown as { document?: { visibilityState?: string } }; + const v = g.document?.visibilityState; + return typeof v === "string" ? v : "visible"; +} + +/** `document.hasFocus()`;取不到或抛错时按「已聚焦」处理(= 不去打扰)。 */ +function documentFocused(): boolean { + const g = globalThis as unknown as { document?: { hasFocus?: () => boolean } }; + const hasFocus = g.document?.hasFocus; + if (typeof hasFocus !== "function") return true; + try { + return hasFocus(); + } catch { + return true; + } +} + +/** 弹一发系统通知;失败(含构造抛错)返回 false,由调用方降级为「只留气泡 + + * 一句可见说明」。 */ +function showSystemNotification(body: string, tag: string): boolean { + const ctor = notificationCtor(); + if (!ctor) return false; + try { + new ctor("昔涟", { body, tag }); + return true; + } catch { + return false; + } +} diff --git a/frontend/web/src/lib/ws/handlers/proactive.test.ts b/frontend/web/src/lib/ws/handlers/proactive.test.ts index e2a9f17..df96aaa 100644 --- a/frontend/web/src/lib/ws/handlers/proactive.test.ts +++ b/frontend/web/src/lib/ws/handlers/proactive.test.ts @@ -8,6 +8,11 @@ // ③ **拒绝授权 ⇒ 如实降级**:只留气泡 + 一句可见说明,绝不报错崩掉、绝不静默; // ④ **同一条只提醒一次**(含同一条既走实时帧、又被 IM 镜像回传的情形)。 // +// 切片 P0b 追加第 ⑤ 组:**IM 路由**的主动消息(`message_persisted` 帧顶带结构化判据 +// `proactive:true`)同样要落气泡 + 非前台补通知 —— `auto` 提示在主人有已连接 IM 渠道时 +// 优先走 IM,这条才是最常见的路径。其中包含「两路都到达仍只提醒一次」与「普通消息绝不 +// 被误判」这两条对照断言。 +// // 项目没有前端测试框架/jsdom,所以这是零依赖的纯 node 检查:它驱动真实的帧解码器 // (lib/ws.ts 的 dispatchFrame)与真实的 store,并把浏览器 API(Notification / // document)用桩装上(handler 只在**调用时**解引用它们,因此模块加载期不碰 DOM)。 @@ -250,4 +255,184 @@ function setDocument(visibility: string, focused: boolean): void { ok(msgs()[0].id !== "", "本端给一个非空 id(渲染与 key 都需要它)"); } +// ── ⑤ 切片 P0b · IM 路由的主动消息:帧顶带结构化判据 `proactive:true` ───────────── +// 后端 IM 主动推送在落库之后发的是同一种 `message_persisted` 帧,只多一个结构化判据 +// (`gateway.BroadcastProactivePersisted`)。走 IM 的主动消息因此也必须在非前台补通知 +// —— `auto` 提示在主人有已连接 IM 渠道时优先走 IM,这条其实才是最常见的路径。 +{ + reset(); + const shown = installNotification("granted"); + setDocument("hidden", false); + dispatchFrame({ + type: "message_persisted", + sessionId: MAIN, + data: { + proactive: true, + message: { + id: "im-row-1", + sessionId: MAIN, + role: "assistant", + content: "IM 路由的这条", + platform: "telegram", + adapterId: "telegram", + createdAt: 1_760_000_100_000, + }, + }, + }); + same(msgs().length, 1, "IM 路由的主动消息 ⇒ 落气泡(与普通 IM 镜像同一条路)"); + same(shown.length, 1, "非前台 ⇒ IM 路由的主动消息也补一发通知"); + same(shown[0].body, "IM 路由的这条", "通知正文 = 这条主动消息的正文"); +} + +// ── ⑤ 两路都到达(同一落库行 id)⇒ 仍只提醒一次、仍只有一个气泡 ──────────────────── +{ + reset(); + const shown = installNotification("granted"); + setDocument("hidden", false); + dispatchFrame({ + type: "message_persisted", + sessionId: MAIN, + data: { + proactive: true, + message: { + id: "im-row-2", + sessionId: MAIN, + role: "assistant", + content: "两路都到的那条", + createdAt: 1_760_000_200_000, + }, + }, + }); + same(shown.length, 1, "先到带判据的 message_persisted ⇒ 补一发"); + dispatchFrame(proactiveFrame({ id: "im-row-2", content: "两路都到的那条" })); + same(shown.length, 1, "同一条又走 proactive_message 到达 ⇒ 不打扰第二次"); + same(msgs().length, 1, "两条帧说的是同一条(同 id)⇒ 仍只有一个气泡"); + + // 反序同样只一次:去重表按落库行 id 共用,与到达顺序无关。 + reset(); + const shown2 = installNotification("granted"); + setDocument("hidden", false); + dispatchFrame(proactiveFrame({ id: "im-row-3", content: "反序也要一次" })); + same(shown2.length, 1, "反序:先 proactive_message ⇒ 补一发"); + dispatchFrame({ + type: "message_persisted", + sessionId: MAIN, + data: { + proactive: true, + message: { + id: "im-row-3", + sessionId: MAIN, + role: "assistant", + content: "反序也要一次", + createdAt: 1_760_000_300_000, + }, + }, + }); + same(shown2.length, 1, "反序:随后带判据的 message_persisted ⇒ 仍只有一次"); + same(msgs().length, 1, "反序也只有一个气泡"); +} + +// ── ⑤ 前台不弹(IM 路由那条帧同样适用) ────────────────────────────────────────── +{ + reset(); + const shown = installNotification("granted"); + setDocument("visible", true); + dispatchFrame({ + type: "message_persisted", + sessionId: MAIN, + data: { + proactive: true, + message: { + id: "im-row-fg", + sessionId: MAIN, + role: "assistant", + content: "前台这条 IM 主动消息", + createdAt: 1_760_000_400_000, + }, + }, + }); + same(shown.length, 0, "可见且聚焦 ⇒ 不弹(气泡就是记录)"); + same(msgs().length, 1, "前台照样落气泡"); +} + +// ── ⑤ 拒绝授权 ⇒ 只留气泡、不崩(IM 路由那条帧同样适用) ────────────────────────── +{ + reset(); + const shown = installNotification("denied"); + setDocument("hidden", false); + dispatchFrame({ + type: "message_persisted", + sessionId: MAIN, + data: { + proactive: true, + message: { + id: "im-row-denied", + sessionId: MAIN, + role: "assistant", + content: "通知被拒时的 IM 主动消息", + createdAt: 1_760_000_500_000, + }, + }, + }); + same(shown.length, 0, "没有授权 ⇒ 不弹(绝不假装弹过)"); + same(msgs().length, 1, "气泡必须仍然落地,且不抛错"); +} + +// ── ⑤ 对照(「不误伤」):普通消息没有判据 ⇒ 一条通知都不弹 ──────────────────────── +// 这些是真实存在的普通消息形状:IM 助手回复(带 turnId/adapterId/platform)、主人的 +// 提问、以及帧顶显式 `proactive:false` 的帧。判据是**结构化字段严格等于 true**,绝不是 +// 「像不像主动消息」,因此普通消息不可能被误判。 +{ + reset(); + const shown = installNotification("granted"); + setDocument("hidden", false); + dispatchFrame({ + type: "message_persisted", + sessionId: MAIN, + data: { + message: { + id: "im-normal-1", + sessionId: MAIN, + role: "assistant", + content: "普通 IM 回复", + platform: "telegram", + adapterId: "telegram:100", + turnId: "turn-abc", + createdAt: 1_760_000_600_000, + }, + }, + }); + dispatchFrame({ + type: "message_persisted", + sessionId: MAIN, + data: { + message: { + id: "im-normal-2", + sessionId: MAIN, + role: "user", + content: "在吗", + platform: "telegram", + turnId: "turn-abc", + createdAt: 1_760_000_600_001, + }, + }, + }); + dispatchFrame({ + type: "message_persisted", + sessionId: MAIN, + data: { + proactive: false, + message: { + id: "im-normal-3", + sessionId: MAIN, + role: "assistant", + content: "帧顶显式 false", + createdAt: 1_760_000_600_002, + }, + }, + }); + same(shown.length, 0, "普通消息(没有结构化判据)绝不弹通知"); + same(msgs().length, 3, "但三条都照常落气泡(气泡与判据无关)"); +} + console.log(`proactive_message logic test: ${checks} checks passed`); diff --git a/frontend/web/src/lib/ws/handlers/proactive.ts b/frontend/web/src/lib/ws/handlers/proactive.ts index 5a1f675..8b66b9b 100644 --- a/frontend/web/src/lib/ws/handlers/proactive.ts +++ b/frontend/web/src/lib/ws/handlers/proactive.ts @@ -2,11 +2,7 @@ import type { ChatMessage } from "../../types"; import { now, uid } from "../../util"; import { toRecord } from "../../wsParse"; import { MAIN_SESSION_ID } from "../../../store/sessionCache"; -import { - createSeenNotices, - decideProactiveNotice, - type NotifyPermission, -} from "../../notify/proactive"; +import { notifyProactiveMessage } from "./proactive-notice"; import { frameText, type FrameEvent, type FramePayload, type StoreState } from "./shared"; /** @@ -22,6 +18,11 @@ import { frameText, type FrameEvent, type FramePayload, type StoreState } from " * ② **非前台才补通知**:见 `lib/notify/proactive.ts` 的裁定。前台不弹、同一条只打扰 * 一次、未授权就如实降级(只留气泡 + 一句可见说明),**绝不静默丢弃**。 * + * 提醒逻辑本身**不在本文件**:它与 IM 路由那条路(`message_persisted` 帧顶带 + * `proactive:true`,见 `handlers/message.ts`)共用 `handlers/proactive-notice.ts` 的同一套 + * 运行时 —— 「她该不该提醒我」因此与后端走了哪条路由无关,而同一条消息走两路也只会打扰 + * 一次(去重表按落库行 id 共用)。 + * * 载荷畸形时也**不静默**:落到既有的「本端 WS 事件回显」可观测面(与未知帧同一去处)。 * * 命中返回 true,未命中返回 false 交给下一组。 @@ -34,10 +35,17 @@ export function handleProactiveEvent(ev: FrameEvent, r: FramePayload, s: StoreSt return true; } s.appendOrUpdateMessage(toChatMessage(payload)); - notifyProactive(payload, s); + notifyProactiveMessage(payload.content, noticeKey(payload.id, payload.createdAt, payload.content), s); return true; } +/** 一条主动消息的提醒去重键:**落库行 id 优先**(两条帧路与握手回放/REST 拉取都用它 + * 对齐同一条消息);落库失败(后端如实省略 id)时才退到「时间 + 正文」的本端键 —— + * 那种情况下没有权威 id 可用,但仍必须只打扰一次。 */ +export function noticeKey(id: string, createdAt: number, content: string): string { + return id || `${createdAt}|${content}`; +} + /** 一帧主动消息的可用字段(已收窄)。 */ interface ProactiveMessage { /** 主会话历史行的权威 id;后端落库失败时**省略**(本端那时只能造一个本地 id)。 */ @@ -90,103 +98,6 @@ function parseTimestamp(v: unknown): number | undefined { return Number.isNaN(t) ? undefined : t; } -/** 本页存活期间的「已提醒」表:同一条消息只打扰一次(含同一条既走实时帧、又被 IM - * 镜像回主会话这种同时到达的情形)。气泡不参与去重 —— 那是消息 store 按 id 的事。 */ -const seenNotices = createSeenNotices(200); - -/** 最近一次已经说明过的降级状态:通知没开是**状态**,不是每次推送都要报告一遍的事故。 */ -let degradeNote: NotifyPermission | null = null; - -/** 按 `lib/notify/proactive.ts` 的裁定决定要不要补一发系统通知,并把「同一条只打扰 - * 一次」记进本页的去重表。 */ -function notifyProactive(p: ProactiveMessage, s: StoreState): void { - const key = p.id || `${p.createdAt}|${p.content}`; - const permission = notifyPermission(); - const decision = decideProactiveNotice({ - seen: seenNotices.has(key), - visibility: documentVisibility(), - focused: documentFocused(), - permission, - }); - // 无论结论如何都记下「这条已经露过面」:前台看过、或提醒过,都不该被第二次打扰。 - seenNotices.add(key); - if (decision === "not-granted") { - noteDegrade(s, permission); - return; - } - if (decision !== "show") return; - if (!showSystemNotification(p.content, key)) { - // 构造通知本身失败(浏览器策略/权限收紧等)也算降级:留一句可见说明, - // 绝不让它冒泡进帧处理把气泡也带崩。 - noteDegrade(s, notifyPermission()); - } -} - -/** 通知没开时留一句**可见说明**(同一状态只说一次,不刷屏):让主人知道「不是她没说, - * 是浏览器通知没开」,而不是以为主动消息根本没来。 */ -function noteDegrade(s: StoreState, permission: NotifyPermission): void { - if (degradeNote === permission) return; - degradeNote = permission; - s.addDeviceUpdate( - permission === "denied" - ? "浏览器通知未授权(已拒绝):主动消息只出现在气泡里,可在本站的站点设置里允许通知。" - : "浏览器通知尚未授权:主动消息只出现在气泡里,可在本站允许通知。" - ); -} - -/** `Notification` 构造器(不存在时 null)。**调用时**才解引用全局,因此纯 node - * 测试可以安全导入本模块(模块加载期不碰 DOM)。 */ -type NotificationCtor = (new (title: string, options?: { body?: string; tag?: string }) => unknown) & { - permission?: string; -}; - -function notificationCtor(): NotificationCtor | null { - const g = globalThis as unknown as { Notification?: NotificationCtor }; - return typeof g.Notification === "function" ? g.Notification : null; -} - -/** 当前通知权限。运行时没有该 API ⇒ 归到 `"denied"`(拿不到通知就是没授权, - * 绝不假装已授权)。 */ -function notifyPermission(): NotifyPermission { - const ctor = notificationCtor(); - if (!ctor) return "denied"; - if (ctor.permission === "granted") return "granted"; - if (ctor.permission === "denied") return "denied"; - return "default"; -} - -/** `document.visibilityState`;取不到时按 `"visible"`(= 不去打扰)。 */ -function documentVisibility(): string { - const g = globalThis as unknown as { document?: { visibilityState?: string } }; - const v = g.document?.visibilityState; - return typeof v === "string" ? v : "visible"; -} - -/** `document.hasFocus()`;取不到或抛错时按「已聚焦」处理(= 不去打扰)。 */ -function documentFocused(): boolean { - const g = globalThis as unknown as { document?: { hasFocus?: () => boolean } }; - const hasFocus = g.document?.hasFocus; - if (typeof hasFocus !== "function") return true; - try { - return hasFocus(); - } catch { - return true; - } -} - -/** 弹一发系统通知;失败(含构造抛错)返回 false,由调用方降级为「只留气泡 + - * 一句可见说明」。 */ -function showSystemNotification(body: string, tag: string): boolean { - const ctor = notificationCtor(); - if (!ctor) return false; - try { - new ctor("昔涟", { body, tag }); - return true; - } catch { - return false; - } -} - /** 把无法解析的载荷转成一行可读文本(本端事件回显用)。 */ function rawText(v: unknown): string { if (typeof v === "string") return v; diff --git a/internal/services/channelbridge/channelbridge.go b/internal/services/channelbridge/channelbridge.go index 7c42b25..4c3face 100644 --- a/internal/services/channelbridge/channelbridge.go +++ b/internal/services/channelbridge/channelbridge.go @@ -183,8 +183,13 @@ type Bridge struct { owner *user.OwnerProfile history history.HistoryStore onPersisted func(history.Message) - onRejected func(adapter.UnifiedMessage, string) - review adapter.Reviewer + // onProactivePersisted 是**主动推送**那条实时通知接缝(切片 P0b):一条主动消息刚 + // 落进主会话时被调用,使客户端能凭结构化判据(帧顶 `proactive:true`)走与 + // proactive_message **同一套**提醒逻辑 —— 「她该不该提醒我」因此与后端走哪条路由 + // 无关。普通消息的通知仍走 onPersisted,两条互不串味(见 proactive_notify.go)。 + onProactivePersisted func(history.Message) + onRejected func(adapter.UnifiedMessage, string) + review adapter.Reviewer light LightJudge quietStartHour int diff --git a/internal/services/channelbridge/persist.go b/internal/services/channelbridge/persist.go index 6ce148a..d49246a 100644 --- a/internal/services/channelbridge/persist.go +++ b/internal/services/channelbridge/persist.go @@ -76,18 +76,35 @@ func (b *Bridge) notifyPersisted(msg history.Message) { // 使调用方能在回合结束后按 id 把文档抽取结论补进同一列 // (inbound_documents_persist.go 的两段式)。未装配历史存储时为空操作, // 因此桥接器在没有存储的情况下行为不变。 +// +// 写入本身走 persistMain(与主动推送同一个写入口径),通知走普通通道 notifyPersisted。 +// **主动推送不经过本函数**:它直接调 persistMain,并额外走 notifyProactive 追加一条带 +// 结构化判据的帧(切片 P0b)—— 因此带判据的帧只可能来自主动推送,**普通消息的帧永远 +// 不带它**。 func (b *Bridge) persistToMain(ctx context.Context, role, content, mood, document, image, platform, deviceID, adapterID, turnID string) history.Message { + return b.persistMain(ctx, history.Message{ + SessionID: history.MainSessionID, Role: role, Content: content, Mood: mood, Document: document, Image: image, Platform: platform, DeviceID: deviceID, AdapterID: adapterID, Mode: modeChat, TurnID: turnID, + }, b.notifyPersisted) +} + +// persistMain 是「写进主会话」的**唯一**写入口径:persistToMain(普通消息)与 +// 主动推送(proactive.go)共用它,因此两条路的存储语义逐字一致 —— 未接线历史存储 +// 时空操作并返回零值、写库失败 WARN 并返回零值(绝不谎称已落库)、成功则返回刚落库的 +// 完整消息。**差别只在 notify**:那是「这条要不要通知实时通道」的接缝,由调用方给出 +// —— 普通消息传 notifyPersisted(`message_persisted` / `channel_persisted`),主动推送 +// 传 notifyProactive(带结构化判据的同一类帧,切片 P0b)。nil 表示本次写入不通知。 +func (b *Bridge) persistMain(ctx context.Context, msg history.Message, notify func(history.Message)) history.Message { if b.history == nil { return history.Message{} } - full, err := b.history.AppendFull(ctx, history.Message{ - SessionID: history.MainSessionID, Role: role, Content: content, Mood: mood, Document: document, Image: image, Platform: platform, DeviceID: deviceID, AdapterID: adapterID, Mode: modeChat, TurnID: turnID, - }) + full, err := b.history.AppendFull(ctx, msg) if err != nil { - b.log.Warn("persist main session", "err", err, "role", role, "platform", platform, "device_id", deviceID, "adapter", adapterID) + b.log.Warn("persist main session", "err", err, "role", msg.Role, "platform", msg.Platform, "device_id", msg.DeviceID, "adapter", msg.AdapterID) return history.Message{} } - b.notifyPersisted(full) + if notify != nil { + notify(full) + } return full } diff --git a/internal/services/channelbridge/proactive.go b/internal/services/channelbridge/proactive.go index 9b9b2ea..f19912f 100644 --- a/internal/services/channelbridge/proactive.go +++ b/internal/services/channelbridge/proactive.go @@ -40,6 +40,12 @@ const proactiveRecentCount = 20 // 当主人档案没有白名单账号、或该账号没有已连接的 // 适配器支撑时,它返回明确错误,便于调用方记录原因, // 而不是静默丢弃推送。 +// +// 成功投递之后它**同时**做两件事:把这条主动消息镜像回主会话(恰好一次;气泡恒落的 +// 根),并让实时通道能凭**结构化判据**认出「这条是她主动说的话」—— 后者是切片 P0b: +// `auto` 提示在主人有已连接 IM 渠道时优先走 IM,因此**实际最可能发生的路径**恰恰是这 +// 一条;它过去只发普通 `message_persisted`,于是挂在 `proactive_message` 上的浏览器 +// 通知永不触发(主人裁定:该不该提醒与走哪条路由无关)。 func (b *Bridge) SendProactive(ctx context.Context, msg adapter.UnifiedMessage) error { if err := ctx.Err(); err != nil { return err @@ -77,16 +83,39 @@ func (b *Bridge) SendProactive(ctx context.Context, msg adapter.UnifiedMessage) // 把主动消息镜像进主对话上下文(design/16 // §4.4 + §4.6.1)。否则模型看不到自己主动说了什么, // 主人后续回复就会显得不连贯(该消息「丢失」了历史)。 - // 它与主人私聊 IM 回复走同一条镜像路径,作用域为 MainSessionID, - // 落库的同样是规整后的那一份(Web 与 IM 看到的必须是同一份)。 - // turn_id 传 "":主动推送是**她单方面开口**,没有对应的入站回合,也就没有 + // 它用的是普通回复那条写入口径(persistMain,相同的列、相同的时间戳语义), + // 作用域恒为 MainSessionID,落库的同样是**规整后**的那一份(Web 与 IM 看到的必须是 + // 同一份),因此落库行为与本切片之前逐字相同;变的只有通知的第二步(见下)。 + // turn_id 传 ""(零值):主动推送是**她单方面开口**,没有对应的入站回合,也就没有 // 「它属于哪一路回合」可归属 —— 空值诚实地表示这一点(见 turnid.go 的口径)。 - b.persistToMain(ctx, history.RoleAssistant, out.Content, "", "", "", target.platform, - fmt.Sprintf("%s:%s:%s", target.platform, target.accountID, target.accountID), - target.platform, "") + // + // 通知分两步,两条都是**结构化**的通道(绝不是「像不像主动消息」的猜测): + // ① notifyPersisted 照旧 —— 这就是 P0 起的行为,任何客户端都能渲染这条镜像消息, + // 逐字不变(`message_persisted`); + // ② 再走 notifyProactive —— 追加一条帧顶带 `proactive:true` 的同类帧,客户端据此在 + // **非前台**补一发浏览器通知(切片 P0b)。两帧说的是同一条消息(同一个落库行 + // id),前端按 id 去重 ⇒ 仍是一个气泡、仍只提醒一次。 + // + // ② 只在**确实落了库**时发:`message_persisted` 的载荷要求权威 id,客户端拿不到 id + // 会整帧丢弃 —— 发一条没有 id 的帧等于假装提醒过。落库失败本身已由 persistMain + // 记 WARN(可见,不静默)。 + row := history.Message{ + SessionID: history.MainSessionID, Role: history.RoleAssistant, Content: out.Content, + Platform: target.platform, DeviceID: proactiveDeviceID(target), AdapterID: target.platform, Mode: modeChat, + } + if full := b.persistMain(ctx, row, b.notifyPersisted); full.ID != "" { + b.notifyProactive(full) + } return nil } +// proactiveDeviceID 是主动推送落进主会话时写入 device_id 的标签:`<平台>:<账号>:<账号>`。 +// 它不是某台设备,而是「这条推送走的是哪个主人渠道账号」——与 sendIMBubbles 出口选中的 +// 那个账号逐字对应,因此在管理日志里能一眼看出这条主动消息投到了哪里。 +func proactiveDeviceID(target proactiveTarget) string { + return fmt.Sprintf("%s:%s:%s", target.platform, target.accountID, target.accountID) +} + // proactiveTarget 解析主动推送应当到达的唯一主人账号。 // 候选范围是每个有已连接适配器支撑的白名单主人渠道 // (含 WeChat),选择遵循 backthink 的优先级: diff --git a/internal/services/channelbridge/proactive_notify.go b/internal/services/channelbridge/proactive_notify.go new file mode 100644 index 0000000..b552331 --- /dev/null +++ b/internal/services/channelbridge/proactive_notify.go @@ -0,0 +1,40 @@ +package channelbridge + +import ( + "git.yeij.top/AskaEth/Cyrene_v2/internal/runtime/history" +) + +// 本文件承载 IM 主动推送那条**实时通知**接缝(切片 P0b「IM 路由的主动消息也要在非前台 +// 补通知」)。它与 persist.go 的 notifyPersisted 并列:普通消息走那一条,主动推送走这 +// 一条。两条都写主会话,因此「写」是同一份代码(persistMain),差别只在通知。 +// +// 为什么必须分开而不是去猜:主人裁定「她说话该不该提醒我,与走哪条路由无关」,因此 +// 主动推送必须自己声明「我是主动推送」。判据是**结构化**的(本次写入走的是哪条通知 +// 通道),**绝不**读正文关键词、**绝不**让提示词/模型判断 —— 后者是项目红线 +// (AGENTS §9:身份与判定靠元数据,不靠提示词)。 +// +// 为什么不在落库行上找判据:主会话的 `platform`/`adapter_id` 区分不出主动推送与普通 +// 回复 —— 主动推送写的是**解析后的真实平台**(proactive.go 的 target.platform,例如 +// "weixin-ilink"),与普通回复行同一形状(普通回复在按平台名注册的适配器上 +// adapter_id 也等于平台名)。因此结构化判据放在**落库那一刻的通知通道**上,随帧顶的 +// `proactive:true` 到达客户端(见 gateway 的 BroadcastProactivePersisted)。 + +// SetOnProactivePersisted 装配(或替换)「一条主动消息刚落进主会话」之后所调用的通知 +// 钩子。组合根把它接进 gateway 的 BroadcastProactivePersisted(帧顶带结构化判据的 +// `message_persisted`)。它可以安全空调用,也可与在途推送安全并发。 +func (b *Bridge) SetOnProactivePersisted(fn func(history.Message)) { + b.mu.Lock() + defer b.mu.Unlock() + b.onProactivePersisted = fn +} + +// notifyProactive 在装配了主动通知钩子时把刚落库的主动消息交给它;未装配时是空操作 +// (行为与本切片之前逐字相同:主动消息照旧落库、只是没有「主动」这条通知通道)。 +func (b *Bridge) notifyProactive(msg history.Message) { + b.mu.RLock() + fn := b.onProactivePersisted + b.mu.RUnlock() + if fn != nil { + fn(msg) + } +} diff --git a/internal/services/gateway/broadcast.go b/internal/services/gateway/broadcast.go index 023d298..4056a2a 100644 --- a/internal/services/gateway/broadcast.go +++ b/internal/services/gateway/broadcast.go @@ -20,14 +20,30 @@ import ( // 会话。Thinking 会被抹除,以与 WS 历史回放保持一致(design/16 §6)。 // 当 hub 接好广播时它是安全空操作。两种帧类型都携带消息内容, // 因此 design/11 §7.1 帧门只把它们投递给 owner/admin 连接。 +// +// 它**绝不**带 `proactive` 键:普通消息的帧顶永远没有那个结构化判据,客户端因此 +// 不可能把普通消息误判成主动消息去弹通知(切片 P0b 的「不误伤」那一条)。主动推送 +// 那条路走 BroadcastProactivePersisted(proactive.go)。 func (s *Server) BroadcastPersisted(msg history.Message) { + s.broadcastPersisted(msg, false) +} + +// broadcastPersisted 是上面两个入口共用的帧构造与扇出:proactive 决定帧顶是否带上 +// 「这是她主动说的话」的结构化判据 `proactive:true`(切片 P0b,见 proactive.go 的 +// BroadcastProactivePersisted)。两条入口走**同一个**函数,因此帧类型推导、thinking +// 抹除与角色门(design/11 §7.1)逐字一致 —— 差别只有那一个键。 +func (s *Server) broadcastPersisted(msg history.Message, proactive bool) { wire := toHistoryMessage(msg) wire.Thinking = "" typ := "channel_persisted" if msg.SessionID == history.MainSessionID || strings.HasPrefix(msg.SessionID, history.MainSessionID+":") { typ = "message_persisted" } - s.hub.broadcast(wsEvent{Type: typ, SessionID: msg.SessionID, Data: map[string]any{"message": wire}}) + data := map[string]any{"message": wire} + if proactive { + data["proactive"] = true + } + s.hub.broadcast(wsEvent{Type: typ, SessionID: msg.SessionID, Data: data}) } // wsCapacityAwaken 是能力状态迁移的 WS 事件类型(design/14 §5)。 diff --git a/internal/services/gateway/proactive.go b/internal/services/gateway/proactive.go index b406ac8..ba0c306 100644 --- a/internal/services/gateway/proactive.go +++ b/internal/services/gateway/proactive.go @@ -92,6 +92,24 @@ func (s *Server) SendProactive(ctx context.Context, msg adapter.UnifiedMessage) return s.hub.SendProactive(ctx, msg) } +// BroadcastProactivePersisted 把一条**刚落进主会话的主动消息**广播为**带结构化判据**的 +// `message_persisted` 帧(切片 P0b)。判据就是帧顶的 `proactive:true`:它是「她主动说的 +// 话」在线上唯一的标记,客户端据此走与 `proactive_message` **同一套**提醒逻辑(非前台才 +// 补一发通知,同一条只提醒一次),于是「她该不该提醒我」**与后端走了哪条路由无关** +// (主人 2026-10-05 裁定 C)。 +// +// 它由 IM 桥的主动推送在**落库之后**调用(组合根接线 SetOnProactivePersisted)。为什么 +// 需要它:IM 路由过去只发普通 `message_persisted`,而浏览器通知挂在 `proactive_message` +// 上 ⇒ 走 IM 的主动消息一条都不弹;偏偏 `auto` 提示在主人有已连接 IM 渠道时优先走 IM +// ⇒ 实际最可能发生的路径恰恰不弹。 +// +// 判据为什么不会误伤普通消息:只有主动推送这条通道会调用本函数,普通消息(Web 回合 / +// IM 回复 / IM 镜像)走的仍是 BroadcastPersisted,那条路径**永不**往帧顶放该键。 +// 帧类型仍是 `message_persisted`,因此角色门(design/11 §7.1)与普通持久化帧逐字相同。 +func (s *Server) BroadcastProactivePersisted(msg history.Message) { + s.broadcastPersisted(msg, true) +} + // proactivePayloadFrom 把 UnifiedMessage 投影为消毒后的线上载荷。 // persisted 是刚落库的主会话消息(未接线历史存储或落库失败时为零值), // 它的 id/时间戳随之进入载荷,使客户端能把实时气泡对齐到历史行。 diff --git a/internal/services/gateway/proactive_im_notify_test.go b/internal/services/gateway/proactive_im_notify_test.go new file mode 100644 index 0000000..9c1f9b0 --- /dev/null +++ b/internal/services/gateway/proactive_im_notify_test.go @@ -0,0 +1,146 @@ +package gateway + +import ( + "context" + "testing" + + "git.yeij.top/AskaEth/Cyrene_v2/internal/runtime/history" + "git.yeij.top/AskaEth/Cyrene_v2/internal/services/channelbridge" + "git.yeij.top/AskaEth/Cyrene_v2/internal/user" +) + +// 本文件锁定切片 P0b:**IM 路由的主动消息也要在「非前台」补一发浏览器通知**。 +// +// 背景(P0 如实报回的边界):`auto` 提示在主人有已连接 IM 渠道时**优先走 IM**,而 IM +// 路由过去只发普通 `message_persisted` —— 浏览器通知挂在 `proactive_message` 上,于是 +// **实际最可能发生的路径恰恰不弹**。主人裁定「她说话该不该提醒我,与走哪条路由无关」。 +// +// 判据是**结构化**的:主动推送在落库之后追加一条**帧顶带 `proactive:true`** 的 +// `message_persisted`(gateway.BroadcastProactivePersisted)。普通消息(Web 回合 / IM +// 回复 / IM 镜像)走的仍是 BroadcastPersisted,那条路**永不**放该键 —— 因此普通消息 +// 不可能被误判成主动消息。下面分别钉住两端:IM 路由真的发得出这条带判据的帧,而普通 +// 广播路径永远发不出它。 + +// dataFlag 报告帧顶是否带 proactive 判据(以及它的值)。 +func dataFlag(t *testing.T, ev wsEvent) (any, bool) { + t.Helper() + data, ok := ev.Data.(map[string]any) + if !ok { + t.Fatalf("frame data type = %T, want map[string]any", ev.Data) + } + v, has := data["proactive"] + return v, has +} + +// frameMessageID 取帧内消息 DTO 的 id。 +func frameMessageID(t *testing.T, ev wsEvent) string { + t.Helper() + data, ok := ev.Data.(map[string]any) + if !ok { + t.Fatalf("frame data type = %T, want map[string]any", ev.Data) + } + msg, ok := data["message"].(map[string]any) + if !ok { + t.Fatalf("frame message type = %T, want map[string]any", data["message"]) + } + id, _ := msg["id"].(string) + return id +} + +// TestChannelBridge_SendProactive_EmitsProactiveFlaggedFrame 是切片 P0b 的端到端证据: +// IM 路由的主动消息**既**照旧广播普通镜像帧(P0 起的行为,任何客户端都能渲染),**又** +// 追加一条帧顶带 `proactive:true`、并携带落库行权威 id 的帧 —— 前端据此走与 +// `proactive_message` 同一套提醒逻辑(非前台补一发通知,两帧同 id ⇒ 去重后一个气泡、 +// 一次提醒)。它同时守住 P0 的红线:主会话里仍**恰好一条**(绝无双份)。 +func TestChannelBridge_SendProactive_EmitsProactiveFlaggedFrame(t *testing.T) { + env := newEnv(t, nil, false) + store := newHistoryStoreForGateway(t) + env.srv.hub.history = store + owner := newOwnerConn(env.srv.hub, 8) + env.srv.hub.register(owner) + // claims 为 nil 的裸连接是 fail-closed 的,与普通持久化帧同一条角色门。 + bare := newFakeConn(env.srv.hub, 8) + env.srv.hub.register(bare) + + ownerProfile := &user.OwnerProfile{Accounts: []user.OwnerAccount{{Platform: "telegram", AccountID: "100"}}} + bridge, err := channelbridge.New(channelbridge.Options{ + Log: gwTestLogger(), + Loop: stubBridgeChatter{}, + Sessions: stubBridgeSessions{}, + Owner: ownerProfile, + History: store, + OnPersisted: env.srv.BroadcastPersisted, + }) + if err != nil { + t.Fatalf("new bridge: %v", err) + } + bridge.SetOnProactivePersisted(env.srv.BroadcastProactivePersisted) + bridge.Add(&fakeIMAdapter{platform: "telegram"}) + + if err := bridge.SendProactive(context.Background(), proactiveStoreMsg("记得喝水哦")); err != nil { + t.Fatalf("SendProactive err = %v", err) + } + rows := mainSessionRows(t, store) + if len(rows) != 1 { + t.Fatalf("主会话里应恰好一条主动消息,得到 %d 条(>1 = 双份)", len(rows)) + } + + // 第一帧:普通镜像帧(P0 起的行为),**不带**判据。 + first := readFakeFrame(t, owner) + if first.Type != "message_persisted" { + t.Fatalf("frame 1 type = %q, want message_persisted", first.Type) + } + if v, has := dataFlag(t, first); has { + t.Fatalf("普通镜像帧带上了 proactive=%v,want 该键缺席(判据只属于主动那条)", v) + } + + // 第二帧:主动帧 —— 帧顶带判据,且消息 id 就是落库行的权威 id。 + second := readFakeFrame(t, owner) + if second.Type != "message_persisted" { + t.Fatalf("frame 2 type = %q, want message_persisted(帧类型不变,只多一个结构化键)", second.Type) + } + if v, has := dataFlag(t, second); !has || v != true { + t.Fatalf("主动帧的 proactive 判据 = %v(present=%v),want true", v, has) + } + if got := frameMessageID(t, second); got != rows[0].ID { + t.Fatalf("主动帧的消息 id = %q, want 落库行的权威 id %q(前端去重与对齐都靠它)", got, rows[0].ID) + } + if err := connHasNoFrame(owner); err != nil { + t.Fatalf("owner 连接应恰好收到两帧(普通 + 主动),多出来的:%v", err) + } + if err := connHasNoFrame(bare); err != nil { + t.Fatalf("主动帧只投递给 owner/admin,裸连接不该收到:%v", err) + } +} + +// TestServer_BroadcastPersisted_NeverCarriesProactiveFlag 是「不误伤」那一条的后端对照: +// 普通广播路径(Web 回合 / IM 回复 / IM 镜像全走它)**永远**不在帧顶放 proactive 判据, +// 因此客户端不可能把普通消息误判成主动消息去弹通知。同一行改走主动那条入口时,判据才 +// 出现 —— 两条入口的差别只有这一个键。 +func TestServer_BroadcastPersisted_NeverCarriesProactiveFlag(t *testing.T) { + env := newEnv(t, nil, false) + owner := newOwnerConn(env.srv.hub, 8) + env.srv.hub.register(owner) + + row := history.Message{ + ID: "row-plain", SessionID: history.MainSessionID, Role: history.RoleAssistant, + Content: "普通 IM 回复", Platform: "telegram", AdapterID: "telegram:100", TurnID: "turn-abc", CreatedAt: 1_760_000_000_000, + } + env.srv.BroadcastPersisted(row) + plain := readFakeFrame(t, owner) + if plain.Type != "message_persisted" { + t.Fatalf("frame type = %q, want message_persisted", plain.Type) + } + if v, has := dataFlag(t, plain); has { + t.Fatalf("普通消息的帧顶带上了 proactive=%v,want 该键缺席(否则会被误判成主动消息)", v) + } + + env.srv.BroadcastProactivePersisted(row) + flagged := readFakeFrame(t, owner) + if v, has := dataFlag(t, flagged); !has || v != true { + t.Fatalf("主动入口的 proactive 判据 = %v(present=%v),want true", v, has) + } + if got := frameMessageID(t, flagged); got != "row-plain" { + t.Fatalf("主动帧的消息 id = %q, want row-plain", got) + } +}