feat: 退群监控接入自动化能力统一管理, 支持发送个人/文件传输助手/指定群聊

This commit is contained in:
Wxw-Gu committed 2026-09-24 16:31:07 +08:00
1 parent 3bd3935042
commit 59872daf52
43 files changed
+5661 -1132

No files matched your search

+126 -1
View File
@@ -8,8 +8,13 @@ import {
type AutomationAction,
type AutomationRule,
type AutomationStep,
type AutomationStepKey
type AutomationStepKey,
type LeaveNotificationConfig
} from '../../shared/automation'
import {
renderLeaveNotificationText,
type GroupMemberExitedEvent
} from '../../shared/group-exit-event'
import type { WechatActionContent, WechatActionRequest, WechatActionResult } from '../../shared/wechat-action'
import {
generateAgentGroupReport,
@@ -17,6 +22,7 @@ import {
type AgentGroupReportResult
} from './agent-group-report-service'
import { wechatActionGateway } from './wechat-action-gateway'
import type { LeaveNotificationTargetResolution } from './leave-notification-target'
/**
* AutomationActionRunner —— 把一次命中跑成**步骤序列**。
@@ -32,6 +38,14 @@ import { wechatActionGateway } from './wechat-action-gateway'
/** 一步执行完毕后,后续步骤的处置方式。 */
const STEP_ORDER: AutomationStepKey[] = ['received', 'matched', 'reply', 'report', 'send']
/** 退群通知的步骤顺序(与消息型规则**不共用**)。 */
const LEAVE_NOTIFICATION_STEP_ORDER: AutomationStepKey[] = [
'exit_received',
'exit_matched',
'exit_target',
'exit_send'
]
/**
* 前置步骤失败时,后续步骤的 `skipReason`。
*
@@ -65,6 +79,30 @@ export interface AutomationRunResult {
pngPath?: string
}
/**
* 退群通知的执行输入。
*
* 目标解析与发送能力预检都由 `AutomationService` 在调用前完成,
* 这里只负责"把它跑成步骤序列" —— 于是**所有步骤构造只在一处**,
* 不会出现"服务拼一半、runner 拼一半"的裂口。
*/
export interface LeaveNotificationRunInput {
executionId: string
event: GroupMemberExitedEvent
config: LeaveNotificationConfig
resolution: LeaveNotificationTargetResolution
/** 事件来源的显示名(群名 / 「群聊」)。**不含 wxid**。 */
sourceDisplayName: string
/** 发送能力缺失时的一句话说明;有值时 `exit_send` 直接判失败。 */
sendBlockedReason?: string
}
export interface LeaveNotificationRunResult {
steps: AutomationStep[]
status: 'success' | 'failed'
errorSummary?: string
}
export interface AutomationActionRunnerDependencies {
generateReport?: (request: AgentGroupReportRequest) => Promise<AgentGroupReportResult>
executeAction?: (request: WechatActionRequest) => Promise<WechatActionResult>
@@ -235,6 +273,93 @@ export class AutomationActionRunner {
return { steps, status: 'success', pngPath }
}
/**
* 退群通知:把「检测到成员退出」这件事跑成一次发送。
*
* 与 `run()` 的差别:没有动作链、没有回复等待、没有 cooldown
* (退群是低频事件,且**不能被时间窗合并** —— 两个成员先后退出就是两条通知)。
*/
async runLeaveNotification(input: LeaveNotificationRunInput): Promise<LeaveNotificationRunResult> {
const steps = LEAVE_NOTIFICATION_STEP_ORDER.map((key) => createStep(key))
const stepAt = (key: AutomationStepKey): AutomationStep =>
steps.find((step) => step.key === key) as AutomationStep
markSuccess(stepAt('exit_received'), this.now())
markSuccess(stepAt('exit_matched'), this.now())
// ---- 目标解析失败:不许 fallback 到任何地方,直接判失败 ----
if (!input.resolution.ok) {
markFailed(stepAt('exit_target'), this.now(), input.resolution.error)
markSkipped(stepAt('exit_send'), '没有可用的通知目标,未发送。')
return { steps, status: 'failed', errorSummary: input.resolution.error }
}
const targetStep = stepAt('exit_target')
targetStep.status = 'success'
targetStep.startedAt = this.now()
targetStep.finishedAt = targetStep.startedAt
targetStep.durationMs = 0
// 用户可读的目标名(例如「文件传输助手」「张三」「我」)—— 不带任何 id。
targetStep.detail = input.resolution.target.displayName
const sendStep = stepAt('exit_send')
// ---- 发送能力缺失:如实判失败(退群事实本身仍然是成功的) ----
if (input.sendBlockedReason) {
markFailed(sendStep, this.now(), input.sendBlockedReason)
return { steps, status: 'failed', errorSummary: input.sendBlockedReason }
}
const text = renderLeaveNotificationText(input.event, input.config.template).trim()
if (!text) {
const error = '通知内容为空,未发送。'
markFailed(sendStep, this.now(), error)
return { steps, status: 'failed', errorSummary: error }
}
sendStep.status = 'running'
sendStep.startedAt = this.now()
const sent = await this.sendLeaveNotification(input, text)
if (!sent.ok) {
markFailed(sendStep, this.now(), sent.error || '发送退群通知失败')
return { steps, status: 'failed', errorSummary: sendStep.error }
}
markSuccess(sendStep, this.now())
return { steps, status: 'success' }
}
/**
* 退群通知的统一发送出口。
*
* **必须走 `WechatActionGateway`**:幂等 + 3 秒发送间隔 + 审计落盘都在那里,
* 直接调个人微信发送会绕过全部三样。Automation 层也不允许知道
* OneBot / WCHook / native host / Windows hook 的存在。
*
* 幂等键由 **eventId** 派生(不是 executionId):审计是落盘的,
* 于是"重启后重复投递同一退群事件"会被持久层直接短路。
*/
private async sendLeaveNotification(
input: LeaveNotificationRunInput,
text: string
): Promise<{ ok: boolean; error?: string }> {
if (!input.resolution.ok) return { ok: false, error: input.resolution.error }
try {
const result = await this.executeAction({
idempotencyKey: `${AUTOMATION_SEND_PURPOSE.leaveNotification}:${input.event.eventId}`,
origin: AUTOMATION_SEND_ORIGIN,
purpose: AUTOMATION_SEND_PURPOSE.leaveNotification,
triggerType: 'automation',
executionId: input.executionId,
sourceId: input.event.eventId,
recipient: input.resolution.target.recipient,
content: { type: 'text', text }
})
if (result.status === 'sent') return { ok: true }
return { ok: false, error: actionErrorMessage(result.errorCode, result.reason) }
} catch (error) {
return { ok: false, error: error instanceof Error ? error.message : String(error) }
}
}
/**
* 统一发送出口。
*
+272 -9
View File
@@ -3,10 +3,22 @@ import path from 'node:path'
import { app } from 'electron'
import fs from 'fs-extra'
import {
BUILTIN_LEAVE_NOTIFICATION_RULE_ID,
createDefaultDailyReportRule,
createDefaultLeaveNotificationRule,
normalizeRuleDraft,
type AutomationRule
type AutomationRule,
type AutomationRuleType
} from '../../shared/automation'
import {
planLeaveNotificationMigration,
type LeaveNotificationMigrationPlan,
type LegacyLeaveNotificationState
} from './leave-notification-migration'
import {
GROUP_EXIT_NOTIFICATION_TEMPLATE_MAX_LENGTH,
insertGroupNamePlaceholder
} from '../../shared/group-exit-monitor'
/**
* AutomationRuleStore —— 自动化规则的持久化与增删改查。
@@ -17,15 +29,31 @@ import {
* **内置规则的播种标记(`builtinSeeded`)单独存**:
* 如果靠"文件里有没有那条内置规则"来判断是否播种,用户一旦删掉它,
* 下次启动就会被重新塞回来 —— 用户会认为删除功能坏了。
*
* 退群通知的迁移标记(`leaveNotificationMigrated`)同理:迁移**只允许跑一次**,
* 否则用户删掉退群通知规则后重启又被塞回来。
*/
const STORAGE_DIR = 'automation'
const RULES_FILE = 'rules.json'
const MIGRATION_BACKUP_FILE = 'leave-notification-migration-backup.json'
/** 旧退群监控的状态文件(迁移时读一次,之后运行期不再读)。 */
const LEGACY_MONITOR_FILE = 'group-exit-monitor.json'
const CURRENT_VERSION = 3
interface StoredRules {
version: number
/** 内置规则是否已经播种过。**即使随后被删除也保持 true**。 */
/** 内置「@我生成日报」是否已经播种过。**即使随后被删除也保持 true**。 */
builtinSeeded: boolean
/** 旧退群通知配置是否已经迁移过。**即使随后被删除也保持 true**。 */
leaveNotificationMigrated: boolean
/**
* 是否已经替用户往模板里补过 `{groupName}`。
*
* **必须有这个标记**:没有它就得靠"模板里有没有 `{groupName}`"来判断,
* 于是用户主动删掉那一行后、下次启动又会被补回来 —— 删不掉的东西最烦人。
*/
notificationTemplateUpgraded: boolean
rules: AutomationRule[]
}
@@ -35,22 +63,95 @@ export interface AutomationRuleStoreDependencies {
}
function emptyState(): StoredRules {
return { version: 1, builtinSeeded: false, rules: [] }
return {
version: CURRENT_VERSION,
builtinSeeded: false,
leaveNotificationMigrated: false,
notificationTemplateUpgraded: false,
rules: []
}
}
/** 读盘容错:任何字段可疑都降级成安全值,绝不因为一个坏文件让功能整体不可用。 */
function normalizeStored(value: unknown): StoredRules {
function normalizeRuleType(value: unknown): AutomationRuleType {
return value === 'leave_notification' ? 'leave_notification' : 'daily_report'
}
/**
* 单条规则的读盘归一化。
*
* 走 `normalizeRuleDraft` —— 它覆盖了 `AutomationRule` 除 id / 时间戳之外的**全部**字段,
* 所以这是无损的,同时自动补上历史 rules.json 缺失的 `ruleType` / `leaveNotification`。
*/
function normalizeStoredRule(value: unknown): AutomationRule | null {
if (!value || typeof value !== 'object') return null
const raw = value as Partial<AutomationRule>
const id = String(raw.id || '').trim()
if (!id) return null
const ruleType = normalizeRuleType(raw.ruleType)
const normalized = normalizeRuleDraft(
{
...raw,
ruleType,
// 历史 daily_report 规则没有 leaveNotification;反过来也要避免脏字段落盘。
...(ruleType === 'leave_notification' ? { leaveNotification: raw.leaveNotification } : {})
},
String(raw.name || '').trim() || '未命名自动化'
)
const createdAt = Number(raw.createdAt) || 0
const updatedAt = Number(raw.updatedAt) || createdAt
return {
...normalized,
id,
createdAt,
updatedAt,
...(normalized.ruleType === 'leave_notification' && normalized.leaveNotification
? { leaveNotification: normalized.leaveNotification }
: {})
}
}
/**
* 一次性替用户把 `{groupName}` 补进退群通知模板。
*
* **为什么替他填**:模板里原先根本没有群名变量(`{groupRemark}` 是成员在本群的昵称)。
* 目标一旦不是「当前群聊」,通知就等于「张三退群了」—— 收件人不知道是哪个群。
* 模板是用户已保存的数据,让他自己去发现"少一个变量"是不合理的。
*
* **为什么只跑一次**:靠"模板里有没有 `{groupName}`"判断会导致用户删掉后被反复补回来。
* 所以由 `notificationTemplateUpgraded` 标记保证一次性;用户之后删掉不会回来。
*/
function upgradeLeaveNotificationTemplate(rules: AutomationRule[]): {
rules: AutomationRule[]
count: number
} {
let count = 0
const next = rules.map((rule) => {
if (rule.ruleType !== 'leave_notification' || !rule.leaveNotification) return rule
const current = rule.leaveNotification.template
const upgraded = insertGroupNamePlaceholder(current)
// 补完不能超长:超了下次读盘会被校验拦下、整条模板被重置成默认,反而更糟。
if (upgraded === current || upgraded.length > GROUP_EXIT_NOTIFICATION_TEMPLATE_MAX_LENGTH) {
return rule
}
count += 1
return { ...rule, leaveNotification: { ...rule.leaveNotification, template: upgraded } }
})
return { rules: next, count }
}
/** 读盘容错:任何字段可疑都降级成安全值,绝不因为一个坏文件让功能整体不可用。 */function normalizeStored(value: unknown): StoredRules {
if (!value || typeof value !== 'object') return emptyState()
const input = value as Partial<StoredRules>
const rules = Array.isArray(input.rules)
? input.rules.filter(
(rule): rule is AutomationRule =>
Boolean(rule && typeof rule === 'object' && String(rule.id || '').trim())
)
? input.rules
.map((rule) => normalizeStoredRule(rule))
.filter((rule): rule is AutomationRule => rule !== null)
: []
return {
version: Number(input.version) || 1,
builtinSeeded: input.builtinSeeded === true,
leaveNotificationMigrated: input.leaveNotificationMigrated === true,
notificationTemplateUpgraded: input.notificationTemplateUpgraded === true,
rules
}
}
@@ -60,6 +161,8 @@ export class AutomationRuleStore {
private readonly now: () => number
private state: StoredRules = emptyState()
private loaded = false
/** 迁移结果,供启动日志/报告读取(不含任何 id)。 */
private lastMigrationPlan: LeaveNotificationMigrationPlan | null = null
constructor(dependencies: AutomationRuleStoreDependencies = {}) {
this.userDataPath = dependencies.userDataPath ?? (() => app.getPath('userData'))
@@ -78,6 +181,12 @@ export class AutomationRuleStore {
return found
}
/** 上一次迁移的判定结果(未迁移时为 null)。 */
getLastLeaveNotificationMigration(): LeaveNotificationMigrationPlan | null {
this.ensureLoaded()
return this.lastMigrationPlan ? { ...this.lastMigrationPlan } : null
}
createRule(draft: unknown): AutomationRule {
this.ensureLoaded()
const timestamp = this.now()
@@ -105,14 +214,51 @@ export class AutomationRuleStore {
...current,
...normalized,
id: current.id,
// ruleType 不允许被草稿改掉:它是规则的**身份**,不是可编辑字段。
ruleType: current.ruleType,
...(current.ruleType === 'leave_notification' && normalized.leaveNotification
? { leaveNotification: normalized.leaveNotification }
: {}),
createdAt: current.createdAt,
updatedAt: this.now()
}
// 切类型时不能留下另一种类型才认识的字段。
if (rule.ruleType === 'daily_report') delete rule.leaveNotification
this.state.rules = this.state.rules.map((item, at) => (at === index ? rule : item))
this.persist()
return structuredClone(rule)
}
/**
* 保存「退群通知」规则(**singleton upsert**)。
*
* 不存在则创建(固定 id),存在则更新 —— 所以点多少次保存都只有一条规则。
*/
saveLeaveNotificationRule(draft: unknown): AutomationRule {
this.ensureLoaded()
const existing = this.state.rules.find(
(rule) => rule.id === BUILTIN_LEAVE_NOTIFICATION_RULE_ID
)
if (existing) {
const updated = this.updateRule(existing.id, { ...(draft as object), ruleType: 'leave_notification' })
if (updated) return updated
}
const timestamp = this.now()
const normalized = normalizeRuleDraft({ ...(draft as object), ruleType: 'leave_notification' })
const rule: AutomationRule = {
...createDefaultLeaveNotificationRule(timestamp),
...normalized,
id: BUILTIN_LEAVE_NOTIFICATION_RULE_ID,
ruleType: 'leave_notification',
name: normalized.name || '退群通知',
createdAt: timestamp,
updatedAt: timestamp
}
this.state.rules = [...this.state.rules, rule]
this.persist()
return structuredClone(rule)
}
deleteRule(id: string): boolean {
this.ensureLoaded()
const key = String(id || '').trim()
@@ -142,10 +288,123 @@ export class AutomationRuleStore {
stored.builtinSeeded = true
stored.rules = [...stored.rules, createDefaultDailyReportRule(this.now())]
}
if (!stored.leaveNotificationMigrated) {
stored.leaveNotificationMigrated = true
stored.rules = this.migrateLeaveNotification(stored.rules)
}
if (!stored.notificationTemplateUpgraded) {
stored.notificationTemplateUpgraded = true
const upgraded = upgradeLeaveNotificationTemplate(stored.rules)
stored.rules = upgraded.rules
// 只记条数,**不记模板正文**。
if (upgraded.count > 0) {
console.log(`[Automation] 退群通知模板已补上群名变量(${upgraded.count} 条)`)
}
}
stored.version = CURRENT_VERSION
this.state = stored
this.persist()
}
/** 旧退群通知配置 → 内置退群通知规则。**只跑一次**,且先备份旧配置。 */
private migrateLeaveNotification(rules: AutomationRule[]): AutomationRule[] {
if (rules.some((rule) => rule.id === BUILTIN_LEAVE_NOTIFICATION_RULE_ID)) return rules
const timestamp = this.now()
const legacy = this.readLegacyLeaveNotificationState()
if (!legacy) {
// 全新安装:没有历史可迁,直接建默认规则(默认目标:文件传输助手)。
this.logMigration('fresh_install', null)
return [...rules, createDefaultLeaveNotificationRule(timestamp)]
}
const plan = planLeaveNotificationMigration(legacy)
this.lastMigrationPlan = plan
this.writeMigrationBackup(legacy, plan)
this.logMigration(plan.outcome, plan)
return [
...rules,
createDefaultLeaveNotificationRule(timestamp, {
template: plan.template,
target: plan.target,
enabled: plan.enabled,
targetNeedsReview: plan.targetNeedsReview
})
]
}
/**
* 读旧退群监控状态文件里的通知相关字段。
*
* 只读、只在这里读一次;运行期其余代码**不再读** legacy(避免双读)。
* 读失败视为"没有历史配置",不抛。
*/
private readLegacyLeaveNotificationState(): LegacyLeaveNotificationState | null {
try {
const raw = fs.readJsonSync(
path.join(this.userDataPath(), LEGACY_MONITOR_FILE)
) as Partial<LegacyLeaveNotificationState>
if (!raw || typeof raw !== 'object') return null
return {
monitoredRoomIds: Array.isArray(raw.monitoredRoomIds) ? raw.monitoredRoomIds : [],
notificationRoomIds: Array.isArray(raw.notificationRoomIds) ? raw.notificationRoomIds : [],
...(raw.notificationTemplate !== undefined
? { notificationTemplate: raw.notificationTemplate }
: {})
}
} catch {
return null
}
}
/**
* 迁移前把旧配置原样落一份 backup。
*
* §「不要不可逆直接覆盖」:旧状态文件本身也**不删**,只是不再被运行时代码读取。
*/
private writeMigrationBackup(
legacy: LegacyLeaveNotificationState,
plan: LeaveNotificationMigrationPlan
): void {
try {
const filePath = path.join(this.userDataPath(), STORAGE_DIR, MIGRATION_BACKUP_FILE)
fs.ensureDirSync(path.dirname(filePath))
fs.writeJsonSync(
filePath,
{
migratedAt: this.now(),
outcome: plan.outcome,
// 备份里保留原始 roomId:这是**用户数据**,不是日志,不进任何用户可见界面。
legacy: {
monitoredRoomIds: legacy.monitoredRoomIds,
notificationRoomIds: legacy.notificationRoomIds,
notificationTemplate: legacy.notificationTemplate
},
applied: {
enabled: plan.enabled,
targetType: plan.target.type,
targetNeedsReview: plan.targetNeedsReview
}
},
{ spaces: 2 }
)
} catch (error) {
console.warn(
`[Automation] 写入退群通知迁移备份失败: ${errorText(error)}`
)
}
}
/** 迁移日志:只允许出现判定结果与布尔量,**禁止** roomId / 模板正文。 */
private logMigration(outcome: string, plan: LeaveNotificationMigrationPlan | null): void {
if (!plan) {
console.log(`[Automation] 退群通知迁移 outcome=${outcome}`)
return
}
console.log(
`[Automation] 退群通知迁移 outcome=${outcome} enabled=${plan.enabled}` +
` targetType=${plan.target.type} needsReview=${plan.targetNeedsReview}`
)
}
private rulesFilePath(): string {
return path.join(this.userDataPath(), STORAGE_DIR, RULES_FILE)
}
@@ -163,4 +422,8 @@ export class AutomationRuleStore {
}
}
function errorText(error: unknown): string {
return error instanceof Error ? error.message : String(error)
}
export const automationRuleStore = new AutomationRuleStore()
+194 -8
View File
@@ -1,18 +1,25 @@
import { randomUUID } from 'node:crypto'
import { createHash, randomUUID } from 'node:crypto'
import {
matchAutomationRule,
type AutomationMatchInput
} from '../../shared/automation-matcher'
import type {
AutomationExecution,
AutomationRule,
AutomationStatusSummary
import {
AUTOMATION_SEND_PURPOSE,
BUILTIN_LEAVE_NOTIFICATION_RULE_ID,
type AutomationExecution,
type AutomationRule,
type AutomationStatusSummary
} from '../../shared/automation'
import type { GroupMemberExitedEvent } from '../../shared/group-exit-event'
import type { PersonalWechatSendCapability } from '../../shared/personal-wechat'
import type { Wcdb4Client } from '../wcdb4-client'
import type { NormalizedIncomingMessage } from './message-listener-service'
import { listContacts } from './chat-service'
import { getSelfAccountInfo, listContacts } from './chat-service'
import { getPersonalWechatSendCapability } from './personal-wechat-capability-service'
import {
resolveLeaveNotificationTarget,
type LeaveNotificationTargetResolution
} from './leave-notification-target'
import {
automationRuleStore,
type AutomationRuleStore
@@ -80,6 +87,37 @@ const CLAIM_MAX_ENTRIES = 5_000
/** 自己的 username 候选集缓存时长 —— 这个值几乎不变,没必要每条消息都查。 */
const SELF_USERNAME_TTL_MS = 30_000
/**
* 退群事件幂等表的容量上限。
*
* 退群是低频事件,这里不需要 MessageListener 那种 5000 级容量;
* 但同样要有界,避免长跑期间无界增长。
*/
const EXIT_CLAIM_MAX_ENTRIES = 1_000
/**
* 由 `ruleId + eventId` 推出**确定性** executionId。
*
* 为什么要确定而不是 `randomUUID()`:幂等必须跨进程重启成立。
* 同一 eventId 重新投递时算出同一个 executionId,`ExecutionLog.record()` 按 id 覆盖,
* 于是"同一事件只产生一条 execution"在重启后依然成立。
*/
export function leaveNotificationExecutionId(ruleId: string, eventId: string): string {
return createHash('sha1')
.update(`leave_notification\u0001${ruleId}\u0001${eventId}`)
.digest('hex')
}
/**
* 退群通知的发送幂等键。
*
* **必须由 eventId 派生**(而不是 executionId 派生):gateway 的审计是落盘的,
* 用 eventId 才能让"重启后重复投递同一事件"被持久层直接短路掉。
*/
export function leaveNotificationIdempotencyKey(eventId: string): string {
return `${AUTOMATION_SEND_PURPOSE.leaveNotification}:${eventId}`
}
export interface AutomationServiceDependencies {
ruleStore?: AutomationRuleStore
executionLog?: AutomationExecutionLogService
@@ -106,6 +144,13 @@ export class AutomationService {
/** `ruleId:sessionId:localId` → 登记时间。 */
private readonly claims = new Map<string, ClaimEntry>()
/**
* 退群事件幂等表:`ruleId:eventId` → 登记时间。
*
* 与消息型 `claims` 分开:退群事件没有 `localId` 这个概念,
* 硬塞进同一张表会让两边的 key 语义混在一起。
*/
private readonly exitClaims = new Map<string, ClaimEntry>()
/**
* Automation rule ↔ conversation gate。
*
@@ -247,8 +292,149 @@ export class AutomationService {
}
}
/** 「在哪些聊天生效」的可选项。`id` 必须是 `xxx@chatroom`,与 message.sessionId 对齐。 */
listGroups(): Array<{ id: string; name: string }> {
/**
* 退群事件入口。**绝不抛** —— 它挂在 `GroupExitMonitorService` 的回调上,
* 抛出去会污染监控循环(退群事实已经记录成功,不能被通知失败连累)。
*
* 与 `handleMessage` 的分工:
* - 消息型规则:MessageListener → handleMessage → 动作链;
* - 退群通知:GroupExitMonitor → **本入口** → 单次文本发送。
*
* 三层闸门(缺一不可):
* 1. `enabled === false` → 不执行,**且不创建 execution**(§「没有执行:不创建」);
* 2. `targetNeedsReview` → 迁移过来但目标无法无损映射,同样不执行、不创建记录;
* 3. `ruleId + eventId` 幂等 → 同一事件即使重复投递也只发送一次。
*/
async handleGroupExit(event: GroupMemberExitedEvent): Promise<void> {
const eventId = String(event?.eventId || '').trim()
let rule: AutomationRule | undefined
try {
rule = this.ruleStore.getRule(BUILTIN_LEAVE_NOTIFICATION_RULE_ID)
} catch (error) {
this.warn(`读取退群通知规则失败: ${errorText(error)}`)
return
}
if (!rule || rule.ruleType !== 'leave_notification' || !rule.leaveNotification) return
if (!eventId) {
this.warn('退群事件缺少事件 id,已跳过本次通知')
return
}
// ① 关闭:不执行、不创建失败记录。
if (!rule.enabled) return
// ② 迁移遗留的"目标待重选":同样不算一次执行,由 UI 提示用户处理。
if (rule.leaveNotification.targetNeedsReview) {
this.warn(`退群通知目标待重新选择,已跳过本次通知 ruleId=${rule.id}`)
return
}
// ③ 幂等(内存快路径)。跨重启那一层由确定性 executionId + gateway 审计兜住。
if (!this.claimGroupExit(rule.id, eventId)) return
const executionId = leaveNotificationExecutionId(rule.id, eventId)
const startedAt = this.now()
const sourceDisplayName = String(event.groupName || '').trim() || '群聊'
// 目标解析与发送能力预检都放在 runner 之外,runner 只负责"跑成步骤"。
const resolution = this.resolveLeaveTarget(rule, event)
const sendBlockedReason = await this.leaveNotificationCapabilityError()
let result: Awaited<ReturnType<AutomationActionRunner['runLeaveNotification']>>
try {
result = await this.runner.runLeaveNotification({
executionId,
event,
config: rule.leaveNotification,
resolution,
sourceDisplayName,
...(sendBlockedReason ? { sendBlockedReason } : {})
})
} catch (error) {
result = {
steps: [],
status: 'failed',
errorSummary: `执行过程异常:${errorText(error)}`
}
}
this.executionLog.record(
this.buildExecution({
executionId,
rule,
startedAt,
sourceDisplayName,
status: result.status,
durationMs: this.now() - startedAt,
steps: result.steps,
...(result.errorSummary ? { errorSummary: result.errorSummary } : {})
})
)
// 隐私红线:日志只允许 ruleId / executionId / 状态 / 耗时 / 步骤状态与目标类型。
// 群名、昵称、wxid、模板正文一律不进日志。
const trail = result.steps.map((step) => `${step.key}=${step.status}`).join(' ')
this.info(
`executed ruleId=${rule.id} executionId=${executionId} status=${result.status}` +
` durationMs=${this.now() - startedAt}${trail ? ` ${trail}` : ''}`
)
}
/** 解析退群通知目标(联系人清单 / 自身身份都取自既有能力,不另建一套)。 */
private resolveLeaveTarget(
rule: AutomationRule,
event: GroupMemberExitedEvent
): LeaveNotificationTargetResolution {
let contacts: ReturnType<typeof listContacts> = []
try {
contacts = listContacts()
} catch (error) {
this.warn(`读取联系人失败: ${errorText(error)}`)
}
let selfWxid = ''
try {
selfWxid = String(getSelfAccountInfo()?.wxid || '')
} catch (error) {
this.warn(`读取当前账号失败: ${errorText(error)}`)
}
return resolveLeaveNotificationTarget({
config: rule.leaveNotification,
event,
contacts,
selfWxid
})
}
/** 退群通知只需要文字能力。缺失时给出用户能看懂的一句说明。 */
private async leaveNotificationCapabilityError(): Promise<string | undefined> {
let capability: PersonalWechatSendCapability | null = null
try {
capability = await this.getCapability()
} catch {
return '暂时无法获知微信发送能力,本次退群通知未发送。'
}
if (!capability?.supported) {
return capability?.message || '当前系统不支持微信消息发送'
}
if (!capability.capabilities?.text) {
return '当前环境无法发送文字,本次退群通知未发送。'
}
return undefined
}
/** 退群事件幂等登记(原子 check + 写入,中间无 await)。 */
private claimGroupExit(ruleId: string, eventId: string): boolean {
const key = `${ruleId}:${eventId}`
const now = this.now()
if (this.exitClaims.has(key)) return false
this.exitClaims.set(key, { at: now })
if (this.exitClaims.size > EXIT_CLAIM_MAX_ENTRIES) {
for (const [entryKey, entry] of this.exitClaims) {
if (this.exitClaims.size <= EXIT_CLAIM_MAX_ENTRIES) break
if (now - entry.at > CLAIM_TTL_MS) this.exitClaims.delete(entryKey)
}
}
return true
}
/** 「在哪些聊天生效」的可选项。`id` 必须是 `xxx@chatroom`,与 message.sessionId 对齐。 */ listGroups(): Array<{ id: string; name: string }> {
try {
return listContacts()
.filter((contact) => contact.type === 'group' || contact.m_nsUsrName?.endsWith('@chatroom'))
+71 -164
View File
@@ -2,19 +2,17 @@ import { app, BrowserWindow } from 'electron'
import fs from 'fs-extra'
import path from 'path'
import * as chat from './chat-service'
import { wechatActionGateway, type WechatActionGateway } from './wechat-action-gateway'
import {
buildMemberLeftNotification,
findRemovedGroupMembers,
groupExitMemberName,
normalizeGroupExitNotificationTemplate,
validateGroupExitNotificationTemplate,
type GroupExitMonitorEvent,
type GroupExitMonitorMember,
type GroupExitNotificationStatus,
type GroupExitNotificationState,
type GroupExitMonitorState
} from '../../shared/group-exit-monitor'
import {
toGroupMemberExitedEvent,
type GroupMemberExitedEvent
} from '../../shared/group-exit-event'
type StoredState = {
enabled?: boolean
@@ -23,9 +21,14 @@ type StoredState = {
lastReadAt?: number
monitorSelectionConfigured?: boolean
monitoredRoomIds?: string[]
notificationRoomIds?: string[]
notificationTemplate?: unknown
snapshots?: Partial<StoredGroupSnapshot>[]
/*
* 历史遗留字段(`notificationRoomIds` / `notificationTemplate`)**刻意不再声明**。
*
* 它们已经迁到「自动化 → 退群通知」规则里,本服务运行期不再读、不再写。
* 旧状态文件原样保留在磁盘上(迁移时另有一份 backup),只是没有任何读取方 ——
* 这是"不双读"的落地方式。迁移逻辑在 `automation-rule-store.ts`。
*/
}
type GroupSnapshotRecord = {
@@ -67,17 +70,20 @@ const DUPLICATE_WINDOW_MS = 2 * 60 * 1000
*/
const MAX_EVENTS = 500
/**
* 退群事件处理器。
*
* 由主进程注入成 `automationService.handleGroupExit` —— 本服务**不再自己发送**。
* 契约:**必须自己吞掉异常**(实现方负责),本服务也会再兜一层。
*/
export type GroupExitEventHandler = (event: GroupMemberExitedEvent) => void | Promise<void>
export interface GroupExitMonitorServiceDependencies {
actionGateway?: GroupExitActionGateway
onGroupExit?: GroupExitEventHandler
}
type GroupExitActionGateway = Pick<WechatActionGateway, 'execute'> &
Partial<
Pick<WechatActionGateway, 'registerMemberEvent' | 'registerMemberEvents' | 'clearMemberEvents'>
>
class GroupExitMonitorService {
private readonly actionGateway: GroupExitActionGateway
private onGroupExit: GroupExitEventHandler | undefined
private active = false
private enabled = true
private nativeMonitorActive = false
@@ -95,7 +101,6 @@ class GroupExitMonitorService {
private events: GroupExitMonitorEvent[] = []
private monitorSelectionConfigured = true
private monitoredRoomIds = new Set<string>()
private notificationRoomIds = new Set<string>()
private loaded = false
private accountRoot = ''
private groupNamesByRoomId = new Map<string, string>()
@@ -103,10 +108,19 @@ class GroupExitMonitorService {
private eventSequence = 0
private scopeGeneration = 0
private legacyFallbackLogged = false
private notificationTemplate = normalizeGroupExitNotificationTemplate(undefined)
constructor(deps: GroupExitMonitorServiceDependencies = {}) {
this.actionGateway = deps.actionGateway || wechatActionGateway
this.onGroupExit = deps.onGroupExit
}
/**
* 注入退群事件处理器(主进程在 AutomationService 初始化后调用)。
*
* 用 setter 而不是构造参数:AutomationService 依赖 `Wcdb4Client`,
* 要等数据库解锁后才存在,而本服务是模块级单例。
*/
setGroupExitHandler(handler: GroupExitEventHandler | undefined): void {
this.onGroupExit = handler
}
getState(): GroupExitMonitorState {
@@ -122,8 +136,6 @@ class GroupExitMonitorService {
monitoredGroupCount: this.snapshots.size,
monitorSelectionConfigured: this.monitorSelectionConfigured,
monitoredRoomIds: Array.from(this.monitoredRoomIds),
notificationRoomIds: Array.from(this.notificationRoomIds),
notificationTemplate: this.notificationTemplate,
lastCheckedAt: this.lastCheckedAt,
lastReadAt: this.lastReadAt,
unreadCount: this.events.filter((event) => event.detectedAt > this.lastReadAt).length
@@ -143,13 +155,11 @@ class GroupExitMonitorService {
(this.accountRoot && !sameAccountRoot(currentRoot, this.accountRoot)) ||
(!this.accountRoot && this.snapshots.size > 0)
) {
this.actionGateway.clearMemberEvents?.()
this.events = []
this.rewriteEventsToDisk([])
this.lastReadAt = 0
this.monitorSelectionConfigured = true
this.monitoredRoomIds.clear()
this.notificationRoomIds.clear()
this.snapshots.clear()
this.groupNamesByRoomId.clear()
}
@@ -220,10 +230,13 @@ class GroupExitMonitorService {
return this.getState()
}
async setMonitoredRoomIds(
roomIds: string[],
notificationRoomIds: string[] = []
): Promise<GroupExitMonitorState> {
/**
* 保存**监控范围**。
*
* 参数只剩监控目标 —— 旧版第二个参数(通知群聊)已经迁到自动化规则里,
* 本服务不再持有任何通知配置。
*/
async setMonitoredRoomIds(roomIds: string[]): Promise<GroupExitMonitorState> {
this.ensureLoaded()
this.eventSequence += 1
this.scopeGeneration += 1
@@ -237,10 +250,6 @@ class GroupExitMonitorService {
}
this.monitoredRoomIds = nextMonitoredRoomIds
this.groupNamesRefreshPending = true
const requestedNotifications = normalizeRoomIds(notificationRoomIds)
this.notificationRoomIds = new Set(
Array.from(requestedNotifications).filter((roomId) => this.monitoredRoomIds.has(roomId))
)
this.lastCheckedAt = undefined
this.save()
this.broadcast()
@@ -273,18 +282,6 @@ class GroupExitMonitorService {
return this.getState()
}
setNotificationTemplate(value: unknown): GroupExitMonitorState {
this.ensureLoaded()
const result = validateGroupExitNotificationTemplate(value)
if (!result.valid || !result.template) {
throw new Error(result.error || '退群监测模板无效')
}
this.notificationTemplate = result.template
this.save()
this.broadcast()
return this.getState()
}
/**
* 按群 / 时间范围查退群事件(档案合并展示用)。
*
@@ -320,7 +317,6 @@ class GroupExitMonitorService {
this.events = []
// 磁盘上的 append-only 历史也要清掉,否则下次启动又读回来了。
this.rewriteEventsToDisk([])
this.actionGateway.clearMemberEvents?.()
this.lastReadAt = Date.now()
this.save()
this.broadcast()
@@ -443,7 +439,7 @@ class GroupExitMonitorService {
groups: GroupMembershipRecord[],
scopeGeneration: number
): Promise<number> {
const notifications: Array<{ group: GroupSnapshotRecord; event: GroupExitMonitorEvent }> = []
const exits: GroupExitMonitorEvent[] = []
let changedGroups = 0
for (const membership of groups) {
if (!this.enabled || !this.active || scopeGeneration !== this.scopeGeneration) {
@@ -474,10 +470,9 @@ class GroupExitMonitorService {
if (previous && next.members.length < previous.members.length) {
const removed = findRemovedGroupMembers(previous.members, next.members)
for (const member of removed) {
// 一人一条事件、一条通知 —— 保持既有产品语义,不聚合。
const event = this.recordExit(next, member, previous.members.length, next.members.length)
if (event && this.notificationRoomIds.has(next.roomId)) {
notifications.push({ group: next, event })
}
if (event) exits.push(event)
}
}
@@ -492,12 +487,11 @@ class GroupExitMonitorService {
return changedGroups
}
this.lastCheckedAt = Date.now()
// 先把事件和新基线作为同一检查点落盘,再执行可失败的通知动作。
// 先把事件和新基线作为同一检查点落盘,再交给自动化。
// 「退群事实已记录」与「通知发送成功」是两件独立的事。
this.save()
this.broadcast()
if (notifications.length) {
await Promise.all(notifications.map(({ group, event }) => this.notifyGroup(group, event)))
}
for (const event of exits) this.emitGroupExit(event)
return changedGroups
}
@@ -633,10 +627,8 @@ class GroupExitMonitorService {
currentCount,
delta: currentCount - previousCount,
message,
detectedAt,
notificationStatus: 'not_requested'
detectedAt
}
this.actionGateway.registerMemberEvent?.(event)
// 内存按时间倒序(新事件在前);磁盘**只追加这一条**,不重写历史。
// 这里不再有 `.slice(0, MAX_EVENTS)` —— 事件是永久保留的。
this.events = [event, ...this.events]
@@ -647,83 +639,37 @@ class GroupExitMonitorService {
return event
}
private async notifyGroup(
group: GroupSnapshotRecord,
event: GroupExitMonitorEvent,
idempotencyKey = `member_left_notification:${event.id}`
): Promise<void> {
event.notificationStatus = 'pending'
event.notification = { status: 'pending' }
this.save()
this.broadcast()
/**
* 把退群事件交给自动化 —— **不等待**。
*
* 三条约束:
* 1. **绝不 await**:快照扫描与成员 diff 不能被微信发送耗时拖住;
* 2. **异常必须被捕获**:`void promise` 漏掉 `.catch` 会变成 unhandled rejection;
* 3. **不影响退群事实**:事件与快照在同一检查点已经先落盘,通知失败不回滚记录。
*/
private emitGroupExit(event: GroupExitMonitorEvent): void {
const handler = this.onGroupExit
if (!handler) return
try {
const result = await this.actionGateway.execute({
idempotencyKey,
origin: 'member_monitor',
purpose: 'member_left_notification',
triggerType: 'automation',
sourceId: event.id,
recipient: {
type: 'group',
id: group.roomId,
name: group.groupName
},
content: {
type: 'text',
text: buildMemberLeftNotification(event, this.notificationTemplate)
},
metadata: {
memberId: event.memberWxid,
memberName: event.memberName,
detectedAt: event.detectedAt,
eventType: 'member_left',
eventRoomId: event.roomId
}
})
const notification: GroupExitNotificationState = {
status: result.status,
actionId: result.actionId,
decision: result.decision,
...(result.errorCode ? { errorCode: result.errorCode } : {}),
...(result.reason ? { reason: result.reason } : {}),
startedAt: result.startedAt,
finishedAt: result.finishedAt
}
event.notificationStatus = result.status
event.notification = notification
if (result.status !== 'sent') {
void Promise.resolve(
handler(toGroupMemberExitedEvent(event))
).catch((error) => {
console.warn(
`[GroupMonitor] 群聊通知未发送 roomId=${group.roomId} status=${result.status} code=${result.errorCode || ''}`
`[GroupMonitor] 退群通知处理失败 eventId=${event.id}: ${
error instanceof Error ? error.message : String(error)
}`
)
}
})
} catch (error) {
event.notificationStatus = 'failed'
event.notification = {
status: 'failed',
errorCode: 'UNKNOWN',
reason: error instanceof Error ? error.message : String(error)
}
// handler 同步抛出的情况(`handleGroupExit` 本身不抛,这里是防御性兜底)。
console.warn(
`[GroupMonitor] 群聊通知异常 roomId=${group.roomId}:`,
error instanceof Error ? error.message : String(error)
`[GroupMonitor] 退群通知处理异常 eventId=${event.id}: ${
error instanceof Error ? error.message : String(error)
}`
)
} finally {
this.save()
this.broadcast()
}
}
async resendEvent(eventId: string): Promise<GroupExitMonitorState> {
const event = this.events.find((item) => item.id === eventId)
if (!event) throw new Error('退群动态不存在')
await this.notifyGroup(
{ roomId: event.roomId, groupName: event.groupName } as GroupSnapshotRecord,
event,
`member_left_notification:${event.id}:retry:${Date.now()}`
)
return this.getState()
}
private filePath(): string {
return path.join(app.getPath('userData'), 'group-exit-monitor.json')
}
@@ -806,20 +752,11 @@ class GroupExitMonitorService {
// 「新在前」这个内存不变量,否则列表顶部会恒为最旧的一批。
this.events = sortEventsNewestFirst(normalizeEvents(fromDisk))
}
this.actionGateway.registerMemberEvents?.(this.events)
this.lastReadAt = Number(stored.lastReadAt) || 0
this.accountRoot = String(stored.accountRoot || '')
// 没有显式范围时按空范围处理,保留已有选择。
this.monitorSelectionConfigured = true
this.monitoredRoomIds = normalizeRoomIds(stored.monitoredRoomIds || [])
this.notificationRoomIds = new Set(
Array.from(normalizeRoomIds(stored.notificationRoomIds || [])).filter((roomId) =>
this.monitoredRoomIds.has(roomId)
)
)
this.notificationTemplate = normalizeGroupExitNotificationTemplate(
stored.notificationTemplate
)
this.snapshots = normalizeSnapshots(stored.snapshots, this.monitoredRoomIds)
} catch {
// 首次启动或状态文件损坏时从空记录开始 —— 但事件在独立文件里,
@@ -829,8 +766,6 @@ class GroupExitMonitorService {
this.lastReadAt = 0
this.monitorSelectionConfigured = true
this.monitoredRoomIds.clear()
this.notificationRoomIds.clear()
this.notificationTemplate = normalizeGroupExitNotificationTemplate(undefined)
this.snapshots.clear()
}
}
@@ -849,8 +784,6 @@ class GroupExitMonitorService {
lastReadAt: this.lastReadAt,
monitorSelectionConfigured: this.monitorSelectionConfigured,
monitoredRoomIds: Array.from(this.monitoredRoomIds),
notificationRoomIds: Array.from(this.notificationRoomIds),
notificationTemplate: this.notificationTemplate,
snapshots: Array.from(this.snapshots.values(), toStoredSnapshot)
},
{ spaces: 2 }
@@ -1047,15 +980,11 @@ function normalizeEvents(
? Number(value.delta)
: currentCount - previousCount,
message: String(value.message || `${memberName}退出了${groupName}`),
detectedAt,
...(value.notificationStatus
? { notificationStatus: normalizeNotificationStatus(value.notificationStatus) }
: {}),
...(value.notification && typeof value.notification === 'object'
? { notification: normalizeNotification(value.notification) }
: {})
detectedAt
})
// 不再按 MAX_EVENTS 截断:事件是永久保留的,截在这里等于每次启动都丢掉历史。
// 历史上的 `notificationStatus` / `notification` 字段被**丢弃**:
// 通知状态已归 Automation 执行日志,退群监控不再持有它。
}
return normalized
}
@@ -1075,28 +1004,6 @@ function sortEventsNewestFirst(events: GroupExitMonitorEvent[]): GroupExitMonito
return [...events].sort((left, right) => right.detectedAt - left.detectedAt)
}
function normalizeNotificationStatus(value: unknown): GroupExitNotificationStatus {
const status = String(value || '').trim()
return status === 'pending' || status === 'sent' || status === 'blocked' || status === 'failed'
? status
: 'not_requested'
}
function normalizeNotification(value: object): GroupExitNotificationState {
const input = value as Partial<GroupExitNotificationState>
return {
status: normalizeNotificationStatus(input.status),
...(input.actionId ? { actionId: String(input.actionId) } : {}),
...(input.decision === 'allow' || input.decision === 'block'
? { decision: input.decision }
: {}),
...(input.errorCode ? { errorCode: String(input.errorCode) } : {}),
...(input.reason ? { reason: String(input.reason) } : {}),
...(input.startedAt ? { startedAt: String(input.startedAt) } : {}),
...(input.finishedAt ? { finishedAt: String(input.finishedAt) } : {})
}
}
function isContactEvent(rawPayload: string): boolean {
const payload = String(rawPayload || '').trim()
if (!payload) return false
@@ -0,0 +1,106 @@
import {
LEAVE_NOTIFICATION_DEFAULT_TARGET_TYPE,
normalizeLeaveNotificationTemplate,
type LeaveNotificationTarget
} from '../../shared/automation'
/**
* 旧「退群监控 → 通知群聊 / 模板」配置 → 新「自动化 → 退群通知」规则的**纯映射器**。
*
* 单独成文件是为了能直接单测:这是整轮迁移里**唯一会改变用户既有行为**的地方,
* 不允许只靠"跑一遍看看"来验证。
*
* ## 旧语义(实测自 `group-exit-monitor-service.ts`)
*
* `notificationRoomIds` **不是**"统一通知接收目标列表",而是
* **"哪些被监控群要在自己群里通报成员退出"**(per-group 多值):
* - `applyCurrentMemberships()` 只在 `notificationRoomIds.has(roomId)` 时通知;
* - `notifyGroup()` 的收件人**恒等于事件所在群**。
*
* ## 新语义
*
* 单值目标:`source_chat` / `self` / `file_transfer` / `contact`。
*
* ⇒ 两者**只在一种情况下等价**:旧配置把**每一个**被监控群都勾上了通知。
* 严格子集无法表达,按保守策略处理,绝不"随便取第一个群"。
*/
export interface LegacyLeaveNotificationState {
monitoredRoomIds: string[]
notificationRoomIds: string[]
notificationTemplate?: unknown
}
export type LeaveNotificationMigrationOutcome =
/** 旧配置从不通知任何人 ⇒ 迁移成"关闭",行为完全一致。 */
| 'lossless_off'
/** 旧配置在**每个**被监控群里通报 ⇒ 等价于 `source_chat`,行为完全一致。 */
| 'lossless_source_chat'
/** 旧配置只在**部分**群里通报 ⇒ 单值目标无法表达,需用户重选。 */
| 'needs_review'
export interface LeaveNotificationMigrationPlan {
outcome: LeaveNotificationMigrationOutcome
enabled: boolean
target: LeaveNotificationTarget
targetNeedsReview: boolean
template: string
}
function uniqueRoomIds(values: unknown): string[] {
if (!Array.isArray(values)) return []
const result: string[] = []
const seen = new Set<string>()
for (const value of values) {
const roomId = String(value || '').trim()
if (!roomId || seen.has(roomId)) continue
seen.add(roomId)
result.push(roomId)
}
return result
}
export function planLeaveNotificationMigration(
legacy: LegacyLeaveNotificationState
): LeaveNotificationMigrationPlan {
const monitored = uniqueRoomIds(legacy.monitoredRoomIds)
const monitoredSet = new Set(monitored)
// 再夹一次:防止脏状态文件把范围外的群带进来。
const notifications = uniqueRoomIds(legacy.notificationRoomIds).filter((roomId) =>
monitoredSet.has(roomId)
)
// 模板永远是无损迁移的那一项:它就是用户写的那段文字。
const template = normalizeLeaveNotificationTemplate(legacy.notificationTemplate)
const defaultTarget: LeaveNotificationTarget = { type: LEAVE_NOTIFICATION_DEFAULT_TARGET_TYPE }
if (!notifications.length) {
// 旧语义是"从不通知" ⇒ 关掉,避免迁移后突然开始发消息。
return {
outcome: 'lossless_off',
enabled: false,
target: defaultTarget,
targetNeedsReview: false,
template
}
}
if (monitored.length > 0 && notifications.length === monitored.length) {
// 每个被监控群都在自己群里通报 ⇔ 单值的 `source_chat`。
return {
outcome: 'lossless_source_chat',
enabled: true,
target: { type: 'source_chat' },
targetNeedsReview: false,
template
}
}
// 部分勾选:**不能**无损映射。不取第一个群、不改写成当前群聊、保持关闭、要求重选。
return {
outcome: 'needs_review',
enabled: false,
target: defaultTarget,
targetNeedsReview: true,
template
}
}
@@ -0,0 +1,172 @@
import {
LEAVE_NOTIFICATION_TARGET_OPTIONS,
leaveNotificationTargetLabel,
type LeaveNotificationConfig
} from '../../shared/automation'
import type { GroupMemberExitedEvent } from '../../shared/group-exit-event'
import { WECHAT_FILE_HELPER_USERNAME, isFileHelperUsername } from '../../shared/wechat-identities'
/**
* 退群通知的**目标解析**。
*
* 纯函数(联系人清单与自身身份由调用方注入),因为这里最容易出错、
* 也最需要被单测穷举:发错人是不可撤销的。
*
* 四条规则:
* 1. `source_chat` 取**事件所在群**(`event.conversationId`),
* 不是"当前正在看的聊天",也不是"最后一个活跃会话"。
* 2. 目标解析失败 → **报错**,绝不 fallback 到别的目标(尤其不许偷偷发文件助手)。
* 3. 只允许出现在选项表里的目标类型。
* 4. 显示名不带 wxid:日志与界面只出现用户能看懂的称呼。
*/
/** 解析所需的最小联系人结构(`FormattedContact` 结构上可赋值给它)。 */
export interface LeaveNotificationCandidateContact {
m_nsUsrName: string
m_nsNickName?: string
type: 'user' | 'group'
isOfficialAccount?: boolean
wechatNickname?: string
remark?: string
}
export interface ResolvedLeaveNotificationTarget {
recipient: { type: 'group' | 'contact'; id: string; name: string }
/** 用户可读的目标名,直接进执行日志的 `detail`。 */
displayName: string
}
export type LeaveNotificationTargetResolution =
| { ok: true; target: ResolvedLeaveNotificationTarget }
| { ok: false; error: string }
/** 联系人显示名:备注 → 微信昵称 → 会话昵称 → 兜底称呼。**永不回落到 wxid**。 */
export function leaveNotificationContactDisplayName(
contact: LeaveNotificationCandidateContact
): string {
return (
contact.remark?.trim() ||
contact.wechatNickname?.trim() ||
contact.m_nsNickName?.trim() ||
'指定好友'
)
}
/**
* 这个联系人能不能作为「指定好友」的发送目标。
*
* 排除:群聊、公众号(`gh_`)、文件传输助手、自己。
* UI 的联系人选择器与运行时的目标解析**共用这一条判定**,
* 否则会出现"能选但发不出去"。
*/
export function isSendableFriendContact(
contact: LeaveNotificationCandidateContact,
selfWxid?: string
): boolean {
if (contact.type !== 'user') return false
if (contact.isOfficialAccount) return false
const username = String(contact.m_nsUsrName || '').trim()
if (!username) return false
if (isFileHelperUsername(username)) return false
const self = String(selfWxid || '').trim()
if (self && username === self) return false
return true
}
/** 供 UI 用的「可选好友」过滤(与运行时同一套判定)。 */
export function filterSendableFriendContacts<T extends LeaveNotificationCandidateContact>(
contacts: T[],
selfWxid?: string
): T[] {
return contacts.filter((contact) => isSendableFriendContact(contact, selfWxid))
}
export function resolveLeaveNotificationTarget(input: {
config: LeaveNotificationConfig | undefined
event: GroupMemberExitedEvent
contacts: LeaveNotificationCandidateContact[]
/** 当前登录账号的 wxid;拿不到时传空串。 */
selfWxid?: string
}): LeaveNotificationTargetResolution {
const config = input.config
if (!config) {
return { ok: false, error: '退群通知尚未配置发送目标' }
}
const known = LEAVE_NOTIFICATION_TARGET_OPTIONS.some(
(option) => option.type === config.target?.type
)
if (!known) {
return { ok: false, error: '退群通知的发送目标无效,请重新选择' }
}
switch (config.target.type) {
case 'source_chat': {
const conversationId = String(input.event.conversationId || '').trim()
if (!conversationId) {
return { ok: false, error: '无法确定发生退群的群聊,本次通知未发送' }
}
const groupName = String(input.event.groupName || '').trim()
return {
ok: true,
target: {
recipient: {
type: 'group',
id: conversationId,
name: groupName || '当前群聊'
},
displayName: groupName || '发生退群事件的群聊'
}
}
}
case 'self': {
const selfWxid = String(input.selfWxid || '').trim()
if (!selfWxid) {
// 明确报错,不 fallback。§「不要偷偷 fallback 文件传输助手」。
return { ok: false, error: '无法确定当前登录的微信账号,本次通知未发送' }
}
return {
ok: true,
target: {
recipient: { type: 'contact', id: selfWxid, name: '我' },
displayName: '我'
}
}
}
case 'file_transfer':
return {
ok: true,
target: {
recipient: {
type: 'contact',
id: WECHAT_FILE_HELPER_USERNAME,
name: leaveNotificationTargetLabel('file_transfer')
},
displayName: leaveNotificationTargetLabel('file_transfer')
}
}
case 'contact': {
const contactId = String(config.target.contactId || '').trim()
if (!contactId) {
return { ok: false, error: '还没有选择通知联系人,请重新选择' }
}
const contact = input.contacts.find(
(item) => String(item.m_nsUsrName || '').trim() === contactId
)
if (!contact || !isSendableFriendContact(contact, input.selfWxid)) {
// §「如果之前选择的联系人被删除 / 不可发送 / 找不到,规则不要偷偷发给其它地方」。
return { ok: false, error: '通知联系人已不存在或当前无法发送,请重新选择' }
}
const displayName = leaveNotificationContactDisplayName(contact)
return {
ok: true,
target: {
recipient: { type: 'contact', id: contactId, name: displayName },
displayName
}
}
}
}
}
+6 -84
View File
@@ -13,7 +13,6 @@ import type {
WechatActionAuditRecord,
WechatActionContent,
WechatActionErrorCode,
WechatActionMemberEventReference,
WechatActionRequest,
WechatActionResult
} from '../../shared/wechat-action'
@@ -25,12 +24,14 @@ 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',
// Automation v1(@我生成日报)。必须与 `src/shared/automation.ts` 的
// Automation(@我生成日报)。必须与 `src/shared/automation.ts` 的
// `AUTOMATION_SEND_PURPOSE` 保持一致,否则会被下面 evaluateWechatActionPolicy
// 以 ACTION_NOT_ALLOWED 拦下 —— 那是有意的闸门,不是 bug。
'automation_reply',
'automation_report',
// 退群通知(由 Automation 发出)。目标可以是群 / 自己 / 文件传输助手 / 指定好友,
// 所以**不绑定**任何 "只能发回原群" 的作用域锁。
'automation_leave_notification',
'manual_report_image',
'manual_report_postfix'
])
@@ -49,12 +50,6 @@ export interface ReportImageSequenceResult {
export interface WechatActionGatewayDependencies {
getCapability?: () => Promise<PersonalWechatSendCapability>
send?: (request: PersonalWechatSendRequest) => Promise<PersonalWechatSendResult>
getMemberEvent?: (
sourceId: string
) =>
| WechatActionMemberEventReference
| Promise<WechatActionMemberEventReference | undefined>
| undefined
getUserDataPath?: () => string
now?: () => Date
wait?: (milliseconds: number) => Promise<void>
@@ -65,10 +60,6 @@ interface LoadedAuditState {
records: WechatActionAuditRecord[]
}
export interface WechatActionPolicyContext {
memberEvent?: WechatActionMemberEventReference
}
const defaultDependencies = (): Required<
Pick<
WechatActionGatewayDependencies,
@@ -98,7 +89,6 @@ export class WechatActionGateway {
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()
@@ -108,22 +98,6 @@ export class WechatActionGateway {
this.deps = { ...defaultDependencies(), ...deps }
}
/** 记录退群事件,发送通知前可确认事件所属群聊。 */
registerMemberEvent(event: WechatActionMemberEventReference): void {
const id = String(event?.id || '').trim()
const roomId = String(event?.roomId || '').trim()
if (!id || !roomId) return
this.memberEvents.set(id, { id, roomId })
}
registerMemberEvents(events: WechatActionMemberEventReference[]): void {
for (const event of events) this.registerMemberEvent(event)
}
clearMemberEvents(): void {
this.memberEvents.clear()
}
/**
* 用户确认后的日报发送序列。两步都进入 automation 发送队列,从而复用既有 3 秒间隔;
* 后置词 action 只在图片明确 sent 后创建,图片失败/blocked 时严格短路。
@@ -196,8 +170,7 @@ export class WechatActionGateway {
)
}
const eventContext = await this.resolveEventContext(request)
const policy = evaluateWechatActionPolicy(request, eventContext)
const policy = evaluateWechatActionPolicy(request)
if (policy.decision !== 'allow') {
return this.finishBlocked(
actionId,
@@ -291,28 +264,6 @@ export class WechatActionGateway {
return queued
}
private async resolveEventContext(
request: WechatActionRequest
): Promise<WechatActionPolicyContext> {
if (request.purpose !== 'member_left_notification') return {}
const sourceId = String(request.sourceId || '').trim()
if (!sourceId) return {}
let memberEvent: WechatActionMemberEventReference | undefined = this.memberEvents.get(sourceId)
if (!memberEvent && this.deps.getMemberEvent) {
let resolved: WechatActionMemberEventReference | undefined
try {
resolved = await this.deps.getMemberEvent(sourceId)
} catch {
resolved = undefined
}
if (resolved && String(resolved.id || '').trim() === sourceId) {
memberEvent = { id: String(resolved.id), roomId: String(resolved.roomId) }
this.registerMemberEvent(memberEvent)
}
}
return memberEvent ? { memberEvent } : {}
}
private async findExisting(idempotencyKey: string): Promise<WechatActionResult | undefined> {
const state = this.loadAuditState()
const existing = state.records.find((record) => record.idempotencyKey === idempotencyKey)
@@ -331,9 +282,6 @@ export class WechatActionGateway {
private idempotencyKey(request: WechatActionRequest): string | undefined {
const explicit = String(request.idempotencyKey || '').trim()
if (explicit) return explicit
if (request.purpose === 'member_left_notification' && request.sourceId) {
return `member_left_notification:${request.sourceId}`
}
if (request.origin === 'scheduled_report' && request.executionId) {
return `scheduled_report:${request.executionId}`
}
@@ -480,10 +428,7 @@ export class WechatActionGateway {
}
}
export function evaluateWechatActionPolicy(
request: WechatActionRequest,
context: WechatActionPolicyContext = {}
): PolicyDecision {
export function evaluateWechatActionPolicy(request: WechatActionRequest): PolicyDecision {
if (!request || typeof request !== 'object') {
return {
decision: 'block',
@@ -514,29 +459,6 @@ export function evaluateWechatActionPolicy(
reason: `自动化动作不允许执行 purpose=${request.purpose}`
}
}
if (request.purpose === 'member_left_notification') {
if (
!request.sourceId ||
!context.memberEvent ||
context.memberEvent.id !== request.sourceId ||
!context.memberEvent.roomId
) {
return {
decision: 'block',
source: 'deterministic',
reasonCode: 'INVALID_REQUEST',
reason: '退群通知必须关联已记录的退群事件'
}
}
if (request.recipient.type !== 'group' || request.recipient.id !== context.memberEvent.roomId) {
return {
decision: 'block',
source: 'deterministic',
reasonCode: 'RECIPIENT_SCOPE_VIOLATION',
reason: '退群通知只能发送回原事件所在群聊'
}
}
}
return { decision: 'allow', source: 'deterministic' }
}