mirror of
https://wget.la/https://github.com/Wxw-Gu/WechatExplorer
synced 2026-12-01 01:05:30 +08:00
feat: 只读验收模式、文件发送类型与消息定位补全
- 只读验收:TRACEMEMO_READ_ONLY=1 时跳过消息写入、自动发送与退群提示 - 微信发送新增 file 类型,文档、能力探测与 Reader Skill 同步 - 消息前后窗口按分片定位,补齐 wcdb4 定位与分片测试
This commit is contained in:
1 parent
0edbf60b2e
commit
518a9662a7
25 files changed
+1278
-154
No files matched your search
@@ -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
@@ -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()
|
||||
|
||||
@@ -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' }
|
||||
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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
@@ -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 || '')
|
||||
|
||||
Reference in new issue
Block a user