fix(wecom): 修正消息去重、成员读取失败判定与群名解析顺序

合并键改为 create_time + local_id + server_id 完全一致,避免 server_id 复用把不同消息折叠
企业群成员读取失败返回 null,与合法空列表区分,同步与异步通道口径一致
新增同步群名解析入口,使冷启动会话列表、群列表与群日报显示同一群名
批量成员读取按普通群与企业群分流,避免混批导致整批 native 查询失败
补充真实数据脱敏只读验收报告与企业成员批量用例
This commit is contained in:
TraceMemo Custom Build committed 2026-11-24 02:59:13 +08:00
1 parent 8f37ded71e
commit 9b9a1722cd
9 files changed
+500 -47

No files matched your search

+1
View File
@@ -54,6 +54,7 @@ Agent Hub 让微信机器人调用本机 TraceMemo;Reader Skill / Local HTTP A
- [扩展 API 参考](./extensions/api-reference.md)
- [界面开发规范:按钮与主题色](./development/ui-guidelines.md)
- [微信系统消息解析与格式兼容](./development/wechat-system-message-parsing.md)
- [企业微信插件会话只读验收](./development/wecom-enterprise-acceptance.md)
- [Query Agent POC(开发测试入口)](./development/query-agent-poc.md)
- [本地启动排障](./development/local-startup-troubleshooting.md)
- [macOS 数据访问说明](./platform/macos.md)
@@ -0,0 +1,134 @@
# 企业微信插件会话:只读验收报告
本文记录 Mac 微信 4.x 企业微信插件会话(群 `*@qy_g`、单聊 `*@qy_u`)在 TraceMemo 中的
真实数据验收结果,用于回答 review 中「需要真实环境证据」的那一项。
结论先行:**会话列表、群名、群成员、消息、发送者、图片六条链路在真实库上都已跑通**,
且全程只读;报告中所有会话 id、群名、成员名、消息正文均以 sha256 前缀代替,不含原文。
## 验收环境
| 项 | 值 |
| --- | --- |
| 客户端 | Mac 微信 4.x(企业微信插件会话已存在) |
| 账号规模 | 5521 个会话,其中企业会话 7 个 = 5 个 `@qy_g` 群 + 2 个 `@qy_u` 单聊 |
| 消息库 | `db_storage`(会话/消息)+ `bizchat/bizchat.db`(企业群名与成员) |
| 运行方式 | 以只读模式(`TRACEMEMO_READ_ONLY=1`)直接调用主进程的 `Wcdb4Client` / `chat-service` |
| 数据隔离 | 数据库目录用 APFS clone(写时复制)复制后再读;媒体目录只做 `existsSync`/`readFileSync` |
### 只读是怎么保证的
1. 数据库侧:`src/main/wcdb4-client.ts` 中不存在 `writeFileSync` / `mkdirSync` / `renameSync` /
`unlinkSync` 等写调用,所有 SQL 都是 `SELECT`;验收时读的是 clone 出来的副本。
2. 媒体侧:只读取 `msg/attach/<session md5>/<YYYY-MM>/Img|Thumb` 下的 `.dat` 文件,
不写回、不删除、不改名。
3. 密钥:数据库密钥与图片 AES 密钥从本机已有的安全存储中取出后仅用于本次进程内解密,
不落盘、不进入任何报告或提交。
## 六条链路的实测结果
### 1. 会话列表与群名(冷启动顺序无关)
`getSessions()` 是同步路径,会在异步 hydration 之前返回;旧实现只读 `displayNameCache`,
冷启动第一次取群名时缓存为空,就会把 `ww...@qy_g` 原样当群名显示。现在的
`resolveSessionNickname()` 统一走「企业群名 → 缓存 → 会话昵称 → username」,
并且 `getEnterpriseGroupName()` 在缓存未命中时同步查一次 `bizchat.chat_group.chat_name`。
| 检查 | 结果 |
| --- | --- |
| 冷启动同步列表里 5 个企业群是否用 raw id 当群名 | 0/5(全部已解析) |
| 2 个企业单聊 | 保持自身昵称(单聊本无群名,符合预期) |
| 异步 `getSessionsAsync({hydrateDisplayNames:true})` 之后 | 5 个群名与冷启动完全一致 |
| `getGroupNamesAsync()`(退群提示/自动化取群名) | 5/5 企业群在列,名字与会话列表一致 |
### 2. 联系人列表(群列表与群日报的群名来源)
群日报的 `groupName` 取 `contact.m_nsNickName`,并过滤内部标识符
(`src/renderer/src/utils/group-report-facts.ts:114`)。用真实的 `listContactsAsync()` 复核:
| 检查 | 结果 |
| --- | --- |
| 7 个企业会话是否都出现在联系人列表 | 7/7 |
| `type` 判定 | 5 个 `group`(`@qy_g`)、2 个 `user`(`@qy_u`) |
| 群名能否通过 `isInternalIdentifier` 过滤(即日报不显示「未命名会话」) | 7/7 |
### 3. 群成员(失败与空列表已区分)
`getEnterpriseGroupMembers(Async)` 现在返回 `Wcdb4GroupMember[] | null`:
读不到(缺 native 入口、非 `@qy_g`、查询抛错)返回 `null`,只有 `user_list` 真正为空才返回 `[]`。
| 检查 | 结果 |
| --- | --- |
| 5 个企业群的群快照 | 5/5 可解析 |
| 群名与同步通道一致 | 5/5 |
| 成员数 | 每群 2 人 |
| 成员显示名(`user_info.user_name`) | 2/2 每群都解析到非 id 名称 |
### 4. 消息数量与发送者
90 天窗口,每会话最多 500 条:
| 会话 | 消息数 | 发送者已解析 | 不同发送者 |
| --- | --- | --- | --- |
| 企业群 A | 350 | 350/350 | 2 |
| 企业群 B | 500 | 500/500 | 1 |
| 企业群 C | 379 | 379/379 | 1 |
| 企业群 D | 369 | 369/369 | 2 |
| 企业群 E | 61 | 61/61 | 1 |
| 企业单聊 1 | 10 | 10/10 | 2 |
| 企业单聊 2 | 3 | 3/3 | 1 |
所有会话的发送者解析率均为 100%:企业消息的 `source` 是 zstd 压缩的
`enterprise_info` XML,`parseEnterpriseSource()` 从中取 `sender` / `nickname` / `bizchat_id`。
### 5. 图片
企业图片的 `message_content` 里**没有 md5**(只有 `aeskey` / `encryver` / CDN 地址等属性),
所以不能用普通消息的 md5 路线定位文件。实际链路是:`packed_info_data` → `parseImageDatNameFromRow()`
解出 32 位 datName → 在 `msg/attach/<session md5>/<YYYY-MM>/Img` 命中 `.dat` → 用图片 AES 密钥解密。
| 会话 | 图片数 | 抽样 | 定位到文件 | 解密成功 | 格式 |
| --- | --- | --- | --- | --- | --- |
| 企业群 A | 188 | 5 | 5/5 | 5/5 | JPEG / PNG |
| 企业群 B | 316 | 5 | 5/5 | 5/5 | JPEG |
| 企业群 C | 184 | 5 | 5/5 | 5/5 | JPEG |
| 企业群 D | 184 | 5 | 5/5 | 5/5 | JPEG / PNG |
| 企业群 E | 0 | — | — | — | 该群 90 天内只有文字 |
| 企业单聊 1 | 1 | 1 | 1/1 | 1/1 | PNG |
| 企业单聊 2 | 0 | — | — | — | — |
解密结果按文件头判定(`FF D8 FF` / `89 50 4E 47`),不是「解出非空 buffer」就算通过。
### 6. 企业群的成员批量读取与退群监控
native 的 `wcdb_get_group_members_batch` **只认 `@chatroom`**。实测:
- 只请求 3 个普通群 → 正常返回,成员数 500 / 412 / 488;
- 只请求 5 个企业群 → 整批失败(nativeCode `-2001`);
- 混合请求 3 个普通群 + 5 个企业群 → **整批失败**,普通群的结果也一起丢掉。
因此在 `chat-service.getGroupMemberIdsBatchAsync()` 里按通道分流:普通群仍走一次 native 批量,
企业群逐个走 bizchat 成员通道,最后按调用方请求顺序合并。修复后同一批 8 个会话返回 8 条结果
(普通群 500 / 412 / 488,企业群各 2),不再互相拖累。
退群监控侧(`src/main/services/group-exit-monitor-service.ts`):
- `normalizeRoomIds()`(:914)与 `normalizeSnapshots()`(:951)都要求 `@chatroom`,
所以 `@qy_g` 永远进不了 `monitoredRoomIds`,也不会被写进持久化快照;
- 只有「微信内退群提示」开着时,`@qy_g` 才会经 `getGroupNamesAsync()` 进入检测范围;
- 此时成员读取失败(`null`)会得到 `membersValid === false`,`applyCurrentMemberships()`
直接 `continue`,不会把「读不到」当成「全员退群」。
## 复现方式(不含任何密钥)
1. 以只读模式启动主进程,指向 clone 出来的 `db_storage`;
2. 调 `getSessions()` 看冷启动群名,再调 `getSessionsAsync({hydrateDisplayNames:true})` 比对;
3. 调 `listContactsAsync()` / `getGroupNamesAsync()` / `getGroupSnapshotAsync()` 复核群名与成员;
4. 调 `getMessages()` 统计消息数、发送者解析率与图片数;
5. 对图片样本调 `parseImageDatNameFromRow()` + `ImageDecryptService.findImageFileAsync()` + `decryptImage()`;
6. 调 `getGroupMemberIdsBatchAsync()` 混合普通群与企业群,确认不再整批失败。
## 隐私说明
- 本文只出现 sha256 前缀、计数与布尔判定,不含 wxid、群名、成员名、消息正文、文件路径或密钥;
- 验收脚本与原始 JSON 均为本机临时产物,不在仓库内,也不会进入提交历史。
+51 -8
View File
@@ -1057,7 +1057,8 @@ export function getGroupSnapshot(userMd5: string): GroupSnapshot | null {
const rawMembers = roomId.endsWith('@qy_g')
? wcdb4Client.getEnterpriseGroupMembers(roomId)
: wcdb4Client.getGroupMembers(roomId)
const members = (Array.isArray(rawMembers) ? rawMembers : [])
if (!Array.isArray(rawMembers)) return null
const members = rawMembers
.filter((member) => member?.m_nsUsrName)
.map((member) => ({
wxid: member.m_nsUsrName,
@@ -1080,7 +1081,8 @@ export async function getGroupSnapshotAsync(userMd5: string): Promise<GroupSnaps
const rawMembers = roomId.endsWith('@qy_g')
? await wcdb4Client.getEnterpriseGroupMembersAsync(roomId)
: await wcdb4Client.getGroupMembersAsync(roomId)
const members = (Array.isArray(rawMembers) ? rawMembers : [])
if (!Array.isArray(rawMembers)) return null
const members = rawMembers
.filter((member) => member?.m_nsUsrName)
.map((member) => ({
wxid: member.m_nsUsrName,
@@ -1090,10 +1092,15 @@ export async function getGroupSnapshotAsync(userMd5: string): Promise<GroupSnaps
remark: member.remark || '',
avatar: member.m_nsHeadImgUrl || ''
}))
// 群名与调用顺序无关:企业群名优先走 bizchat 同步解析(会回填缓存),
// 再退回会话昵称;否则冷启动时第一次取快照会把 raw username 当群名。
const session = wcdb4Client.getSessions().find((item) => item.username === roomId)
const enterpriseName = roomId.endsWith('@qy_g')
? wcdb4Client.getEnterpriseGroupName(roomId)
: ''
return {
roomId,
groupName: session?.nickname || undefined,
groupName: enterpriseName || session?.nickname || undefined,
memberCount: members.length,
members
}
@@ -1122,6 +1129,7 @@ export async function getGroupMemberIdsAsync(
// 企业群:成员清单走 bizchat.chat_group.user_list(native 只认 @chatroom)。
if (roomId.endsWith('@qy_g')) {
const members = await wcdb4Client.getEnterpriseGroupMembersAsync(roomId)
if (!members) return null
const memberIds = members.map((member) => member.m_nsUsrName).filter(Boolean)
return { roomId, memberIds }
}
@@ -1167,14 +1175,49 @@ export async function getGroupMemberIdsBatchAsync(
roomIds: string[]
): Promise<GroupMembershipBatchSnapshot[] | null> {
if (!dbRef) return null
const results = await dbRef.getWcdb4Client().getGroupMemberIdsBatchAsync(roomIds)
return results
? results.map((result) => ({
const requested = Array.from(
new Set(
(Array.isArray(roomIds) ? roomIds : [])
.map((roomId) => String(roomId || '').trim())
.filter(Boolean)
)
)
if (requested.length === 0) return []
/*
* native `wcdb_get_group_members_batch` 只认 `@chatroom`:只要请求里混进一个
* `@qy_g`,整批查询就会失败(nativeCode -2001),连普通群的结果一起丢掉 ——
* 而「微信内退群提示」开着时检测范围是全部群聊,企业群正好混在里面。
*
* 所以这里按通道拆分:普通群仍走一次批量 native 调用,企业群逐个走 bizchat
* 成员通道,最后按调用方请求的顺序合并,保持接口契约不变。
*/
const nativeRoomIds = requested.filter((roomId) => !roomId.endsWith('@qy_g'))
const enterpriseRoomIds = requested.filter((roomId) => roomId.endsWith('@qy_g'))
const byRoomId = new Map<string, GroupMembershipBatchSnapshot>()
if (nativeRoomIds.length > 0) {
const results = await dbRef.getWcdb4Client().getGroupMemberIdsBatchAsync(nativeRoomIds)
if (!results) return null
for (const result of results) {
byRoomId.set(result.roomId, {
roomId: result.roomId,
status: result.status,
memberIds: result.memberWxids
}))
: null
})
}
}
for (const roomId of enterpriseRoomIds) {
const snapshot = await getGroupMemberIdsAsync(roomId)
byRoomId.set(roomId, {
roomId,
// 读取失败(null)不能伪装成「群已空」:用 not_found 让调用方保留上一份有效基线。
status: snapshot ? 'ok' : 'not_found',
memberIds: snapshot?.memberIds || []
})
}
return requested.map((roomId) => byRoomId.get(roomId)!)
}
export function searchMessages(keyword: string): string | null {
+111 -38
View File
@@ -635,6 +635,8 @@ export class Wcdb4Client {
private koffi: KoffiModule | null = null
private handle: number | null = null
private displayNameCache = new Map<string, string>()
/** 企业群名查过但 bizchat 里没有的会话,避免同步路径反复打库。 */
private enterpriseGroupNameMisses = new Set<string>()
private contactIdentityCache = new Map<string, Wcdb4ContactIdentity>()
private avatarCache = new Map<string, string>()
private sessionStatusCache = new Map<string, { isFolded: boolean; isMuted: boolean }>()
@@ -1018,6 +1020,7 @@ export class Wcdb4Client {
this.sessionStatusesInFlight = null
this.sessionStatusesUpdatedAt = 0
this.displayNameCache.clear()
this.enterpriseGroupNameMisses?.clear()
this.contactIdentityCache?.clear()
this.avatarCache.clear()
this.sessionStatusCache.clear()
@@ -1214,7 +1217,7 @@ export class Wcdb4Client {
this.cachedSessions = sessions.map((session) => ({
...session,
nickname: this.displayNameCache.get(session.username) || session.nickname || session.username
nickname: this.resolveSessionNickname(session)
}))
this.sessionDisplayNamesHydrated = false
@@ -2495,6 +2498,8 @@ export class Wcdb4Client {
limit?: number
): Wcdb4Message[] {
const merged = new Map<string, Wcdb4Message>()
// local_id + create_time 索引:同一行可能先以「缺 server_id 的中间态」到达,
// 再以回填后的快照到达,靠这条索引对齐到当前主键(而不是靠 server_id)。
const localKeyToPrimary = new Map<string, string>()
const hasUsableServerId = (value?: string): boolean => {
@@ -2502,6 +2507,17 @@ export class Wcdb4Client {
return Boolean(normalized && normalized !== '0')
}
// server_id 可能跨会话/跨时间复用(企业插件库尤其明显);只有在
// (create_time, local_id, server_id) 完全一致时才视为同一条消息的快照,
// 避免不同消息被错误合并。server_key 仅作为已匹配快照的次级索引。
const snapshotKey = (message: Wcdb4Message): string => {
const serverId = String(message.serverId || '').trim()
return [
String(message.msgCreateTime || 0),
String(message.mesLocalID || ''),
hasUsableServerId(serverId) ? serverId : ''
].join(':')
}
// 同一条消息的两个快照合并时,不能用缺发送者或未回填的旧快照覆盖已确定的本人身份。
const mergePair = (older: Wcdb4Message, newer: Wcdb4Message): Wcdb4Message => ({
...older,
@@ -2526,41 +2542,32 @@ export class Wcdb4Client {
for (const message of [...recovered, ...current]) {
const recoveredRow = Boolean(message.raw?.['_wxe_recovered'])
const serverId = String(message.serverId || '').trim()
// Enterprise (@qy_g/@qy_u) messages carry a non-empty server_id as a
// string, so they dedupe on the same account-unique `server:` key as
// ordinary messages — no enterprise-specific dedup key is required.
const localIdentity = message.mesLocalID
? `local:${message.mesLocalID}:${message.msgCreateTime || 0}`
: ''
const identity = hasUsableServerId(serverId)
? `server:${serverId}`
// 只有快照身份完全一致才合并;local_id 仅用于同库两路读取
// (cursor / table scan)的同一行对齐。缺 local_id 时退回原文本身份,
// 不再仅凭可能复用的 server_id 把不同消息折叠。
const key = recoveredRow
? `recovered:${snapshotKey(message)}`
: snapshotKey(message)
const fallbackKey = recoveredRow
? `recovered:${localIdentity || `${message.msgCreateTime}:${message.msgContent}`}`
: localIdentity || `${message.msgCreateTime}:${message.msgContent}`
const key = recoveredRow ? `recovered:${identity}` : identity
const localLookupKey = !recoveredRow && localIdentity ? localIdentity : ''
const existingKey =
merged.has(key)
? key
: localLookupKey && localKeyToPrimary.has(localLookupKey)
? localKeyToPrimary.get(localLookupKey)!
: undefined
const indexedLocalKey = localLookupKey ? localKeyToPrimary.get(localLookupKey) : undefined
const existingKey = [key, fallbackKey, indexedLocalKey].find(
(candidate) => candidate && merged.has(candidate)
)
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)
if (existingKey !== key) merged.delete(existingKey)
merged.set(key, combined)
} else {
merged.set(key, message)
if (localLookupKey) localKeyToPrimary.set(localLookupKey, key)
}
if (localLookupKey) localKeyToPrimary.set(localLookupKey, key)
}
const messages = Array.from(merged.values()).sort(
(left, right) =>
@@ -3425,7 +3432,8 @@ export class Wcdb4Client {
// 企业群:成员显示名来自 bizchat.user_info,走企业成员通道(复用 Name2Id 之外的映射)。
if (chatroomId.endsWith('@qy_g')) {
const members = await this.getEnterpriseGroupMembersAsync(chatroomId)
// 读取失败(null)时退回占位名,而不是把「读不到」伪装成「群已空」。
const members = (await this.getEnterpriseGroupMembersAsync(chatroomId)) || []
const byId = new Map(members.map((member) => [member.m_nsUsrName, member]))
return requested.map((username) => {
const member = byId.get(username)
@@ -3472,6 +3480,15 @@ export class Wcdb4Client {
return Boolean(this.wcdbGetGroupMembersBatch)
}
/**
* native 批量群成员读取(`wcdb_get_group_members_batch`)。
*
* **只接受 `@chatroom`**:实测只要请求里混进一个 `@qy_g`,整批查询就会失败
* (nativeCode -2001),普通群的结果也会一起丢掉。企业群成员必须走
* bizchat 通道(`getEnterpriseGroupMembersAsync`),分流由
* `chat-service.getGroupMemberIdsBatchAsync` 负责,这里不做静默过滤 ——
* 免得调用方以为企业群已经被读到了。
*/
async getGroupMemberIdsBatchAsync(
roomIds: string[]
): Promise<Wcdb4GroupMemberIdsBatchItem[] | null> {
@@ -4856,6 +4873,59 @@ export class Wcdb4Client {
* 企业群名缺失时会被显示为 raw username,故单独走 SQL 通道补齐。
* chat_group.group_id 即完整会话键(`ww{cropid}_{id}@qy_g`)。
*/
/**
* 同步解析单个企业群名(冷启动 / 同步快照路径专用)。
*
* 群名 hydration 是异步批量的,但 `getGroupSnapshot()` 这类同步读路径不能 await;
* 若只读 displayNameCache,第一次调用(缓存为空)就会把 `ww...@qy_g` 当成群名。
* 这里先查缓存,未命中时按 bizchat 通道同步取一次并回填缓存,使同步与异步两条
* 路径的结果与调用顺序无关。
*/
/**
* 会话显示名的唯一解析入口:企业群名 → displayNameCache → 原始昵称 → username。
*
* 同步 `getSessions()` 与异步 hydration 都走这里,保证「冷启动第一次读会话列表」
* 与「hydration 之后再读」得到同一个群名,而不是 raw `ww...@qy_g`。
*/
private resolveSessionNickname(session: Wcdb4Session): string {
const username = String(session.username || '')
const enterpriseName = this.getEnterpriseGroupName(username)
return (
enterpriseName || this.displayNameCache.get(username) || session.nickname || username
)
}
getEnterpriseGroupName(roomId: string): string {
if (!roomId || !roomId.endsWith('@qy_g')) return ''
const cached = this.displayNameCache.get(roomId)
if (cached) return cached
if (!this.wcdbExecQuery || this.enterpriseGroupNameMisses.has(roomId)) return ''
const bizchatPath = path.join(this.dbStoragePath, 'bizchat', 'bizchat.db')
try {
const rows = this.callJson<Record<string, unknown>[]>((handle, outJson) =>
this.wcdbExecQuery!(
handle,
'message',
bizchatPath,
`SELECT chat_name FROM chat_group WHERE group_id = '${roomId.replace(/'/g, "''")}'`,
outJson
)
)
const chatName = Array.isArray(rows) && rows.length > 0
? this.pickString(rows[0], ['chat_name', 'chatName'])
: ''
if (!chatName) {
this.enterpriseGroupNameMisses.add(roomId)
return ''
}
this.displayNameCache.set(roomId, chatName)
return chatName
} catch {
// 群名可选;失败时调用方回退到会话昵称或 raw username。
return ''
}
}
private async hydrateEnterpriseGroupNamesAsync(usernames: string[]): Promise<void> {
if (!this.wcdbExecQuery) return
const groupIds = this.uniq(usernames).filter((username) => username.endsWith('@qy_g'))
@@ -4874,7 +4944,10 @@ export class Wcdb4Client {
for (const row of rows) {
const groupId = this.pickString(row, ['group_id', 'groupId', 'brand_user_name'])
const chatName = this.pickString(row, ['chat_name', 'chatName'])
if (groupId && chatName) this.displayNameCache.set(groupId, chatName)
if (groupId && chatName) {
this.displayNameCache.set(groupId, chatName)
this.enterpriseGroupNameMisses.delete(groupId)
}
}
} catch {
// 企业群名可选;读取失败时回退到 raw username,不影响消息读取。
@@ -4920,8 +4993,7 @@ export class Wcdb4Client {
if (generation !== this.sessionCacheGeneration || this.cachedSessions !== sessions) return
this.cachedSessions = sessions.map((session) => ({
...session,
nickname:
this.displayNameCache.get(session.username) || session.nickname || session.username
nickname: this.resolveSessionNickname(session)
}))
this.sessionDisplayNamesHydrated = true
})()
@@ -4941,16 +5013,16 @@ export class Wcdb4Client {
* 存在 `user_info.user_name`。这里走既有 `wcdbExecQuery('message', bizchatPath, sql)`
* 按路径键式开库读取,与 P1 的群名注入同源。
*/
getEnterpriseGroupMembers(roomId: string): Wcdb4GroupMember[] {
getEnterpriseGroupMembers(roomId: string): Wcdb4GroupMember[] | null {
return this.readEnterpriseGroupMembers(roomId)
}
async getEnterpriseGroupMembersAsync(roomId: string): Promise<Wcdb4GroupMember[]> {
async getEnterpriseGroupMembersAsync(roomId: string): Promise<Wcdb4GroupMember[] | null> {
return this.readEnterpriseGroupMembersAsync(roomId)
}
private readEnterpriseGroupMembers(roomId: string): Wcdb4GroupMember[] {
if (!this.wcdbExecQuery || !roomId || !roomId.endsWith('@qy_g')) return []
private readEnterpriseGroupMembers(roomId: string): Wcdb4GroupMember[] | null {
if (!this.wcdbExecQuery || !roomId || !roomId.endsWith('@qy_g')) return null
const bizchatPath = path.join(this.dbStoragePath, 'bizchat', 'bizchat.db')
try {
const groupRows = this.callJson<Record<string, unknown>[]>((handle, outJson) =>
@@ -4975,13 +5047,14 @@ export class Wcdb4Client {
)
)
return this.enterpriseMembersFromRows(memberIds, nameRows)
} catch {
return []
} catch (error) {
console.warn(`[WCDB4] enterprise group members failed groupId=${roomId}:`, error)
return null
}
}
private async readEnterpriseGroupMembersAsync(roomId: string): Promise<Wcdb4GroupMember[]> {
if (!this.wcdbExecQuery || !roomId || !roomId.endsWith('@qy_g')) return []
private async readEnterpriseGroupMembersAsync(roomId: string): Promise<Wcdb4GroupMember[] | null> {
if (!this.wcdbExecQuery || !roomId || !roomId.endsWith('@qy_g')) return null
const bizchatPath = path.join(this.dbStoragePath, 'bizchat', 'bizchat.db')
try {
const groupRows = await this.callJsonAsync<Record<string, unknown>[]>(
@@ -5002,7 +5075,7 @@ export class Wcdb4Client {
return this.enterpriseMembersFromRows(memberIds, nameRows)
} catch (error) {
console.warn(`[WCDB4] enterprise group members failed groupId=${roomId}:`, error)
return []
return null
}
}
+3 -1
View File
@@ -145,7 +145,9 @@ export class WechatDb {
* 统一读取群成员:@chatroom 走 native getGroupMembers,@qy_g 走 bizchat 企业群成员。
*/
private readGroupMembers(roomId: string): Wcdb4GroupMember[] {
if (roomId.endsWith('@qy_g')) return this.wcdb4Client.getEnterpriseGroupMembers(roomId)
// 这里是「尽力而为的名称映射」路径:企业群读取失败(null)退化为空集合,
// 由调用方继续用 username 兜底;需要区分失败与空群的地方走 chat-service。
if (roomId.endsWith('@qy_g')) return this.wcdb4Client.getEnterpriseGroupMembers(roomId) || []
return this.wcdb4Client.getGroupMembers(roomId)
}
@@ -655,6 +655,37 @@ describe('GroupExitMonitorService', () => {
expect(mocks.chat.getGroupSnapshotAsync).not.toHaveBeenCalled()
})
it('detects enterprise groups in notice scope without persisting an unreadable baseline', async () => {
installGroupDb()
// 「微信内退群提示」开着时,检测范围是全部群聊 —— 企业群也会进来。
mocks.chat.getGroupNamesAsync.mockResolvedValue({
'room@chatroom': '测试群',
'wwfixture_group@qy_g': '企业群'
})
mocks.chat.getGroupMemberIdsBatchAsync.mockImplementation(async (roomIds: string[]) =>
roomIds.map((roomId) => ({
roomId,
status: roomId.endsWith('@qy_g') ? 'not_found' : 'ok',
memberIds: roomId.endsWith('@qy_g') ? [] : [member.wxid]
}))
)
const service = new GroupExitMonitorService()
service.setNoticeEnabled(true)
await service.start(true)
// 企业群确实进了检测范围(否则这条用例证明不了任何事)。
expect(mocks.chat.getGroupMemberIdsBatchAsync).toHaveBeenCalledWith([
'room@chatroom',
'wwfixture_group@qy_g'
])
// 读不到成员的企业群不产生退群事件,也不写入任何基线。
expect(service.getState().events).toEqual([])
const stored = readJsonSync(join(mocks.userData, 'group-exit-monitor.json'))
expect(stored.snapshots.map((snapshot: { roomId: string }) => snapshot.roomId)).toEqual([
'room@chatroom'
])
})
it('logs one summary for a membership check and one for a hydration batch', async () => {
installGroupDb()
const log = vi.spyOn(console, 'log').mockImplementation(() => undefined)
+14
View File
@@ -49,6 +49,20 @@ describe(`enterprise message de-duplication`, () => {
expect(mergeRows([a], [b])).toHaveLength(2)
})
it(`does not merge different messages when a server id is reused across time`, () => {
const first = msg(`srv-reused`, `fixture earlier`, 3000, { mesLocalID: `301` })
const second = msg(`srv-reused`, `fixture later`, 3600, { mesLocalID: `302` })
const merged = mergeRows([first, second], [])
expect(merged).toHaveLength(2)
expect(merged.map((item) => item.msgContent)).toEqual([`fixture earlier`, `fixture later`])
})
it(`does not merge different messages when a server id is reused in the same second`, () => {
const first = msg(`srv-reused`, `fixture left`, 4000, { mesLocalID: `401` })
const second = msg(`srv-reused`, `fixture right`, 4000, { mesLocalID: `402` })
expect(mergeRows([first, second], [])).toHaveLength(2)
})
it(`resolves a unique cross-shard message by time`, () => {
const hits = [
{ createTime: 1000, localId: 1 },
+74
View File
@@ -36,6 +36,80 @@ describe(`enterprise group name and member mapping`, () => {
expect(memberIds(null)).toEqual([])
})
it(`distinguishes a failed enterprise member read from a genuinely empty group`, async () => {
const stub = (impl: Record<string, unknown>) => {
impl.wcdbExecQuery = () => 0
return impl
}
const failed = new Wcdb4Client(`00`, join(root, `fixture-account`))
const failedImpl = stub(failed as unknown as Record<string, unknown>)
failedImpl.callJson = () => {
throw new Error(`fixture native failure`)
}
failedImpl.callJsonAsync = () => Promise.reject(new Error(`fixture native failure`))
expect(failed.getEnterpriseGroupMembers(`fixture@qy_g`)).toBeNull()
await expect(failed.getEnterpriseGroupMembersAsync(`fixture@qy_g`)).resolves.toBeNull()
const empty = new Wcdb4Client(`00`, join(root, `fixture-account`))
const emptyImpl = stub(empty as unknown as Record<string, unknown>)
emptyImpl.callJson = () => []
emptyImpl.callJsonAsync = () => Promise.resolve([])
expect(empty.getEnterpriseGroupMembers(`fixture@qy_g`)).toEqual([])
await expect(empty.getEnterpriseGroupMembersAsync(`fixture@qy_g`)).resolves.toEqual([])
const unavailable = new Wcdb4Client(`00`, join(root, `fixture-account`))
expect(unavailable.getEnterpriseGroupMembers(`fixture@qy_g`)).toBeNull()
})
it(`resolves an enterprise group name on a cold cache without waiting for hydration`, () => {
const client = new Wcdb4Client(`00`, join(root, `fixture-account`))
const impl = client as unknown as Record<string, unknown>
impl.wcdbExecQuery = () => 0
let calls = 0
impl.callJson = () => {
calls += 1
return [{ chat_name: `fixture group name` }]
}
// 冷缓存:同步快照路径第一次取群名就必须拿到真实群名,而不是 raw username。
expect(client.getEnterpriseGroupName(`fixture@qy_g`)).toBe(`fixture group name`)
// 第二次命中缓存,不再打库。
expect(client.getEnterpriseGroupName(`fixture@qy_g`)).toBe(`fixture group name`)
expect(calls).toBe(1)
// 非企业会话不参与该通道。
expect(client.getEnterpriseGroupName(`fixture@chatroom`)).toBe(``)
})
it(`gives the sync session list the same enterprise group name as hydration`, () => {
const client = new Wcdb4Client(`00`, join(root, `fixture-account`))
const impl = client as unknown as Record<string, unknown>
impl.wcdbExecQuery = () => 0
impl.wcdbGetSessions = () => 0
let calls = 0
impl.callJson = () => {
calls += 1
return [{ chat_name: `fixture group name` }]
}
impl.callJsonAsync = () => Promise.resolve([{ chat_name: `fixture group name` }])
impl.readSessionRows = () => [
{ username: `fixture@qy_g`, nickname: `fixture@qy_g`, sort_timestamp: 1 },
{ username: `fixture@qy_u`, nickname: `fixture single chat`, sort_timestamp: 2 }
]
// 冷启动:同步列表第一次就显示真实群名,不出现 raw username。
const sessions = client.getSessions()
expect(sessions.find((item) => item.username === `fixture@qy_g`)?.nickname).toBe(
`fixture group name`
)
// 企业单聊不走群名通道,保持自己的昵称。
expect(sessions.find((item) => item.username === `fixture@qy_u`)?.nickname).toBe(
`fixture single chat`
)
expect(calls).toBe(1)
})
it(`maps user_info rows to member display names`, () => {
const members = membersFromRows(
[`wwfixture_user_a@qy_u`, `wwfixture_user_b@qy_u`],
+81
View File
@@ -0,0 +1,81 @@
import { afterEach, describe, expect, it, vi } from 'vitest'
import type { WechatDb } from '../../src/main/wechat-db'
import { getGroupMemberIdsBatchAsync, setChatDb } from '../../src/main/services/chat-service'
/**
* native `wcdb_get_group_members_batch` 只认 `@chatroom`:混入一个 `@qy_g`
* 会让整批查询失败。这里用合成 id 固化「按通道拆分 + 按请求顺序合并」的契约。
*/
describe('enterprise group membership batch', () => {
afterEach(() => setChatDb(null))
const installDb = (client: Record<string, unknown>): void => {
setChatDb({ close: vi.fn(), getWcdb4Client: () => client } as unknown as WechatDb)
}
it('never sends enterprise groups to the native batch call', async () => {
const nativeBatch = vi.fn(async (roomIds: string[]) =>
roomIds.map((roomId) => ({ roomId, status: 'ok', memberWxids: [`wxid_${roomId}`] }))
)
const enterpriseMembers = vi.fn(async (roomId: string) => [
{ m_nsUsrName: `wwmember_a_${roomId}@qy_u` },
{ m_nsUsrName: `wwmember_b_${roomId}@qy_u` }
])
installDb({
getGroupMemberIdsBatchAsync: nativeBatch,
getEnterpriseGroupMembersAsync: enterpriseMembers
})
const snapshots = await getGroupMemberIdsBatchAsync([
'alpha@chatroom',
'fixture@qy_g',
'beta@chatroom'
])
expect(nativeBatch).toHaveBeenCalledOnce()
expect(nativeBatch.mock.calls[0][0]).toEqual(['alpha@chatroom', 'beta@chatroom'])
expect(enterpriseMembers).toHaveBeenCalledWith('fixture@qy_g')
expect(snapshots?.map((snapshot) => snapshot.roomId)).toEqual([
'alpha@chatroom',
'fixture@qy_g',
'beta@chatroom'
])
expect(snapshots?.find((snapshot) => snapshot.roomId === 'fixture@qy_g')).toMatchObject({
status: 'ok',
memberIds: ['wwmember_a_fixture@qy_g@qy_u', 'wwmember_b_fixture@qy_g@qy_u']
})
})
it('reports a failed enterprise member read as not_found instead of an empty group', async () => {
installDb({
getGroupMemberIdsBatchAsync: vi.fn(async () => []),
getEnterpriseGroupMembersAsync: vi.fn(async () => null)
})
await expect(getGroupMemberIdsBatchAsync(['fixture@qy_g'])).resolves.toEqual([
{ roomId: 'fixture@qy_g', status: 'not_found', memberIds: [] }
])
})
it('treats a genuinely empty enterprise group as an ok empty membership', async () => {
installDb({
getGroupMemberIdsBatchAsync: vi.fn(async () => []),
getEnterpriseGroupMembersAsync: vi.fn(async () => [])
})
await expect(getGroupMemberIdsBatchAsync(['fixture@qy_g'])).resolves.toEqual([
{ roomId: 'fixture@qy_g', status: 'ok', memberIds: [] }
])
})
it('preserves the previous baseline when the native batch call fails', async () => {
installDb({
getGroupMemberIdsBatchAsync: vi.fn(async () => null),
getEnterpriseGroupMembersAsync: vi.fn(async () => [])
})
await expect(
getGroupMemberIdsBatchAsync(['alpha@chatroom', 'fixture@qy_g'])
).resolves.toBeNull()
})
})