feat: 优化档案搜索与头像

新增退群监控开关
发送限速
This commit is contained in:
Wxw-Gu committed 2026-09-03 18:12:29 +08:00
1 parent 3462d49516
commit 719ffa0a24
33 files changed
+1025 -64

No files matched your search

+13 -5
View File
@@ -112,6 +112,7 @@ import {
import { installSafeConsole } from './safe-log'
import { agentHubService } from './services/agent-hub-service'
import { groupExitMonitorService } from './services/group-exit-monitor-service'
import { wechatActionLogService } from './services/wechat-action-log-service'
import { personalWechatSendService } from './services/personal-wechat-send-service'
import { getPersonalWechatSendCapability } from './services/personal-wechat-capability-service'
import { scheduledReportService } from './services/scheduled-report-service'
@@ -1079,11 +1080,14 @@ app.whenReady().then(async () => {
return contacts
})
ipcMain.handle('db:getContactAvatars', async (_, usernames: string[]) => {
const avatars = await chat.getContactAvatars(usernames)
if (chat.isReady()) mergeBootstrapAvatars(chat.getCurrentAccountRoot(), avatars)
return avatars
})
ipcMain.handle(
'db:getContactAvatars',
async (_, usernames: string[], options?: { refresh?: boolean }) => {
const avatars = await chat.getContactAvatars(usernames, options)
if (chat.isReady()) mergeBootstrapAvatars(chat.getCurrentAccountRoot(), avatars)
return avatars
}
)
ipcMain.handle(
'db:getMessages',
@@ -1130,6 +1134,9 @@ app.whenReady().then(async () => {
})
ipcMain.handle('group-exit-monitor:getState', () => groupExitMonitorService.getState())
ipcMain.handle('group-exit-monitor:setEnabled', (_, enabled: boolean) =>
groupExitMonitorService.setEnabled(enabled === true)
)
ipcMain.handle(
'group-exit-monitor:setGroups',
(_, roomIds: string[], notificationRoomIds?: string[]) =>
@@ -1146,6 +1153,7 @@ app.whenReady().then(async () => {
ipcMain.handle('group-exit-monitor:markRead', (_, readAt?: number) =>
groupExitMonitorService.markRead(readAt)
)
ipcMain.handle('wechat-action-log:list', () => wechatActionLogService.list())
ipcMain.handle('db:search', (_, keyword: string) => chat.searchMessages(keyword))
ipcMain.handle(
+11 -2
View File
@@ -44,6 +44,8 @@ export interface FormattedContact {
avatar?: string
wechatNickname?: string
remark?: string
alias?: string
wechatId?: string
isFolded?: boolean
isMuted?: boolean
}
@@ -202,6 +204,8 @@ export function listContacts(filter?: string): FormattedContact[] {
avatar: typeof user.avatar === 'string' ? user.avatar : undefined,
wechatNickname: user.wechatNickname,
remark: user.remark,
alias: user.alias,
wechatId: user.wechatId,
isFolded: user.isFolded,
isMuted: user.isMuted
})
@@ -259,13 +263,18 @@ export async function getGroupNamesAsync(): Promise<Record<string, string>> {
return names
}
export async function getContactAvatars(usernames: string[]): Promise<Record<string, string>> {
export async function getContactAvatars(
usernames: string[],
options?: { refresh?: boolean }
): Promise<Record<string, string>> {
if (!dbRef) return {}
const normalized = Array.from(
new Set((usernames || []).map((username) => String(username || '').trim()).filter(Boolean))
)
if (normalized.length === 0) return {}
return dbRef.getWcdb4Client().getAvatarUrlsAsync(normalized)
const client = dbRef.getWcdb4Client()
if (options?.refresh) client.invalidateAvatarCache(normalized)
return client.getAvatarUrlsAsync(normalized)
}
function listSourceMessages(
@@ -17,6 +17,7 @@ import {
} from '../../shared/group-exit-monitor'
type StoredState = {
enabled?: boolean
accountRoot?: string
events?: Partial<GroupExitMonitorEvent>[]
lastReadAt?: number
@@ -70,6 +71,7 @@ type GroupExitActionGateway = Pick<WechatActionGateway, 'execute'> &
class GroupExitMonitorService {
private readonly actionGateway: GroupExitActionGateway
private active = false
private enabled = true
private nativeMonitorActive = false
private snapshots = new Map<string, GroupSnapshotRecord>()
private changeTimer: NodeJS.Timeout | null = null
@@ -103,7 +105,8 @@ class GroupExitMonitorService {
this.ensureLoaded()
return {
events: [...this.events],
running: this.active && chat.isReady(),
enabled: this.enabled,
running: this.enabled && this.active && chat.isReady(),
nativeMonitorActive: this.nativeMonitorActive,
monitoredGroupCount: this.snapshots.size,
monitorSelectionConfigured: this.monitorSelectionConfigured,
@@ -143,6 +146,11 @@ class GroupExitMonitorService {
this.active = true
this.nativeMonitorActive = nativeMonitorActive
this.checkQueued = false
if (!this.enabled) {
this.save()
this.broadcast()
return
}
this.initializing = true
const scopeGeneration = ++this.scopeGeneration
this.eventSequence += 1
@@ -178,7 +186,7 @@ class GroupExitMonitorService {
}
notifyDatabaseChanged(rawPayload: string): void {
if (!this.active || !isContactEvent(rawPayload)) return
if (!this.enabled || !this.active || !isContactEvent(rawPayload)) return
try {
chat.getChatDb()?.getWcdb4Client().invalidateGroupNicknameCache()
} catch {
@@ -193,6 +201,8 @@ class GroupExitMonitorService {
}
async checkNow(): Promise<GroupExitMonitorState> {
this.ensureLoaded()
if (!this.enabled) return this.getState()
if (!this.active && chat.isReady()) await this.start(false)
await this.check()
return this.getState()
@@ -223,7 +233,31 @@ class GroupExitMonitorService {
this.save()
this.broadcast()
// 建立基线放到后台,保存配置可以立即返回。
if (this.active) void this.check()
if (this.enabled && this.active) void this.check()
return this.getState()
}
async setEnabled(enabled: boolean): Promise<GroupExitMonitorState> {
this.ensureLoaded()
if (this.enabled === enabled) return this.getState()
this.enabled = enabled
this.eventSequence += 1
this.scopeGeneration += 1
this.checkQueued = false
this.hydrationQueue.clear()
if (this.changeTimer) clearTimeout(this.changeTimer)
this.changeTimer = null
if (enabled) {
// 用户主动暂停期间的成员变化不补报;重新开启后从当前状态建立新基线。
this.snapshots.clear()
this.lastCheckedAt = undefined
this.groupNamesRefreshPending = true
}
this.save()
this.broadcast()
if (enabled && this.active && chat.isReady()) await this.check()
return this.getState()
}
@@ -261,6 +295,7 @@ class GroupExitMonitorService {
const currentRoot = chat.getCurrentAccountRoot()
if (
!this.active ||
!this.enabled ||
!chat.isReady() ||
!currentRoot ||
!this.accountRoot ||
@@ -296,7 +331,7 @@ class GroupExitMonitorService {
const result = await this.readMemberships()
const membershipCostMs = Date.now() - startedAt
let changedGroups = 0
if (result.groups && this.active && scopeGeneration === this.scopeGeneration) {
if (result.groups && this.enabled && this.active && scopeGeneration === this.scopeGeneration) {
changedGroups = await this.applyCurrentMemberships(result.groups, scopeGeneration)
}
console.log(
@@ -367,7 +402,9 @@ class GroupExitMonitorService {
const notifications: Array<{ group: GroupSnapshotRecord; event: GroupExitMonitorEvent }> = []
let changedGroups = 0
for (const membership of groups) {
if (!this.active || scopeGeneration !== this.scopeGeneration) return changedGroups
if (!this.enabled || !this.active || scopeGeneration !== this.scopeGeneration) {
return changedGroups
}
if (membership.membersValid === false) continue
const previous = this.snapshots.get(membership.roomId)
// 空数组可能是查询失败,先保留旧基线,避免误报和覆盖最后有效快照。
@@ -407,7 +444,9 @@ class GroupExitMonitorService {
}
}
if (!this.active || scopeGeneration !== this.scopeGeneration) return changedGroups
if (!this.enabled || !this.active || scopeGeneration !== this.scopeGeneration) {
return changedGroups
}
this.lastCheckedAt = Date.now()
// 先把事件和新基线作为同一检查点落盘,再执行可失败的通知动作。
this.save()
@@ -419,7 +458,7 @@ class GroupExitMonitorService {
}
private startNextSnapshotHydration(): void {
if (!this.active) {
if (!this.enabled || !this.active) {
this.finishHydrationBatch()
return
}
@@ -635,6 +674,7 @@ class GroupExitMonitorService {
this.loaded = true
try {
const stored = fs.readJsonSync(this.filePath()) as StoredState
this.enabled = stored.enabled !== false
this.events = normalizeEvents(stored.events)
this.actionGateway.registerMemberEvents?.(this.events)
this.lastReadAt = Number(stored.lastReadAt) || 0
@@ -654,6 +694,7 @@ class GroupExitMonitorService {
} catch {
// 首次启动或文件损坏时从空记录开始。
this.events = []
this.enabled = true
this.lastReadAt = 0
this.monitorSelectionConfigured = true
this.monitoredRoomIds.clear()
@@ -671,6 +712,7 @@ class GroupExitMonitorService {
this.filePath(),
{
accountRoot: this.accountRoot,
enabled: this.enabled,
events: this.events,
lastReadAt: this.lastReadAt,
monitorSelectionConfigured: this.monitorSelectionConfigured,
+44 -5
View File
@@ -21,6 +21,7 @@ import { personalWechatSendService } from './personal-wechat-send-service'
const MAX_AUDIT_RECORDS = 500
const MAX_CONTENT_PREVIEW_LENGTH = 240
export const AUTOMATION_SEND_INTERVAL_MS = 3_000
const AUTOMATION_PURPOSE_ALLOWLIST = new Set(['scheduled_report', 'member_left_notification'])
export interface WechatActionGatewayDependencies {
@@ -34,6 +35,7 @@ export interface WechatActionGatewayDependencies {
| undefined
getUserDataPath?: () => string
now?: () => Date
wait?: (milliseconds: number) => Promise<void>
}
interface LoadedAuditState {
@@ -46,12 +48,16 @@ export interface WechatActionPolicyContext {
}
const defaultDependencies = (): Required<
Pick<WechatActionGatewayDependencies, 'getCapability' | 'send' | 'getUserDataPath' | 'now'>
Pick<
WechatActionGatewayDependencies,
'getCapability' | 'send' | 'getUserDataPath' | 'now' | 'wait'
>
> => ({
getCapability: () => personalWechatCapabilityService.getPersonalWechatSendCapability(),
send: (request) => personalWechatSendService.send(request),
getUserDataPath: () => app.getPath('userData'),
now: () => new Date()
now: () => new Date(),
wait: (milliseconds) => new Promise((resolve) => setTimeout(resolve, milliseconds))
})
/**
@@ -60,12 +66,20 @@ const defaultDependencies = (): Required<
*/
export class WechatActionGateway {
private readonly deps: Required<
Pick<WechatActionGatewayDependencies, 'getCapability' | 'send' | 'getUserDataPath' | 'now'>
Pick<
WechatActionGatewayDependencies,
'getCapability' | 'send' | 'getUserDataPath' | 'now' | 'wait'
>
> &
Omit<WechatActionGatewayDependencies, 'getCapability' | 'send' | 'getUserDataPath' | 'now'>
Omit<
WechatActionGatewayDependencies,
'getCapability' | 'send' | 'getUserDataPath' | 'now' | 'wait'
>
private readonly memberEvents = new Map<string, WechatActionMemberEventReference>()
private readonly inFlight = new Map<string, Promise<WechatActionResult>>()
private auditState: LoadedAuditState | null = null
private automationSendTail: Promise<void> = Promise.resolve()
private lastAutomationSendStartedAt: number | undefined
constructor(deps: WechatActionGatewayDependencies = {}) {
this.deps = { ...defaultDependencies(), ...deps }
@@ -87,6 +101,10 @@ export class WechatActionGateway {
this.memberEvents.clear()
}
listAuditRecords(): WechatActionAuditRecord[] {
return this.loadAuditState().records.map((record) => ({ ...record }))
}
async execute(request: WechatActionRequest): Promise<WechatActionResult> {
const normalized = normalizeActionRequest(request)
const idempotencyKey = normalized ? this.idempotencyKey(normalized) : undefined
@@ -176,7 +194,7 @@ export class WechatActionGateway {
let sendResult: PersonalWechatSendResult
try {
sendResult = await this.deps.send(toPersonalWechatSendRequest(request))
sendResult = await this.send(request)
} catch (error) {
return this.finishFailed(
actionId,
@@ -201,6 +219,26 @@ export class WechatActionGateway {
return this.finishSent(actionId, request, idempotencyKey, startedAt, sendResult)
}
private send(request: WechatActionRequest): Promise<PersonalWechatSendResult> {
const sendRequest = toPersonalWechatSendRequest(request)
if (request.triggerType !== 'automation') return this.deps.send(sendRequest)
const queued = this.automationSendTail.then(async () => {
const now = this.deps.now().getTime()
const remaining = this.lastAutomationSendStartedAt !== undefined
? Math.max(0, AUTOMATION_SEND_INTERVAL_MS - (now - this.lastAutomationSendStartedAt))
: 0
if (remaining > 0) await this.deps.wait(remaining)
this.lastAutomationSendStartedAt = this.deps.now().getTime()
return this.deps.send(sendRequest)
})
this.automationSendTail = queued.then(
() => undefined,
() => undefined
)
return queued
}
private async resolveEventContext(
request: WechatActionRequest
): Promise<WechatActionPolicyContext> {
@@ -364,6 +402,7 @@ export class WechatActionGateway {
...(request.executionId ? { executionId: request.executionId } : {}),
recipientType: request.recipient.type,
recipientId: request.recipient.id,
...(request.recipient.name ? { recipientName: request.recipient.name } : {}),
contentType: request.content.type,
...contentAudit(request.content),
createdAt: result.startedAt,
@@ -0,0 +1,55 @@
import type { ActionLogEntry } from '../../shared/action-log'
import type { Contact } from '../../shared/types'
import type { WechatActionAuditRecord } from '../../shared/wechat-action'
import * as chat from './chat-service'
import { wechatActionGateway } from './wechat-action-gateway'
export interface WechatActionLogServiceDependencies {
listAuditRecords?: () => WechatActionAuditRecord[]
listContacts?: () => Contact[]
}
export class WechatActionLogService {
private readonly listAuditRecords: () => WechatActionAuditRecord[]
private readonly listContacts: () => Contact[]
constructor(deps: WechatActionLogServiceDependencies = {}) {
this.listAuditRecords = deps.listAuditRecords || (() => wechatActionGateway.listAuditRecords())
this.listContacts = deps.listContacts || (() => chat.listContacts())
}
list(): ActionLogEntry[] {
let contacts: Contact[] = []
try {
contacts = this.listContacts()
} catch {
// 数据库未连接时仍可查看历史审计。
}
const names = new Map(
contacts.map((contact) => [
contact.m_nsUsrName,
contact.m_nsNickName?.trim() || contact.remark?.trim() || contact.m_nsUsrName
])
)
return this.listAuditRecords()
.map((record) => ({
id: record.actionId,
category: 'wechat_send' as const,
source: record.origin,
purpose: record.purpose,
timestamp: record.finishedAt || record.startedAt || record.createdAt,
recipientType: record.recipientType,
recipientId: record.recipientId,
recipientName: record.recipientName || names.get(record.recipientId),
contentType: record.contentType,
contentPreview: record.contentPreview,
status: record.sendStatus,
errorCode: record.errorCode,
reason: record.decisionReason
}))
.sort((left, right) => Date.parse(right.timestamp) - Date.parse(left.timestamp))
}
}
export const wechatActionLogService = new WechatActionLogService()
+20
View File
@@ -13,6 +13,8 @@ export interface Wcdb4Session {
avatar?: string
wechatNickname?: string
remark?: string
alias?: string
wechatId?: string
isFolded?: boolean
isMuted?: boolean
raw: Record<string, unknown>
@@ -1030,6 +1032,14 @@ export class Wcdb4Client {
this.sessionDisplayNamesHydrated = false
}
invalidateAvatarCache(usernames?: string[]): void {
if (!usernames) {
this.avatarCache.clear()
return
}
for (const username of this.uniq(usernames)) this.avatarCache.delete(username)
}
/** 清理群备注缓存,不影响会话缓存。 */
invalidateGroupNicknameCache(): void {
this.groupNicknameCache.clear()
@@ -2813,12 +2823,22 @@ export class Wcdb4Client {
'contactRemark',
'contact_remark'
])
const alias = this.pickString(row, ['alias', 'aliasName', 'alias_name', 'm_nsAlias'])
const wechatId = this.pickString(row, [
'wechatId',
'wechat_id',
'wxAccount',
'wx_account',
'account'
])
const status = this.sessionStatusCache.get(username)
return {
username,
nickname,
wechatNickname,
remark,
alias,
wechatId: wechatId || alias,
isFolded: status?.isFolded,
isMuted: status?.isMuted,
raw: row
+12 -4
View File
@@ -7,6 +7,8 @@ export interface UserContact {
avatar?: string
wechatNickname?: string
remark?: string
alias?: string
wechatId?: string
isFolded?: boolean
isMuted?: boolean
}
@@ -102,15 +104,21 @@ export class WechatDb {
avatar: session.avatar,
wechatNickname: session.wechatNickname,
remark: session.remark,
alias: session.alias,
wechatId: session.wechatId,
isFolded: session.isFolded,
isMuted: session.isMuted
}))
.filter((contact) => {
if (!keyword) return true
return (
contact.m_nsUsrName.toLowerCase().includes(keyword) ||
contact.nickname.toLowerCase().includes(keyword)
)
return [
contact.remark,
contact.wechatNickname,
contact.nickname,
contact.alias,
contact.wechatId,
contact.m_nsUsrName
].some((value) => value?.toLocaleLowerCase().includes(keyword))
})
}