feat: 只读验收模式、文件发送类型与消息定位补全

- 只读验收:TRACEMEMO_READ_ONLY=1 时跳过消息写入、自动发送与退群提示
- 微信发送新增 file 类型,文档、能力探测与 Reader Skill 同步
- 消息前后窗口按分片定位,补齐 wcdb4 定位与分片测试
This commit is contained in:
Wxw-Gu committed 2026-11-21 15:26:03 +08:00
1 parent 0edbf60b2e
commit 518a9662a7
25 files changed
+1278 -154

No files matched your search

+10 -3
View File
@@ -87,7 +87,7 @@ Token 由应用生成并保存在本机,**不接受用环境变量覆盖**:A
| 身份 | 你本人当前登录的微信账号 | 已扫码接入的机器人 |
| 用途 | **以你的身份把消息发给别人**(好友 / 群 / 文件传输助手) | **机器人给自己发通知**(测试连通性) |
| 前置条件 | 本机微信已启动,发送能力为 `ready` | 连接器为 `online` |
| 内容类型 | `text` / `image` / `voice`,媒体只接受本地文件 | `text` / `image`(URL 或本地路径) |
| 内容类型 | `text` / `image` / `voice` / `file`,媒体只接受本地文件 | `text` / `image`(URL 或本地路径) |
| 典型失败 | 能力未就绪 `503`、发送失败 `502` | 连接器离线 `503`、凭证过期 `401` |
### 本地发送:`POST /api/v1/wechat/send`
@@ -100,6 +100,12 @@ curl -X POST http://127.0.0.1:6131/api/v1/wechat/send \
-H "Authorization: Bearer $TRACEMEMO_API_TOKEN" \
-H "Content-Type: application/json" \
-d '{"to":"filehelper","type":"text","text":"来自 Agent 的一条消息"}'
# 发送本地文件(macOS / Windows 均走本机发送能力)
curl -X POST http://127.0.0.1:6131/api/v1/wechat/send \
-H "Authorization: Bearer $TRACEMEMO_API_TOKEN" \
-H "Content-Type: application/json" \
-d '{"to":"filehelper","type":"file","filePath":"/abs/path/report.pdf","fileName":"周报.pdf"}'
```
请求体:
@@ -107,9 +113,10 @@ curl -X POST http://127.0.0.1:6131/api/v1/wechat/send \
| 字段 | 必填 | 说明 |
| --- | --- | --- |
| `to` | 是 | 接收者:好友 wxid、群 id(以 `@chatroom` 结尾),或 `filehelper`(文件传输助手)。**不做昵称解析**,先调 `/api/v1/resolve?q=张三` 换 wxid |
| `type` | 否 | `text`(默认)/ `image` / `voice` |
| `type` | 否 | `text`(默认)/ `image` / `voice` / `file` |
| `text` | `type=text` 时必填 | **最长 2000 字符**,超限返回 `400`,不会截断 |
| `filePath` | `type=image\|voice` 时必填 | 本机**绝对路径**,必须已存在。不接受 URL —— 需要发网络图片时先落盘 |
| `filePath` | `type=image\|voice\|file` 时必填 | 本机**绝对路径**,必须已存在。不接受 URL —— 需要发网络文件时先落盘 |
| `fileName` | 否 | 仅 `type=file`:接收方看到的文件名。macOS 会透传;Windows 当前由 runtime 使用 `filePath` 的 basename,`fileName` 可能被忽略 |
| `isGroup` | 否 | 通常可省略;`to` 以 `@chatroom` 结尾时自动判为群 |
| `idempotencyKey` | 否 | 幂等键。**重试时请原样带上**,避免 Agent 超时重发导致重复消息 |
+4 -3
View File
@@ -1,6 +1,6 @@
---
name: tracememo-reader
version: 1.4.0
version: 1.4.1
description: 本机微信聊天记录的读取入口(TraceMemo 本地 HTTP API,默认 http://127.0.0.1:6131/api/v1)。凡是「看微信内容」的请求都必须先走本 Skill:某个群或某人今天聊了什么、刚刚聊了啥、最近消息、谁说了什么、总结聊天、翻历史记录、撤回的消息、图片内容、语音转文字、查找联系人或群聊、群成员、生成群聊总结、定时日报、给好友或群发微信消息、查看发送记录、查看未读。本 Skill 已处理鉴权、撤回归档、图片媒体、语音转写与压缩编码解码,当用户要求查看微信消息、查找联系人或群聊、总结聊天、查看或理解图片、生成群聊总结、查询或修改定时日报、给好友或群发送微信消息、代发消息、查看发送记录时使用。此 Skill 由本机 TraceMemo 提供数据,不是 MCP Server。
---
@@ -123,9 +123,10 @@ curl -H "Authorization: Bearer $TRACEMEMO_API_TOKEN" \
| 字段 | 必填 | 说明 |
| ---------------- | ------------------ | ------------------------------------------------------------------- |
| `to` | 是 | wxid / `xxx@chatroom` / `filehelper`;以 `@chatroom` 结尾自动判为群 |
| `type` | 否 | `text`(默认)/ `image` / `voice` |
| `type` | 否 | `text`(默认)/ `image` / `voice` / `file` |
| `text` | `type=text` 时必填 | **最多 2000 字符**,超限返回 `400`,不会自动截断 |
| `filePath` | `type=image/voice` | 本机**绝对路径**且文件必须存在;**不接受 URL** |
| `filePath` | `type=image/voice/file` | 本机**绝对路径**且文件必须存在;**不接受 URL** |
| `fileName` | 否 | 仅 `type=file`:macOS 透传名称;Windows 当前可能忽略,按路径 basename 发送 |
| `idempotencyKey` | 否 | 重试时原样带回,避免超时重发产生重复消息 |
几个必须遵守的限制:
+9 -2
View File
@@ -39,6 +39,7 @@ import { LocalAgentApiError, LocalAgentApiService } from './services/local-agent
import { wechatActionGateway } from './services/wechat-action-gateway'
import type { WechatActionRequest, WechatActionResult } from '../shared/wechat-action'
import type { PersonalWechatSendCapability } from '../shared/personal-wechat'
import { WECHAT_SEND_TYPES, type WechatSendType } from '../shared/wechat-send'
import type { GroupStatsService } from './services/group-stats-service'
import { encodeMessageRef } from '../shared/local-query-api'
import type {
@@ -48,6 +49,7 @@ import type {
} from '../shared/voice-recognition'
import { voiceMessageReferenceOf } from './voice-pipeline/voice-message-identity'
import type {
MessageBackfillReport,
MessageBrokerStatus,
MessageEventBroker,
MessageEventRecord,
@@ -622,8 +624,9 @@ const WECHAT_SEND_MAX_TEXT_LENGTH = 2_000
const WECHAT_SEND_MAX_RECIPIENT_LENGTH = 512
const WECHAT_SEND_MAX_IDEMPOTENCY_KEY_LENGTH = 200
const WECHAT_SEND_CONTENT_TYPES = ['text', 'image', 'voice', 'file'] as const
type WechatSendContentType = (typeof WECHAT_SEND_CONTENT_TYPES)[number]
// 白名单真源在 `shared/wechat-send.ts`;这里只做别名,避免第二份清单漂移。
const WECHAT_SEND_CONTENT_TYPES = WECHAT_SEND_TYPES
type WechatSendContentType = WechatSendType
interface WechatSendApiDependencies {
getCapability: () => Promise<PersonalWechatSendCapability>
@@ -1564,6 +1567,10 @@ function createMessageEventsRoute(
},
onGap(gap: MessageGap) {
writeSseFrame(res, { event: 'gap', data: gap })
},
onBackfill(report: MessageBackfillReport) {
// 明确告知客户端这次回补是否被上限截断,不能把部分回补当成全部。
writeSseFrame(res, { event: 'backfill', data: report })
}
}
)
+181 -92
View File
@@ -190,6 +190,7 @@ import {
wechatLocalExitNoticeService
} from './services/wechat-local-exit-notice-service'
import { MessageEventBroker } from './services/message-event-broker'
import { isReadOnlyMode, logReadOnlySkip } from './services/read-only-mode'
import { AgentTaskDispatcher } from './services/agent-task-dispatcher'
import { AgentTaskStore } from './services/agent-task-store'
import {
@@ -400,6 +401,10 @@ let lastMsgInsertReconciledShards = ''
* 清单记下来。渲染层读状态**不会**走到这里 —— GET 必须是纯读。
*/
async function reconcileMsgInsertRulesOnStart(): Promise<void> {
if (isReadOnlyMode()) {
logReadOnlySkip('MsgInsert 启动 reconciliation')
return
}
const scope = resolveMsgInsertScopeInput()
const client = chat.getChatDb()?.getWcdb4Client()
if (!scope || !client) return
@@ -490,6 +495,10 @@ async function reconcileMsgInsertRulesNow(extraRooms: string[] = []): Promise<bo
* 只剩一份的副本);日志只记数量(对象名含 sha1(会话表名) 派生的稳定标识)。
*/
async function cleanupLegacyRecallResidueOnStart(): Promise<void> {
if (isReadOnlyMode()) {
logReadOnlySkip('防撤回残留清理')
return
}
const client = chat.getChatDb()?.getWcdb4Client()
if (!client) return
try {
@@ -719,6 +728,14 @@ function resolveConversationMd5(sessionId: string): string | undefined {
}
let messageEventBroker: MessageEventBroker | null = null
/** 当前绑定的监听器;重开库时先 dispose 再换新,避免重复监听。 */
let activeMessageListener: MessageListenerService | null = null
/** Native Monitor 是否已成功挂上(status.monitor 的唯一来源)。 */
let messageMonitorActive = false
/** 微信进程状态缓存;undefined 表示还没采样过。 */
let wechatProcessRunning: boolean | null = null
/** Automation 的 isListening 闭包读取这个值;重开库后必须跟着更新。 */
let automationListening = false
/**
* 实时事件代理(单例)。
@@ -732,6 +749,9 @@ function ensureMessageEventBroker(): MessageEventBroker {
messageEventBroker = new MessageEventBroker({
resolveConversationId: resolveConversationMd5,
isDatabaseReady: () => chat.isReady(),
getMonitorState: () => (messageMonitorActive ? 'running' : 'stopped'),
getWechatProcessState: () =>
wechatProcessRunning === null ? 'unknown' : wechatProcessRunning ? 'running' : 'stopped',
readMessages: async (sessionIdOrMd5, startTimeSec, endTimeSec, limit) => {
const client = chat.getChatDb()?.getWcdb4Client()
if (!client) return []
@@ -785,6 +805,107 @@ function ensureAgentTaskDispatcher(): AgentTaskDispatcher {
return dispatcher
}
/**
* 把一条 MessageListener 接到所有消费者。
*
* 数据库重开时旧 listener 必须先 dispose,再对新 listener 调用本函数;
* 否则同一条 native event 会被两套监听器各回读一次。
*/
function bindMessageConsumers(listener: MessageListenerService): void {
listener.onMessage((message) => {
// 日志只允许出现「类型 / 群或私聊 / 是否自己发 / @ 数量」这类不可逆标识,
// 不含 wxid、昵称、群名、正文与 source。
console.log(
`[MessageListener] incoming messageType=${message.messageType}` +
` group=${message.isGroup} self=${message.isSelf}` +
` mentions=${message.mentionTargets.length}`
)
/*
* 实时事件是 Automation 之外的第二个消费者,两者互不依赖:
* broker 只搬运已经回读并规范化的消息,不触发自动化、不调 AI。
* 放在 Automation 之前,保证后者异常不会让 SSE 订阅者漏事件。
*/
ensureMessageEventBroker().publish(message)
try {
void agentTaskDispatcher?.handleMessage(message).catch((error) => {
console.warn(
`[AgentTask] handleMessage failed: ${
error instanceof Error ? error.message : String(error)
}`
)
})
} catch (error) {
console.warn(
`[AgentTask] 未初始化,已跳过本次消息: ${
error instanceof Error ? error.message : String(error)
}`
)
}
// Automation 自带 isSelf / cooldown / 同消息幂等三重闸,不会形成回复循环。
// 用 try 包住同步那一段:`getAutomationService()` 在未初始化时会抛,
// 而 `.catch()` 只能接住异步拒绝 —— 漏了这层就会把异常抛进 MessageListener 的投递循环。
try {
void getAutomationService()
.handleMessage(message)
.catch((error) => {
console.warn(
`[Automation] handleMessage failed: ${
error instanceof Error ? error.message : String(error)
}`
)
})
} catch (error) {
console.warn(
`[Automation] 未初始化,已跳过本次消息: ${
error instanceof Error ? error.message : String(error)
}`
)
}
/*
* 扩展事件分发:与 Automation 并行、互不影响。
* 扩展侧的异常不能污染 MessageListener 的投递循环,也不能阻断 Automation。
*/
if (hasExtensionManager()) {
try {
getExtensionManager().handleMessage(message)
} catch (error) {
console.warn(
`[Extension] handleMessage failed: ${
error instanceof Error ? error.message : String(error)
}`
)
}
}
})
}
/**
* 给指定 client 挂上 Native Monitor,并把事件分发给监听器与既有消费者。
*
* 只允许一处调用点存活:重开库前先 `stopMonitor()`,否则两条 monitor 会重复喂事件。
*/
async function startMessageMonitor(
client: Wcdb4Client,
listener: MessageListenerService
): Promise<boolean> {
const monitoring = await client.startMonitor((event) => {
client.invalidateSessionCache()
listener.handleNativeChange(event)
groupExitMonitorService.notifyDatabaseChanged(event.raw)
recallArchiveMonitor?.handleDatabaseChange(event.raw)
for (const window of BrowserWindow.getAllWindows()) {
if (!window.isDestroyed()) {
window.webContents.send('wcdb-change', { type: event.type, json: event.raw })
}
}
})
automationListening = monitoring === true
messageMonitorActive = monitoring === true
// 只读测试模式连本地退群监控状态也不落盘;SSE 不依赖它。
if (!isReadOnlyMode()) void groupExitMonitorService.start(monitoring)
return monitoring
}
type ColdImageLoadItem = {
priority: number
sequence: number
@@ -854,6 +975,10 @@ function configureRecallProtection(
enabled: boolean,
installJournal = false
): void {
if (enabled && isReadOnlyMode()) {
logReadOnlySkip('防撤回保护写入')
enabled = false
}
recallProtectionGeneration += 1
const generation = recallProtectionGeneration
recallArchiveMonitor?.stop()
@@ -1211,6 +1336,22 @@ app.whenReady().then(async () => { if (isLegacyMigrationHelper) {
// 此时 SSE 应当能如实报告 database=unavailable,而不是把连接打回 503。
ensureMessageEventBroker()
ensureAgentTaskDispatcher()
/*
* 微信进程状态只用于 SSE status 的区分展示;每 5s 采样一次并缓存,
* 避免每次 status() 都去 spawn 探针。
*/
const refreshWechatProcessState = (): void => {
void isWechatRunning()
.then((running) => {
wechatProcessRunning = running
})
.catch(() => {
wechatProcessRunning = null
})
}
refreshWechatProcessState()
const wechatProcessTimer = setInterval(refreshWechatProcessState, 5_000)
wechatProcessTimer.unref?.()
const migration = isUserDataIsolated ? null : await runFirstLaunchMigration(appDataRoots)
apiTokenStore.setAutomaticGenerationBlocked(migration?.tokenBlockReason)
if (!migration) {
@@ -1739,14 +1880,15 @@ app.whenReady().then(async () => { if (isLegacyMigrationHelper) {
* 不匹配关键词、不判断 @我、不出日报、不回复、不调 AI / Agent、不发送。
* 业务响应由上层消费者自行订阅,不在监听层实现。
*/
activeMessageListener?.dispose()
const messageListener = new MessageListenerService(wcdb4Client)
activeMessageListener = messageListener
/**
* Automation v1(@我生成日报)。
*
* `isListening` 反映 `startMonitor` 的实际结果,因此通过闭包读取,
* 而不是在初始化时传入快照。
*/
let automationListening = false
initAutomationService(wcdb4Client, { isListening: () => automationListening })
/**
@@ -1836,92 +1978,14 @@ app.whenReady().then(async () => { if (isLegacyMigrationHelper) {
})
/* 把「微信内退群监控消息」的开关交给 monitor:开着时检测范围扩到全部群聊。 */
syncExitNoticeScope()
messageListener.onMessage((message) => {
// 日志只允许出现「类型 / 群或私聊 / 是否自己发 / @ 数量」这类不可逆标识,
// 不含 wxid、昵称、群名、正文与 source。
console.log(
`[MessageListener] incoming messageType=${message.messageType}` +
` group=${message.isGroup} self=${message.isSelf}` +
` mentions=${message.mentionTargets.length}`
)
/*
* 实时事件是 Automation 之外的第二个消费者,两者互不依赖:
* broker 只搬运已经回读并规范化的消息,不触发自动化、不调 AI。
* 放在 Automation 之前,保证后者异常不会让 SSE 订阅者漏事件。
*/
ensureMessageEventBroker().publish(message)
try {
void agentTaskDispatcher?.handleMessage(message).catch((error) => {
console.warn(
`[AgentTask] handleMessage failed: ${
error instanceof Error ? error.message : String(error)
}`
)
})
} catch (error) {
console.warn(
`[AgentTask] 未初始化,已跳过本次消息: ${
error instanceof Error ? error.message : String(error)
}`
)
}
// Automation 自带 isSelf / cooldown / 同消息幂等三重闸,不会形成回复循环。
// 用 try 包住同步那一段:`getAutomationService()` 在未初始化时会抛,
// 而 `.catch()` 只能接住异步拒绝 —— 漏了这层就会把异常抛进 MessageListener 的投递循环。
try {
void getAutomationService()
.handleMessage(message)
.catch((error) => {
console.warn(
`[Automation] handleMessage failed: ${
error instanceof Error ? error.message : String(error)
}`
)
})
} catch (error) {
console.warn(
`[Automation] 未初始化,已跳过本次消息: ${
error instanceof Error ? error.message : String(error)
}`
)
}
/*
* 扩展事件分发:与 Automation 并行、互不影响。
* 扩展侧的异常不能污染 MessageListener 的投递循环,也不能阻断 Automation。
*/
if (hasExtensionManager()) {
try {
getExtensionManager().handleMessage(message)
} catch (error) {
console.warn(
`[Extension] handleMessage failed: ${
error instanceof Error ? error.message : String(error)
}`
)
}
}
})
bindMessageConsumers(messageListener)
const sessions = await wcdb4Client.getSessionsAsync({ hydrateDisplayNames: false })
configureRecallProtection(wcdb4Client, resolvedRoot, settings.recallProtectionEnabled)
voiceService = new VoiceService(wcdb4Client, resolvedRoot)
voiceRecognition?.connect(voiceService, resolvedRoot)
stickerService = new StickerService(wcdb4Client)
videoAssetService = new VideoAssetService(wcdb4Client)
const monitoring = await wcdb4Client.startMonitor((event) => {
wcdb4Client.invalidateSessionCache()
// 正式 MessageListener:只做 coalesce + 有界回读 + dedup + 投递,不触发业务。
// v2 事件带 sessionId ⇒ 回读不再依赖「最近活跃会话」。
messageListener.handleNativeChange(event)
groupExitMonitorService.notifyDatabaseChanged(event.raw)
recallArchiveMonitor?.handleDatabaseChange(event.raw)
for (const window of BrowserWindow.getAllWindows()) {
if (!window.isDestroyed()) {
window.webContents.send('wcdb-change', { type: event.type, json: event.raw })
}
}
})
automationListening = monitoring === true
void groupExitMonitorService.start(monitoring)
const monitoring = await startMessageMonitor(wcdb4Client, messageListener)
const recentSession = sessions[0]
if (recentSession?.username) {
void wcdb4Client
@@ -3592,22 +3656,47 @@ app.whenReady().then(async () => { if (isLegacyMigrationHelper) {
ipcMain.handle('db:reopenWithRoot', async (_, accountRoot: string) => {
groupExitMonitorService.stop()
const previousClient = chat.getChatDb()?.getWcdb4Client()
const previousListener = activeMessageListener
try {
// 先停旧 monitor,避免重开期间两条监听同时喂事件。
previousClient?.stopMonitor()
} catch (error) {
console.warn('[db:reopenWithRoot] 停止旧 monitor 失败:', error)
}
const ok = chat.reopenWithRoot(accountRoot)
if (!ok) return { success: false, error: '数据库未初始化或重新打开失败' }
if (!ok) {
// 重开失败:把旧监听恢复,不能让 SSE 因为一次失败的重开而静默停更。
if (previousClient && previousListener) {
await startMessageMonitor(previousClient, previousListener).catch((error) =>
console.warn('[db:reopenWithRoot] 恢复旧 monitor 失败:', error)
)
}
return { success: false, error: '数据库未初始化或重新打开失败' }
}
// 旧 listener 绑定的是旧 WechatDb;必须 dispose,否则同一事件会被回读两次。
previousListener?.dispose()
activeMessageListener = null
messageMonitorActive = false
automationListening = false
/*
* 旧缓冲属于旧库/旧账号,不能再被重放;保留订阅者与序号,
* 客户端的旧游标会落到新 buffer 下界之前,从而收到 gap。
*/
messageEventBroker?.resetBuffer()
const client = chat.getChatDb()?.getWcdb4Client()
if (client) {
voiceService = new VoiceService(client, client.getAccountRoot())
voiceRecognition?.connect(voiceService, client.getAccountRoot())
const monitoring = await client.startMonitor((event) => {
client.invalidateSessionCache()
groupExitMonitorService.notifyDatabaseChanged(event.raw)
for (const window of BrowserWindow.getAllWindows()) {
if (!window.isDestroyed()) {
window.webContents.send('wcdb-change', { type: event.type, json: event.raw })
}
}
})
void groupExitMonitorService.start(monitoring)
// Automation 持有 client 引用;重开库必须重建,否则仍在读旧句柄。
initAutomationService(client, { isListening: () => automationListening })
const listener = new MessageListenerService(client)
activeMessageListener = listener
bindMessageConsumers(listener)
await startMessageMonitor(client, listener)
}
// 同步 imageKeyRoot,避免自动获取扫描到旧目录
const settings = loadSettings()
+13
View File
@@ -16,6 +16,7 @@ import { buildEventId } from '../extensions/extension-event-bus'
import type { PersonalWechatSendCapability } from '../../shared/personal-wechat'
import type { Wcdb4Client } from '../wcdb4-client'
import type { NormalizedIncomingMessage } from './message-listener-service'
import { isReadOnlyMode, logReadOnlySkip } from './read-only-mode'
import { getSelfAccountInfo, listContacts } from './chat-service'
import { getPersonalWechatSendCapability } from './personal-wechat-capability-service'
import {
@@ -213,6 +214,10 @@ export class AutomationService {
* 抛出去会影响后续监听者。
*/
async handleMessage(message: NormalizedIncomingMessage): Promise<void> {
if (isReadOnlyMode()) {
logReadOnlySkip('自动化消息处理')
return
}
let rules: AutomationRule[]
try {
rules = this.ruleStore.listRules()
@@ -340,6 +345,10 @@ export class AutomationService {
* 该事件的幂等位(用户随后真的补勾了那个群,反而发不出去)。
*/
async handleGroupExit(event: GroupMemberExitedEvent): Promise<void> {
if (isReadOnlyMode()) {
logReadOnlySkip('退群自动化通知')
return
}
const eventId = String(event?.eventId || '').trim()
let rule: AutomationRule | undefined
try {
@@ -474,6 +483,10 @@ export class AutomationService {
ruleId: string,
options: { trigger: 'schedule' | 'manual'; scheduledSlot?: string }
): Promise<ScheduledRuleRunOutcome> {
if (isReadOnlyMode()) {
logReadOnlySkip('定时日报执行')
return { executed: false, reason: 'read_only' }
}
const key = String(ruleId || '').trim()
if (!key) return { executed: false, reason: 'missing_rule' }
+99 -6
View File
@@ -73,14 +73,43 @@ export interface MessageEventRecord {
mentionTargets: string[]
}
export type MessageRuntimeState = 'running' | 'stopped' | 'unknown'
export interface MessageBrokerStatus {
/** TraceMemo 自己的数据库句柄是否可用;**不等于**微信进程在运行。 */
database: 'ready' | 'unavailable'
/** Native Monitor 是否已成功挂上。 */
monitor: MessageRuntimeState
/** 微信进程状态(缓存采样,非实时探针)。 */
wechat: MessageRuntimeState
subscribers: number
buffered: number
oldestSeq: number | null
newestSeq: number | null
}
/**
* 一次数据库回补的结果。
*
* `truncated=true` 表示**至少有一个上限命中**,客户端必须知道这段空档没有补全:
* - `messageTruncated`:某会话返回行数达到 `perConversationLimit`;
* - `conversationTruncated`:订阅的会话数超过 `maxConversations`,后面的被跳过。
*/
export interface MessageBackfillReport {
requestedConversations: number
processedConversations: number
delivered: number
failedConversations: number
conversationTruncated: boolean
messageTruncated: boolean
truncated: boolean
/** 是否完整:没有截断、没有会话读取失败。客户端应优先看这个字段。 */
complete: boolean
perConversationLimit: number
maxConversations: number
windowSec: number
}
export interface MessageGap {
reason: 'buffer_overflow' | 'invalid_cursor' | 'cursor_from_previous_process'
requestedLastEventId: string
@@ -99,6 +128,8 @@ export interface MessageEventSink {
onStatus(status: MessageBrokerStatus & { subscriptionId: string }): void
onEvent(event: MessageEventRecord, origin: MessageEventOrigin): void
onGap(gap: MessageGap): void
/** 回补结束后的完整性报告;旧适配器可以不实现。 */
onBackfill?(report: MessageBackfillReport): void
}
export interface MessageSubscribeOptions {
@@ -128,6 +159,10 @@ export interface MessageEventBrokerOptions {
resolveConversationId: (sessionId: string) => string | undefined
/** 数据库当前是否可用。用于 status 事件,不做连接管理。 */
isDatabaseReady?: () => boolean
/** Native Monitor 当前状态。未注入时 status 报 `unknown`。 */
getMonitorState?: () => MessageRuntimeState
/** 微信进程状态(调用方应缓存,避免 status 每次都 spawn 探针)。 */
getWechatProcessState?: () => MessageRuntimeState
/** 回补读取器。参数与 `getMessagesAsync(usernameOrMd5, startSec, endSec, {limit})` 一致。 */
readMessages?: (
sessionIdOrMd5: string,
@@ -283,6 +318,8 @@ export class MessageEventBroker {
status(): MessageBrokerStatus {
return {
database: this.options.isDatabaseReady?.() === false ? 'unavailable' : 'ready',
monitor: this.options.getMonitorState?.() ?? 'unknown',
wechat: this.options.getWechatProcessState?.() ?? 'unknown',
subscribers: this.subscribers.size,
buffered: this.buffer.length,
oldestSeq: this.buffer[0]?.seq ?? null,
@@ -290,6 +327,18 @@ export class MessageEventBroker {
}
}
/**
* 清空缓冲与去重表,但**保留订阅者与序号**。
*
* 用于数据库重开 / 切账号:旧事件不能再被重放,客户端的旧游标会自然落到
* `oldestSeq` 之前,从而收到 gap;而已经连着的订阅者不需要断开重连。
*/
resetBuffer(): void {
this.buffer = []
this.index.clear()
this.seen.clear()
}
stats(): typeof this.counters & MessageBrokerStatus {
return { ...this.counters, ...this.status() }
}
@@ -399,14 +448,20 @@ export class MessageEventBroker {
return 'scheduled'
}
/** 执行已经通过 `backfillPlan` 判定的回补。 */
/** 执行已经通过 `backfillPlan` 判定的回补,并报告是否被上限截断。 */
private async runBackfill(state: SubscriberState): Promise<void> {
if (!state.conversationIds || !this.options.readMessages) return
const nowMs = this.now()
const endSec = Math.floor(nowMs / 1000)
const startSec = endSec - this.backfillLookbackSec
const requestedConversations = state.conversationIds.size
const conversations = Array.from(state.conversationIds).slice(0, this.backfillMaxConversations)
const conversationTruncated = requestedConversations > conversations.length
let delivered = 0
let failedConversations = 0
let messageTruncated = false
for (const conversationId of conversations) {
if (state.closed) return
@@ -415,6 +470,7 @@ export class MessageEventBroker {
try {
rows = await this.options.readMessages(sessionId, startSec, endSec, this.backfillLimit)
} catch (error) {
failedConversations += 1
console.warn(
`[MessageEventBroker] backfill read failed: ${
error instanceof Error ? error.message : String(error)
@@ -422,6 +478,11 @@ export class MessageEventBroker {
)
continue
}
/*
* 返回行数达到 limit 就按「可能被截断」上报:多读一条的代价没有必要,
* 但把「正好读满」当成完整回补,会让客户端误以为没有漏消息。
*/
if (rows.length >= this.backfillLimit) messageTruncated = true
for (const row of rows) {
if (state.closed) return
const normalized = normalizeIncomingMessage(sessionId, row)
@@ -432,9 +493,34 @@ export class MessageEventBroker {
record.seq = this.nextSeq
this.nextSeq += 1
this.counters.backfilled += 1
delivered += 1
this.deliver(state, record, 'db_backfill')
}
}
if (state.closed) return
const report: MessageBackfillReport = {
requestedConversations,
processedConversations: conversations.length,
delivered,
failedConversations,
conversationTruncated,
messageTruncated,
truncated: conversationTruncated || messageTruncated,
complete: !conversationTruncated && !messageTruncated && failedConversations === 0,
perConversationLimit: this.backfillLimit,
maxConversations: this.backfillMaxConversations,
windowSec: this.backfillLookbackSec
}
try {
state.sink.onBackfill?.(report)
} catch (error) {
console.warn(
`[MessageEventBroker] backfill report sink threw: ${
error instanceof Error ? error.message : String(error)
}`
)
}
}
private deliverLive(record: MessageEventRecord): void {
@@ -475,9 +561,16 @@ export class MessageEventBroker {
this.counters.unmapped += 1
return null
}
/*
* 消息身份必须是 `create_time:local_id`:
* `local_id` 只在单库/单分片内唯一,跨分片会重复;只带 localId 的 ref
* 会让 `/query/message-context` 判 `ambiguous_message`。
* `locateMessageAsync` 已经支持复合身份,这里与 Knowledge 的 `local:${time}:${id}` 同口径。
*/
const identity = `${message.createTime}:${message.localId}`
let messageRef: string
try {
messageRef = encodeMessageRef(conversationId, message.localId)
messageRef = encodeMessageRef(conversationId, identity)
} catch (error) {
this.counters.rejected += 1
console.warn(
@@ -491,7 +584,7 @@ export class MessageEventBroker {
const rawText = message.content ?? ''
const truncated = rawText.length > this.maxTextChars
return {
id: eventIdFor(conversationId, message.localId),
id: eventIdFor(conversationId, identity),
seq: 0,
conversationId,
messageRef,
@@ -548,10 +641,10 @@ export class MessageEventBroker {
}
}
/** 同一会话 + 同一条消息的确定性事件 ID。 */
export function eventIdFor(conversationId: string, localId: string): string {
/** 同一会话 + 同一条消息的确定性事件 ID。`messageIdentity` 为 `createTime:localId`。 */
export function eventIdFor(conversationId: string, messageIdentity: string): string {
return `evt_${createHash('sha256')
.update(`${conversationId}\u0000${localId}`, 'utf8')
.update(`${conversationId}\u0000${messageIdentity}`, 'utf8')
.digest('hex')
.slice(0, 24)}`
}
@@ -50,6 +50,10 @@ const DEFAULT_READ_LIMIT = 50
const DEFAULT_DEDUP_TTL_MS = 5 * 60 * 1000
/** dedup 容量上限,防止长时间运行后无限增长。 */
const DEFAULT_DEDUP_MAX_ENTRIES = 5_000
/** 未稳定发送行的重试间隔与最大等待时间,避免把写库中间态误判为对方来信。 */
const DEFAULT_SETTLE_RETRY_MS = 400
const DEFAULT_MAX_SETTLE_WAIT_MS = 2_000
const SYSTEM_MESSAGE_TYPES = new Set([10000, 10002])
/**
* 规范化后的入站消息。
@@ -112,6 +116,8 @@ export interface MessageListenerOptions {
readLimit?: number
dedupTtlMs?: number
dedupMaxEntries?: number
settleRetryMs?: number
maxSettleWaitMs?: number
}
/**
@@ -225,6 +231,28 @@ export function normalizeIncomingMessage(
}
}
/**
* 判断消息是否处于微信两阶段写库的中间态(发送中或尚未回填发送者与 server_id)。
* 提前投递会把未稳定的本人发出行误判为 isSelf=false 并锁死去重键。
*/
export function isMessageIdentityUnsettled(
message: Wcdb4Message,
normalized: NormalizedIncomingMessage
): boolean {
if (normalized.isSelf) return false
if (SYSTEM_MESSAGE_TYPES.has(normalized.messageType)) return false
const raw = (message.raw ?? {}) as Record<string, unknown>
const status = raw.status !== undefined && raw.status !== null ? Number(raw.status) : NaN
if (status === 1) return true
const serverId = String(normalized.serverId ?? '').trim()
if (!serverId || serverId === '0') return true
if (!normalized.senderId) return true
return false
}
/**
* 实时消息监听。
*
@@ -255,7 +283,10 @@ export class MessageListenerService {
* 120ms 内收到 `A B A C B` 必须回读 A/B/C 三个,绝不能「最后一个 wins」。
*/
private readonly pendingSessions = new Set<string>()
private readonly pendingUnsettled = new Map<string, number>()
private readonly settleSessions = new Set<string>()
private coalesceTimer: ReturnType<typeof setTimeout> | null = null
private settleTimer: ReturnType<typeof setTimeout> | null = null
private readbackInFlight = false
private pendingReadback = false
private disposed = false
@@ -266,6 +297,8 @@ export class MessageListenerService {
private readonly readLimit: number
private readonly dedupTtlMs: number
private readonly dedupMaxEntries: number
private readonly settleRetryMs: number
private readonly maxSettleWaitMs: number
private counters: MessageListenerStats = {
nativeEvents: 0,
@@ -286,6 +319,8 @@ export class MessageListenerService {
this.readLimit = options.readLimit ?? DEFAULT_READ_LIMIT
this.dedupTtlMs = options.dedupTtlMs ?? DEFAULT_DEDUP_TTL_MS
this.dedupMaxEntries = options.dedupMaxEntries ?? DEFAULT_DEDUP_MAX_ENTRIES
this.settleRetryMs = options.settleRetryMs ?? DEFAULT_SETTLE_RETRY_MS
this.maxSettleWaitMs = options.maxSettleWaitMs ?? DEFAULT_MAX_SETTLE_WAIT_MS
}
/**
@@ -308,8 +343,14 @@ export class MessageListenerService {
clearTimeout(this.coalesceTimer)
this.coalesceTimer = null
}
if (this.settleTimer) {
clearTimeout(this.settleTimer)
this.settleTimer = null
}
this.listeners.clear()
this.seen.clear()
this.pendingUnsettled.clear()
this.settleSessions.clear()
}
/**
@@ -433,9 +474,21 @@ export class MessageListenerService {
if (this.disposed) return 0
let delivered = 0
let needsSettleRetry = false
const now = Date.now()
for (const message of messages) {
const normalized = this.normalize(sessionId, message)
if (!normalized) continue
const key = `${normalized.sessionId}:${normalized.localId}`
if (this.seen.has(key)) {
this.counters.deduped += 1
continue
}
if (this.shouldDeferUnsettled(key, message, normalized, now)) {
needsSettleRetry = true
continue
}
this.pendingUnsettled.delete(key)
// dedup:同一条消息可能在多个读回窗口中反复出现(native 事件本身也可能重复)。
if (!this.markSeen(normalized)) {
this.counters.deduped += 1
@@ -445,9 +498,55 @@ export class MessageListenerService {
delivered += 1
this.deliver(normalized)
}
if (needsSettleRetry) {
this.scheduleSettleRetry(sessionId)
}
return delivered
}
private shouldDeferUnsettled(
key: string,
message: Wcdb4Message,
normalized: NormalizedIncomingMessage,
now: number
): boolean {
if (this.maxSettleWaitMs <= 0 || !isMessageIdentityUnsettled(message, normalized)) {
return false
}
const firstSeenAt = this.pendingUnsettled.get(key)
if (firstSeenAt === undefined) {
this.pendingUnsettled.set(key, now)
if (this.pendingUnsettled.size > this.dedupMaxEntries) {
this.evictUnsettled(now)
}
return true
}
return now - firstSeenAt < this.maxSettleWaitMs
}
private scheduleSettleRetry(sessionId: string): void {
if (this.disposed) return
this.settleSessions.add(sessionId)
if (this.settleTimer) return
this.settleTimer = setTimeout(() => {
this.settleTimer = null
if (this.disposed) return
for (const id of this.settleSessions) {
this.pendingSessions.add(id)
}
this.settleSessions.clear()
void this.readback()
}, this.settleRetryMs)
}
private evictUnsettled(now: number): void {
for (const [key, firstSeenAt] of this.pendingUnsettled) {
if (now - firstSeenAt >= this.maxSettleWaitMs) {
this.pendingUnsettled.delete(key)
}
}
}
private deliver(message: NormalizedIncomingMessage): void {
for (const listener of this.listeners) {
try {
+17 -5
View File
@@ -38,7 +38,7 @@ export const messagesAroundRadii = (
): number[] => (anchorSeconds && anchorSeconds > 0 ? [baseRadius, widenRadius] : [])
/** 有界窗口 + 精确身份定位。窗口按上限截断,绝不返回整段历史。 */
export const sliceMessagesAroundWindow = <T extends { id?: unknown }>(
export const sliceMessagesAroundWindow = <T extends { id?: unknown; createTime?: number }>(
messages: T[],
conversationId: string,
targetMessageId: string,
@@ -46,9 +46,21 @@ export const sliceMessagesAroundWindow = <T extends { id?: unknown }>(
): { window: T[]; index: number; truncated: boolean } => {
const truncated = messages.length > maxWindowMessages
const window = truncated ? messages.slice(0, maxWindowMessages) : messages
const index = window.findIndex(
(message) =>
normalizeMessageIdentity(conversationId, String(message.id ?? ''))?.messageId === targetMessageId
)
const separator = targetMessageId.lastIndexOf(':')
const wantedTime = separator > 0 ? targetMessageId.slice(0, separator) : ''
const wantedLocalId = separator > 0 ? targetMessageId.slice(separator + 1) : ''
const matchesTarget = (message: T): boolean => {
const identity = normalizeMessageIdentity(conversationId, String(message.id ?? ''))
if (!identity) return false
// 裸 localId:旧调用方与 query API 的 `message.id` 都走这条。
if (identity.messageId === targetMessageId) return true
// 复合身份:SSE 的 messageRef 为 `createTime:localId`,必须同时比对时间。
return (
separator > 0 &&
identity.messageId === wantedLocalId &&
String(message.createTime ?? '') === wantedTime
)
}
const index = window.findIndex(matchesTarget)
return { window, index, truncated }
}
@@ -31,6 +31,7 @@ import path from 'node:path'
import { findResource } from '../resource-paths'
import { isMacNativeRuntimeUnavailable, resolveWcdbConfigHelper } from '../native-runtime-paths'
import { resolveExternalComponent } from './external-component-locator'
import { isReadOnlyMode, logReadOnlySkip } from './read-only-mode'
import type { Wcdb4Client } from '../wcdb4-client'
import {
MSG_INSERT_SWITCHES,
@@ -205,6 +206,16 @@ function runHelper(
request: { key: string; rooms: string[]; myWxid: string },
timeoutMs = HELPER_TIMEOUT_MS
): Promise<HelperRunResult> {
// 只读测试模式:任何 helper 写入(开关 / ensure-rules)都不允许发生。
if (isReadOnlyMode()) {
logReadOnlySkip('MsgInsert helper 写入')
return Promise.resolve({
ok: false,
exitCode: null,
errorCode: 'READ_ONLY_MODE',
message: '只读测试模式:禁止写入微信数据库'
})
}
return new Promise((resolve) => {
let child: ReturnType<typeof spawn>
try {
@@ -730,6 +741,10 @@ export async function applyMsgInsertSwitch(
export async function reconcileMsgInsertRules(
input: MsgInsertScopeInput & { myWxid: string; databaseKey: string; extraRooms?: string[] }
): Promise<{ done: boolean; rooms: number; written: number; errorCode?: MsgInsertErrorCode }> {
if (isReadOnlyMode()) {
logReadOnlySkip('MsgInsert reconciliation')
return { done: false, rooms: 0, written: 0, errorCode: 'READ_ONLY_MODE' }
}
if (isMacNativeRuntimeUnavailable()) {
return { done: false, rooms: 0, written: 0, errorCode: 'HELPER_NOT_FOUND' }
}
@@ -13,6 +13,7 @@ import {
import { homedir, tmpdir } from 'os'
import { delimiter, dirname, extname, join, sep, basename } from 'path'
import { resolveBundledFfmpegPath } from '../ffmpeg-path'
import { isReadOnlyMode, logReadOnlySkip } from './read-only-mode'
import { promisify } from 'util'
import type {
PersonalWechatSendRequest,
@@ -809,6 +810,14 @@ export class PersonalWechatSendService {
}
async send(request: PersonalWechatSendRequest): Promise<PersonalWechatSendResult> {
if (isReadOnlyMode()) {
logReadOnlySkip('个人微信发送')
return {
success: false,
status: await this.getStatus(),
error: '只读测试模式:不发送任何微信消息'
}
}
if (process.platform === 'win32') return this.sendWindows(request)
if (process.platform === 'darwin') {
if (request.type === 'text') return this.sendMacText(request)
+26
View File
@@ -0,0 +1,26 @@
/**
* 只读验收模式。
*
* 用于「接真实微信库、但不允许任何写副作用」的验收场景。启用后:
* - 不执行 MsgInsert reconciliation / 规则写入;
* - 不发送任何微信消息(网关直接 blocked);
* - 不执行自动化与定时日报的发送步骤;
* - 不写退群本地提示。
*
* 读取、SSE 订阅、数据库回补不受影响。
*
* 生产模式默认关闭:只有显式设置 `TRACEMEMO_READ_ONLY=1` 才生效。
*/
export const READ_ONLY_ENV = 'TRACEMEMO_READ_ONLY'
const TRUE_VALUES = new Set(['1', 'true', 'yes', 'on'])
export function isReadOnlyMode(): boolean {
const value = process.env[READ_ONLY_ENV]
return typeof value === 'string' && TRUE_VALUES.has(value.trim().toLowerCase())
}
/** 统一日志:只记录被跳过的操作名,不记录会话 / 消息内容。 */
export function logReadOnlySkip(operation: string): void {
console.log(`[ReadOnly] 已跳过 ${operation}`)
}
@@ -2,6 +2,7 @@ import { app } from 'electron'
import { createHash, randomUUID } from 'crypto'
import fs from 'fs-extra'
import path from 'path'
import { isReadOnlyMode } from './read-only-mode'
import type {
PersonalWechatSendCapability,
PersonalWechatSendRequest,
@@ -186,6 +187,22 @@ export class WechatActionGateway {
}
async execute(request: WechatActionRequest): Promise<WechatActionResult> {
/*
* 只读闸门必须在幂等查表**之前**:否则同一个 idempotencyKey 命中历史
* 已发送记录时,会直接返回旧的 sent 结果,看似没发、实际绕过了闸门。
*/
if (isReadOnlyMode()) {
const startedAt = this.deps.now().toISOString()
return {
actionId: String(request?.id || '').trim() || randomUUID(),
status: 'blocked',
decision: 'block',
errorCode: 'READ_ONLY_MODE',
reason: '只读测试模式:不发送任何微信消息',
startedAt,
finishedAt: startedAt
}
}
const normalized = normalizeActionRequest(request)
const idempotencyKey = normalized ? this.idempotencyKey(normalized) : undefined
if (idempotencyKey) {
@@ -35,6 +35,7 @@ import { renderLeaveNotificationText } from '../../shared/group-exit-event'
import { GROUP_EXIT_NOTIFICATION_TEMPLATE } from '../../shared/group-exit-monitor'
import { resolveWcdbConfigHelper } from '../native-runtime-paths'
import { msgInsertCapabilityService } from './msg-insert-capability-service'
import { isReadOnlyMode, logReadOnlySkip } from './read-only-mode'
import { resolveHelperPath } from './msg-insert-switch-service'
export type LocalExitNoticeOutcome =
@@ -140,6 +141,10 @@ export class WechatLocalExitNoticeService {
eventId: event.eventId,
conversationId: event.conversationId
}
if (isReadOnlyMode()) {
logReadOnlySkip('退群本地提示写入')
return { ...base, outcome: 'disabled', code: 'READ_ONLY_MODE' }
}
try {
this.ensureLoaded()
if (!this.enabled) return this.finish({ ...base, outcome: 'disabled', code: 'DISABLED' })
+83 -28
View File
@@ -51,6 +51,25 @@ export interface Wcdb4MessageCursor {
localId: number
}
/**
* 从跨分片命中里选出唯一消息。
*
* `local_id` 只在单库内唯一;同一会话可能横跨多个 message_N.db,同一个
* `local_id` 会命中多条。带 `create_time` 的复合身份才能唯一定位。
*/
export function selectMessageLocation(
hits: Wcdb4MessageCursor[],
wantedTime: number | null
): { status: 'found'; location: Wcdb4MessageCursor } | { status: 'ambiguous' | 'not_found' } {
if (wantedTime !== null) {
const exact = hits.filter((hit) => hit.createTime === wantedTime)
if (exact.length === 1) return { status: 'found', location: exact[0] }
return { status: exact.length > 1 ? 'ambiguous' : 'not_found' }
}
if (hits.length === 1) return { status: 'found', location: hits[0] }
return { status: hits.length > 1 ? 'ambiguous' : 'not_found' }
}
export interface Wcdb4MessagePage {
messages: Wcdb4Message[]
/** 下一页起点;`null` 表示该会话已读完。 */
@@ -2436,28 +2455,68 @@ export class Wcdb4Client {
limit?: number
): Wcdb4Message[] {
const merged = new Map<string, Wcdb4Message>()
const localKeyToPrimary = new Map<string, string>()
const hasUsableServerId = (value?: string): boolean => {
const normalized = String(value || '').trim()
return Boolean(normalized && normalized !== '0')
}
// 同一条消息的两个快照合并时,不能用缺发送者或未回填的旧快照覆盖已确定的本人身份。
const mergePair = (older: Wcdb4Message, newer: Wcdb4Message): Wcdb4Message => ({
...older,
...newer,
serverId: hasUsableServerId(newer.serverId)
? newer.serverId
: hasUsableServerId(older.serverId)
? older.serverId
: newer.serverId || older.serverId,
mesDes: newer.mesDes === 0 || older.mesDes === 0 ? 0 : newer.mesDes,
sender: newer.sender || older.sender,
senderNickname: newer.senderNickname || older.senderNickname,
senderAvatar: newer.senderAvatar || older.senderAvatar,
raw:
older.raw && newer.raw
? {
...older.raw,
...newer.raw
}
: newer.raw || older.raw
})
for (const message of [...recovered, ...current]) {
const recoveredRow = Boolean(message.raw?.['_wxe_recovered'])
const serverId = String(message.serverId || '').trim()
const identity =
serverId && serverId !== '0'
? `server:${serverId}`
: message.mesLocalID
? `local:${message.mesLocalID}:${message.msgCreateTime || 0}`
: `${message.msgCreateTime}:${message.msgContent}`
const localIdentity = message.mesLocalID
? `local:${message.mesLocalID}:${message.msgCreateTime || 0}`
: ''
const identity = hasUsableServerId(serverId)
? `server:${serverId}`
: localIdentity || `${message.msgCreateTime}:${message.msgContent}`
const key = recoveredRow ? `recovered:${identity}` : identity
const existing = merged.get(key)
if (existing?.raw && message.raw) {
merged.set(key, {
...existing,
...message,
raw: {
...existing.raw,
...message.raw
}
})
const localLookupKey = !recoveredRow && localIdentity ? localIdentity : ''
const existingKey =
merged.has(key)
? key
: localLookupKey && localKeyToPrimary.has(localLookupKey)
? localKeyToPrimary.get(localLookupKey)!
: undefined
const existing = existingKey ? merged.get(existingKey) : undefined
if (existing && existingKey) {
const combined = mergePair(existing, message)
const targetKey = hasUsableServerId(combined.serverId)
? recoveredRow
? `recovered:server:${String(combined.serverId).trim()}`
: `server:${String(combined.serverId).trim()}`
: existingKey
if (targetKey !== existingKey) {
merged.delete(existingKey)
}
merged.set(targetKey, combined)
if (localLookupKey) localKeyToPrimary.set(localLookupKey, targetKey)
} else {
merged.set(key, message)
if (localLookupKey) localKeyToPrimary.set(localLookupKey, key)
}
}
const messages = Array.from(merged.values()).sort(
@@ -2947,13 +3006,7 @@ export class Wcdb4Client {
}
}
if (wantedTime !== null) {
const exact = hits.filter((hit) => hit.createTime === wantedTime)
if (exact.length === 1) return { status: 'found', location: exact[0] }
return { status: exact.length > 1 ? 'ambiguous' : 'not_found' }
}
if (hits.length === 1) return { status: 'found', location: hits[0] }
return { status: hits.length > 1 ? 'ambiguous' : 'not_found' }
return selectMessageLocation(hits, wantedTime)
}
private rowCreateTimeSeconds(row: Record<string, unknown>): number {
@@ -4617,20 +4670,22 @@ export class Wcdb4Client {
'computedIsSend',
'is_send',
'isSend',
'mesDes',
'WCDB_CT_is_send'
])
const rawMesDes = this.pickValue(row, ['mesDes', 'mes_des'])
// mesDes=0 表示本人发出,与 is_send 布尔语义相反,必须分开解析。
const parsedIsSend =
rawIsSend === undefined || rawIsSend === null
? false
: this.pickBoolean(row, [
rawIsSend !== undefined && rawIsSend !== null
? this.pickBoolean(row, [
'computed_is_send',
'computedIsSend',
'is_send',
'isSend',
'mesDes',
'WCDB_CT_is_send'
])
: rawMesDes !== undefined && rawMesDes !== null
? Number(rawMesDes) === 0
: false
const isSelfSender = sender
? this.getMyUsernameCandidates().some((candidate) => {
const left = String(candidate || '')
+1
View File
@@ -194,6 +194,7 @@ export type MsgInsertErrorCode =
| 'UNSUPPORTED_SWITCH'
| 'NO_TARGET_ROOMS'
| 'DATABASE_UNAVAILABLE'
| 'READ_ONLY_MODE'
| 'LICENSE_REQUIRED'
| 'LICENSE_PENDING'
| 'LICENSE_EXPIRED'
+13 -1
View File
@@ -8,7 +8,19 @@
export type WechatSendTransport = 'personal' | 'ilink'
export type WechatSendType = 'text' | 'image' | 'voice' | 'file'
/**
* 发送内容类型 —— 运行时白名单的**唯一真源**。
*
* HTTP 路由(`/api/v1/wechat/send`)直接引用这个数组,不再维护第二份。
* 新增类型时必须同步以下契约,否则会出现「代码能发、文档/能力探测说不能」的假缺口:
*
* 1. `docs/agent/api.md` 的「本地发送」字段表(`type` / 路径字段 / 备注);
* 2. `docs/skill/tracememo-reader/SKILL.md` 的 `type` 字段(改完记得提升 frontmatter version);
* 3. `PersonalWechatSendCapability.capabilities` 与各平台的 `send*` 分支;
* 4. `tests/integration/wechat-send-api.test.ts` 增加该类型的请求形状断言。
*/
export const WECHAT_SEND_TYPES = ['text', 'image', 'voice', 'file'] as const
export type WechatSendType = (typeof WECHAT_SEND_TYPES)[number]
/**
* 统一发送请求。
+23 -9
View File
@@ -259,7 +259,13 @@ describe('GET /api/v1/events/messages', () => {
const client = await openSse(handle)
const status = await client.waitFor((frame) => frame.event === 'status')
expect(status.data).toMatchObject({ database: 'ready', filter: 'all', backfill: 'enabled' })
expect(status.data).toMatchObject({
database: 'ready',
monitor: 'unknown',
wechat: 'unknown',
filter: 'all',
backfill: 'enabled'
})
broker.publish(normalize(SESSION_A, '1', '实时消息'))
const message = await client.waitFor((frame) => frame.event === 'message')
@@ -270,10 +276,9 @@ describe('GET /api/v1/events/messages', () => {
text: '实时消息',
isSelf: false
})
expect(decodeMessageRef(String(message.data?.messageRef))).toEqual({
conversationId: CONVERSATION_A,
messageId: '1'
})
const ref = decodeMessageRef(String(message.data?.messageRef))
expect(ref?.conversationId).toBe(CONVERSATION_A)
expect(ref?.messageId).toMatch(/^\d+:1$/)
})
it('同一条消息重复发布只推送一次(事件去重)', async () => {
@@ -344,10 +349,9 @@ describe('GET /api/v1/events/messages', () => {
})
const replayed = await second.waitFor((frame) => frame.event === 'message')
expect(replayed.data).toMatchObject({ origin: 'replay', text: 'hello' })
expect(decodeMessageRef(String(replayed.data?.messageRef))).toEqual({
conversationId: CONVERSATION_A,
messageId: '2'
})
const ref = decodeMessageRef(String(replayed.data?.messageRef))
expect(ref?.conversationId).toBe(CONVERSATION_A)
expect(ref?.messageId).toMatch(/^\d+:2$/)
})
it('缓冲覆盖不到时先发 gap,再从数据库有界回补(origin=db_backfill)', async () => {
@@ -373,6 +377,16 @@ describe('GET /api/v1/events/messages', () => {
(frame) => frame.event === 'message' && frame.data?.origin === 'db_backfill'
)
expect(backfilled.data?.text).toBe('补回来的消息')
const report = await client.waitFor((frame) => frame.event === 'backfill')
expect(report.data).toMatchObject({
requestedConversations: 1,
processedConversations: 1,
delivered: 1,
truncated: false,
complete: true,
messageTruncated: false,
conversationTruncated: false
})
expect(client.frames.findIndex((f) => f.event === 'gap')).toBeLessThan(
client.frames.findIndex((f) => f.event === 'message' && f.data?.origin === 'db_backfill')
)
+26 -1
View File
@@ -64,7 +64,7 @@ function capabilityOf(
supported: true,
ready: true,
status: 'ready',
capabilities: { text: true, image: true, voice: true },
capabilities: { text: true, image: true, voice: true, file: true },
senderStatus: {} as PersonalWechatSendCapability['senderStatus'],
message: '可以发送',
...overrides
@@ -164,6 +164,31 @@ describe('POST /api/v1/wechat/send', () => {
expect(execute).not.toHaveBeenCalled()
})
it('type=file 时接受 filePath 与可选 fileName,并按 file 动作投递', async () => {
const filePath = path.join(root, '周报.txt')
await fs.writeFile(filePath, 'hello')
const response = await post({
to: 'filehelper',
type: 'file',
filePath,
fileName: '周报.txt'
})
expect(response.status).toBe(200)
expect((await response.json()).success).toBe(true)
const action = lastAction()
expect(action.purpose).toBe('api_file')
expect(action.content).toEqual({ type: 'file', path: filePath, name: '周报.txt' })
})
it('type=file 缺少 filePath 时返回 400,不进入投递', async () => {
const response = await post({ to: 'filehelper', type: 'file' })
expect(response.status).toBe(400)
expect((await response.json()).errorCode).toBe('INVALID_REQUEST')
expect(execute).not.toHaveBeenCalled()
})
it('发送能力未就绪时返回 503', async () => {
capability = capabilityOf({
ready: false,
+166 -4
View File
@@ -3,6 +3,7 @@ import {
MessageEventBroker,
eventIdFor,
parseLastEventId,
type MessageBackfillReport,
type MessageEventOrigin,
type MessageEventRecord,
type MessageGap
@@ -53,6 +54,7 @@ interface Collected {
statuses: unknown[]
events: Array<{ event: MessageEventRecord; origin: MessageEventOrigin }>
gaps: MessageGap[]
backfills: MessageBackfillReport[]
order: string[]
}
@@ -61,9 +63,10 @@ function makeSink(): Collected & {
onStatus: (status: unknown) => void
onEvent: (event: MessageEventRecord, origin: MessageEventOrigin) => void
onGap: (gap: MessageGap) => void
onBackfill: (report: MessageBackfillReport) => void
}
} {
const collected: Collected = { statuses: [], events: [], gaps: [], order: [] }
const collected: Collected = { statuses: [], events: [], gaps: [], backfills: [], order: [] }
return {
...collected,
get statuses() {
@@ -75,6 +78,9 @@ function makeSink(): Collected & {
get gaps() {
return collected.gaps
},
get backfills() {
return collected.backfills
},
get order() {
return collected.order
},
@@ -90,6 +96,10 @@ function makeSink(): Collected & {
onGap: (gap) => {
collected.gaps.push(gap)
collected.order.push('gap')
},
onBackfill: (report) => {
collected.backfills.push(report)
collected.order.push('backfill')
}
}
}
@@ -100,6 +110,8 @@ function makeBroker(
bufferSize?: number
dbReady?: boolean
reader?: ReturnType<typeof vi.fn>
backfillLimit?: number
backfillMaxConversations?: number
} = {}
): MessageEventBroker {
return new MessageEventBroker({
@@ -108,6 +120,10 @@ function makeBroker(
isDatabaseReady: () => options.dbReady !== false,
readMessages: options.reader as never,
bufferSize: options.bufferSize ?? 10,
...(options.backfillLimit !== undefined ? { backfillLimit: options.backfillLimit } : {}),
...(options.backfillMaxConversations !== undefined
? { backfillMaxConversations: options.backfillMaxConversations }
: {}),
bufferTtlMs: 10 * 60 * 1000,
now: () => NOW
})
@@ -126,10 +142,26 @@ describe('事件 ID 与 messageRef', () => {
expect(record).not.toBeNull()
expect(decodeMessageRef(record!.messageRef)).toEqual({
conversationId: CONVERSATION,
messageId: '100'
messageId: '1800000000:100'
})
})
it('同一 localId、不同 createTime 是两条消息(复合身份不被 localId 合并)', () => {
const broker = makeBroker()
const first = broker.publish(
normalize(makeRow({ mesLocalID: '7', msgCreateTime: '1800000000' }))
)
const second = broker.publish(
normalize(makeRow({ mesLocalID: '7', msgCreateTime: '1800000100' }))
)
expect(first).not.toBeNull()
expect(second).not.toBeNull()
expect(first!.id).not.toBe(second!.id)
expect(decodeMessageRef(first!.messageRef)!.messageId).toBe('1800000000:7')
expect(decodeMessageRef(second!.messageRef)!.messageId).toBe('1800000100:7')
})
it('无法映射会话时不发布,也不伪造 messageRef', () => {
const broker = makeBroker()
const other = normalizeIncomingMessage('unknown_session', makeRow())
@@ -181,7 +213,7 @@ describe('订阅、过滤与重放', () => {
expect(sink.events.map((item) => item.origin)).toEqual(['replay'])
expect(decodeMessageRef(sink.events[0].event.messageRef)).toEqual({
conversationId: CONVERSATION,
messageId: '2'
messageId: '1800000000:2'
})
})
@@ -261,6 +293,66 @@ describe('订阅、过滤与重放', () => {
expect(startArg).toBeLessThan(endArg)
expect(endArg - startArg).toBeLessThanOrEqual(300)
expect(limitArg).toBeLessThanOrEqual(100)
expect(sink.backfills).toHaveLength(1)
expect(sink.backfills[0]).toMatchObject({
truncated: false,
complete: true,
conversationTruncated: false,
messageTruncated: false,
processedConversations: 1
})
})
it('单会话回补读满 limit 时明确报告 messageTruncated', async () => {
const reader = vi.fn(async () => [
makeRow({ mesLocalID: '21' }),
makeRow({ mesLocalID: '22' })
])
const broker = makeBroker({ bufferSize: 1, reader, backfillLimit: 2 })
for (const id of ['1', '2', '3']) broker.publish(normalize(makeRow({ mesLocalID: id })))
const sink = makeSink()
broker.subscribe({ conversationIds: [CONVERSATION], lastEventId: '1' }, sink.sink)
await vi.waitFor(() => expect(sink.backfills.length).toBe(1))
expect(sink.backfills[0]).toMatchObject({
messageTruncated: true,
conversationTruncated: false,
truncated: true,
complete: false,
perConversationLimit: 2
})
})
it('订阅会话数超过上限时明确报告 conversationTruncated', async () => {
const reader = vi.fn(async () => [makeRow({ mesLocalID: '31' })])
const broker = new MessageEventBroker({
resolveConversationId: (sessionId) => (sessionId === 'A@chatroom' ? 'conv-a' : 'conv-b'),
resolveSessionId: (conversationId) => (conversationId === 'conv-a' ? 'A@chatroom' : 'B@chatroom'),
isDatabaseReady: () => true,
readMessages: reader as never,
bufferSize: 1,
backfillLimit: 10,
backfillMaxConversations: 1,
now: () => NOW
})
for (const id of ['1', '2', '3']) {
broker.publish(normalizeIncomingMessage('A@chatroom', makeRow({ mesLocalID: id }))!)
}
const sink = makeSink()
broker.subscribe({ conversationIds: ['conv-a', 'conv-b'], lastEventId: '1' }, sink.sink)
await vi.waitFor(() => expect(sink.backfills.length).toBe(1))
expect(sink.backfills[0]).toMatchObject({
requestedConversations: 2,
processedConversations: 1,
conversationTruncated: true,
messageTruncated: false,
truncated: true,
complete: false,
maxConversations: 1
})
})
it('没有会话过滤时不做回补(无法有界),并如实说明', () => {
@@ -371,7 +463,7 @@ describe('多订阅者与 Automation 扇出', () => {
for (const sink of sinks) {
expect(sink.events).toHaveLength(1)
expect(sink.events[0].event.id).toBe(eventIdFor(CONVERSATION, 'fanout-1'))
expect(sink.events[0].event.id).toBe(eventIdFor(CONVERSATION, '1800000000:fanout-1'))
}
expect(broker.status().subscribers).toBe(5)
})
@@ -407,3 +499,73 @@ describe('多订阅者与 Automation 扇出', () => {
expect(broker.stats().published).toBe(1)
})
})
describe('运行状态区分', () => {
it('database / monitor / wechat 分别报告,不互相冒充', () => {
const broker = new MessageEventBroker({
resolveConversationId: () => CONVERSATION,
isDatabaseReady: () => true,
getMonitorState: () => 'running',
getWechatProcessState: () => 'stopped',
now: () => NOW
})
expect(broker.status()).toMatchObject({
database: 'ready',
monitor: 'running',
wechat: 'stopped'
})
})
it('未注入 monitor/wechat 时是 unknown,而不是默认 ready', () => {
const broker = new MessageEventBroker({
resolveConversationId: () => CONVERSATION,
now: () => NOW
})
expect(broker.status()).toMatchObject({ monitor: 'unknown', wechat: 'unknown' })
})
})
describe('重开库缓冲重置', () => {
it('resetBuffer 清空缓冲但保留订阅者,新事件序号继续递增', () => {
const broker = makeBroker()
const sink = makeSink()
broker.subscribe({}, sink.sink)
broker.publish(normalize(makeRow({ mesLocalID: '1' })))
broker.publish(normalize(makeRow({ mesLocalID: '2' })))
expect(broker.status()).toMatchObject({ buffered: 2, subscribers: 1 })
broker.resetBuffer()
expect(broker.status()).toMatchObject({
buffered: 0,
oldestSeq: null,
newestSeq: null,
subscribers: 1
})
broker.publish(normalize(makeRow({ mesLocalID: '3' })))
expect(broker.status().newestSeq).toBe(3)
expect(sink.events.map((item) => item.event.seq)).toEqual([1, 2, 3])
})
})
describe('回补失败也必须标记不完整', () => {
it('会话读取抛错时 complete=false,且不是 truncated 语义', async () => {
const reader = vi.fn(async () => {
throw new Error('shard unavailable')
})
const broker = makeBroker({ bufferSize: 1, reader })
for (const id of ['1', '2', '3']) broker.publish(normalize(makeRow({ mesLocalID: id })))
const sink = makeSink()
broker.subscribe({ conversationIds: [CONVERSATION], lastEventId: '1' }, sink.sink)
await vi.waitFor(() => expect(sink.backfills.length).toBe(1))
expect(sink.backfills[0]).toMatchObject({
failedConversations: 1,
truncated: false,
complete: false,
delivered: 0
})
})
})
+132
View File
@@ -4,6 +4,8 @@ import {
MessageListenerService,
decodeSourcePayload,
extractMentionTargets,
isMessageIdentityUnsettled,
normalizeIncomingMessage,
type NormalizedIncomingMessage
} from '../../src/main/services/message-listener-service'
import { parseMonitorEvent } from '../../src/main/wcdb4-client'
@@ -695,3 +697,133 @@ describe('MessageListener · 回读进行中到达的事件', () => {
expect(listener.stats().readbacks).toBe(3)
})
})
describe('两阶段写库未稳定行延迟确认', () => {
const v2Event = (sessionId: string): ReturnType<typeof parseMonitorEvent> =>
parseMonitorEvent(
JSON.stringify({ version: 2, kind: 'message_change', session_id: sessionId, table: 'message' })
)
it('发送中中间态(status=1 / 缺 serverId / 缺 sender)暂缓投递,回填后再以 isSelf=true 投递', async () => {
let phase = 0
const client = {
getSessions: vi.fn(() => [{ username: SESSION_DIRECT }]),
getMessagesAsync: vi.fn(async () => {
phase += 1
if (phase === 1) {
return [
makeMessage({
mesLocalID: '501',
serverId: '0',
mesDes: 1,
sender: '',
raw: { status: 1 }
})
]
}
return [
makeMessage({
mesLocalID: '501',
serverId: '7000000000000000501',
mesDes: 0,
sender: 'SELF_USER',
raw: { status: 2 }
})
]
})
} as unknown as Wcdb4Client
const listener = new MessageListenerService(client, {
settleRetryMs: 400,
maxSettleWaitMs: 2_000
})
collect(listener)
listener.handleNativeChange(v2Event(SESSION_DIRECT))
await flush(200)
expect(received).toHaveLength(0)
await flush(450)
expect(received).toHaveLength(1)
expect(received[0].localId).toBe('501')
expect(received[0].isSelf).toBe(true)
expect(received[0].serverId).toBe('7000000000000000501')
})
it('超过最大等待时间仍未回填的未稳定行会兜底放行,不会永久丢消息', async () => {
const unsettled = makeMessage({
mesLocalID: '502',
serverId: undefined,
mesDes: 1,
sender: '',
raw: { status: 1 }
})
const client = makeClient([unsettled], SESSION_DIRECT)
const listener = new MessageListenerService(client, {
settleRetryMs: 300,
maxSettleWaitMs: 900
})
collect(listener)
listener.handleNativeChange(v2Event(SESSION_DIRECT))
await flush(200)
expect(received).toHaveLength(0)
await flush(1_200)
expect(received).toHaveLength(1)
expect(received[0].localId).toBe('502')
})
it('正常外部入站消息与系统消息不进入延迟暂存,立即投递', async () => {
const incoming = makeMessage({
mesLocalID: '503',
serverId: '7000000000000000503',
mesDes: 1,
sender: 'OTHER_USER',
raw: { status: 3 }
})
const systemMsg = makeMessage({
mesLocalID: '504',
serverId: undefined,
mesDes: 1,
messageType: '10000',
sender: '',
raw: {}
})
const normIncoming = normalizeIncomingMessage(SESSION_DIRECT, incoming)!
const normSystem = normalizeIncomingMessage(SESSION_DIRECT, systemMsg)!
expect(isMessageIdentityUnsettled(incoming, normIncoming)).toBe(false)
expect(isMessageIdentityUnsettled(systemMsg, normSystem)).toBe(false)
const client = makeClient([incoming, systemMsg], SESSION_DIRECT)
const listener = new MessageListenerService(client)
collect(listener)
listener.handleNativeChange(v2Event(SESSION_DIRECT))
await flush(200)
expect(received.map((m) => m.localId)).toEqual(['503', '504'])
expect(listener.stats().readbacks).toBe(1)
})
it('dispose 会取消待执行的未稳定行重试定时器', async () => {
const unsettled = makeMessage({
mesLocalID: '505',
serverId: '0',
mesDes: 1,
sender: '',
raw: { status: 1 }
})
const client = makeClient([unsettled], SESSION_DIRECT)
const listener = new MessageListenerService(client, { settleRetryMs: 400 })
collect(listener)
listener.handleNativeChange(v2Event(SESSION_DIRECT))
await flush(200)
expect(listener.stats().readbacks).toBe(1)
listener.dispose()
await flush(1_000)
expect(listener.stats().readbacks).toBe(1)
expect(received).toHaveLength(0)
})
})
+31
View File
@@ -0,0 +1,31 @@
import { describe, expect, it } from 'vitest'
import { sliceMessagesAroundWindow } from '../../src/main/services/messages-around'
/**
* 消息跳转的身份匹配。
*
* 裸 `localId` 与 `createTime:localId` 都必须支持;后者是 SSE messageRef 的格式。
*/
describe('sliceMessagesAroundWindow', () => {
const messages = [
{ id: '7', createTime: 1_795_158_000, text: '前一天' },
{ id: '7', createTime: 1_795_158_061, text: '目标' },
{ id: '8', createTime: 1_795_158_062, text: '后一条' }
]
it('复合身份同时匹配 createTime 与 localId,选中正确的那一条', () => {
const result = sliceMessagesAroundWindow(messages, 'conv', '1795158061:7')
expect(result.index).toBe(1)
expect(result.window[result.index]).toMatchObject({ text: '目标' })
})
it('只有 localId 时保持旧行为(第一条匹配)', () => {
const result = sliceMessagesAroundWindow(messages, 'conv', '7')
expect(result.index).toBe(0)
})
it('时间不匹配时不会误选另一条同 localId 的消息', () => {
const result = sliceMessagesAroundWindow(messages, 'conv', '1795158999:7')
expect(result.index).toBe(-1)
})
})
+144
View File
@@ -0,0 +1,144 @@
import os from 'node:os'
import path from 'node:path'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
vi.mock('electron', () => ({
app: { getPath: () => '/tmp/tracememo-readonly-test' }
}))
import { READ_ONLY_ENV, isReadOnlyMode } from '../../src/main/services/read-only-mode'
import { WechatActionGateway } from '../../src/main/services/wechat-action-gateway'
import { reconcileMsgInsertRules } from '../../src/main/services/msg-insert-switch-service'
import { AutomationService } from '../../src/main/services/automation-service'
import { personalWechatSendService } from '../../src/main/services/personal-wechat-send-service'
import { wechatLocalExitNoticeService } from '../../src/main/services/wechat-local-exit-notice-service'
/**
* 只读闸门的有效性:不是「复制了 profile」,而是真实写入入口被短路。
*/
const original = process.env[READ_ONLY_ENV]
beforeEach(() => {
delete process.env[READ_ONLY_ENV]
})
afterEach(() => {
if (original === undefined) delete process.env[READ_ONLY_ENV]
else process.env[READ_ONLY_ENV] = original
})
describe('isReadOnlyMode', () => {
it('默认关闭,只有显式真值才开启', () => {
expect(isReadOnlyMode()).toBe(false)
for (const value of ['1', 'true', 'YES', 'on']) {
process.env[READ_ONLY_ENV] = value
expect(isReadOnlyMode()).toBe(true)
}
for (const value of ['0', 'false', '', 'off']) {
process.env[READ_ONLY_ENV] = value
expect(isReadOnlyMode()).toBe(false)
}
})
})
describe('只读模式下的写入入口', () => {
it('发送网关直接 blocked,不调用底层 send', async () => {
process.env[READ_ONLY_ENV] = '1'
const send = vi.fn()
const gateway = new WechatActionGateway({
getCapability: vi.fn() as never,
send: send as never,
getUserDataPath: () => path.join(os.tmpdir(), 'tracememo-readonly-test'),
now: () => new Date('2026-11-20T00:00:00.000Z'),
wait: async () => undefined
})
const result = await gateway.execute({
origin: 'http_api',
purpose: 'manual_text',
triggerType: 'user',
recipient: { type: 'contact', id: 'filehelper' },
content: { type: 'text', text: '必须被拦住' }
})
expect(result.status).toBe('blocked')
expect(result.errorCode).toBe('READ_ONLY_MODE')
expect(send).not.toHaveBeenCalled()
})
it('MsgInsert reconciliation 不 spawn helper,直接返回 READ_ONLY_MODE', async () => {
process.env[READ_ONLY_ENV] = '1'
const result = await reconcileMsgInsertRules({
client: {} as never,
monitoredRoomIds: [],
myWxid: 'wxid_fixture',
databaseKey: 'key_fixture'
})
expect(result).toEqual({
done: false,
rooms: 0,
written: 0,
errorCode: 'READ_ONLY_MODE'
})
})
it('Automation 不读规则、不执行定时任务', async () => {
process.env[READ_ONLY_ENV] = '1'
const listRules = vi.fn(() => [])
const ruleStore = { listRules, getRule: vi.fn() } as never
const service = new AutomationService({} as never, {
ruleStore,
executionLog: { record: vi.fn() } as never,
runner: {} as never,
isListening: () => true
})
await service.handleMessage({
sessionId: 'fixture@chatroom',
localId: '1',
createTime: 1_800_000_000,
messageType: 1,
isSelf: false,
content: '@机器人 日报',
isGroup: true,
mentionTargets: []
})
expect(listRules).not.toHaveBeenCalled()
await expect(
service.executeScheduledRule('rule-1', { trigger: 'schedule' })
).resolves.toEqual({ executed: false, reason: 'read_only' })
})
it('个人发送服务直连入口(语音 IPC 旁路)同样 blocked', async () => {
process.env[READ_ONLY_ENV] = '1'
const statusSpy = vi
.spyOn(personalWechatSendService, 'getStatus')
.mockResolvedValue({ state: 'ready' } as never)
const result = await personalWechatSendService.send({
to: 'filehelper',
isGroup: false,
type: 'text',
text: '必须被拦住'
})
expect(result.success).toBe(false)
expect(result.error).toContain('只读测试模式')
statusSpy.mockRestore()
})
it('退群本地提示不写微信库', async () => {
process.env[READ_ONLY_ENV] = '1'
const result = await wechatLocalExitNoticeService.handleExitEvent({
eventId: 'fixture-event',
conversationId: 'fixture@chatroom',
memberWxid: 'wxid_fixture',
memberName: '测试成员',
occurredAt: 1_800_000_000
} as never)
expect(result).toMatchObject({ outcome: 'disabled', code: 'READ_ONLY_MODE' })
})
})
+67
View File
@@ -217,4 +217,71 @@ describe('WCDB message shard pagination', () => {
)
expect(fs.existsSync(path.join(publicRoot, 'TraceMemo'))).toBe(false)
})
it('merges provisional cursor row with settled table-scan row without losing self identity', () => {
const client = Object.assign(Object.create(Wcdb4Client.prototype), {
accountRoot: '/tmp/fixture-account/wxid_self',
wxid: 'wxid_self',
displayNameCache: new Map(),
avatarCache: new Map()
}) as Wcdb4Client
const normalize = Reflect.get(client, 'normalizeMessage').bind(client) as (
row: Record<string, unknown>
) => {
mesLocalID: string
serverId?: string
mesDes: number
sender: string
}
const merge = Reflect.get(client, 'mergeMessageRows').bind(client) as (
current: ReturnType<typeof normalize>[],
recovered: ReturnType<typeof normalize>[]
) => ReturnType<typeof normalize>[]
// cursor 读到旧中间态(无 server_id、无 sender),tableScan 读到已回填的本人发出行。
const cursorRow = normalize({
local_id: 900,
server_id: 0,
local_type: 1,
create_time: 1800000100,
message_content: 'fixture text',
computed_is_send: 0,
status: 1
})
const tableRow = normalize({
local_id: 900,
server_id: '7000000000000000900',
local_type: 1,
create_time: 1800000100,
message_content: 'fixture text',
sender_username: 'wxid_self',
status: 2
})
const merged = merge([cursorRow], [tableRow])
expect(merged).toHaveLength(1)
expect(merged[0]).toMatchObject({
mesLocalID: '900',
serverId: '7000000000000000900',
mesDes: 0,
sender: 'wxid_self'
})
})
it('normalizes mesDes using 0=self and 1=peer semantics when is_send is absent', () => {
const client = Object.assign(Object.create(Wcdb4Client.prototype), {
accountRoot: '/tmp/fixture-account/wxid_self',
wxid: 'wxid_self',
displayNameCache: new Map(),
avatarCache: new Map()
}) as Wcdb4Client
const normalize = Reflect.get(client, 'normalizeMessage').bind(client) as (
row: Record<string, unknown>
) => { mesDes: number }
expect(normalize({ local_id: 1, create_time: 1800000001, mesDes: 0 }).mesDes).toBe(0)
expect(normalize({ local_id: 2, create_time: 1800000002, mesDes: 1 }).mesDes).toBe(1)
})
})
+38
View File
@@ -0,0 +1,38 @@
import { describe, expect, it } from 'vitest'
import { selectMessageLocation, type Wcdb4MessageCursor } from '../../src/main/wcdb4-client'
/**
* 跨分片 localId 重复时的定位回归。
*
* 真实事故:同一会话的 `local_id=31455` 在多个 message_N.db 中命中,
* 只带 localId 的 messageRef 被判 `ambiguous_message`;带 create_time 的
* 复合身份必须能唯一选中。
*/
describe('selectMessageLocation', () => {
const hits: Wcdb4MessageCursor[] = [
{ createTime: 1_795_158_061, localId: 31_455 },
{ createTime: 1_795_158_099, localId: 31_455 }
]
it('同 localId 跨分片命中时,create_time 唯一选中', () => {
expect(selectMessageLocation(hits, 1_795_158_099)).toEqual({
status: 'found',
location: { createTime: 1_795_158_099, localId: 31_455 }
})
})
it('只给 localId(wantedTime=null)时必须报 ambiguous', () => {
expect(selectMessageLocation(hits, null)).toEqual({ status: 'ambiguous' })
})
it('create_time 不匹配时是 not_found,而不是随便挑一条', () => {
expect(selectMessageLocation(hits, 1_795_158_000)).toEqual({ status: 'not_found' })
})
it('单分片唯一命中时仍然可以只靠 localId 定位', () => {
expect(selectMessageLocation([hits[0]], null)).toEqual({
status: 'found',
location: hits[0]
})
})
})
+50
View File
@@ -0,0 +1,50 @@
import { readFileSync } from 'node:fs'
import path from 'node:path'
import { describe, expect, it } from 'vitest'
import { WECHAT_SEND_TYPES } from '../../src/shared/wechat-send'
/**
* 发送类型的文档一致性守卫。
*
* 历史缺口:运行时白名单已经有 `file`,但 `docs/agent/api.md` 与 Reader Skill
* 的 `type` 字段仍只写 `text/image/voice`,外部调用方会以为不支持文件。
*
* 这里直接比对「文档里 `type` 那一行」与运行时数组:新增类型但忘了改文档时,
* 这两条会红,而不是等到用户试出来。
*/
const ROOT = path.resolve(__dirname, '../..')
function read(relativePath: string): string {
return readFileSync(path.join(ROOT, relativePath), 'utf8')
}
function typeRowOf(markdown: string): string {
const row = markdown
.split('\n')
.find((line) => /^\|\s*`type`\s*\|/.test(line))
if (!row) throw new Error('文档里找不到 `type` 字段行')
return row
}
describe('WECHAT_SEND_TYPES 与 API 文档同步', () => {
it('docs/agent/api.md 的 `type` 行覆盖全部运行时类型', () => {
const row = typeRowOf(read('docs/agent/api.md'))
for (const type of WECHAT_SEND_TYPES) {
expect(row).toContain(`\`${type}\``)
}
})
it('Reader Skill 的 `type` 行覆盖全部运行时类型', () => {
const row = typeRowOf(read('docs/skill/tracememo-reader/SKILL.md'))
for (const type of WECHAT_SEND_TYPES) {
expect(row).toContain(`\`${type}\``)
}
})
it('仍然包含 file(防止回退)', () => {
expect(WECHAT_SEND_TYPES).toContain('file')
expect(typeRowOf(read('docs/agent/api.md'))).toContain('`file`')
expect(typeRowOf(read('docs/skill/tracememo-reader/SKILL.md'))).toContain('`file`')
})
})