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

@@ -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()
})
})