mirror of
https://wget.la/https://github.com/Wxw-Gu/WechatExplorer
synced 2026-11-30 16:02:58 +08:00
feat: 退群监控接入自动化能力统一管理, 支持发送个人/文件传输助手/指定群聊
This commit is contained in:
1 parent
3bd3935042
commit
59872daf52
43 files changed
+5661
-1132
No files matched your search
@@ -0,0 +1,300 @@
|
||||
import { render, screen, waitFor, within } from '@testing-library/react'
|
||||
import userEvent from '@testing-library/user-event'
|
||||
import React from 'react'
|
||||
import { describe, expect, it, vi } from 'vitest'
|
||||
|
||||
import { ToastProvider } from '../../src/renderer/src/components/ui'
|
||||
import {
|
||||
AutomationWorkspace,
|
||||
type AutomationOpenRuleRequest
|
||||
} from '../../src/renderer/src/features/automation/AutomationWorkspace'
|
||||
import {
|
||||
BUILTIN_DAILY_REPORT_RULE_ID,
|
||||
createDefaultDailyReportRule,
|
||||
createDefaultLeaveNotificationRule,
|
||||
type AutomationRule
|
||||
} from '../../src/shared/automation'
|
||||
|
||||
/**
|
||||
* 规则类型切换的**目标归属**回归。
|
||||
*
|
||||
* 真实事故:从「退群通知」卡片进编辑器(编辑器内部记的是"没有具体目标"),
|
||||
* 切到「@我生成日报」Tab 后保存 —— 结果改掉了**内置日报**(用户看到的就是
|
||||
* "我编辑退群通知,保存却改到了另一条日报上")。
|
||||
*
|
||||
* 根因两条,都要锁死:
|
||||
* 1. 切换类型时继承了上一个类型的 `mode`,留下 `mode='edit'` 却没有目标的中间态;
|
||||
* 2. 编辑目标**不可见** —— 表单不显示它在改哪条规则。
|
||||
*/
|
||||
|
||||
const DAILY_NAME = '我的日报'
|
||||
|
||||
function installApi(): {
|
||||
rules: AutomationRule[]
|
||||
updateAutomationRule: ReturnType<typeof vi.fn>
|
||||
createAutomationRule: ReturnType<typeof vi.fn>
|
||||
saveLeaveNotificationRule: ReturnType<typeof vi.fn>
|
||||
} {
|
||||
const renamedDaily: AutomationRule = {
|
||||
...createDefaultDailyReportRule(Date.now()),
|
||||
name: DAILY_NAME
|
||||
}
|
||||
const leaveRule = createDefaultLeaveNotificationRule(Date.now())
|
||||
const rules = [renamedDaily, leaveRule]
|
||||
|
||||
const updateAutomationRule = vi.fn(async (id: string, draft: AutomationRule) => ({
|
||||
...renamedDaily,
|
||||
...draft,
|
||||
id
|
||||
}))
|
||||
const createAutomationRule = vi.fn(async (draft: AutomationRule) => ({
|
||||
...renamedDaily,
|
||||
...draft,
|
||||
id: 'created-rule'
|
||||
}))
|
||||
const saveLeaveNotificationRule = vi.fn(async (draft: AutomationRule) => draft)
|
||||
|
||||
window.api = {
|
||||
getAutomationStatus: vi.fn().mockResolvedValue({
|
||||
listening: true,
|
||||
listeningDegraded: false,
|
||||
todayExecutions: 0,
|
||||
todaySuccesses: 0,
|
||||
sendCapability: {
|
||||
supported: true,
|
||||
ready: true,
|
||||
canSendText: true,
|
||||
canSendImage: true,
|
||||
message: 'ready'
|
||||
}
|
||||
}),
|
||||
listAutomationRules: vi.fn().mockResolvedValue(rules),
|
||||
listAutomationGroups: vi.fn().mockResolvedValue([]),
|
||||
listAutomationExecutions: vi.fn().mockResolvedValue([]),
|
||||
listSendableContacts: vi.fn().mockResolvedValue([]),
|
||||
getGroupExitMonitorState: vi.fn().mockResolvedValue({
|
||||
events: [],
|
||||
enabled: true,
|
||||
running: true,
|
||||
nativeMonitorActive: true,
|
||||
monitoredGroupCount: 3,
|
||||
monitorSelectionConfigured: true,
|
||||
monitoredRoomIds: [],
|
||||
lastReadAt: 0,
|
||||
unreadCount: 0
|
||||
}),
|
||||
onGroupExitMonitorState: vi.fn(() => () => undefined),
|
||||
updateAutomationRule,
|
||||
createAutomationRule,
|
||||
saveLeaveNotificationRule
|
||||
} as unknown as typeof window.api
|
||||
|
||||
return { rules, updateAutomationRule, createAutomationRule, saveLeaveNotificationRule }
|
||||
}
|
||||
|
||||
const renderWorkspace = (): void => {
|
||||
render(
|
||||
<ToastProvider>
|
||||
<AutomationWorkspace dbReady onOpenExitMonitorGroups={() => {}} />
|
||||
</ToastProvider>
|
||||
)
|
||||
}
|
||||
|
||||
const editingTarget = (): string =>
|
||||
screen.getByTestId('automation-editing-target').textContent ?? ''
|
||||
|
||||
const leaveCard = async (): Promise<HTMLElement> =>
|
||||
(await screen.findByText('退群通知')).closest('article') as HTMLElement
|
||||
|
||||
describe('规则类型切换 · 编辑目标归属', () => {
|
||||
it('从退群通知进编辑器时,「正在编辑」显示退群通知', async () => {
|
||||
const user = userEvent.setup()
|
||||
installApi()
|
||||
renderWorkspace()
|
||||
|
||||
await user.click(within(await leaveCard()).getByRole('button', { name: '编辑' }))
|
||||
|
||||
expect(editingTarget()).toContain('退群通知')
|
||||
})
|
||||
|
||||
/*
|
||||
* 事故核心:切到日报后,界面必须**明说**现在改的是哪条。
|
||||
* 以前这里什么都不显示,用户以为还在改退群通知。
|
||||
*/
|
||||
it('切到日报后,「正在编辑」显示那条日报的名字(不再隐式指向未知目标)', async () => {
|
||||
const user = userEvent.setup()
|
||||
installApi()
|
||||
renderWorkspace()
|
||||
|
||||
await user.click(within(await leaveCard()).getByRole('button', { name: '编辑' }))
|
||||
await user.click(screen.getByRole('radio', { name: '@我生成日报' }))
|
||||
|
||||
expect(editingTarget()).toContain(DAILY_NAME)
|
||||
expect(editingTarget()).not.toContain('退群通知')
|
||||
})
|
||||
|
||||
it('切到日报后保存:只更新那一条日报,退群通知与新建都不受影响', async () => {
|
||||
const user = userEvent.setup()
|
||||
const api = installApi()
|
||||
renderWorkspace()
|
||||
|
||||
await user.click(within(await leaveCard()).getByRole('button', { name: '编辑' }))
|
||||
await user.click(screen.getByRole('radio', { name: '@我生成日报' }))
|
||||
await user.click(screen.getByRole('button', { name: '保存' }))
|
||||
|
||||
await waitFor(() => expect(api.updateAutomationRule).toHaveBeenCalledTimes(1))
|
||||
// 必须更新"屏幕上显示的那条"。
|
||||
expect(api.updateAutomationRule.mock.calls[0][0]).toBe(BUILTIN_DAILY_REPORT_RULE_ID)
|
||||
// 绝不能顺手新建一条重复规则,也不能动退群通知。
|
||||
expect(api.createAutomationRule).not.toHaveBeenCalled()
|
||||
expect(api.saveLeaveNotificationRule).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('从日报卡片进入并保存:更新日报,且不会误存到退群通知', async () => {
|
||||
const user = userEvent.setup()
|
||||
const api = installApi()
|
||||
renderWorkspace()
|
||||
|
||||
const dailyCard = (await screen.findByText(DAILY_NAME)).closest('article') as HTMLElement
|
||||
await user.click(within(dailyCard).getByRole('button', { name: '编辑' }))
|
||||
expect(editingTarget()).toContain(DAILY_NAME)
|
||||
|
||||
await user.click(screen.getByRole('button', { name: '保存' }))
|
||||
|
||||
await waitFor(() => expect(api.updateAutomationRule).toHaveBeenCalledTimes(1))
|
||||
expect(api.saveLeaveNotificationRule).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('从日报切到退群通知后保存:走退群通知通道,不改日报', async () => {
|
||||
const user = userEvent.setup()
|
||||
const api = installApi()
|
||||
renderWorkspace()
|
||||
|
||||
const dailyCard = (await screen.findByText(DAILY_NAME)).closest('article') as HTMLElement
|
||||
await user.click(within(dailyCard).getByRole('button', { name: '编辑' }))
|
||||
await user.click(screen.getByRole('radio', { name: '退群通知' }))
|
||||
|
||||
expect(editingTarget()).toContain('退群通知')
|
||||
|
||||
await user.click(screen.getByRole('button', { name: '保存' }))
|
||||
|
||||
await waitFor(() => expect(api.saveLeaveNotificationRule).toHaveBeenCalledTimes(1))
|
||||
expect(api.updateAutomationRule).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('内置日报不存在时切到日报:显示「新建自动化」,保存走新建而不是更新', async () => {
|
||||
const user = userEvent.setup()
|
||||
const api = installApi()
|
||||
// 只剩退群通知(等价于用户把内置日报删掉了)。
|
||||
;(window.api.listAutomationRules as ReturnType<typeof vi.fn>).mockResolvedValue([
|
||||
createDefaultLeaveNotificationRule(Date.now())
|
||||
])
|
||||
renderWorkspace()
|
||||
|
||||
await user.click(within(await leaveCard()).getByRole('button', { name: '编辑' }))
|
||||
await user.click(screen.getByRole('radio', { name: '@我生成日报' }))
|
||||
|
||||
expect(editingTarget()).toContain('新建自动化')
|
||||
|
||||
await user.click(screen.getByRole('button', { name: '保存' }))
|
||||
await waitFor(() => expect(api.createAutomationRule).toHaveBeenCalledTimes(1))
|
||||
expect(api.updateAutomationRule).not.toHaveBeenCalled()
|
||||
expect(api.saveLeaveNotificationRule).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
/*
|
||||
* 日报可以有多条。切走再切回时必须回到**刚才那条**,
|
||||
* 否则用户会在不知情的情况下被带到内置日报上(等于换个方式误改规则)。
|
||||
*/
|
||||
it('从别的日报进入,切走再切回仍指向那条日报,不会被换回内置日报', async () => {
|
||||
const user = userEvent.setup()
|
||||
const api = installApi()
|
||||
const OTHER_NAME = '我的另一条日报'
|
||||
;(window.api.listAutomationRules as ReturnType<typeof vi.fn>).mockResolvedValue([
|
||||
{ ...createDefaultDailyReportRule(Date.now()), name: DAILY_NAME },
|
||||
{
|
||||
...createDefaultDailyReportRule(Date.now()),
|
||||
id: 'custom-daily',
|
||||
name: OTHER_NAME
|
||||
},
|
||||
createDefaultLeaveNotificationRule(Date.now())
|
||||
])
|
||||
renderWorkspace()
|
||||
|
||||
const otherCard = (await screen.findByText(OTHER_NAME)).closest('article') as HTMLElement
|
||||
await user.click(within(otherCard).getByRole('button', { name: '编辑' }))
|
||||
expect(editingTarget()).toContain(OTHER_NAME)
|
||||
|
||||
await user.click(screen.getByRole('radio', { name: '退群通知' }))
|
||||
await user.click(screen.getByRole('radio', { name: '@我生成日报' }))
|
||||
|
||||
expect(editingTarget()).toContain(OTHER_NAME)
|
||||
expect(editingTarget()).not.toContain(DAILY_NAME)
|
||||
|
||||
// 保存也必须落在这一条上。
|
||||
await user.click(screen.getByRole('button', { name: '保存' }))
|
||||
await waitFor(() => expect(api.updateAutomationRule).toHaveBeenCalledTimes(1))
|
||||
expect(api.updateAutomationRule.mock.calls[0][0]).toBe('custom-daily')
|
||||
})
|
||||
|
||||
/*
|
||||
* 同类 bug 的第二处:`mode === 'edit' || !target ? createRule : updateRule` ——
|
||||
* "编辑态但没有目标"被静默当成"新建",用户以为在改 A,结果多出一条新规则。
|
||||
* 现在必须明确报错,且不能给 User 一个看起来能保存的空表单。
|
||||
*/
|
||||
it('编辑态但目标规则已不存在:不给新建入口,明确提示', async () => {
|
||||
const api = installApi()
|
||||
// 内置日报不存在(等价于用户把它删掉了)。
|
||||
;(window.api.listAutomationRules as ReturnType<typeof vi.fn>).mockResolvedValue([
|
||||
createDefaultLeaveNotificationRule(Date.now())
|
||||
])
|
||||
|
||||
function DeepLinkHarness(): React.ReactElement {
|
||||
const [request] = React.useState<AutomationOpenRuleRequest>({
|
||||
ruleType: 'daily_report',
|
||||
requestId: 1
|
||||
})
|
||||
return <AutomationWorkspace dbReady openRuleRequest={request} />
|
||||
}
|
||||
|
||||
render(
|
||||
<ToastProvider>
|
||||
<DeepLinkHarness />
|
||||
</ToastProvider>
|
||||
)
|
||||
|
||||
expect(await screen.findByText(/要编辑的规则已不存在/)).toBeVisible()
|
||||
// 关键:没有可点的「保存」——否则用户点下去就会凭空新建一条规则。
|
||||
expect(screen.queryByRole('button', { name: '保存' })).toBeNull()
|
||||
expect(api.createAutomationRule).not.toHaveBeenCalled()
|
||||
expect(api.updateAutomationRule).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('切类型不会静默新建出重复规则', async () => {
|
||||
const user = userEvent.setup()
|
||||
const api = installApi()
|
||||
renderWorkspace()
|
||||
|
||||
await user.click(within(await leaveCard()).getByRole('button', { name: '编辑' }))
|
||||
for (const label of ['@我生成日报', '退群通知', '@我生成日报', '退群通知']) {
|
||||
await user.click(screen.getByRole('radio', { name: label }))
|
||||
}
|
||||
|
||||
expect(api.createAutomationRule).not.toHaveBeenCalled()
|
||||
expect(api.updateAutomationRule).not.toHaveBeenCalled()
|
||||
expect(api.saveLeaveNotificationRule).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('Tab 文案说明它是「切换规则类型」,不是改当前规则的类型', async () => {
|
||||
const user = userEvent.setup()
|
||||
installApi()
|
||||
renderWorkspace()
|
||||
|
||||
await user.click(within(await leaveCard()).getByRole('button', { name: '编辑' }))
|
||||
|
||||
expect(screen.getByText('切换规则类型')).toBeVisible()
|
||||
expect(
|
||||
screen.getByRole('radiogroup', { name: '切换规则类型' }) as HTMLElement
|
||||
).toBeInTheDocument()
|
||||
})
|
||||
})
|
||||
@@ -1,4 +1,4 @@
|
||||
import { fireEvent, render, screen, waitFor } from '@testing-library/react'
|
||||
import { render, screen, waitFor } from '@testing-library/react'
|
||||
import userEvent from '@testing-library/user-event'
|
||||
import type { ReactElement } from 'react'
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
@@ -48,7 +48,6 @@ const state: GroupExitMonitorState = {
|
||||
monitoredGroupCount: 3,
|
||||
monitorSelectionConfigured: true,
|
||||
monitoredRoomIds: ['研发群@chatroom', '设计群@chatroom'],
|
||||
notificationRoomIds: [],
|
||||
lastCheckedAt: 1_756_600_000_000,
|
||||
lastReadAt: 0,
|
||||
unreadCount: 1
|
||||
@@ -163,25 +162,23 @@ describe('GroupExitMonitorWorkspace', () => {
|
||||
await user.click(screen.getByRole('checkbox', { name: '监控研发群' }))
|
||||
await user.click(screen.getByRole('button', { name: '保存监控群聊' }))
|
||||
|
||||
await waitFor(() => expect(setGroups).toHaveBeenCalledWith(['研发群@chatroom'], []))
|
||||
await waitFor(() => expect(setGroups).toHaveBeenCalledWith(['研发群@chatroom']))
|
||||
expect(screen.getByRole('heading', { name: '退群监控' })).toBeVisible()
|
||||
expect(screen.getByText('已监控群聊')).toBeVisible()
|
||||
})
|
||||
|
||||
it('filters group rows by selection and persists notification targets separately', async () => {
|
||||
it('filters group rows by selection and saves the monitoring scope', async () => {
|
||||
const user = userEvent.setup()
|
||||
const configuredState: GroupExitMonitorState = {
|
||||
...state,
|
||||
events: [],
|
||||
monitorSelectionConfigured: true,
|
||||
monitoredRoomIds: ['研发群@chatroom'],
|
||||
notificationRoomIds: [],
|
||||
monitoredGroupCount: 1,
|
||||
unreadCount: 0
|
||||
}
|
||||
const savedState: GroupExitMonitorState = {
|
||||
...configuredState,
|
||||
notificationRoomIds: ['研发群@chatroom']
|
||||
}
|
||||
const setGroups = vi.fn().mockResolvedValue(savedState)
|
||||
window.api = {
|
||||
@@ -209,12 +206,9 @@ describe('GroupExitMonitorWorkspace', () => {
|
||||
|
||||
await user.click(screen.getByRole('combobox', { name: '筛选群聊状态' }))
|
||||
await user.click(await screen.findByRole('option', { name: '全部' }))
|
||||
await user.click(screen.getByRole('checkbox', { name: '是否通知研发群' }))
|
||||
await user.click(screen.getByRole('button', { name: '保存监控群聊' }))
|
||||
|
||||
await waitFor(() =>
|
||||
expect(setGroups).toHaveBeenCalledWith(['研发群@chatroom'], ['研发群@chatroom'])
|
||||
)
|
||||
await waitFor(() => expect(setGroups).toHaveBeenCalledWith(['研发群@chatroom']))
|
||||
})
|
||||
|
||||
it('selects every group even when a search term is active', async () => {
|
||||
@@ -224,7 +218,6 @@ describe('GroupExitMonitorWorkspace', () => {
|
||||
events: [],
|
||||
monitorSelectionConfigured: true,
|
||||
monitoredRoomIds: [],
|
||||
notificationRoomIds: [],
|
||||
monitoredGroupCount: 0,
|
||||
unreadCount: 0
|
||||
}
|
||||
@@ -244,7 +237,7 @@ describe('GroupExitMonitorWorkspace', () => {
|
||||
await user.click(screen.getByRole('button', { name: '保存监控群聊' }))
|
||||
|
||||
await waitFor(() =>
|
||||
expect(setGroups).toHaveBeenCalledWith(['研发群@chatroom', '设计群@chatroom'], [])
|
||||
expect(setGroups).toHaveBeenCalledWith(['研发群@chatroom', '设计群@chatroom'])
|
||||
)
|
||||
})
|
||||
|
||||
@@ -275,43 +268,17 @@ describe('GroupExitMonitorWorkspace', () => {
|
||||
await waitFor(() => expect(screen.getByRole('tooltip')).toHaveTextContent('请先绑定个人微信'))
|
||||
})
|
||||
|
||||
it('shows the notification template from the management page header', async () => {
|
||||
/*
|
||||
* 迁移后这里**不再有模板入口与「通知群聊」列**:
|
||||
* 模板的唯一编辑处是「自动化 → 规则 → 退群通知」。
|
||||
* 退群监控只负责监控范围与退群事实。
|
||||
*/
|
||||
it('管理群聊页不再提供通知模板与通知群聊配置', async () => {
|
||||
const user = userEvent.setup()
|
||||
window.api = {
|
||||
getGroupExitMonitorState: vi.fn().mockResolvedValue(state),
|
||||
onGroupExitMonitorState: vi.fn(() => () => undefined),
|
||||
getPersonalWechatSendCapability: vi.fn().mockResolvedValue({
|
||||
supported: true,
|
||||
ready: false,
|
||||
status: 'needs_binding',
|
||||
capabilities: { text: false, image: false, voice: false },
|
||||
senderStatus: {} as never,
|
||||
message: '请先绑定个人微信'
|
||||
}),
|
||||
setGroupExitMonitorGroups: vi.fn().mockResolvedValue(state),
|
||||
checkGroupExitMonitorNow: vi.fn().mockResolvedValue(state),
|
||||
clearGroupExitMonitorEvents: vi.fn().mockResolvedValue(state)
|
||||
} as typeof window.api
|
||||
|
||||
renderWorkspace(<GroupExitMonitorWorkspace dbReady contacts={groups} />)
|
||||
await user.click(await screen.findByRole('button', { name: '管理群聊' }))
|
||||
await user.click(screen.getByRole('button', { name: '查看退群监测模板' }))
|
||||
|
||||
expect(screen.getByRole('heading', { name: '退群监测模板' })).toBeVisible()
|
||||
const template = screen.getByLabelText('退群监测模板内容')
|
||||
expect((template as HTMLTextAreaElement).value).toContain('用户: {user}')
|
||||
expect((template as HTMLTextAreaElement).value).toContain('群备注: {groupRemark}')
|
||||
})
|
||||
|
||||
it('edits and persists the notification template', async () => {
|
||||
const user = userEvent.setup()
|
||||
const savedTemplate = '[退群监测]\n用户: {user}\n群: {groupRemark}'
|
||||
const setTemplate = vi.fn().mockResolvedValue({ ...state, notificationTemplate: savedTemplate })
|
||||
window.api = {
|
||||
getGroupExitMonitorState: vi.fn().mockResolvedValue(state),
|
||||
onGroupExitMonitorState: vi.fn(() => () => undefined),
|
||||
getPersonalWechatSendCapability: vi.fn().mockResolvedValue(null),
|
||||
setGroupExitMonitorNotificationTemplate: setTemplate,
|
||||
setGroupExitMonitorGroups: vi.fn().mockResolvedValue(state),
|
||||
checkGroupExitMonitorNow: vi.fn().mockResolvedValue(state),
|
||||
clearGroupExitMonitorEvents: vi.fn().mockResolvedValue(state)
|
||||
@@ -319,16 +286,16 @@ describe('GroupExitMonitorWorkspace', () => {
|
||||
|
||||
renderWorkspace(<GroupExitMonitorWorkspace dbReady contacts={groups} />)
|
||||
await user.click(await screen.findByRole('button', { name: '管理群聊' }))
|
||||
await user.click(screen.getByRole('button', { name: '查看退群监测模板' }))
|
||||
const template = screen.getByLabelText('退群监测模板内容')
|
||||
fireEvent.change(template, { target: { value: savedTemplate } })
|
||||
await user.click(screen.getByRole('button', { name: '保存模板' }))
|
||||
|
||||
await waitFor(() => expect(setTemplate).toHaveBeenCalledWith(savedTemplate))
|
||||
expect(screen.queryByRole('heading', { name: '退群监测模板' })).not.toBeInTheDocument()
|
||||
expect(screen.queryByRole('button', { name: '查看退群监测模板' })).toBeNull()
|
||||
expect(screen.queryByRole('heading', { name: '退群监测模板' })).toBeNull()
|
||||
expect(screen.queryByText('通知群聊')).toBeNull()
|
||||
expect(screen.queryByLabelText('退群监测模板内容')).toBeNull()
|
||||
// 监控选择本身仍然可用。
|
||||
expect(screen.getByRole('checkbox', { name: '监控研发群' })).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('copies the exit notice built from the template saved on the management page', async () => {
|
||||
it('复制退群信息用的模板来自自动化规则,而不是退群监控自己存的', async () => {
|
||||
const user = userEvent.setup()
|
||||
const template = [
|
||||
'[退群监测]',
|
||||
@@ -340,11 +307,19 @@ describe('GroupExitMonitorWorkspace', () => {
|
||||
].join('\n')
|
||||
const copyText = vi.fn().mockResolvedValue({ success: true })
|
||||
window.api = {
|
||||
getGroupExitMonitorState: vi
|
||||
.fn()
|
||||
.mockResolvedValue({ ...state, notificationTemplate: template }),
|
||||
getGroupExitMonitorState: vi.fn().mockResolvedValue(state),
|
||||
onGroupExitMonitorState: vi.fn(() => () => undefined),
|
||||
copyText,
|
||||
// 模板唯一来源:自动化里的退群通知规则。
|
||||
listAutomationRules: vi.fn().mockResolvedValue([
|
||||
{
|
||||
id: 'builtin-leave-notification',
|
||||
name: '退群通知',
|
||||
enabled: true,
|
||||
ruleType: 'leave_notification',
|
||||
leaveNotification: { target: { type: 'file_transfer' }, template }
|
||||
}
|
||||
]),
|
||||
checkGroupExitMonitorNow: vi.fn().mockResolvedValue(state),
|
||||
clearGroupExitMonitorEvents: vi.fn().mockResolvedValue(state)
|
||||
} as typeof window.api
|
||||
@@ -396,7 +371,6 @@ describe('GroupExitMonitorWorkspace', () => {
|
||||
events: [],
|
||||
monitorSelectionConfigured: false,
|
||||
monitoredRoomIds: [],
|
||||
notificationRoomIds: [],
|
||||
monitoredGroupCount: 0,
|
||||
unreadCount: 0
|
||||
}
|
||||
|
||||
@@ -0,0 +1,665 @@
|
||||
import React from 'react'
|
||||
import { render, screen, waitFor, within } from '@testing-library/react'
|
||||
import userEvent from '@testing-library/user-event'
|
||||
import type { ReactElement } from 'react'
|
||||
import { describe, expect, it, vi } from 'vitest'
|
||||
|
||||
import { ToastProvider, TooltipProvider } from '../../src/renderer/src/components/ui'
|
||||
import {
|
||||
AutomationWorkspace,
|
||||
type AutomationOpenRuleRequest
|
||||
} from '../../src/renderer/src/features/automation/AutomationWorkspace'
|
||||
import { GroupExitMonitorWorkspace } from '../../src/renderer/src/features/group-exit-monitor/GroupExitMonitorWorkspace'
|
||||
import {
|
||||
BUILTIN_LEAVE_NOTIFICATION_RULE_ID,
|
||||
createDefaultDailyReportRule,
|
||||
createDefaultLeaveNotificationRule,
|
||||
type AutomationRule
|
||||
} from '../../src/shared/automation'
|
||||
import type { GroupExitMonitorState } from '../../src/shared/group-exit-monitor'
|
||||
|
||||
/**
|
||||
* 「自动化 → 规则 → 退群通知」现在是**真实配置页**。
|
||||
*
|
||||
* 这组测试锁的是「真实化」之后的契约:
|
||||
* - 已监控群聊数量来自退群监控(不是硬编码的 243);
|
||||
* - 好友清单来自 main 侧的可发送联系人接口(不是 mock 的张三李四);
|
||||
* - 保存真的会调用 singleton upsert;
|
||||
* - **效果预览永远不发送**;
|
||||
* - 退群监控里旧的通知群聊列与模板入口已经不存在。
|
||||
*/
|
||||
|
||||
const MONITOR_STATE: GroupExitMonitorState = {
|
||||
events: [],
|
||||
enabled: true,
|
||||
running: true,
|
||||
nativeMonitorActive: true,
|
||||
monitoredGroupCount: 7,
|
||||
monitorSelectionConfigured: true,
|
||||
monitoredRoomIds: ['a@chatroom', 'b@chatroom', 'c@chatroom'],
|
||||
lastReadAt: 0,
|
||||
unreadCount: 0
|
||||
}
|
||||
|
||||
const SENDABLE_CONTACTS = [
|
||||
{ id: 'wxid_friend_a', name: '好友甲' },
|
||||
{ id: 'wxid_friend_b', name: '好友乙' }
|
||||
]
|
||||
|
||||
interface ApiSpies {
|
||||
saveLeaveNotificationRule: ReturnType<typeof vi.fn>
|
||||
createAutomationRule: ReturnType<typeof vi.fn>
|
||||
updateAutomationRule: ReturnType<typeof vi.fn>
|
||||
deleteAutomationRule: ReturnType<typeof vi.fn>
|
||||
setAutomationRuleEnabled: ReturnType<typeof vi.fn>
|
||||
setGroupExitMonitorGroups: ReturnType<typeof vi.fn>
|
||||
listSendableContacts: ReturnType<typeof vi.fn>
|
||||
listAutomationRules: ReturnType<typeof vi.fn>
|
||||
}
|
||||
|
||||
function installApi(
|
||||
overrides: { leaveRule?: AutomationRule } = {}
|
||||
): { spies: ApiSpies; rules: AutomationRule[] } {
|
||||
const leaveRule = overrides.leaveRule ?? createDefaultLeaveNotificationRule(Date.now())
|
||||
const rules = [createDefaultDailyReportRule(Date.now()), leaveRule]
|
||||
const spies: ApiSpies = {
|
||||
saveLeaveNotificationRule: vi.fn(async (draft: AutomationRule) => ({
|
||||
...leaveRule,
|
||||
...draft,
|
||||
id: BUILTIN_LEAVE_NOTIFICATION_RULE_ID
|
||||
})),
|
||||
createAutomationRule: vi.fn().mockResolvedValue(null),
|
||||
updateAutomationRule: vi.fn().mockResolvedValue(null),
|
||||
deleteAutomationRule: vi.fn().mockResolvedValue(false),
|
||||
setAutomationRuleEnabled: vi.fn().mockResolvedValue(null),
|
||||
setGroupExitMonitorGroups: vi.fn().mockResolvedValue(MONITOR_STATE),
|
||||
listSendableContacts: vi.fn().mockResolvedValue(SENDABLE_CONTACTS),
|
||||
listAutomationRules: vi.fn().mockResolvedValue(rules)
|
||||
}
|
||||
|
||||
window.api = {
|
||||
getAutomationStatus: vi.fn().mockResolvedValue({
|
||||
listening: true,
|
||||
listeningDegraded: false,
|
||||
todayExecutions: 0,
|
||||
todaySuccesses: 0,
|
||||
sendCapability: {
|
||||
supported: true,
|
||||
ready: true,
|
||||
canSendText: true,
|
||||
canSendImage: true,
|
||||
message: '个人微信发送能力已就绪'
|
||||
}
|
||||
}),
|
||||
listAutomationRules: spies.listAutomationRules,
|
||||
listAutomationGroups: vi.fn().mockResolvedValue([]),
|
||||
listAutomationExecutions: vi.fn().mockResolvedValue([]),
|
||||
listSendableContacts: spies.listSendableContacts,
|
||||
getGroupExitMonitorState: vi.fn().mockResolvedValue(MONITOR_STATE),
|
||||
onGroupExitMonitorState: vi.fn(() => () => undefined),
|
||||
saveLeaveNotificationRule: spies.saveLeaveNotificationRule,
|
||||
createAutomationRule: spies.createAutomationRule,
|
||||
updateAutomationRule: spies.updateAutomationRule,
|
||||
deleteAutomationRule: spies.deleteAutomationRule,
|
||||
setAutomationRuleEnabled: spies.setAutomationRuleEnabled,
|
||||
setGroupExitMonitorGroups: spies.setGroupExitMonitorGroups
|
||||
} as unknown as typeof window.api
|
||||
|
||||
return { spies, rules }
|
||||
}
|
||||
|
||||
const renderWithProviders = (element: ReactElement): void => {
|
||||
render(<ToastProvider>{element}</ToastProvider>)
|
||||
}
|
||||
|
||||
const renderMonitorWithProviders = (element: ReactElement): void => {
|
||||
render(
|
||||
<TooltipProvider>
|
||||
<ToastProvider>{element}</ToastProvider>
|
||||
</TooltipProvider>
|
||||
)
|
||||
}
|
||||
|
||||
/** 找到首页那张「退群通知」卡片(现在有两张卡,都有「编辑」)。 */
|
||||
async function leaveNotificationCard(): Promise<HTMLElement> {
|
||||
return (await screen.findByText('退群通知')).closest('article') as HTMLElement
|
||||
}
|
||||
|
||||
/** 从自动化首页那张退群通知卡片的「编辑」进编辑器。 */
|
||||
async function openLeaveNotificationEditor(overrides: {
|
||||
leaveRule?: AutomationRule
|
||||
} = {}): Promise<{ spies: ApiSpies }> {
|
||||
const user = userEvent.setup()
|
||||
const { spies } = installApi(overrides)
|
||||
renderWithProviders(<AutomationWorkspace dbReady onOpenExitMonitorGroups={() => {}} />)
|
||||
|
||||
const card = await leaveNotificationCard()
|
||||
await user.click(within(card).getByRole('button', { name: '编辑' }))
|
||||
return { spies }
|
||||
}
|
||||
|
||||
const previewRecipient = (): string =>
|
||||
screen.getByTestId('leave-preview-recipient').textContent ?? ''
|
||||
|
||||
const previewFact = (label: string): string => {
|
||||
const rows = Array.from(document.querySelectorAll('.automation-preview-facts > div'))
|
||||
for (const row of rows) {
|
||||
if (row.querySelector('dt')?.textContent === label) {
|
||||
return row.querySelector('dd')?.textContent ?? ''
|
||||
}
|
||||
}
|
||||
return ''
|
||||
}
|
||||
|
||||
const targetRadio = (label: string): HTMLElement => screen.getByRole('radio', { name: label })
|
||||
|
||||
describe('自动化 · 规则类型 Tab', () => {
|
||||
it('两种规则类型都是真规则,切换互不影响', async () => {
|
||||
const user = userEvent.setup()
|
||||
installApi()
|
||||
renderWithProviders(<AutomationWorkspace dbReady />)
|
||||
|
||||
await screen.findByText('退群通知')
|
||||
await user.click(screen.getAllByRole('button', { name: '新建自动化' })[0])
|
||||
expect(screen.getByLabelText('关键词')).toBeInTheDocument()
|
||||
|
||||
await user.click(screen.getByRole('radio', { name: '退群通知' }))
|
||||
expect(screen.getByLabelText('退群通知模板内容')).toBeInTheDocument()
|
||||
expect(screen.queryByLabelText('关键词')).toBeNull()
|
||||
|
||||
await user.click(screen.getByRole('radio', { name: '@我生成日报' }))
|
||||
expect(screen.getByLabelText('关键词')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('首页卡片显示真实状态与真实目标,不再有「待配置 / UI 预览」', async () => {
|
||||
installApi()
|
||||
renderWithProviders(<AutomationWorkspace dbReady />)
|
||||
|
||||
await screen.findByText('退群通知')
|
||||
const card = screen.getByText('退群通知').closest('article') as HTMLElement
|
||||
|
||||
expect(card.textContent).toContain('运行中')
|
||||
expect(card.textContent).toContain('当前群聊')
|
||||
expect(card.textContent).toContain('3 个已监控群聊')
|
||||
expect(document.body.textContent).not.toContain('待配置')
|
||||
expect(document.body.textContent).not.toContain('UI 预览')
|
||||
})
|
||||
|
||||
it('迁移待重选的规则在首页显示为「配置异常」', async () => {
|
||||
installApi({
|
||||
leaveRule: createDefaultLeaveNotificationRule(Date.now(), {
|
||||
enabled: false,
|
||||
targetNeedsReview: true
|
||||
})
|
||||
})
|
||||
renderWithProviders(<AutomationWorkspace dbReady />)
|
||||
|
||||
const card = (await screen.findByText('退群通知')).closest('article') as HTMLElement
|
||||
expect(card.textContent).toContain('配置异常')
|
||||
})
|
||||
})
|
||||
|
||||
describe('退群通知 · 真实数据', () => {
|
||||
it('已监控群聊数量来自退群监控', async () => {
|
||||
await openLeaveNotificationEditor()
|
||||
|
||||
expect(await screen.findByText('3 个群聊')).toBeVisible()
|
||||
expect(screen.queryByText('243 个群聊')).toBeNull()
|
||||
})
|
||||
|
||||
it('好友清单来自 main 侧的可发送联系人接口', async () => {
|
||||
const user = userEvent.setup()
|
||||
await openLeaveNotificationEditor()
|
||||
|
||||
await user.click(targetRadio('指定好友'))
|
||||
|
||||
expect(screen.getByRole('radio', { name: '好友甲' })).toBeInTheDocument()
|
||||
expect(screen.getByRole('radio', { name: '好友乙' })).toBeInTheDocument()
|
||||
expect(screen.queryByRole('radio', { name: '张三' })).toBeNull()
|
||||
})
|
||||
|
||||
it('Section 1 没有「触发范围」,只有唯一的「管理监控群聊」入口', async () => {
|
||||
await openLeaveNotificationEditor()
|
||||
|
||||
expect(screen.queryByText('触发范围')).toBeNull()
|
||||
expect(screen.queryByText('全部已监控群聊')).toBeNull()
|
||||
expect(screen.queryByText('指定已监控群聊')).toBeNull()
|
||||
expect(screen.getByRole('button', { name: /管理监控群聊/ })).toBeEnabled()
|
||||
})
|
||||
|
||||
it('规则级启停只有一个开关,没有第二个「发送退群通知」', async () => {
|
||||
await openLeaveNotificationEditor()
|
||||
|
||||
expect(screen.getAllByRole('switch')).toHaveLength(1)
|
||||
expect(screen.getByRole('switch', { name: '启用这条自动化' })).toBeVisible()
|
||||
expect(screen.queryByText('发送退群通知')).toBeNull()
|
||||
})
|
||||
})
|
||||
|
||||
describe('退群通知 · 四种目标', () => {
|
||||
it('是四选一,「当前群聊」排第一且默认选中', async () => {
|
||||
await openLeaveNotificationEditor()
|
||||
|
||||
const order = Array.from(
|
||||
document.querySelectorAll('.automation-leave-targets .automation-leave-radio label')
|
||||
).map((label) => label.textContent?.trim())
|
||||
|
||||
expect(order).toEqual(['当前群聊', '文件传输助手', '发给自己', '指定好友'])
|
||||
expect(targetRadio('当前群聊')).toBeChecked()
|
||||
})
|
||||
|
||||
it('只有「指定好友」才展开好友选择器', async () => {
|
||||
const user = userEvent.setup()
|
||||
await openLeaveNotificationEditor()
|
||||
|
||||
for (const label of ['文件传输助手', '当前群聊', '发给自己']) {
|
||||
await user.click(targetRadio(label))
|
||||
expect(screen.queryByPlaceholderText('搜索好友')).toBeNull()
|
||||
}
|
||||
|
||||
await user.click(targetRadio('指定好友'))
|
||||
expect(screen.getByPlaceholderText('搜索好友')).toBeVisible()
|
||||
})
|
||||
|
||||
it('好友只能选一个', async () => {
|
||||
const user = userEvent.setup()
|
||||
await openLeaveNotificationEditor()
|
||||
await user.click(targetRadio('指定好友'))
|
||||
|
||||
await user.click(screen.getByRole('radio', { name: '好友甲' }))
|
||||
expect(screen.getByRole('radio', { name: '好友甲' })).toBeChecked()
|
||||
|
||||
await user.click(screen.getByRole('radio', { name: '好友乙' }))
|
||||
expect(screen.getByRole('radio', { name: '好友乙' })).toBeChecked()
|
||||
expect(screen.getByRole('radio', { name: '好友甲' })).not.toBeChecked()
|
||||
})
|
||||
})
|
||||
|
||||
describe('退群通知 · 保存与取消', () => {
|
||||
it('保存会写入 singleton 规则(含目标、模板、开关)', async () => {
|
||||
const user = userEvent.setup()
|
||||
const { spies } = await openLeaveNotificationEditor()
|
||||
|
||||
// 刻意选一个**与默认不同**的目标:这样才验证了"保存的是用户选的"。
|
||||
await user.click(targetRadio('发给自己'))
|
||||
await user.click(screen.getByRole('button', { name: '保存' }))
|
||||
|
||||
await waitFor(() => expect(spies.saveLeaveNotificationRule).toHaveBeenCalledTimes(1))
|
||||
const draft = spies.saveLeaveNotificationRule.mock.calls[0][0] as AutomationRule
|
||||
expect(draft.id).toBe(BUILTIN_LEAVE_NOTIFICATION_RULE_ID)
|
||||
expect(draft.ruleType).toBe('leave_notification')
|
||||
expect(draft.enabled).toBe(true)
|
||||
expect(draft.leaveNotification?.target).toEqual({ type: 'self' })
|
||||
expect(draft.leaveNotification?.template).toContain('[退群监测]')
|
||||
})
|
||||
|
||||
it('取消不写任何东西', async () => {
|
||||
const user = userEvent.setup()
|
||||
const { spies } = await openLeaveNotificationEditor()
|
||||
|
||||
await user.click(targetRadio('发给自己'))
|
||||
await user.click(screen.getByRole('button', { name: '取消' }))
|
||||
|
||||
expect(spies.saveLeaveNotificationRule).not.toHaveBeenCalled()
|
||||
// 回到首页:卡片上的目标仍是持久化的那个(默认「当前群聊」),不是刚点的「发给自己」。
|
||||
expect((await screen.findByText('退群通知')).closest('article')?.textContent).toContain(
|
||||
'当前群聊'
|
||||
)
|
||||
})
|
||||
|
||||
it('重新打开时恢复的是已持久化配置,不是上次未保存的改动', async () => {
|
||||
const user = userEvent.setup()
|
||||
const { spies } = await openLeaveNotificationEditor()
|
||||
|
||||
await user.click(targetRadio('发给自己'))
|
||||
await user.click(screen.getByRole('button', { name: '取消' }))
|
||||
|
||||
await user.click(within(await leaveNotificationCard()).getByRole('button', { name: '编辑' }))
|
||||
expect(targetRadio('当前群聊')).toBeChecked()
|
||||
expect(spies.saveLeaveNotificationRule).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('启用开关也会被保存', async () => {
|
||||
const user = userEvent.setup()
|
||||
const { spies } = await openLeaveNotificationEditor()
|
||||
|
||||
await user.click(screen.getByRole('switch', { name: '启用这条自动化' }))
|
||||
await user.click(screen.getByRole('button', { name: '保存' }))
|
||||
|
||||
await waitFor(() => expect(spies.saveLeaveNotificationRule).toHaveBeenCalledTimes(1))
|
||||
const draft = spies.saveLeaveNotificationRule.mock.calls[0][0] as AutomationRule
|
||||
expect(draft.enabled).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
describe('退群通知 · 效果预览', () => {
|
||||
it('预览用的是模板渲染结果,不是写死的示例', async () => {
|
||||
await openLeaveNotificationEditor()
|
||||
|
||||
const bubble = document.querySelector('.automation-chat-bubble.pre')
|
||||
expect(bubble?.textContent).toContain('[退群监测]')
|
||||
// 占位符已按样本事件替换(同一套 shared 渲染规则)。
|
||||
expect(bubble?.textContent).toContain('用户: 张三')
|
||||
expect(bubble?.textContent).toContain('人数: 243 -> 242')
|
||||
})
|
||||
|
||||
it('改发送目标 → 顶部模拟收件人跟着变', async () => {
|
||||
const user = userEvent.setup()
|
||||
await openLeaveNotificationEditor()
|
||||
|
||||
// 默认 = 当前群聊 ⇒ 顶部收件会话就是发生退群的那个群。
|
||||
expect(previewRecipient()).toBe('TraceMemo 交流群')
|
||||
|
||||
await user.click(targetRadio('文件传输助手'))
|
||||
expect(previewRecipient()).toBe('文件传输助手')
|
||||
|
||||
await user.click(targetRadio('发给自己'))
|
||||
expect(previewRecipient()).toBe('我')
|
||||
})
|
||||
|
||||
it('指定好友时预览收件人跟着好友变,未选时如实说未选择', async () => {
|
||||
const user = userEvent.setup()
|
||||
await openLeaveNotificationEditor()
|
||||
|
||||
await user.click(targetRadio('指定好友'))
|
||||
expect(previewRecipient()).toBe('未选择好友')
|
||||
|
||||
await user.click(screen.getByRole('radio', { name: '好友甲' }))
|
||||
expect(previewRecipient()).toBe('好友甲')
|
||||
})
|
||||
|
||||
it('底部摘要随目标变化,且不含「执行方式」', async () => {
|
||||
const user = userEvent.setup()
|
||||
await openLeaveNotificationEditor()
|
||||
|
||||
expect(previewFact('触发事件')).toBe('成员退出')
|
||||
expect(previewFact('监控来源')).toBe('3 个已监控群聊')
|
||||
expect(previewFact('通知目标')).toBe('发生退群事件的群聊')
|
||||
expect(document.querySelector('.automation-preview-facts')?.textContent).not.toContain('执行方式')
|
||||
|
||||
await user.click(targetRadio('文件传输助手'))
|
||||
expect(previewFact('通知目标')).toBe('文件传输助手')
|
||||
})
|
||||
|
||||
it('预览永远不触发发送与保存', async () => {
|
||||
const user = userEvent.setup()
|
||||
const { spies } = await openLeaveNotificationEditor()
|
||||
|
||||
await user.click(targetRadio('当前群聊'))
|
||||
await user.click(targetRadio('指定好友'))
|
||||
|
||||
for (const spy of [
|
||||
spies.saveLeaveNotificationRule,
|
||||
spies.createAutomationRule,
|
||||
spies.updateAutomationRule,
|
||||
spies.setAutomationRuleEnabled
|
||||
]) {
|
||||
expect(spy).not.toHaveBeenCalled()
|
||||
}
|
||||
})
|
||||
|
||||
it('编辑器里不出现底层实现词', async () => {
|
||||
await openLeaveNotificationEditor()
|
||||
|
||||
expect(document.body.textContent).not.toMatch(/AutomationRule|trigger matcher|ActionRunner|WCDB/)
|
||||
})
|
||||
})
|
||||
|
||||
describe('退群通知 · 通知内容与变量', () => {
|
||||
it('变量清单以 {groupName} 打头,且可以插进模板', async () => {
|
||||
const user = userEvent.setup()
|
||||
await openLeaveNotificationEditor()
|
||||
|
||||
const chips = Array.from(document.querySelectorAll('.automation-leave-template-chip')).map(
|
||||
(chip) => chip.textContent
|
||||
)
|
||||
expect(chips).toEqual([
|
||||
'{groupName}',
|
||||
'{user}',
|
||||
'{groupRemark}',
|
||||
'{wxid}',
|
||||
'{previousCount}',
|
||||
'{currentCount}',
|
||||
'{time}'
|
||||
])
|
||||
|
||||
await user.click(screen.getByRole('button', { name: '插入变量 groupName' }))
|
||||
const textarea = screen.getByLabelText('退群通知模板内容') as HTMLTextAreaElement
|
||||
expect(textarea.value).toContain('{groupName}')
|
||||
})
|
||||
|
||||
/*
|
||||
* 预览必须能同时看出「哪个群」和「谁退的」:
|
||||
* groupName 与 groupRemark 一旦取值相同,两者的区别就从界面上消失了。
|
||||
*/
|
||||
it('预览里群名与成员群昵称是两个不同的值', async () => {
|
||||
await openLeaveNotificationEditor()
|
||||
|
||||
const bubble = document.querySelector('.automation-chat-bubble.pre')
|
||||
expect(bubble?.textContent).toContain('群聊: TraceMemo 交流群')
|
||||
expect(bubble?.textContent).toContain('群备注: 小张')
|
||||
})
|
||||
|
||||
it('底部说明直说「群名 vs 成员群昵称」的区别,且不含旧语义残句', async () => {
|
||||
await openLeaveNotificationEditor()
|
||||
|
||||
const note = document.querySelector('.automation-leave-template-note')?.textContent ?? ''
|
||||
expect(note).toContain('未读取到')
|
||||
// 实测有人把 {groupRemark} 当成群名 —— 这句必须直说区别。
|
||||
expect(note).toContain('群聊名')
|
||||
expect(note).toContain('不是群名')
|
||||
// 旧文案两句都是错的:回退链被安到了 groupRemark 上;后半句是"只能发回原群"时代的残句。
|
||||
expect(note).not.toContain('通知仅发送到本规则配置的通知群聊')
|
||||
expect(note).not.toContain('群备注为空时可回退显示群昵称')
|
||||
})
|
||||
|
||||
/*
|
||||
* 变量清单原先只有 {groupRemark} 这种符号,用户看不出含义,
|
||||
* 于是有人把它当成群名。每个 chip 必须带中文说明。
|
||||
*/
|
||||
it('每个变量 chip 都带中文含义说明', async () => {
|
||||
await openLeaveNotificationEditor()
|
||||
|
||||
const chips = Array.from(document.querySelectorAll('.automation-leave-template-chip'))
|
||||
const titleOf = (token: string): string =>
|
||||
chips
|
||||
.find((chip) => chip.textContent?.trim() === token)
|
||||
?.getAttribute('title') ?? ''
|
||||
|
||||
expect(titleOf('{groupName}')).toBe('{groupName}:群聊名(发生退群的群)')
|
||||
expect(titleOf('{groupRemark}')).toContain('不是群名')
|
||||
expect(titleOf('{user}')).toContain('退群成员')
|
||||
expect(titleOf('{time}')).toContain('退群时间')
|
||||
})
|
||||
})
|
||||
|
||||
describe('退群通知 · 群聊名护栏', () => {
|
||||
/** 一份没有群名变量的模板(模拟用户主动删掉了那一行)。 */
|
||||
const ruleWithoutGroupName = (): AutomationRule => ({
|
||||
...createDefaultLeaveNotificationRule(Date.now()),
|
||||
leaveNotification: {
|
||||
target: { type: 'source_chat' },
|
||||
template: '[退群监测]\n\n用户: {user}'
|
||||
}
|
||||
})
|
||||
|
||||
it('目标是「当前群聊」时不提示 —— 通知就发在群里,群名是多余的', async () => {
|
||||
await openLeaveNotificationEditor({ leaveRule: ruleWithoutGroupName() })
|
||||
|
||||
expect(screen.queryByText(/收件人看不出是哪个群退的人/)).toBeNull()
|
||||
expect(screen.queryByRole('button', { name: '补上群聊名' })).toBeNull()
|
||||
})
|
||||
|
||||
it('目标改成非当前群聊时才提示,并给一键补上', async () => {
|
||||
const user = userEvent.setup()
|
||||
await openLeaveNotificationEditor({ leaveRule: ruleWithoutGroupName() })
|
||||
|
||||
await user.click(targetRadio('文件传输助手'))
|
||||
expect(await screen.findByText(/收件人看不出是哪个群退的人/)).toBeVisible()
|
||||
|
||||
await user.click(screen.getByRole('button', { name: '补上群聊名' }))
|
||||
|
||||
const textarea = screen.getByLabelText('退群通知模板内容') as HTMLTextAreaElement
|
||||
expect(textarea.value).toContain('群聊: {groupName}')
|
||||
// 补完提示就消失。
|
||||
expect(screen.queryByText(/收件人看不出是哪个群退的人/)).toBeNull()
|
||||
})
|
||||
|
||||
it('模板本来就含群名时,任何目标都不提示', async () => {
|
||||
const user = userEvent.setup()
|
||||
await openLeaveNotificationEditor()
|
||||
|
||||
await user.click(targetRadio('发给自己'))
|
||||
expect(screen.queryByText(/收件人看不出是哪个群退的人/)).toBeNull()
|
||||
})
|
||||
})
|
||||
|
||||
describe('退群监控 → 退群通知自动化', () => {
|
||||
it('退群监控页顶部有自动化入口', async () => {
|
||||
installApi()
|
||||
renderMonitorWithProviders(
|
||||
<GroupExitMonitorWorkspace dbReady onOpenLeaveNotificationAutomation={() => {}} />
|
||||
)
|
||||
|
||||
expect(await screen.findByRole('button', { name: '配置退群通知自动化' })).toBeVisible()
|
||||
})
|
||||
|
||||
it('点入口直接落到「自动化 → 规则 → 退群通知」', async () => {
|
||||
const user = userEvent.setup()
|
||||
installApi()
|
||||
|
||||
function Harness(): React.ReactElement {
|
||||
const [page, setPage] = React.useState<'exit-monitor' | 'automation'>('exit-monitor')
|
||||
const [request, setRequest] = React.useState<AutomationOpenRuleRequest | null>(null)
|
||||
return page === 'exit-monitor' ? (
|
||||
<GroupExitMonitorWorkspace
|
||||
dbReady
|
||||
onOpenLeaveNotificationAutomation={() => {
|
||||
setRequest({ ruleType: 'leave_notification', requestId: 1 })
|
||||
setPage('automation')
|
||||
}}
|
||||
/>
|
||||
) : (
|
||||
<AutomationWorkspace dbReady openRuleRequest={request} />
|
||||
)
|
||||
}
|
||||
|
||||
renderMonitorWithProviders(<Harness />)
|
||||
|
||||
await user.click(await screen.findByRole('button', { name: '配置退群通知自动化' }))
|
||||
|
||||
expect(await screen.findByLabelText('退群通知模板内容')).toBeVisible()
|
||||
expect(screen.getByRole('radio', { name: '退群通知' })).toBeChecked()
|
||||
})
|
||||
|
||||
it('「管理监控群聊 →」把用户送回退群监控的管理群聊页', async () => {
|
||||
const user = userEvent.setup()
|
||||
installApi()
|
||||
const onOpenExitMonitorGroups = vi.fn()
|
||||
renderWithProviders(
|
||||
<AutomationWorkspace dbReady onOpenExitMonitorGroups={onOpenExitMonitorGroups} />
|
||||
)
|
||||
|
||||
await user.click(within(await leaveNotificationCard()).getByRole('button', { name: '编辑' }))
|
||||
await user.click(screen.getByRole('button', { name: /管理监控群聊/ }))
|
||||
|
||||
expect(onOpenExitMonitorGroups).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
})
|
||||
|
||||
describe('退群通知 · 规则缺失时的兜底', () => {
|
||||
/** 深链的对象引用必须稳定,否则 effect 每次渲染都会重跑。 */
|
||||
function DeepLinkHarness(): React.ReactElement {
|
||||
const [request] = React.useState<AutomationOpenRuleRequest>({
|
||||
ruleType: 'leave_notification',
|
||||
requestId: 1
|
||||
})
|
||||
return <AutomationWorkspace dbReady openRuleRequest={request} />
|
||||
}
|
||||
|
||||
/*
|
||||
* 深链进来时编辑器是**同步**打开的,而规则列表还在 IPC 回来的路上。
|
||||
* 这一帧必然还没有规则 —— 它是最正常的加载状态,不能说成"尚未就绪 / 版本不匹配"。
|
||||
*/
|
||||
it('规则还在读取时显示加载态,不把正常加载描述成故障', async () => {
|
||||
const { spies } = installApi()
|
||||
let release: (rules: AutomationRule[]) => void = () => undefined
|
||||
spies.listAutomationRules.mockReturnValue(
|
||||
new Promise<AutomationRule[]>((resolve) => {
|
||||
release = resolve
|
||||
})
|
||||
)
|
||||
|
||||
renderWithProviders(<DeepLinkHarness />)
|
||||
|
||||
expect(await screen.findByText('正在读取退群通知规则…')).toBeVisible()
|
||||
// 旧兜底文案(把正常加载说成故障)必须消失。这里用**完整旧句子**匹配 ——
|
||||
// 宽泛的 /尚未就绪/ 会命中顶部「发送能力」卡片,那是另一块 UI。
|
||||
expect(screen.queryByText(/退群通知规则尚未就绪/)).toBeNull()
|
||||
expect(screen.queryByText(/没有找到内置的退群通知规则/)).toBeNull()
|
||||
|
||||
release([
|
||||
createDefaultDailyReportRule(Date.now()),
|
||||
createDefaultLeaveNotificationRule(Date.now())
|
||||
])
|
||||
expect(await screen.findByLabelText('退群通知模板内容')).toBeVisible()
|
||||
})
|
||||
|
||||
it('读完了确实没有这条规则时,给出准确说明与重试入口', async () => {
|
||||
const user = userEvent.setup()
|
||||
const { spies } = installApi()
|
||||
// 只有日报规则 —— 等价于「主进程还是迁移前的旧构建」。
|
||||
spies.listAutomationRules.mockResolvedValue([createDefaultDailyReportRule(Date.now())])
|
||||
|
||||
renderWithProviders(<DeepLinkHarness />)
|
||||
|
||||
expect(await screen.findByText('没有找到内置的退群通知规则。')).toBeVisible()
|
||||
expect(screen.getByText(/请重启 TraceMemo/)).toBeVisible()
|
||||
expect(screen.queryByText('正在读取退群通知规则…')).toBeNull()
|
||||
|
||||
const before = spies.listAutomationRules.mock.calls.length
|
||||
await user.click(screen.getByRole('button', { name: '重新加载' }))
|
||||
await waitFor(() =>
|
||||
expect(spies.listAutomationRules.mock.calls.length).toBeGreaterThan(before)
|
||||
)
|
||||
})
|
||||
|
||||
it('重试后规则回来了就直接进编辑器', async () => {
|
||||
const user = userEvent.setup()
|
||||
const { spies } = installApi()
|
||||
spies.listAutomationRules
|
||||
.mockResolvedValueOnce([createDefaultDailyReportRule(Date.now())])
|
||||
.mockResolvedValue([
|
||||
createDefaultDailyReportRule(Date.now()),
|
||||
createDefaultLeaveNotificationRule(Date.now())
|
||||
])
|
||||
|
||||
renderWithProviders(<DeepLinkHarness />)
|
||||
await user.click(await screen.findByRole('button', { name: '重新加载' }))
|
||||
|
||||
expect(await screen.findByLabelText('退群通知模板内容')).toBeVisible()
|
||||
})
|
||||
})
|
||||
|
||||
describe('退群监控 · 旧通知 UI 已移除', () => {
|
||||
it('管理群聊页没有「通知群聊」列,也没有「模板」按钮', async () => {
|
||||
const user = userEvent.setup()
|
||||
installApi()
|
||||
renderMonitorWithProviders(
|
||||
<GroupExitMonitorWorkspace
|
||||
dbReady
|
||||
contacts={[
|
||||
{ m_nsUsrName: 'group_a@chatroom', m_nsNickName: '群 A', md5: 'md5-a', type: 'group' }
|
||||
]}
|
||||
onOpenLeaveNotificationAutomation={() => {}}
|
||||
/>
|
||||
)
|
||||
|
||||
await user.click(await screen.findByRole('button', { name: '管理群聊' }))
|
||||
|
||||
expect(screen.queryByText('通知群聊')).toBeNull()
|
||||
expect(screen.queryByRole('button', { name: '查看退群监测模板' })).toBeNull()
|
||||
// 监控选择本身仍然可用。
|
||||
expect(screen.getByLabelText('监控群 A')).toBeInTheDocument()
|
||||
})
|
||||
})
|
||||
@@ -289,9 +289,6 @@ let groupExitMonitorState = {
|
||||
monitoredGroupCount: 2,
|
||||
monitorSelectionConfigured: true,
|
||||
monitoredRoomIds: ['group_regular@chatroom', 'group_folded@chatroom'],
|
||||
notificationRoomIds: [],
|
||||
notificationTemplate:
|
||||
'[退群监测]\n\n用户: {user}\n\n群备注: {groupRemark}\n\n微信号: {wxid}\n\n人数: {previousCount} -> {currentCount}\n\n退群时间: {time}',
|
||||
lastCheckedAt: fixtureNowMs - 30 * 1000,
|
||||
lastReadAt: 0,
|
||||
unreadCount: 1
|
||||
@@ -304,33 +301,20 @@ const cloneGroupExitMonitorState = () => ({
|
||||
).length
|
||||
})
|
||||
handle('group-exit-monitor:getState', () => cloneGroupExitMonitorState())
|
||||
handle('group-exit-monitor:setGroups', (roomIds, notificationRoomIds) => {
|
||||
// 只保存**监控范围**:通知配置已迁到自动化规则。
|
||||
handle('group-exit-monitor:setGroups', (roomIds) => {
|
||||
const selected = Array.isArray(roomIds)
|
||||
? roomIds.filter((roomId) => typeof roomId === 'string' && roomId.endsWith('@chatroom'))
|
||||
: []
|
||||
const notifications = Array.isArray(notificationRoomIds)
|
||||
? notificationRoomIds.filter(
|
||||
(roomId) => typeof roomId === 'string' && selected.includes(roomId)
|
||||
)
|
||||
: []
|
||||
groupExitMonitorState = {
|
||||
...groupExitMonitorState,
|
||||
monitorSelectionConfigured: true,
|
||||
monitoredRoomIds: [...new Set(selected)],
|
||||
notificationRoomIds: [...new Set(notifications)],
|
||||
monitoredGroupCount: selected.length,
|
||||
lastCheckedAt: fixtureNowMs
|
||||
}
|
||||
return cloneGroupExitMonitorState()
|
||||
})
|
||||
handle('group-exit-monitor:setTemplate', (template) => {
|
||||
if (typeof template !== 'string' || !template.trim()) throw new Error('模板不能为空')
|
||||
groupExitMonitorState = {
|
||||
...groupExitMonitorState,
|
||||
notificationTemplate: template.trim()
|
||||
}
|
||||
return cloneGroupExitMonitorState()
|
||||
})
|
||||
handle('group-exit-monitor:checkNow', () => {
|
||||
groupExitMonitorState = {
|
||||
...groupExitMonitorState,
|
||||
@@ -358,6 +342,133 @@ handle('group-exit-monitor:markRead', (readAt) => {
|
||||
return cloneGroupExitMonitorState()
|
||||
})
|
||||
|
||||
// ---- Automation v1(@我生成日报)----
|
||||
//
|
||||
// 这组桩只服务 UI / 视觉评审:让自动化首页拿到一份确定性的规则与群列表,
|
||||
// 而不是整页挂着「自动化接口尚未就绪」。
|
||||
// 它**不**参与任何真实发送,也**不**代表自动化功能已迁移。
|
||||
const automationGroupOptions = () =>
|
||||
contacts
|
||||
.filter(
|
||||
(contact) =>
|
||||
contact.type === 'group' || String(contact.m_nsUsrName || '').endsWith('@chatroom')
|
||||
)
|
||||
.map((contact) => ({
|
||||
id: contact.m_nsUsrName,
|
||||
name: contact.m_nsNickName || contact.m_nsUsrName
|
||||
}))
|
||||
|
||||
const builtinDailyReportRule = () => ({
|
||||
id: 'builtin-mention-me-daily-report',
|
||||
name: '@我生成日报',
|
||||
enabled: true,
|
||||
ruleType: 'daily_report',
|
||||
trigger: 'message',
|
||||
scope: 'group',
|
||||
conditions: {
|
||||
requireMentionMe: true,
|
||||
keyword: '日报',
|
||||
keywordMatchMode: 'contains',
|
||||
conversationIds: [],
|
||||
ignoreSelf: true
|
||||
},
|
||||
actions: [
|
||||
{ type: 'replyText', enabled: true, text: '收到,正在生成今日日报' },
|
||||
{ type: 'generateReport', enabled: true },
|
||||
{ type: 'sendReportImage', enabled: true }
|
||||
],
|
||||
cooldownSeconds: 60,
|
||||
replyDelaySeconds: 2,
|
||||
createdAt: fixtureNowMs,
|
||||
updatedAt: fixtureNowMs
|
||||
})
|
||||
|
||||
/*
|
||||
* ⚠️ 这里的默认值必须与 `src/shared/automation.ts` 的
|
||||
* `createDefaultLeaveNotificationRule()` **逐字一致**。
|
||||
*
|
||||
* 它扮演"一个全新安装的 main 进程":一旦漂移,E2E 与截图验证的就不是真实默认行为。
|
||||
* 由 `tests/integration/automation-default-contract.test.ts` 锁住。
|
||||
*/
|
||||
let leaveNotificationRule = {
|
||||
id: 'builtin-leave-notification',
|
||||
name: '退群通知',
|
||||
enabled: true,
|
||||
ruleType: 'leave_notification',
|
||||
trigger: 'message',
|
||||
scope: 'group',
|
||||
conditions: {
|
||||
requireMentionMe: false,
|
||||
keyword: '',
|
||||
keywordMatchMode: 'contains',
|
||||
conversationIds: [],
|
||||
ignoreSelf: true
|
||||
},
|
||||
actions: [],
|
||||
cooldownSeconds: 0,
|
||||
replyDelaySeconds: 2,
|
||||
leaveNotification: {
|
||||
// 默认目标 = 当前群聊(旧退群监控通知的原始行为)。
|
||||
target: { type: 'source_chat' },
|
||||
template:
|
||||
'[退群监测]\n\n群聊: {groupName}\n\n用户: {user}\n\n群备注: {groupRemark}\n\n微信号: {wxid}\n\n人数: {previousCount} -> {currentCount}\n\n退群时间: {time}'
|
||||
},
|
||||
createdAt: fixtureNowMs,
|
||||
updatedAt: fixtureNowMs
|
||||
}
|
||||
|
||||
/** 「指定好友」候选:个人联系人,排除群 / 公众号 / 文件传输助手 / 自己。 */
|
||||
const sendableContactOptions = () =>
|
||||
contacts
|
||||
.filter(
|
||||
(contact) =>
|
||||
contact.type !== 'group' &&
|
||||
!String(contact.m_nsUsrName || '').endsWith('@chatroom') &&
|
||||
!String(contact.m_nsUsrName || '').startsWith('gh_') &&
|
||||
contact.m_nsUsrName !== 'filehelper'
|
||||
)
|
||||
.map((contact) => ({
|
||||
id: contact.m_nsUsrName,
|
||||
name: contact.m_nsNickName || contact.m_nsUsrName
|
||||
}))
|
||||
|
||||
handle('automation:getStatus', () => ({
|
||||
listening: connected,
|
||||
listeningDegraded: false,
|
||||
todayExecutions: connected ? 3 : 0,
|
||||
todaySuccesses: connected ? 3 : 0,
|
||||
sendCapability: {
|
||||
supported: personalWechatSupported,
|
||||
ready: connected,
|
||||
canSendText: connected,
|
||||
canSendImage: connected,
|
||||
message: connected ? '个人微信发送能力已就绪' : '尚未绑定个人微信发送能力'
|
||||
}
|
||||
}))
|
||||
handle('automation:listRules', () => [
|
||||
builtinDailyReportRule(),
|
||||
structuredClone(leaveNotificationRule)
|
||||
])
|
||||
handle('automation:listGroups', () => automationGroupOptions())
|
||||
handle('automation:listExecutions', () => [])
|
||||
handle('automation:clearExecutions', () => true)
|
||||
handle('automation:listSendableContacts', () => sendableContactOptions())
|
||||
handle('automation:saveLeaveNotificationRule', (draft) => {
|
||||
leaveNotificationRule = {
|
||||
...leaveNotificationRule,
|
||||
...(draft && typeof draft === 'object' ? draft : {}),
|
||||
id: 'builtin-leave-notification',
|
||||
ruleType: 'leave_notification',
|
||||
updatedAt: fixtureNowMs
|
||||
}
|
||||
if (leaveNotificationRule.leaveNotification) {
|
||||
const { targetNeedsReview, ...rest } = leaveNotificationRule.leaveNotification
|
||||
void targetNeedsReview
|
||||
leaveNotificationRule.leaveNotification = rest
|
||||
}
|
||||
return structuredClone(leaveNotificationRule)
|
||||
})
|
||||
|
||||
const scheduledReportTasks = []
|
||||
const scheduledReportExecutions = []
|
||||
const generatedReports = []
|
||||
|
||||
@@ -0,0 +1,74 @@
|
||||
import { readFileSync } from 'fs-extra'
|
||||
import { join } from 'path'
|
||||
import { describe, expect, it } from 'vitest'
|
||||
|
||||
import { createDefaultLeaveNotificationRule } from '../../src/shared/automation'
|
||||
import { GROUP_EXIT_NOTIFICATION_TEMPLATE } from '../../src/shared/group-exit-monitor'
|
||||
|
||||
/**
|
||||
* E2E main 替身(`tests/e2e/support/electron-main.cjs`)的**默认值契约**。
|
||||
*
|
||||
* 替身扮演"一个全新安装的 main 进程"。它里面的默认值必须与真实默认值逐字一致,
|
||||
* 否则 E2E 与截图验证的就是一个**不存在的世界**。
|
||||
*
|
||||
* 这个契约是被真实事故逼出来的:迁移时把默认目标从"文件传输助手"改成"当前群聊"、
|
||||
* 并往默认模板里加了「群聊: {groupName}」一行,但替身没跟着改 ——
|
||||
* 于是截图里看到的是"当前群聊没被选中、模板也没有群聊行",
|
||||
* 而组件测试却全绿(组件测试用的是内存 mock,不是替身)。
|
||||
*/
|
||||
|
||||
const DOUBLE_PATH = join(process.cwd(), 'tests/e2e/support/electron-main.cjs')
|
||||
|
||||
/**
|
||||
* 取出替身里整条退群通知规则(该声明在文件里只出现一次)。
|
||||
*
|
||||
* 起点取 `let leaveNotificationRule = {` 而不是 `leaveNotification:` ——
|
||||
* `enabled` / `ruleType` / `cooldownSeconds` 都在嵌套的 leaveNotification 之前。
|
||||
*/
|
||||
function leaveNotificationBlock(): string {
|
||||
const source = readFileSync(DOUBLE_PATH, 'utf8')
|
||||
const start = source.indexOf('let leaveNotificationRule = {')
|
||||
expect(start, '替身里找不到 leaveNotificationRule').toBeGreaterThan(-1)
|
||||
return source.slice(start)
|
||||
}
|
||||
|
||||
describe('E2E main 替身的默认值契约', () => {
|
||||
const defaults = createDefaultLeaveNotificationRule(0)
|
||||
|
||||
it('退群通知的默认目标与真实默认值一致', () => {
|
||||
const block = leaveNotificationBlock()
|
||||
const match = block.match(/target:\s*\{\s*type:\s*'([a-z_]+)'/)
|
||||
|
||||
expect(match?.[1]).toBe(defaults.leaveNotification?.target.type)
|
||||
})
|
||||
|
||||
it('退群通知的默认模板与真实默认值逐字一致', () => {
|
||||
const block = leaveNotificationBlock()
|
||||
const match = block.match(/template:\s*'((?:[^'\\]|\\.)*)'/)
|
||||
|
||||
expect(match, '替身里找不到 template 字面量').not.toBeNull()
|
||||
// 替身里是单引号 + \n 转义的 JS 字面量,反转义后与 shared 常量比对。
|
||||
const template = (match as RegExpMatchArray)[1].replace(/\\n/g, '\n')
|
||||
|
||||
expect(template).toBe(defaults.leaveNotification?.template)
|
||||
expect(template).toBe(GROUP_EXIT_NOTIFICATION_TEMPLATE)
|
||||
})
|
||||
|
||||
it('替身里必须存在群名占位符(否则截图看不出群名变量)', () => {
|
||||
expect(leaveNotificationBlock()).toContain('群聊: {groupName}')
|
||||
})
|
||||
|
||||
it('起停/冷却语义与真实默认值一致', () => {
|
||||
const block = leaveNotificationBlock()
|
||||
|
||||
expect(block).toMatch(/enabled:\s*true/)
|
||||
expect(block).toMatch(/ruleType:\s*'leave_notification'/)
|
||||
// 退群通知不套用消息型规则的冷却,否则两次退群会被并成一次。
|
||||
expect(block).toMatch(/cooldownSeconds:\s*0/)
|
||||
})
|
||||
|
||||
it('替身里的日报规则类型与真实分派一致', () => {
|
||||
const source = readFileSync(DOUBLE_PATH, 'utf8')
|
||||
expect(source).toContain("ruleType: 'daily_report'")
|
||||
})
|
||||
})
|
||||
@@ -73,14 +73,6 @@ describe('preload IPC contract', () => {
|
||||
expect(invoke).toHaveBeenLastCalledWith('group-exit-monitor:setEnabled', false)
|
||||
await api.setGroupExitMonitorGroups(['room@chatroom'])
|
||||
expect(invoke).toHaveBeenLastCalledWith('group-exit-monitor:setGroups', ['room@chatroom'])
|
||||
await api.setGroupExitMonitorGroups(['room@chatroom'], ['room@chatroom'])
|
||||
expect(invoke).toHaveBeenLastCalledWith(
|
||||
'group-exit-monitor:setGroups',
|
||||
['room@chatroom'],
|
||||
['room@chatroom']
|
||||
)
|
||||
await api.setGroupExitMonitorNotificationTemplate('用户: {user}')
|
||||
expect(invoke).toHaveBeenLastCalledWith('group-exit-monitor:setTemplate', '用户: {user}')
|
||||
await api.checkGroupExitMonitorNow()
|
||||
expect(invoke).toHaveBeenLastCalledWith('group-exit-monitor:checkNow')
|
||||
await api.clearGroupExitMonitorEvents()
|
||||
@@ -90,6 +82,24 @@ describe('preload IPC contract', () => {
|
||||
await api.listWechatActionLogs()
|
||||
expect(invoke).toHaveBeenLastCalledWith('wechat-action-log:list')
|
||||
|
||||
// 退群通知:保存走 singleton upsert,联系人候选由 main 侧过滤。
|
||||
const leaveDraft = {
|
||||
name: '退群通知',
|
||||
enabled: true,
|
||||
ruleType: 'leave_notification',
|
||||
trigger: 'message',
|
||||
scope: 'group',
|
||||
conditions: {},
|
||||
actions: [],
|
||||
cooldownSeconds: 0,
|
||||
replyDelaySeconds: 2,
|
||||
leaveNotification: { target: { type: 'file_transfer' }, template: '[退群监测]' }
|
||||
} as never
|
||||
await api.saveLeaveNotificationRule(leaveDraft)
|
||||
expect(invoke).toHaveBeenLastCalledWith('automation:saveLeaveNotificationRule', leaveDraft)
|
||||
await api.listSendableContacts()
|
||||
expect(invoke).toHaveBeenLastCalledWith('automation:listSendableContacts')
|
||||
|
||||
await api.getImage('fixture-md5', 'fixture.dat', 'fixture-session', {
|
||||
force: true,
|
||||
priority: 0
|
||||
|
||||
@@ -14,7 +14,7 @@ const root = vi.hoisted(() => {
|
||||
|
||||
vi.mock('electron', () => ({ app: { getPath: () => root } }))
|
||||
|
||||
import { BUILTIN_DAILY_REPORT_RULE_ID } from '../../src/shared/automation'
|
||||
import { BUILTIN_DAILY_REPORT_RULE_ID, BUILTIN_LEAVE_NOTIFICATION_RULE_ID } from '../../src/shared/automation'
|
||||
import {
|
||||
AutomationRuleStore,
|
||||
type AutomationRuleStoreDependencies
|
||||
@@ -31,6 +31,15 @@ const deps = (dir: string, now?: () => number): AutomationRuleStoreDependencies
|
||||
...(now ? { now } : {})
|
||||
})
|
||||
|
||||
/** 写旧退群监控状态文件(退群通知迁移的唯一输入)。 */
|
||||
function writeLegacyMonitorState(input: {
|
||||
monitoredRoomIds?: string[]
|
||||
notificationRoomIds?: string[]
|
||||
notificationTemplate?: string
|
||||
}): void {
|
||||
fs.writeJsonSync(path.join(root, 'group-exit-monitor.json'), input)
|
||||
}
|
||||
|
||||
describe('AutomationRuleStore', () => {
|
||||
beforeEach(() => {
|
||||
fs.removeSync(path.join(root, 'automation'))
|
||||
@@ -38,21 +47,22 @@ describe('AutomationRuleStore', () => {
|
||||
|
||||
afterAll(() => fs.removeSync(root))
|
||||
|
||||
it('首次加载会播种内置规则「@我生成日报」并落盘', () => {
|
||||
it('首次加载会播种内置规则「@我生成日报」与「退群通知」并落盘', () => {
|
||||
const store = new AutomationRuleStore(deps(root))
|
||||
const rules = store.listRules()
|
||||
|
||||
expect(rules).toHaveLength(1)
|
||||
const builtin = rules[0]
|
||||
expect(builtin.id).toBe(BUILTIN_DAILY_REPORT_RULE_ID)
|
||||
expect(builtin.name).toBe('@我生成日报')
|
||||
expect(builtin.enabled).toBe(true)
|
||||
expect(builtin.scope).toBe('group')
|
||||
expect(builtin.conditions.requireMentionMe).toBe(true)
|
||||
expect(builtin.conditions.keyword).toBe('日报')
|
||||
expect(builtin.conditions.ignoreSelf).toBe(true)
|
||||
expect(builtin.cooldownSeconds).toBe(60)
|
||||
expect(builtin.actions.map((action) => action.type)).toEqual([
|
||||
expect(rules).toHaveLength(2)
|
||||
const builtin = rules.find((rule) => rule.id === BUILTIN_DAILY_REPORT_RULE_ID)
|
||||
expect(builtin).toBeDefined()
|
||||
expect(builtin?.name).toBe('@我生成日报')
|
||||
expect(builtin?.ruleType).toBe('daily_report')
|
||||
expect(builtin?.enabled).toBe(true)
|
||||
expect(builtin?.scope).toBe('group')
|
||||
expect(builtin?.conditions.requireMentionMe).toBe(true)
|
||||
expect(builtin?.conditions.keyword).toBe('日报')
|
||||
expect(builtin?.conditions.ignoreSelf).toBe(true)
|
||||
expect(builtin?.cooldownSeconds).toBe(60)
|
||||
expect(builtin?.actions.map((action) => action.type)).toEqual([
|
||||
'replyText',
|
||||
'generateReport',
|
||||
'sendReportImage'
|
||||
@@ -60,9 +70,25 @@ describe('AutomationRuleStore', () => {
|
||||
expect(fs.pathExistsSync(rulesFile())).toBe(true)
|
||||
})
|
||||
|
||||
it('全新安装的退群通知规则:默认目标是「当前群聊」', () => {
|
||||
const store = new AutomationRuleStore(deps(root))
|
||||
const leave = store.listRules().find((rule) => rule.id === BUILTIN_LEAVE_NOTIFICATION_RULE_ID)
|
||||
|
||||
expect(leave).toBeDefined()
|
||||
expect(leave?.ruleType).toBe('leave_notification')
|
||||
expect(leave?.name).toBe('退群通知')
|
||||
// 「当前群聊」= 旧退群监控通知的原始行为,所以既是默认值也是第一项。
|
||||
expect(leave?.leaveNotification?.target).toEqual({ type: 'source_chat' })
|
||||
expect(leave?.leaveNotification?.targetNeedsReview).toBeUndefined()
|
||||
// 退群通知不套用消息型规则的冷却,避免把两次退群合并成一次。
|
||||
expect(leave?.cooldownSeconds).toBe(0)
|
||||
expect(leave?.actions).toEqual([])
|
||||
})
|
||||
|
||||
it('删掉内置规则后不会在下次启动时被重新塞回来', () => {
|
||||
const store = new AutomationRuleStore(deps(root))
|
||||
expect(store.deleteRule(BUILTIN_DAILY_REPORT_RULE_ID)).toBe(true)
|
||||
expect(store.deleteRule(BUILTIN_LEAVE_NOTIFICATION_RULE_ID)).toBe(true)
|
||||
expect(store.listRules()).toHaveLength(0)
|
||||
|
||||
// 关键:新实例(等于重启)不应该重新播种。
|
||||
@@ -83,12 +109,13 @@ describe('AutomationRuleStore', () => {
|
||||
|
||||
expect(created.id).not.toBe(BUILTIN_DAILY_REPORT_RULE_ID)
|
||||
expect(created.name).toBe('关键词回复')
|
||||
expect(created.ruleType).toBe('daily_report')
|
||||
expect(created.scope).toBe('group')
|
||||
expect(created.conditions.keywordMatchMode).toBe('contains')
|
||||
expect(created.conditions.conversationIds).toEqual(['a'])
|
||||
expect(created.createdAt).toBe(now)
|
||||
expect(created.updatedAt).toBe(now)
|
||||
expect(store.listRules()).toHaveLength(2)
|
||||
expect(store.listRules()).toHaveLength(3)
|
||||
})
|
||||
|
||||
it('updateRule 保留 id 与 createdAt,刷新 updatedAt', () => {
|
||||
@@ -137,13 +164,20 @@ describe('AutomationRuleStore', () => {
|
||||
fs.writeFileSync(rulesFile(), '{ 这不是 JSON', 'utf8')
|
||||
|
||||
const store = new AutomationRuleStore(deps(root))
|
||||
expect(store.listRules()).toHaveLength(1)
|
||||
expect(store.listRules()[0].id).toBe(BUILTIN_DAILY_REPORT_RULE_ID)
|
||||
expect(store.listRules()).toHaveLength(2)
|
||||
expect(store.listRules().map((rule) => rule.id)).toEqual(
|
||||
expect.arrayContaining([BUILTIN_DAILY_REPORT_RULE_ID, BUILTIN_LEAVE_NOTIFICATION_RULE_ID])
|
||||
)
|
||||
})
|
||||
|
||||
it('已播种但规则列表为空的存档不会被再次播种', () => {
|
||||
it('已播种但规则列表为空的存档不会被再次播种「@我生成日报」', () => {
|
||||
fs.ensureDirSync(path.dirname(rulesFile()))
|
||||
fs.writeJsonSync(rulesFile(), { version: 1, builtinSeeded: true, rules: [] })
|
||||
fs.writeJsonSync(rulesFile(), {
|
||||
version: 2,
|
||||
builtinSeeded: true,
|
||||
leaveNotificationMigrated: true,
|
||||
rules: []
|
||||
})
|
||||
|
||||
const store = new AutomationRuleStore(deps(root))
|
||||
expect(store.listRules()).toHaveLength(0)
|
||||
@@ -156,6 +190,291 @@ describe('AutomationRuleStore', () => {
|
||||
const reopened = new AutomationRuleStore(deps(root))
|
||||
expect(reopened.listRules().map((rule) => rule.name)).toContain('持久化检查')
|
||||
})
|
||||
|
||||
it('saveLeaveNotificationRule 是 singleton upsert:保存多次也只有一条', () => {
|
||||
const store = new AutomationRuleStore(deps(root))
|
||||
for (let index = 0; index < 3; index += 1) {
|
||||
store.saveLeaveNotificationRule({
|
||||
name: '退群通知',
|
||||
enabled: true,
|
||||
ruleType: 'leave_notification',
|
||||
scope: 'group',
|
||||
conditions: {},
|
||||
actions: [],
|
||||
cooldownSeconds: 0,
|
||||
replyDelaySeconds: 2,
|
||||
leaveNotification: {
|
||||
target: { type: 'contact', contactId: `wxid_friend_${index}` },
|
||||
template: '[退群监测]\n用户: {user}'
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
const leaveRules = store
|
||||
.listRules()
|
||||
.filter((rule) => rule.id === BUILTIN_LEAVE_NOTIFICATION_RULE_ID)
|
||||
expect(leaveRules).toHaveLength(1)
|
||||
expect(leaveRules[0].leaveNotification?.target).toEqual({
|
||||
type: 'contact',
|
||||
contactId: 'wxid_friend_2'
|
||||
})
|
||||
})
|
||||
|
||||
it('保存退群通知会清掉迁移遗留的「目标待重选」标记', () => {
|
||||
writeLegacyMonitorState({
|
||||
monitoredRoomIds: ['a@chatroom', 'b@chatroom'],
|
||||
notificationRoomIds: ['a@chatroom']
|
||||
})
|
||||
const store = new AutomationRuleStore(deps(root))
|
||||
expect(
|
||||
store.getRule(BUILTIN_LEAVE_NOTIFICATION_RULE_ID)?.leaveNotification?.targetNeedsReview
|
||||
).toBe(true)
|
||||
|
||||
store.saveLeaveNotificationRule({
|
||||
...store.getRule(BUILTIN_LEAVE_NOTIFICATION_RULE_ID),
|
||||
enabled: true,
|
||||
leaveNotification: { target: { type: 'source_chat' }, template: '[退群监测]' }
|
||||
})
|
||||
|
||||
const saved = store.getRule(BUILTIN_LEAVE_NOTIFICATION_RULE_ID)
|
||||
expect(saved?.leaveNotification?.targetNeedsReview).toBeUndefined()
|
||||
expect(saved?.leaveNotification?.target).toEqual({ type: 'source_chat' })
|
||||
})
|
||||
|
||||
/*
|
||||
* 加上群名变量之前的默认模板(有「人数」行、没有「群聊」行)。
|
||||
* 这正是老用户手上那份 —— 模板是他们的已保存数据。
|
||||
*/
|
||||
const PREVIOUS_DEFAULT_TEMPLATE = [
|
||||
'[退群监测]',
|
||||
'',
|
||||
'用户: {user}',
|
||||
'',
|
||||
'群备注: {groupRemark}',
|
||||
'',
|
||||
'微信号: {wxid}',
|
||||
'',
|
||||
'人数: {previousCount} -> {currentCount}',
|
||||
'',
|
||||
'退群时间: {time}'
|
||||
].join('\n')
|
||||
|
||||
/** 写一份"老用户"的规则文件(退群通知模板里没有群名变量)。 */
|
||||
function writeRulesWithTemplate(
|
||||
template: string,
|
||||
flags: { notificationTemplateUpgraded?: boolean } = {}
|
||||
): void {
|
||||
fs.ensureDirSync(path.dirname(rulesFile()))
|
||||
fs.writeJsonSync(rulesFile(), {
|
||||
version: 2,
|
||||
builtinSeeded: true,
|
||||
leaveNotificationMigrated: true,
|
||||
notificationTemplateUpgraded: flags.notificationTemplateUpgraded === true,
|
||||
rules: [
|
||||
{
|
||||
id: BUILTIN_DAILY_REPORT_RULE_ID,
|
||||
name: '@我生成日报',
|
||||
enabled: true,
|
||||
ruleType: 'daily_report',
|
||||
trigger: 'message',
|
||||
scope: 'group',
|
||||
conditions: { requireMentionMe: true, keyword: '日报', keywordMatchMode: 'contains' },
|
||||
actions: [{ type: 'generateReplyText', enabled: true }],
|
||||
cooldownSeconds: 60,
|
||||
replyDelaySeconds: 2,
|
||||
createdAt: 1,
|
||||
updatedAt: 1
|
||||
},
|
||||
{
|
||||
id: BUILTIN_LEAVE_NOTIFICATION_RULE_ID,
|
||||
name: '退群通知',
|
||||
enabled: true,
|
||||
ruleType: 'leave_notification',
|
||||
trigger: 'message',
|
||||
scope: 'group',
|
||||
conditions: { requireMentionMe: false, keyword: '', keywordMatchMode: 'contains' },
|
||||
actions: [],
|
||||
cooldownSeconds: 0,
|
||||
replyDelaySeconds: 2,
|
||||
leaveNotification: { target: { type: 'source_chat' }, template },
|
||||
createdAt: 1,
|
||||
updatedAt: 1
|
||||
}
|
||||
]
|
||||
})
|
||||
}
|
||||
|
||||
describe('替用户把群名变量补进模板(一次性)', () => {
|
||||
it('老用户首次读盘时自动补上「群聊」这一行,其余内容保留', () => {
|
||||
writeRulesWithTemplate(PREVIOUS_DEFAULT_TEMPLATE)
|
||||
|
||||
const rule = new AutomationRuleStore(deps(root)).getRule(BUILTIN_LEAVE_NOTIFICATION_RULE_ID)
|
||||
const template = rule?.leaveNotification?.template ?? ''
|
||||
|
||||
expect(template).toContain('群聊: {groupName}')
|
||||
// 原来每一行都还在。
|
||||
for (const line of PREVIOUS_DEFAULT_TEMPLATE.split('\n')) {
|
||||
if (line.trim()) expect(template).toContain(line)
|
||||
}
|
||||
})
|
||||
|
||||
it('只补一次:之后用户删掉这一行,重启不会被加回来', () => {
|
||||
writeRulesWithTemplate(PREVIOUS_DEFAULT_TEMPLATE)
|
||||
// 第一轮:自动补上,并落盘标记。
|
||||
const first = new AutomationRuleStore(deps(root))
|
||||
expect(first.getRule(BUILTIN_LEAVE_NOTIFICATION_RULE_ID)?.leaveNotification?.template).toContain(
|
||||
'群聊: {groupName}'
|
||||
)
|
||||
|
||||
// 用户主动把这一行删掉并保存。
|
||||
const stripped = PREVIOUS_DEFAULT_TEMPLATE
|
||||
first.saveLeaveNotificationRule({
|
||||
...first.getRule(BUILTIN_LEAVE_NOTIFICATION_RULE_ID),
|
||||
leaveNotification: { target: { type: 'source_chat' }, template: stripped }
|
||||
})
|
||||
|
||||
// 重启:不能再替他补 —— "删不掉"比缺信息更讨厌。
|
||||
const reopened = new AutomationRuleStore(deps(root))
|
||||
expect(
|
||||
reopened.getRule(BUILTIN_LEAVE_NOTIFICATION_RULE_ID)?.leaveNotification?.template
|
||||
).toBe(stripped)
|
||||
})
|
||||
|
||||
it('已经含 {groupName} 的模板原样不动', () => {
|
||||
const already = '[退群监测]\n\n群聊: {groupName}\n\n用户: {user}'
|
||||
writeRulesWithTemplate(already)
|
||||
|
||||
const rule = new AutomationRuleStore(deps(root)).getRule(BUILTIN_LEAVE_NOTIFICATION_RULE_ID)
|
||||
expect(rule?.leaveNotification?.template).toBe(already)
|
||||
})
|
||||
|
||||
it('用户完全自定义的模板也不会被覆盖内容', () => {
|
||||
writeRulesWithTemplate('退群: {user}')
|
||||
|
||||
const rule = new AutomationRuleStore(deps(root)).getRule(BUILTIN_LEAVE_NOTIFICATION_RULE_ID)
|
||||
const template = rule?.leaveNotification?.template ?? ''
|
||||
|
||||
expect(template).toContain('退群: {user}')
|
||||
expect(template).toContain('群聊: {groupName}')
|
||||
})
|
||||
|
||||
it('标记已是 true 时不再动模板', () => {
|
||||
writeRulesWithTemplate(PREVIOUS_DEFAULT_TEMPLATE, { notificationTemplateUpgraded: true })
|
||||
|
||||
const rule = new AutomationRuleStore(deps(root)).getRule(BUILTIN_LEAVE_NOTIFICATION_RULE_ID)
|
||||
expect(rule?.leaveNotification?.template).toBe(PREVIOUS_DEFAULT_TEMPLATE)
|
||||
})
|
||||
|
||||
it('全新安装的模板本来就带群名,不需要补', () => {
|
||||
const rule = new AutomationRuleStore(deps(root)).getRule(BUILTIN_LEAVE_NOTIFICATION_RULE_ID)
|
||||
expect(rule?.leaveNotification?.template).toContain('群聊: {groupName}')
|
||||
})
|
||||
})
|
||||
|
||||
describe('旧退群通知配置迁移', () => {
|
||||
it('旧配置从不通知任何人 → 迁移成关闭,且保留自定义模板', () => {
|
||||
writeLegacyMonitorState({
|
||||
monitoredRoomIds: ['a@chatroom', 'b@chatroom'],
|
||||
notificationRoomIds: [],
|
||||
notificationTemplate: '退群: {user}'
|
||||
})
|
||||
|
||||
const leave = new AutomationRuleStore(deps(root)).getRule(
|
||||
BUILTIN_LEAVE_NOTIFICATION_RULE_ID
|
||||
)
|
||||
|
||||
expect(leave?.enabled).toBe(false)
|
||||
// 关闭状态下 target 只是占位值(= 默认目标),不会发送任何东西。
|
||||
expect(leave?.leaveNotification?.target).toEqual({ type: 'source_chat' })
|
||||
// 用户写的模板内容保留;同一次启动的"补群名"升级会另加一行。
|
||||
expect(leave?.leaveNotification?.template).toContain('退群: {user}')
|
||||
expect(leave?.leaveNotification?.template).toContain('群聊: {groupName}')
|
||||
})
|
||||
|
||||
it('旧配置在每个被监控群都通知 → 无损映射为「当前群聊」且保持启用', () => {
|
||||
writeLegacyMonitorState({
|
||||
monitoredRoomIds: ['a@chatroom', 'b@chatroom'],
|
||||
notificationRoomIds: ['a@chatroom', 'b@chatroom']
|
||||
})
|
||||
|
||||
const leave = new AutomationRuleStore(deps(root)).getRule(
|
||||
BUILTIN_LEAVE_NOTIFICATION_RULE_ID
|
||||
)
|
||||
|
||||
expect(leave?.enabled).toBe(true)
|
||||
expect(leave?.leaveNotification?.target).toEqual({ type: 'source_chat' })
|
||||
expect(leave?.leaveNotification?.targetNeedsReview).toBeUndefined()
|
||||
})
|
||||
|
||||
/*
|
||||
* 关键的一条:旧「通知群聊」是**逐群**的多值配置,新目标是**单值**。
|
||||
* 只勾了一部分时无法无损映射 —— 这时候:
|
||||
* 不取第一个群、不改写成当前群聊、保持关闭、要求用户重选,并留一份备份。
|
||||
*/
|
||||
it('旧配置只勾了部分群 → 标记待重选、不发送、留下备份,绝不猜', () => {
|
||||
writeLegacyMonitorState({
|
||||
monitoredRoomIds: ['a@chatroom', 'b@chatroom', 'c@chatroom'],
|
||||
notificationRoomIds: ['b@chatroom'],
|
||||
notificationTemplate: '退群: {user}'
|
||||
})
|
||||
|
||||
const store = new AutomationRuleStore(deps(root))
|
||||
const leave = store.getRule(BUILTIN_LEAVE_NOTIFICATION_RULE_ID)
|
||||
|
||||
expect(leave?.enabled).toBe(false)
|
||||
expect(leave?.leaveNotification?.targetNeedsReview).toBe(true)
|
||||
// 不回落到「取第一个群」,也不改写成别的具体目标 —— 只留默认占位(当前群聊),
|
||||
// 且因为 enabled=false + targetNeedsReview=true,在用户重选之前不会发送。
|
||||
expect(leave?.leaveNotification?.target).toEqual({ type: 'source_chat' })
|
||||
// 用户写的模板内容保留;同一次启动的"补群名"升级会另加一行。
|
||||
expect(leave?.leaveNotification?.template).toContain('退群: {user}')
|
||||
expect(leave?.leaveNotification?.template).toContain('群聊: {groupName}')
|
||||
|
||||
const backup = fs.readJsonSync(
|
||||
path.join(root, 'automation', 'leave-notification-migration-backup.json')
|
||||
)
|
||||
expect(backup).toMatchObject({
|
||||
outcome: 'needs_review',
|
||||
legacy: { notificationRoomIds: ['b@chatroom'] }
|
||||
})
|
||||
expect(store.getLastLeaveNotificationMigration()?.outcome).toBe('needs_review')
|
||||
})
|
||||
|
||||
it('迁移只跑一次:重启两次也只有一条退群通知规则', () => {
|
||||
writeLegacyMonitorState({
|
||||
monitoredRoomIds: ['a@chatroom', 'b@chatroom'],
|
||||
notificationRoomIds: ['a@chatroom', 'b@chatroom']
|
||||
})
|
||||
|
||||
const first = new AutomationRuleStore(deps(root))
|
||||
const second = new AutomationRuleStore(deps(root))
|
||||
|
||||
for (const store of [first, second]) {
|
||||
expect(
|
||||
store.listRules().filter((rule) => rule.id === BUILTIN_LEAVE_NOTIFICATION_RULE_ID)
|
||||
).toHaveLength(1)
|
||||
}
|
||||
})
|
||||
|
||||
it('迁移完成标记会被持久化,删掉退群通知规则后重启不会再被塞回来', () => {
|
||||
const store = new AutomationRuleStore(deps(root))
|
||||
expect(store.deleteRule(BUILTIN_LEAVE_NOTIFICATION_RULE_ID)).toBe(true)
|
||||
|
||||
const reopened = new AutomationRuleStore(deps(root))
|
||||
expect(reopened.getRule(BUILTIN_LEAVE_NOTIFICATION_RULE_ID)).toBeUndefined()
|
||||
})
|
||||
|
||||
it('旧状态文件在迁移后仍留在磁盘上(不做不可逆删除)', () => {
|
||||
writeLegacyMonitorState({
|
||||
monitoredRoomIds: ['a@chatroom'],
|
||||
notificationRoomIds: ['a@chatroom']
|
||||
})
|
||||
|
||||
void new AutomationRuleStore(deps(root))
|
||||
|
||||
expect(fs.pathExistsSync(path.join(root, 'group-exit-monitor.json'))).toBe(true)
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
describe('AutomationExecutionLogService', () => {
|
||||
|
||||
@@ -0,0 +1,394 @@
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
chat: {
|
||||
listContacts: vi.fn(),
|
||||
getSelfAccountInfo: vi.fn()
|
||||
}
|
||||
}))
|
||||
|
||||
vi.mock('electron', () => ({ app: { getPath: () => '/tmp/tracememo-automation-group-exit' } }))
|
||||
vi.mock('../../src/main/services/chat-service', () => mocks.chat)
|
||||
|
||||
import {
|
||||
AutomationService,
|
||||
leaveNotificationExecutionId,
|
||||
leaveNotificationIdempotencyKey
|
||||
} from '../../src/main/services/automation-service'
|
||||
import { AutomationActionRunner } from '../../src/main/services/automation-action-runner'
|
||||
import type { AutomationExecutionLogService } from '../../src/main/services/automation-execution-log-service'
|
||||
import type { AutomationRuleStore } from '../../src/main/services/automation-rule-store'
|
||||
import {
|
||||
BUILTIN_LEAVE_NOTIFICATION_RULE_ID,
|
||||
createDefaultLeaveNotificationRule,
|
||||
type AutomationExecution,
|
||||
type AutomationRule,
|
||||
type LeaveNotificationConfig
|
||||
} from '../../src/shared/automation'
|
||||
import type { GroupMemberExitedEvent } from '../../src/shared/group-exit-event'
|
||||
import type { PersonalWechatSendCapability } from '../../src/shared/personal-wechat'
|
||||
import type { WechatActionRequest, WechatActionResult } from '../../src/shared/wechat-action'
|
||||
|
||||
/**
|
||||
* 退群事件 → 自动化执行。
|
||||
*
|
||||
* 这是迁移后的**唯一发送链路**,所以这里锁的是行为契约而不是实现细节:
|
||||
* 关闭不执行、四种目标各自解析正确、同一事件只发一次、失败不影响退群事实。
|
||||
*/
|
||||
|
||||
const readyCapability: PersonalWechatSendCapability = {
|
||||
supported: true,
|
||||
ready: true,
|
||||
status: 'ready',
|
||||
capabilities: { text: true, image: true, voice: true },
|
||||
senderStatus: {} as never,
|
||||
message: 'ready'
|
||||
}
|
||||
|
||||
const NOW = 1_700_000_000_000
|
||||
|
||||
function exitEvent(overrides: Partial<GroupMemberExitedEvent> = {}): GroupMemberExitedEvent {
|
||||
return {
|
||||
eventId: 'room@chatroom:wxid_member:1700000000000:1',
|
||||
conversationId: 'room@chatroom',
|
||||
groupName: '产品测试群',
|
||||
memberId: 'wxid_member',
|
||||
memberName: '张三',
|
||||
wechatNickname: '张三',
|
||||
previousCount: 243,
|
||||
currentCount: 242,
|
||||
occurredAt: NOW,
|
||||
...overrides
|
||||
}
|
||||
}
|
||||
|
||||
function sentAction(): WechatActionResult {
|
||||
return {
|
||||
actionId: 'action-1',
|
||||
status: 'sent',
|
||||
decision: 'allow',
|
||||
startedAt: new Date(NOW).toISOString(),
|
||||
finishedAt: new Date(NOW).toISOString()
|
||||
}
|
||||
}
|
||||
|
||||
interface Harness {
|
||||
service: AutomationService
|
||||
requests: WechatActionRequest[]
|
||||
executions: AutomationExecution[]
|
||||
setRule: (rule: AutomationRule | undefined) => void
|
||||
setCapability: (capability: PersonalWechatSendCapability) => void
|
||||
}
|
||||
|
||||
function createHarness(
|
||||
options: {
|
||||
config?: Partial<LeaveNotificationConfig>
|
||||
rule?: Partial<AutomationRule>
|
||||
actionResult?: () => Promise<WechatActionResult> | WechatActionResult
|
||||
} = {}
|
||||
): Harness {
|
||||
const base = createDefaultLeaveNotificationRule(NOW)
|
||||
let rule: AutomationRule | undefined = {
|
||||
...base,
|
||||
...options.rule,
|
||||
leaveNotification: { ...base.leaveNotification!, ...options.config }
|
||||
}
|
||||
let capability: PersonalWechatSendCapability = readyCapability
|
||||
const requests: WechatActionRequest[] = []
|
||||
const executions: AutomationExecution[] = []
|
||||
|
||||
const ruleStore = {
|
||||
listRules: () => (rule ? [rule] : []),
|
||||
getRule: (id: string) => (rule && rule.id === id ? rule : undefined)
|
||||
} as unknown as AutomationRuleStore
|
||||
const executionLog = {
|
||||
record: (execution: AutomationExecution) => {
|
||||
const index = executions.findIndex((item) => item.executionId === execution.executionId)
|
||||
if (index >= 0) executions[index] = execution
|
||||
else executions.push(execution)
|
||||
},
|
||||
list: () => executions,
|
||||
clear: () => true,
|
||||
countSince: () => ({ total: executions.length, success: 0 })
|
||||
} as unknown as AutomationExecutionLogService
|
||||
const runner = new AutomationActionRunner({
|
||||
executeAction: async (request) => {
|
||||
requests.push(request)
|
||||
return options.actionResult ? options.actionResult() : sentAction()
|
||||
},
|
||||
now: () => NOW
|
||||
})
|
||||
|
||||
const service = new AutomationService({} as never, {
|
||||
ruleStore,
|
||||
executionLog,
|
||||
runner,
|
||||
getCapability: async () => capability,
|
||||
now: () => NOW
|
||||
})
|
||||
|
||||
return {
|
||||
service,
|
||||
requests,
|
||||
executions,
|
||||
setRule: (next) => {
|
||||
rule = next
|
||||
},
|
||||
setCapability: (next) => {
|
||||
capability = next
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
mocks.chat.listContacts.mockReset().mockReturnValue([
|
||||
{ m_nsUsrName: 'wxid_friend', m_nsNickName: '好友', remark: '好友备注', type: 'user' },
|
||||
{ m_nsUsrName: 'room@chatroom', m_nsNickName: '产品测试群', type: 'group' }
|
||||
])
|
||||
mocks.chat.getSelfAccountInfo.mockReset().mockReturnValue({ wxid: 'wxid_self' })
|
||||
})
|
||||
|
||||
describe('AutomationService.handleGroupExit', () => {
|
||||
it('退群事件 → 命中规则 → 解析目标 → Gateway 调用一次 → execution 成功', async () => {
|
||||
const harness = createHarness({ config: { target: { type: 'file_transfer' } } })
|
||||
|
||||
await harness.service.handleGroupExit(exitEvent())
|
||||
|
||||
expect(harness.requests).toHaveLength(1)
|
||||
expect(harness.requests[0]).toMatchObject({
|
||||
origin: 'automation',
|
||||
purpose: 'automation_leave_notification',
|
||||
triggerType: 'automation',
|
||||
recipient: { type: 'contact', id: 'filehelper', name: '文件传输助手' },
|
||||
content: { type: 'text' }
|
||||
})
|
||||
expect(harness.executions).toHaveLength(1)
|
||||
expect(harness.executions[0]).toMatchObject({
|
||||
ruleId: BUILTIN_LEAVE_NOTIFICATION_RULE_ID,
|
||||
ruleName: '退群通知',
|
||||
sourceDisplayName: '产品测试群',
|
||||
status: 'success'
|
||||
})
|
||||
// 步骤序列:触发 → 匹配 → 目标 → 发送
|
||||
expect(harness.executions[0].steps.map((step) => step.key)).toEqual([
|
||||
'exit_received',
|
||||
'exit_matched',
|
||||
'exit_target',
|
||||
'exit_send'
|
||||
])
|
||||
// 用户可见的「目标」是显示名,不是 wxid。
|
||||
const targetStep = harness.executions[0].steps.find((step) => step.key === 'exit_target')
|
||||
expect(targetStep?.detail).toBe('文件传输助手')
|
||||
})
|
||||
|
||||
it('规则关闭时不执行、也不创建 execution', async () => {
|
||||
const harness = createHarness({ rule: { enabled: false } })
|
||||
|
||||
await harness.service.handleGroupExit(exitEvent())
|
||||
|
||||
expect(harness.requests).toHaveLength(0)
|
||||
expect(harness.executions).toHaveLength(0)
|
||||
})
|
||||
|
||||
it('目标待重选(迁移遗留)时不执行、也不创建 execution', async () => {
|
||||
const harness = createHarness({
|
||||
config: { targetNeedsReview: true, target: { type: 'file_transfer' } }
|
||||
})
|
||||
|
||||
await harness.service.handleGroupExit(exitEvent())
|
||||
|
||||
expect(harness.requests).toHaveLength(0)
|
||||
expect(harness.executions).toHaveLength(0)
|
||||
})
|
||||
|
||||
it('缺少 eventId 时直接跳过,绝不发送', async () => {
|
||||
const harness = createHarness()
|
||||
|
||||
await harness.service.handleGroupExit(exitEvent({ eventId: '' }))
|
||||
|
||||
expect(harness.requests).toHaveLength(0)
|
||||
})
|
||||
|
||||
it('当前群聊 → 发送目标是事件所在群', async () => {
|
||||
const harness = createHarness({ config: { target: { type: 'source_chat' } } })
|
||||
|
||||
await harness.service.handleGroupExit(
|
||||
exitEvent({ conversationId: 'A@chatroom', groupName: 'A 群' })
|
||||
)
|
||||
|
||||
expect(harness.requests[0].recipient).toEqual({
|
||||
type: 'group',
|
||||
id: 'A@chatroom',
|
||||
name: 'A 群'
|
||||
})
|
||||
})
|
||||
|
||||
it('发给自己 → 发送目标是当前账号 wxid', async () => {
|
||||
mocks.chat.getSelfAccountInfo.mockReturnValue({ wxid: 'wxid_realme' })
|
||||
const harness = createHarness({ config: { target: { type: 'self' } } })
|
||||
|
||||
await harness.service.handleGroupExit(exitEvent())
|
||||
|
||||
expect(harness.requests[0].recipient).toEqual({
|
||||
type: 'contact',
|
||||
id: 'wxid_realme',
|
||||
name: '我'
|
||||
})
|
||||
})
|
||||
|
||||
it('文件传输助手 → 稳定 identity,而不是昵称', async () => {
|
||||
const harness = createHarness({ config: { target: { type: 'file_transfer' } } })
|
||||
|
||||
await harness.service.handleGroupExit(exitEvent())
|
||||
|
||||
expect(harness.requests[0].recipient.id).toBe('filehelper')
|
||||
expect(harness.requests[0].recipient.id).not.toBe('文件传输助手')
|
||||
})
|
||||
|
||||
it('指定好友 → 发送目标是保存的稳定 id', async () => {
|
||||
const harness = createHarness({
|
||||
config: { target: { type: 'contact', contactId: 'wxid_friend' } }
|
||||
})
|
||||
|
||||
await harness.service.handleGroupExit(exitEvent())
|
||||
|
||||
expect(harness.requests[0].recipient).toEqual({
|
||||
type: 'contact',
|
||||
id: 'wxid_friend',
|
||||
name: '好友备注'
|
||||
})
|
||||
})
|
||||
|
||||
/*
|
||||
* §「旧联系人失效」:不偷偷发给别人,execution 记 failed,Gateway 一次都不调。
|
||||
*/
|
||||
it('指定好友已不存在 → execution failed 且不调用 Gateway', async () => {
|
||||
const harness = createHarness({
|
||||
config: { target: { type: 'contact', contactId: 'wxid_gone' } }
|
||||
})
|
||||
|
||||
await harness.service.handleGroupExit(exitEvent())
|
||||
|
||||
expect(harness.requests).toHaveLength(0)
|
||||
expect(harness.executions).toHaveLength(1)
|
||||
expect(harness.executions[0].status).toBe('failed')
|
||||
expect(harness.executions[0].errorSummary).toContain('已不存在或当前无法发送')
|
||||
const sendStep = harness.executions[0].steps.find((step) => step.key === 'exit_send')
|
||||
expect(sendStep?.status).toBe('skipped')
|
||||
})
|
||||
|
||||
it('发送能力缺失 → execution failed(退群事实不受影响)', async () => {
|
||||
const harness = createHarness()
|
||||
harness.setCapability({ ...readyCapability, capabilities: { text: false, image: false, voice: false } })
|
||||
|
||||
await harness.service.handleGroupExit(exitEvent())
|
||||
|
||||
expect(harness.requests).toHaveLength(0)
|
||||
expect(harness.executions[0].status).toBe('failed')
|
||||
expect(harness.executions[0].errorSummary).toContain('无法发送文字')
|
||||
})
|
||||
|
||||
it('Gateway 抛错 → execution failed,且 handleGroupExit 自己绝不抛', async () => {
|
||||
const harness = createHarness({
|
||||
actionResult: () => {
|
||||
throw new Error('connector timeout')
|
||||
}
|
||||
})
|
||||
|
||||
await expect(harness.service.handleGroupExit(exitEvent())).resolves.toBeUndefined()
|
||||
expect(harness.executions).toHaveLength(1)
|
||||
expect(harness.executions[0].status).toBe('failed')
|
||||
})
|
||||
|
||||
it('Gateway 返回失败状态 → execution failed', async () => {
|
||||
const harness = createHarness({
|
||||
actionResult: () => ({
|
||||
actionId: 'action-x',
|
||||
status: 'failed',
|
||||
decision: 'allow',
|
||||
errorCode: 'SEND_FAILED',
|
||||
reason: '微信发送失败',
|
||||
startedAt: new Date(NOW).toISOString(),
|
||||
finishedAt: new Date(NOW).toISOString()
|
||||
})
|
||||
})
|
||||
|
||||
await harness.service.handleGroupExit(exitEvent())
|
||||
|
||||
expect(harness.executions[0].status).toBe('failed')
|
||||
expect(harness.executions[0].errorSummary).toBe('微信发送失败')
|
||||
})
|
||||
|
||||
it('模板里所有变量都被替换(预览与实发共用同一套规则)', async () => {
|
||||
const harness = createHarness({
|
||||
config: {
|
||||
target: { type: 'file_transfer' },
|
||||
template: '{groupName}|{user}|{groupRemark}|{wxid}|{previousCount}->{currentCount}|{time}'
|
||||
}
|
||||
})
|
||||
|
||||
await harness.service.handleGroupExit(
|
||||
exitEvent({ groupName: '产品测试群', groupRemark: '群内备注', wechatNickname: '微信昵称' })
|
||||
)
|
||||
|
||||
const content = harness.requests[0].content
|
||||
expect(content.type).toBe('text')
|
||||
if (content.type === 'text') {
|
||||
// 群名({groupName})与成员群昵称({groupRemark})是两个值,不能混。
|
||||
expect(content.text).toBe(
|
||||
'产品测试群|微信昵称|群内备注|wxid_member|243->242|2023-11-15 06:13:20'
|
||||
)
|
||||
}
|
||||
})
|
||||
|
||||
it('同一个 eventId 投递两次 → 只发一次、只产生一条 execution', async () => {
|
||||
const harness = createHarness()
|
||||
const event = exitEvent()
|
||||
|
||||
await harness.service.handleGroupExit(event)
|
||||
await harness.service.handleGroupExit(event)
|
||||
|
||||
expect(harness.requests).toHaveLength(1)
|
||||
expect(harness.executions).toHaveLength(1)
|
||||
})
|
||||
|
||||
/*
|
||||
* §「不同事件」:同群两个成员先后退出就是两条通知。
|
||||
* 退群通知**不复用**消息型规则的 cooldown,否则第二次会被时间窗吞掉。
|
||||
*/
|
||||
it('不同 eventId 各自执行一次,不被合并', async () => {
|
||||
const harness = createHarness()
|
||||
|
||||
await harness.service.handleGroupExit(exitEvent({ eventId: 'event-a' }))
|
||||
await harness.service.handleGroupExit(exitEvent({ eventId: 'event-b' }))
|
||||
|
||||
expect(harness.requests).toHaveLength(2)
|
||||
expect(harness.executions).toHaveLength(2)
|
||||
expect(new Set(harness.executions.map((item) => item.executionId)).size).toBe(2)
|
||||
})
|
||||
|
||||
it('幂等键与 executionId 都由 eventId 派生(跨重启也稳定)', () => {
|
||||
const eventId = 'room@chatroom:wxid_member:1700000000000:1'
|
||||
|
||||
expect(leaveNotificationIdempotencyKey(eventId)).toBe(
|
||||
`automation_leave_notification:${eventId}`
|
||||
)
|
||||
// 同一个 (ruleId, eventId) 永远算出同一个 executionId —— 重启后重复投递会覆盖同一条记录。
|
||||
expect(leaveNotificationExecutionId('rule-1', eventId)).toBe(
|
||||
leaveNotificationExecutionId('rule-1', eventId)
|
||||
)
|
||||
expect(leaveNotificationExecutionId('rule-1', eventId)).not.toBe(
|
||||
leaveNotificationExecutionId('rule-1', 'another-event')
|
||||
)
|
||||
})
|
||||
|
||||
it('规则不存在或不是退群通知类型时静默跳过', async () => {
|
||||
const harness = createHarness()
|
||||
harness.setRule(undefined)
|
||||
|
||||
await harness.service.handleGroupExit(exitEvent())
|
||||
|
||||
expect(harness.requests).toHaveLength(0)
|
||||
expect(harness.executions).toHaveLength(0)
|
||||
})
|
||||
})
|
||||
@@ -44,7 +44,7 @@ vi.mock('../../src/main/services/personal-wechat-send-service', () => ({
|
||||
}))
|
||||
|
||||
import { GroupExitMonitorService } from '../../src/main/services/group-exit-monitor-service'
|
||||
import { GROUP_EXIT_NOTIFICATION_TEMPLATE } from '../../src/shared/group-exit-monitor'
|
||||
import type { GroupMemberExitedEvent } from '../../src/shared/group-exit-event'
|
||||
|
||||
const member = { wxid: 'wxid_member', wechatNickname: '微信名', groupNickname: '群内名' }
|
||||
const otherMember = { wxid: 'wxid_other', wechatNickname: '另一个人' }
|
||||
@@ -93,14 +93,12 @@ function writeBaseline(
|
||||
roomId: string
|
||||
groupName: string
|
||||
members: Array<{ wxid: string; [key: string]: string }>
|
||||
}>,
|
||||
notificationRoomIds: string[] = []
|
||||
}>
|
||||
): void {
|
||||
writeJsonSync(join(mocks.userData, 'group-exit-monitor.json'), {
|
||||
accountRoot: 'fixture-account',
|
||||
events: [],
|
||||
monitoredRoomIds: snapshots.map((snapshot) => snapshot.roomId),
|
||||
notificationRoomIds,
|
||||
snapshots: snapshots.map((snapshot) => ({
|
||||
contactId: `${snapshot.roomId}-md5`,
|
||||
roomId: snapshot.roomId,
|
||||
@@ -135,36 +133,16 @@ describe('GroupExitMonitorService', () => {
|
||||
}
|
||||
})
|
||||
|
||||
it('persists a validated custom template in the monitor state file', () => {
|
||||
const service = new GroupExitMonitorService()
|
||||
const template = '[退群监测]\n用户: {user}'
|
||||
|
||||
const state = service.setNotificationTemplate(template)
|
||||
expect(state.notificationTemplate).toBe(template)
|
||||
expect(readJsonSync(join(mocks.userData, 'group-exit-monitor.json')).notificationTemplate).toBe(
|
||||
template
|
||||
)
|
||||
expect(() => service.setNotificationTemplate('用户: {unknown}')).toThrow('不支持的占位符')
|
||||
})
|
||||
|
||||
it('migrates the previous default notification template', () => {
|
||||
writeJsonSync(join(mocks.userData, 'group-exit-monitor.json'), {
|
||||
notificationTemplate:
|
||||
'[退群监测]\n\n用户: {user}\n\n群备注: {groupRemark}\n\n微信号: {wxid}\n\n退群时间: {time}'
|
||||
})
|
||||
|
||||
const service = new GroupExitMonitorService()
|
||||
|
||||
expect(service.getState().notificationTemplate).toBe(GROUP_EXIT_NOTIFICATION_TEMPLATE)
|
||||
})
|
||||
/*
|
||||
* 模板相关的用例(保存 / 归一化 / 渲染)**已随迁移移出本文件**:
|
||||
* 模板现在属于自动化规则,由 `leave-notification-*` 那组测试覆盖。
|
||||
* 退群监控不再持有模板,所以这里没有任何模板可测。
|
||||
*/
|
||||
|
||||
it('persists OFF without checking contact changes or deleting configuration', async () => {
|
||||
vi.useFakeTimers()
|
||||
installGroupDb()
|
||||
writeBaseline(
|
||||
[{ roomId: 'room@chatroom', groupName: '测试群', members: [member, otherMember] }],
|
||||
['room@chatroom']
|
||||
)
|
||||
writeBaseline([{ roomId: 'room@chatroom', groupName: '测试群', members: [member, otherMember] }])
|
||||
const service = new GroupExitMonitorService()
|
||||
await service.setEnabled(false)
|
||||
await service.start(true)
|
||||
@@ -176,8 +154,7 @@ describe('GroupExitMonitorService', () => {
|
||||
const stored = readJsonSync(join(mocks.userData, 'group-exit-monitor.json'))
|
||||
expect(stored).toMatchObject({
|
||||
enabled: false,
|
||||
monitoredRoomIds: ['room@chatroom'],
|
||||
notificationRoomIds: ['room@chatroom']
|
||||
monitoredRoomIds: ['room@chatroom']
|
||||
})
|
||||
expect(stored.snapshots[0].members).toEqual([member, otherMember])
|
||||
vi.useRealTimers()
|
||||
@@ -186,8 +163,7 @@ describe('GroupExitMonitorService', () => {
|
||||
it('rebuilds the current baseline when re-enabled without reporting paused exits', async () => {
|
||||
installGroupDb()
|
||||
writeBaseline(
|
||||
[{ roomId: 'room@chatroom', groupName: '测试群', members: [member, otherMember] }],
|
||||
['room@chatroom']
|
||||
[{ roomId: 'room@chatroom', groupName: '测试群', members: [member, otherMember] }]
|
||||
)
|
||||
const service = new GroupExitMonitorService()
|
||||
await service.setEnabled(false)
|
||||
@@ -344,33 +320,26 @@ describe('GroupExitMonitorService', () => {
|
||||
).toMatchObject({ roomId: 'A@chatroom', groupName: '测试群A' })
|
||||
})
|
||||
|
||||
it('uses one resolved group name for both 3-to-1 events and Gateway notification recipients', async () => {
|
||||
it('uses one resolved group name for both 3-to-1 events and the emitted leave events', async () => {
|
||||
installGroupDb()
|
||||
const departed = { wxid: 'wxid_departed', groupNickname: '离群一' }
|
||||
const secondDeparted = { wxid: 'wxid_second_departed', groupNickname: '离群二' }
|
||||
writeBaseline(
|
||||
[
|
||||
{
|
||||
roomId: 'A@chatroom',
|
||||
groupName: 'A@chatroom',
|
||||
members: [member, departed, secondDeparted]
|
||||
}
|
||||
],
|
||||
['A@chatroom']
|
||||
)
|
||||
writeBaseline([
|
||||
{
|
||||
roomId: 'A@chatroom',
|
||||
groupName: 'A@chatroom',
|
||||
members: [member, departed, secondDeparted]
|
||||
}
|
||||
])
|
||||
mocks.chat.getGroupNamesAsync.mockResolvedValue({ 'A@chatroom': '测试群A' })
|
||||
mocks.chat.getGroupMemberIdsBatchAsync.mockResolvedValue([
|
||||
{ roomId: 'A@chatroom', status: 'ok', memberIds: [member.wxid] }
|
||||
])
|
||||
const requests: Array<{ recipient?: { name?: string } }> = []
|
||||
const actionGateway = {
|
||||
execute: vi.fn(async (request: { recipient?: { name?: string } }) => {
|
||||
requests.push(request)
|
||||
return { status: 'sent', actionId: 'action-1', decision: 'allow' }
|
||||
}),
|
||||
registerMemberEvent: vi.fn()
|
||||
}
|
||||
const service = new GroupExitMonitorService({ actionGateway })
|
||||
const emitted: GroupMemberExitedEvent[] = []
|
||||
const service = new GroupExitMonitorService()
|
||||
service.setGroupExitHandler((event) => {
|
||||
emitted.push(event)
|
||||
})
|
||||
|
||||
await service.start(true)
|
||||
|
||||
@@ -393,8 +362,10 @@ describe('GroupExitMonitorService', () => {
|
||||
})
|
||||
])
|
||||
)
|
||||
expect(requests).toHaveLength(2)
|
||||
expect(requests.every((request) => request.recipient?.name === '测试群A')).toBe(true)
|
||||
// 事件里的群名与存储里的一致 —— 通知目标要显示的就是这个名字。
|
||||
expect(emitted).toHaveLength(2)
|
||||
expect(emitted.every((event) => event.groupName === '测试群A')).toBe(true)
|
||||
expect(emitted.every((event) => event.conversationId === 'A@chatroom')).toBe(true)
|
||||
expect(mocks.chat.getGroupSnapshotAsync).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
@@ -559,15 +530,18 @@ describe('GroupExitMonitorService', () => {
|
||||
warn.mockRestore()
|
||||
})
|
||||
|
||||
it('keeps snapshots when only notification settings change', async () => {
|
||||
it('keeps snapshots when the monitor scope is re-saved', async () => {
|
||||
writeBaseline([{ roomId: 'room@chatroom', groupName: '测试群', members: [member] }])
|
||||
const service = new GroupExitMonitorService()
|
||||
service.getState()
|
||||
|
||||
await service.setMonitoredRoomIds(['room@chatroom'], ['room@chatroom'])
|
||||
await service.setMonitoredRoomIds(['room@chatroom'])
|
||||
|
||||
const stored = readJsonSync(join(mocks.userData, 'group-exit-monitor.json'))
|
||||
expect(stored.notificationRoomIds).toEqual(['room@chatroom'])
|
||||
expect(stored.monitoredRoomIds).toEqual(['room@chatroom'])
|
||||
// 通知配置已经不在这个文件里了 —— 迁到自动化规则后不允许双写。
|
||||
expect(stored.notificationRoomIds).toBeUndefined()
|
||||
expect(stored.notificationTemplate).toBeUndefined()
|
||||
expect(stored.snapshots).toHaveLength(1)
|
||||
expect(stored.snapshots[0].members).toEqual([member])
|
||||
})
|
||||
@@ -756,33 +730,50 @@ describe('GroupExitMonitorService', () => {
|
||||
vi.useRealTimers()
|
||||
})
|
||||
|
||||
it('renders the saved template before sending a group notification', async () => {
|
||||
/**
|
||||
* 迁移后的分工:**退群监控只产生事件,发送完全归自动化**。
|
||||
*
|
||||
* 它不再读发送能力、不再调 `WechatActionGateway`、也不在事件上记发送状态。
|
||||
*/
|
||||
it('hands the exit event to automation and never touches the send path itself', async () => {
|
||||
installGroupDb()
|
||||
writeBaseline(
|
||||
[{ roomId: 'room@chatroom', groupName: '测试群', members: [member, otherMember] }],
|
||||
['room@chatroom']
|
||||
)
|
||||
mocks.capability.getPersonalWechatSendCapability.mockResolvedValue({
|
||||
ready: true,
|
||||
capabilities: { text: true }
|
||||
})
|
||||
mocks.sender.send.mockResolvedValue({ success: true })
|
||||
writeBaseline([
|
||||
{ roomId: 'room@chatroom', groupName: '测试群', members: [member, otherMember] }
|
||||
])
|
||||
mocks.chat.getGroupMemberIdsBatchAsync.mockResolvedValue([
|
||||
{ roomId: 'room@chatroom', status: 'ok', memberIds: [member.wxid] }
|
||||
])
|
||||
const emitted: GroupMemberExitedEvent[] = []
|
||||
const service = new GroupExitMonitorService()
|
||||
service.setNotificationTemplate('退群: {user}/{groupRemark}/{wxid}')
|
||||
await service.start(true)
|
||||
|
||||
expect(mocks.sender.send).toHaveBeenCalledWith({
|
||||
type: 'text',
|
||||
to: 'room@chatroom',
|
||||
isGroup: true,
|
||||
text: '退群: 另一个人/未设置/wxid_other'
|
||||
service.setGroupExitHandler((event) => {
|
||||
emitted.push(event)
|
||||
})
|
||||
await service.start(true)
|
||||
const state = service.getState()
|
||||
|
||||
expect(state.events[0]).toMatchObject({ memberWxid: 'wxid_other' })
|
||||
// 事件上不再有发送状态字段(发送结果归自动化执行日志)。
|
||||
expect(state.events[0]).not.toHaveProperty('notificationStatus')
|
||||
expect(state.events[0]).not.toHaveProperty('notification')
|
||||
expect(emitted).toHaveLength(1)
|
||||
expect(emitted[0]).toMatchObject({
|
||||
eventId: state.events[0].id,
|
||||
conversationId: 'room@chatroom',
|
||||
memberId: 'wxid_other',
|
||||
previousCount: 2,
|
||||
currentCount: 1
|
||||
})
|
||||
// 监控自己不发送、也不去问发送能力。
|
||||
expect(mocks.sender.send).not.toHaveBeenCalled()
|
||||
expect(mocks.capability.getPersonalWechatSendCapability).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('records an exit without creating a send action when notification is disabled', async () => {
|
||||
/*
|
||||
* 处理器抛错**不能**污染监控循环:退群事实已经落盘,
|
||||
* 通知失败是自动化那边的事(§「退群事实已检测成功 ≠ 通知发送成功」)。
|
||||
* 未捕获的 rejection 也会让整个 diff 循环挂掉。
|
||||
*/
|
||||
it('keeps recording exits when the automation handler rejects', async () => {
|
||||
installGroupDb()
|
||||
writeBaseline([
|
||||
{ roomId: 'room@chatroom', groupName: '测试群', members: [member, otherMember] }
|
||||
@@ -791,72 +782,39 @@ describe('GroupExitMonitorService', () => {
|
||||
{ roomId: 'room@chatroom', status: 'ok', memberIds: [member.wxid] }
|
||||
])
|
||||
const service = new GroupExitMonitorService()
|
||||
await service.start(true)
|
||||
const state = service.getState()
|
||||
|
||||
expect(state.events[0]).toMatchObject({
|
||||
memberWxid: 'wxid_other',
|
||||
notificationStatus: 'not_requested'
|
||||
service.setGroupExitHandler(async () => {
|
||||
throw new Error('通知发送失败')
|
||||
})
|
||||
expect(mocks.sender.send).not.toHaveBeenCalled()
|
||||
expect(mocks.capability.getPersonalWechatSendCapability).not.toHaveBeenCalled()
|
||||
|
||||
await service.start(true)
|
||||
// 让 handler 的 rejection 落地。
|
||||
await Promise.resolve()
|
||||
|
||||
const state = service.getState()
|
||||
expect(state.events).toHaveLength(1)
|
||||
expect(state.events[0]).toMatchObject({ memberWxid: 'wxid_other' })
|
||||
expect(state.lastCheckedAt).toBeDefined()
|
||||
})
|
||||
|
||||
it('微信发送能力不可用时仍保留退群事件', async () => {
|
||||
it('does not re-emit the same snapshot diff when checked again', async () => {
|
||||
installGroupDb()
|
||||
writeBaseline(
|
||||
[{ roomId: 'room@chatroom', groupName: '测试群', members: [member, otherMember] }],
|
||||
['room@chatroom']
|
||||
)
|
||||
mocks.capability.getPersonalWechatSendCapability.mockResolvedValue({
|
||||
ready: false,
|
||||
supported: true,
|
||||
status: 'needs_binding',
|
||||
capabilities: { text: false, image: false, voice: false },
|
||||
senderStatus: {},
|
||||
message: '当前微信发送能力不可用'
|
||||
})
|
||||
writeBaseline([
|
||||
{ roomId: 'room@chatroom', groupName: '测试群', members: [member, otherMember] }
|
||||
])
|
||||
mocks.chat.getGroupMemberIdsBatchAsync.mockResolvedValue([
|
||||
{ roomId: 'room@chatroom', status: 'ok', memberIds: [member.wxid] }
|
||||
])
|
||||
const emitted: GroupMemberExitedEvent[] = []
|
||||
const service = new GroupExitMonitorService()
|
||||
await service.start(true)
|
||||
const state = service.getState()
|
||||
|
||||
expect(state.events[0]).toMatchObject({
|
||||
notificationStatus: 'failed',
|
||||
notification: {
|
||||
status: 'failed',
|
||||
errorCode: 'SEND_CAPABILITY_UNAVAILABLE'
|
||||
}
|
||||
service.setGroupExitHandler((event) => {
|
||||
emitted.push(event)
|
||||
})
|
||||
expect(mocks.sender.send).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('does not send twice when the same snapshot diff is checked again', async () => {
|
||||
installGroupDb()
|
||||
writeBaseline(
|
||||
[{ roomId: 'room@chatroom', groupName: '测试群', members: [member, otherMember] }],
|
||||
['room@chatroom']
|
||||
)
|
||||
mocks.capability.getPersonalWechatSendCapability.mockResolvedValue({
|
||||
ready: true,
|
||||
capabilities: { text: true, image: false, voice: false },
|
||||
supported: true,
|
||||
status: 'ready',
|
||||
senderStatus: {},
|
||||
message: 'ready'
|
||||
})
|
||||
mocks.sender.send.mockResolvedValue({ success: true })
|
||||
mocks.chat.getGroupMemberIdsBatchAsync.mockResolvedValue([
|
||||
{ roomId: 'room@chatroom', status: 'ok', memberIds: [member.wxid] }
|
||||
])
|
||||
const service = new GroupExitMonitorService()
|
||||
await service.start(true)
|
||||
await service.checkNow()
|
||||
await service.checkNow()
|
||||
|
||||
expect(mocks.sender.send).toHaveBeenCalledOnce()
|
||||
// 快照已更新 ⇒ 后续检查没有新的 diff,也就不会重复投递事件。
|
||||
expect(emitted).toHaveLength(1)
|
||||
expect(service.getState().events).toHaveLength(1)
|
||||
})
|
||||
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import {
|
||||
GROUP_EXIT_NOTIFICATION_TEMPLATE,
|
||||
findRemovedGroupMembers,
|
||||
groupExitMemberName,
|
||||
insertGroupNamePlaceholder,
|
||||
normalizeGroupExitNotificationTemplate,
|
||||
renderGroupExitMonitorNotification,
|
||||
validateGroupExitNotificationTemplate
|
||||
@@ -62,6 +64,8 @@ describe('group exit monitor member diff', () => {
|
||||
})
|
||||
|
||||
expect(message).toContain('[退群监测]')
|
||||
// 群名是**独立变量**,且默认模板第一行就是它 —— 通知发给别人时才认得出是哪个群。
|
||||
expect(message).toContain('群聊: 测试群')
|
||||
expect(message).toContain('用户: 微信名')
|
||||
expect(message).toContain('群备注: 未设置')
|
||||
expect(message).toContain('微信号: wxid_fixture')
|
||||
@@ -69,11 +73,69 @@ describe('group exit monitor member diff', () => {
|
||||
expect(message).toContain('退群时间: 2026-08-31 00:19:07')
|
||||
})
|
||||
|
||||
/*
|
||||
* 回归:`{groupName}`(群名)与 `{groupRemark}`(成员在本群的昵称)是两个不同的东西。
|
||||
*
|
||||
* 起因是预览样本曾把群名填进 `groupRemark`,导致「群备注」看起来就是群名,
|
||||
* 于是没人发现模板里**根本没有群名变量** —— 通知发给好友时收件人不知道是哪个群。
|
||||
* 这条用例把两者钉死成不同的值。
|
||||
*/
|
||||
it('keeps the group name and the member group nickname as two separate variables', () => {
|
||||
const message = renderGroupExitMonitorNotification(
|
||||
{
|
||||
id: 'event-3',
|
||||
contactId: 'group-md5',
|
||||
roomId: '测试群@chatroom',
|
||||
groupName: '产品测试群',
|
||||
memberWxid: 'wxid_fixture',
|
||||
memberName: '群昵称',
|
||||
wechatName: '微信名',
|
||||
groupRemark: '小张',
|
||||
previousCount: 3,
|
||||
currentCount: 2,
|
||||
delta: -1,
|
||||
message: '小张退出了产品测试群',
|
||||
detectedAt: new Date(2026, 7, 31, 0, 19, 7).getTime()
|
||||
},
|
||||
'{groupName} / {groupRemark}'
|
||||
)
|
||||
|
||||
expect(message).toBe('产品测试群 / 小张')
|
||||
expect(message).not.toContain('{')
|
||||
})
|
||||
|
||||
it('falls back to 未读取到 when the group name is unavailable', () => {
|
||||
const message = renderGroupExitMonitorNotification(
|
||||
{
|
||||
id: 'event-4',
|
||||
contactId: 'group-md5',
|
||||
roomId: '测试群@chatroom',
|
||||
groupName: '',
|
||||
memberWxid: 'wxid_fixture',
|
||||
memberName: '群昵称',
|
||||
groupRemark: '',
|
||||
previousCount: 2,
|
||||
currentCount: 1,
|
||||
delta: -1,
|
||||
message: '群昵称退出了测试群',
|
||||
detectedAt: new Date(2026, 7, 31, 0, 19, 7).getTime()
|
||||
},
|
||||
'群聊: {groupName}'
|
||||
)
|
||||
|
||||
expect(message).toBe('群聊: 未读取到')
|
||||
})
|
||||
|
||||
it('validates custom notification templates and rejects unknown placeholders', () => {
|
||||
expect(validateGroupExitNotificationTemplate(' 用户: {user} ')).toEqual({
|
||||
valid: true,
|
||||
template: '用户: {user}'
|
||||
})
|
||||
// 新增的群名变量必须被校验通过,否则用户存不下来。
|
||||
expect(validateGroupExitNotificationTemplate('群聊: {groupName}')).toEqual({
|
||||
valid: true,
|
||||
template: '群聊: {groupName}'
|
||||
})
|
||||
expect(validateGroupExitNotificationTemplate('用户: {unknown}')).toEqual({
|
||||
valid: false,
|
||||
error: '不支持的占位符: unknown'
|
||||
@@ -98,8 +160,77 @@ describe('group exit monitor member diff', () => {
|
||||
message: '群昵称退出了测试群',
|
||||
detectedAt: new Date(2026, 7, 31, 0, 19, 7).getTime()
|
||||
},
|
||||
'{user}|{groupRemark}|{wxid}|{previousCount}|{currentCount}|{time}'
|
||||
'{groupName}|{user}|{groupRemark}|{wxid}|{previousCount}|{currentCount}|{time}'
|
||||
)
|
||||
expect(message).toBe('微信名|群内昵称|wxid_fixture|2|1|2026-08-31 00:19:07')
|
||||
expect(message).toBe('测试群|微信名|群内昵称|wxid_fixture|2|1|2026-08-31 00:19:07')
|
||||
})
|
||||
})
|
||||
|
||||
describe('把群聊名补进已有模板', () => {
|
||||
/** 加上群名变量之前的默认模板(有「人数」行、没有「群聊」行)。 */
|
||||
const previousDefault = [
|
||||
'[退群监测]',
|
||||
'',
|
||||
'用户: {user}',
|
||||
'',
|
||||
'群备注: {groupRemark}',
|
||||
'',
|
||||
'微信号: {wxid}',
|
||||
'',
|
||||
'人数: {previousCount} -> {currentCount}',
|
||||
'',
|
||||
'退群时间: {time}'
|
||||
].join('\n')
|
||||
|
||||
it('插在标题行之后,其余内容一字不动', () => {
|
||||
const result = insertGroupNamePlaceholder(previousDefault)
|
||||
|
||||
expect(result).toBe(
|
||||
[
|
||||
'[退群监测]',
|
||||
'',
|
||||
'群聊: {groupName}',
|
||||
'',
|
||||
'用户: {user}',
|
||||
'',
|
||||
'群备注: {groupRemark}',
|
||||
'',
|
||||
'微信号: {wxid}',
|
||||
'',
|
||||
'人数: {previousCount} -> {currentCount}',
|
||||
'',
|
||||
'退群时间: {time}'
|
||||
].join('\n')
|
||||
)
|
||||
// 用户原有内容全部保留。
|
||||
for (const line of previousDefault.split('\n')) {
|
||||
if (line.trim()) expect(result).toContain(line)
|
||||
}
|
||||
})
|
||||
|
||||
it('补完就是当前的默认模板形状', () => {
|
||||
expect(insertGroupNamePlaceholder(previousDefault)).toBe(GROUP_EXIT_NOTIFICATION_TEMPLATE)
|
||||
})
|
||||
|
||||
it('已经含 {groupName} 时原样返回(幂等)', () => {
|
||||
const template = '[退群监测]\n\n群聊: {groupName}\n\n用户: {user}'
|
||||
expect(insertGroupNamePlaceholder(template)).toBe(template)
|
||||
// 连续补两次结果不变。
|
||||
expect(insertGroupNamePlaceholder(insertGroupNamePlaceholder(previousDefault))).toBe(
|
||||
insertGroupNamePlaceholder(previousDefault)
|
||||
)
|
||||
})
|
||||
|
||||
it('没有标题行时插到最前面', () => {
|
||||
expect(insertGroupNamePlaceholder('用户: {user}')).toBe('群聊: {groupName}\n\n用户: {user}')
|
||||
})
|
||||
|
||||
it('空模板原样返回,不硬造内容', () => {
|
||||
expect(insertGroupNamePlaceholder('')).toBe('')
|
||||
expect(insertGroupNamePlaceholder(' ')).toBe(' ')
|
||||
})
|
||||
|
||||
it('不会留下连续空行', () => {
|
||||
expect(insertGroupNamePlaceholder('[退群监测]\n\n\n\n用户: {user}')).not.toMatch(/\n{3,}/)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,222 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
|
||||
import {
|
||||
filterSendableFriendContacts,
|
||||
isSendableFriendContact,
|
||||
leaveNotificationContactDisplayName,
|
||||
resolveLeaveNotificationTarget,
|
||||
type LeaveNotificationCandidateContact
|
||||
} from '../../src/main/services/leave-notification-target'
|
||||
import type { GroupMemberExitedEvent } from '../../src/shared/group-exit-event'
|
||||
import { WECHAT_FILE_HELPER_USERNAME } from '../../src/shared/wechat-identities'
|
||||
import type { LeaveNotificationConfig } from '../../src/shared/automation'
|
||||
|
||||
/**
|
||||
* 退群通知的**目标解析**。
|
||||
*
|
||||
* 这是整轮迁移里最不能出错的一处:解析错就等于发错人,而发出去的消息撤不回来。
|
||||
* 所以这里把四种目标、失效、不可发送、自身身份缺失全部穷举。
|
||||
*/
|
||||
|
||||
const EVENT: GroupMemberExitedEvent = {
|
||||
eventId: 'room@chatroom:wxid_member:1700000000000:1',
|
||||
conversationId: 'room@chatroom',
|
||||
groupName: '产品测试群',
|
||||
groupRemark: '',
|
||||
memberId: 'wxid_member',
|
||||
memberName: '张三',
|
||||
previousCount: 243,
|
||||
currentCount: 242,
|
||||
occurredAt: 1_700_000_000_000
|
||||
}
|
||||
|
||||
const FRIEND: LeaveNotificationCandidateContact = {
|
||||
m_nsUsrName: 'wxid_friend',
|
||||
m_nsNickName: '好友昵称',
|
||||
remark: '好友备注',
|
||||
type: 'user'
|
||||
}
|
||||
|
||||
const contacts: LeaveNotificationCandidateContact[] = [
|
||||
FRIEND,
|
||||
{ m_nsUsrName: 'room@chatroom', m_nsNickName: '测试群', type: 'group' },
|
||||
{ m_nsUsrName: 'gh_official', m_nsNickName: '某公众号', type: 'user', isOfficialAccount: true },
|
||||
{ m_nsUsrName: WECHAT_FILE_HELPER_USERNAME, m_nsNickName: '文件传输助手', type: 'user' },
|
||||
{ m_nsUsrName: 'wxid_self', m_nsNickName: '我自己', type: 'user' }
|
||||
]
|
||||
|
||||
function resolve(
|
||||
config: LeaveNotificationConfig,
|
||||
overrides: { selfWxid?: string; event?: GroupMemberExitedEvent } = {}
|
||||
) {
|
||||
return resolveLeaveNotificationTarget({
|
||||
config,
|
||||
event: overrides.event ?? EVENT,
|
||||
contacts,
|
||||
selfWxid: overrides.selfWxid ?? 'wxid_self'
|
||||
})
|
||||
}
|
||||
|
||||
describe('leaveNotificationTarget · 四种目标', () => {
|
||||
it('当前群聊 = 事件所在群,不是"最后活跃会话"', () => {
|
||||
const result = resolve({ target: { type: 'source_chat' }, template: '' })
|
||||
|
||||
expect(result).toEqual({
|
||||
ok: true,
|
||||
target: {
|
||||
recipient: { type: 'group', id: 'room@chatroom', name: '产品测试群' },
|
||||
displayName: '产品测试群'
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
it('当前群聊在群名缺失时用中性称呼,不回落成 roomId', () => {
|
||||
const result = resolveLeaveNotificationTarget({
|
||||
config: { target: { type: 'source_chat' }, template: '' },
|
||||
event: { ...EVENT, groupName: undefined },
|
||||
contacts,
|
||||
selfWxid: 'wxid_self'
|
||||
})
|
||||
|
||||
expect(result.ok).toBe(true)
|
||||
if (result.ok) {
|
||||
expect(result.target.recipient.name).toBe('当前群聊')
|
||||
expect(result.target.displayName).toBe('发生退群事件的群聊')
|
||||
}
|
||||
})
|
||||
|
||||
it('当前群聊在缺少 conversationId 时直接失败', () => {
|
||||
const result = resolveLeaveNotificationTarget({
|
||||
config: { target: { type: 'source_chat' }, template: '' },
|
||||
event: { ...EVENT, conversationId: '' },
|
||||
contacts,
|
||||
selfWxid: 'wxid_self'
|
||||
})
|
||||
|
||||
expect(result.ok).toBe(false)
|
||||
})
|
||||
|
||||
it('发给自己 = 当前登录账号的真实 wxid', () => {
|
||||
const result = resolve({ target: { type: 'self' }, template: '' }, { selfWxid: 'wxid_me' })
|
||||
|
||||
expect(result).toEqual({
|
||||
ok: true,
|
||||
target: {
|
||||
recipient: { type: 'contact', id: 'wxid_me', name: '我' },
|
||||
displayName: '我'
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
/*
|
||||
* 拿不到自身身份时必须**报 blocker**,绝不偷偷 fallback 到文件传输助手 ——
|
||||
* 那会让用户以为"发给自己"生效了,实际消息去了别处。
|
||||
*/
|
||||
it('拿不到自身身份时失败,且不 fallback 文件传输助手', () => {
|
||||
const result = resolve({ target: { type: 'self' }, template: '' }, { selfWxid: '' })
|
||||
|
||||
expect(result.ok).toBe(false)
|
||||
if (!result.ok) {
|
||||
expect(result.error).toContain('当前登录的微信账号')
|
||||
expect(result.error).not.toContain('文件传输助手')
|
||||
}
|
||||
})
|
||||
|
||||
it('文件传输助手用协议级固定身份,不靠昵称搜索', () => {
|
||||
const result = resolve({ target: { type: 'file_transfer' }, template: '' })
|
||||
|
||||
expect(result.ok).toBe(true)
|
||||
if (result.ok) {
|
||||
expect(result.target.recipient).toEqual({
|
||||
type: 'contact',
|
||||
id: WECHAT_FILE_HELPER_USERNAME,
|
||||
name: '文件传输助手'
|
||||
})
|
||||
}
|
||||
})
|
||||
|
||||
it('指定好友用稳定 id,显示名用备注', () => {
|
||||
const result = resolve({
|
||||
target: { type: 'contact', contactId: 'wxid_friend' },
|
||||
template: ''
|
||||
})
|
||||
|
||||
expect(result).toEqual({
|
||||
ok: true,
|
||||
target: {
|
||||
recipient: { type: 'contact', id: 'wxid_friend', name: '好友备注' },
|
||||
displayName: '好友备注'
|
||||
}
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
describe('leaveNotificationTarget · 失效与非法', () => {
|
||||
it('联系人不在了 → 失败,且不往别处发', () => {
|
||||
const result = resolve({ target: { type: 'contact', contactId: 'wxid_gone' }, template: '' })
|
||||
|
||||
expect(result.ok).toBe(false)
|
||||
if (!result.ok) expect(result.error).toContain('已不存在或当前无法发送')
|
||||
})
|
||||
|
||||
it('还没选好友 → 失败并提示重新选择', () => {
|
||||
const result = resolve({ target: { type: 'contact' }, template: '' })
|
||||
|
||||
expect(result.ok).toBe(false)
|
||||
if (!result.ok) expect(result.error).toContain('还没有选择通知联系人')
|
||||
})
|
||||
|
||||
it('把群 / 公众号 / 文件传输助手 / 自己填进「指定好友」也会被拒', () => {
|
||||
for (const contactId of [
|
||||
'room@chatroom',
|
||||
'gh_official',
|
||||
WECHAT_FILE_HELPER_USERNAME,
|
||||
'wxid_self'
|
||||
]) {
|
||||
const result = resolve({ target: { type: 'contact', contactId }, template: '' })
|
||||
expect(result.ok).toBe(false)
|
||||
}
|
||||
})
|
||||
|
||||
it('未配置配置项 → 失败', () => {
|
||||
expect(resolveLeaveNotificationTarget({
|
||||
config: undefined,
|
||||
event: EVENT,
|
||||
contacts,
|
||||
selfWxid: 'wxid_self'
|
||||
}).ok).toBe(false)
|
||||
})
|
||||
|
||||
it('未知目标类型 → 失败(不允许静默当成默认值)', () => {
|
||||
const result = resolve({
|
||||
target: { type: 'webhook' as never },
|
||||
template: ''
|
||||
})
|
||||
expect(result.ok).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
describe('leaveNotificationTarget · 可选好友过滤', () => {
|
||||
it('排除群 / 公众号 / 文件传输助手 / 自己', () => {
|
||||
const sendable = filterSendableFriendContacts(contacts, 'wxid_self').map(
|
||||
(contact) => contact.m_nsUsrName
|
||||
)
|
||||
|
||||
expect(sendable).toEqual(['wxid_friend'])
|
||||
})
|
||||
|
||||
it('UI 选择器与运行时判定共用同一个函数', () => {
|
||||
for (const contact of contacts) {
|
||||
expect(isSendableFriendContact(contact, 'wxid_self')).toBe(
|
||||
filterSendableFriendContacts([contact], 'wxid_self').length === 1
|
||||
)
|
||||
}
|
||||
})
|
||||
|
||||
it('显示名依次回落到备注 → 微信昵称 → 会话昵称 → 中性称呼,永不出现 wxid', () => {
|
||||
expect(leaveNotificationContactDisplayName(FRIEND)).toBe('好友备注')
|
||||
expect(
|
||||
leaveNotificationContactDisplayName({ m_nsUsrName: 'wxid_x', type: 'user' })
|
||||
).toBe('指定好友')
|
||||
})
|
||||
})
|
||||
@@ -51,26 +51,34 @@ describe('WechatActionGateway', () => {
|
||||
return new WechatActionGateway({ getUserDataPath: () => userData })
|
||||
}
|
||||
|
||||
function memberAction(
|
||||
/**
|
||||
* 退群通知 —— 迁移后由 **Automation** 发出(purpose `automation_leave_notification`)。
|
||||
*
|
||||
* 幂等键由 eventId 派生,与 `AutomationService.leaveNotificationIdempotencyKey` 同口径;
|
||||
* 收件人**不再被锁死在事件所在群**(可以发给自己 / 文件传输助手 / 指定好友)。
|
||||
*/
|
||||
function leaveNotificationAction(
|
||||
gateway: WechatActionGateway,
|
||||
roomId = 'room@chatroom'
|
||||
recipient: WechatActionRequest['recipient'] = { type: 'group', id: 'room@chatroom' },
|
||||
eventId = 'event-1'
|
||||
): Promise<WechatActionResult> {
|
||||
gateway.registerMemberEvent({ id: 'event-1', roomId: 'room@chatroom' })
|
||||
return gateway.execute({
|
||||
origin: 'member_monitor',
|
||||
purpose: 'member_left_notification',
|
||||
idempotencyKey: `automation_leave_notification:${eventId}`,
|
||||
origin: 'automation',
|
||||
purpose: 'automation_leave_notification',
|
||||
triggerType: 'automation',
|
||||
sourceId: 'event-1',
|
||||
recipient: { type: 'group', id: roomId },
|
||||
executionId: `exec-${eventId}`,
|
||||
sourceId: eventId,
|
||||
recipient,
|
||||
content: { type: 'text', text: '张三已退出群聊' }
|
||||
})
|
||||
}
|
||||
|
||||
it('allows a valid member action, sends once, and writes an audit record', async () => {
|
||||
it('sends a leave notification once and writes an audit record', async () => {
|
||||
const userData = mkdtempSync(join(tmpdir(), 'tracememo-wechat-action-'))
|
||||
directories.push(userData)
|
||||
const gateway = new WechatActionGateway({ getUserDataPath: () => userData })
|
||||
const result = await memberAction(gateway)
|
||||
const result = await leaveNotificationAction(gateway)
|
||||
|
||||
expect(result).toMatchObject({ status: 'sent', decision: 'allow' })
|
||||
expect(mocks.sender.send).toHaveBeenCalledOnce()
|
||||
@@ -83,7 +91,7 @@ describe('WechatActionGateway', () => {
|
||||
const audit = readJsonSync(join(userData, 'actions', 'wechat-actions.json'))
|
||||
expect(audit).toEqual([
|
||||
expect.objectContaining({
|
||||
purpose: 'member_left_notification',
|
||||
purpose: 'automation_leave_notification',
|
||||
recipientId: 'room@chatroom',
|
||||
sendStatus: 'sent',
|
||||
decision: 'allow',
|
||||
@@ -92,23 +100,70 @@ describe('WechatActionGateway', () => {
|
||||
])
|
||||
})
|
||||
|
||||
it('deduplicates the same member event across repeated execution calls', async () => {
|
||||
it('deduplicates the same leave event across repeated execution calls', async () => {
|
||||
const gateway = createGateway()
|
||||
const first = await memberAction(gateway)
|
||||
const second = await memberAction(gateway)
|
||||
const first = await leaveNotificationAction(gateway)
|
||||
const second = await leaveNotificationAction(gateway)
|
||||
|
||||
expect(second.actionId).toBe(first.actionId)
|
||||
expect(mocks.sender.send).toHaveBeenCalledOnce()
|
||||
})
|
||||
|
||||
it('blocks a recipient outside the source group', async () => {
|
||||
/**
|
||||
* 迁移的核心:**不再有「只能发回原群」的作用域锁**。
|
||||
* 四种目标必须都能发出去,否则「自己 / 文件传输助手 / 指定好友」形同虚设。
|
||||
*/
|
||||
it('allows every leave-notification recipient, not just the source group', async () => {
|
||||
// 四条自动化发送串行且彼此间隔 3 秒 —— 用假定时器推过去,别真的等 9 秒。
|
||||
vi.useFakeTimers()
|
||||
vi.setSystemTime(new Date('2026-09-24T10:00:00.000Z'))
|
||||
const gateway = createGateway()
|
||||
const result = await memberAction(gateway, 'other@chatroom')
|
||||
const targets: Array<{ to: string; isGroup: boolean }> = []
|
||||
mocks.sender.send.mockImplementation(async (request: { to: string; isGroup: boolean }) => {
|
||||
targets.push({ to: request.to, isGroup: request.isGroup })
|
||||
return { success: true, status: {} }
|
||||
})
|
||||
|
||||
const pending = [
|
||||
leaveNotificationAction(gateway, { type: 'group', id: 'room@chatroom' }, 'event-1'),
|
||||
leaveNotificationAction(gateway, { type: 'contact', id: 'wxid_self' }, 'event-2'),
|
||||
leaveNotificationAction(gateway, { type: 'contact', id: 'filehelper' }, 'event-3'),
|
||||
leaveNotificationAction(gateway, { type: 'contact', id: 'wxid_friend' }, 'event-4')
|
||||
]
|
||||
await vi.advanceTimersByTimeAsync(AUTOMATION_SEND_INTERVAL_MS * 4)
|
||||
const results = await Promise.all(pending)
|
||||
|
||||
for (const result of results) {
|
||||
expect(result).toMatchObject({ status: 'sent', decision: 'allow' })
|
||||
}
|
||||
expect(targets).toEqual([
|
||||
{ to: 'room@chatroom', isGroup: true },
|
||||
{ to: 'wxid_self', isGroup: false },
|
||||
{ to: 'filehelper', isGroup: false },
|
||||
{ to: 'wxid_friend', isGroup: false }
|
||||
])
|
||||
vi.useRealTimers()
|
||||
})
|
||||
|
||||
/**
|
||||
* 回归闸门:旧的发送用途**已经在代码上不可能再发出去**。
|
||||
* 退群监控不再产生它,allowlist 也把它摘了 —— 谁要是把它加回来,这里会红。
|
||||
*/
|
||||
it('blocks the legacy member_left_notification purpose', async () => {
|
||||
const gateway = createGateway()
|
||||
const result = await gateway.execute({
|
||||
origin: 'member_monitor',
|
||||
purpose: 'member_left_notification',
|
||||
triggerType: 'automation',
|
||||
sourceId: 'event-1',
|
||||
recipient: { type: 'group', id: 'room@chatroom' },
|
||||
content: { type: 'text', text: '张三已退出群聊' }
|
||||
})
|
||||
|
||||
expect(result).toMatchObject({
|
||||
status: 'blocked',
|
||||
decision: 'block',
|
||||
errorCode: 'RECIPIENT_SCOPE_VIOLATION'
|
||||
errorCode: 'ACTION_NOT_ALLOWED'
|
||||
})
|
||||
expect(mocks.sender.send).not.toHaveBeenCalled()
|
||||
})
|
||||
@@ -135,8 +190,8 @@ describe('WechatActionGateway', () => {
|
||||
it('returns INVALID_REQUEST for malformed input without throwing from audit handling', async () => {
|
||||
const gateway = createGateway()
|
||||
const result = await gateway.execute({
|
||||
origin: 'member_monitor',
|
||||
purpose: 'member_left_notification',
|
||||
origin: 'automation',
|
||||
purpose: 'automation_leave_notification',
|
||||
triggerType: 'automation',
|
||||
recipient: { type: 'group', id: 'room@chatroom' }
|
||||
} as never)
|
||||
@@ -151,8 +206,8 @@ describe('WechatActionGateway', () => {
|
||||
it('returns INVALID_RECIPIENT when the recipient id is missing', async () => {
|
||||
const gateway = createGateway()
|
||||
const result = await gateway.execute({
|
||||
origin: 'member_monitor',
|
||||
purpose: 'member_left_notification',
|
||||
origin: 'automation',
|
||||
purpose: 'automation_leave_notification',
|
||||
triggerType: 'automation',
|
||||
sourceId: 'event-1',
|
||||
recipient: { type: 'group', id: '' },
|
||||
@@ -167,30 +222,6 @@ describe('WechatActionGateway', () => {
|
||||
expect(mocks.sender.send).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('does not accept an event lookup for a different source id', async () => {
|
||||
const userData = mkdtempSync(join(tmpdir(), 'tracememo-wechat-action-'))
|
||||
directories.push(userData)
|
||||
const gateway = new WechatActionGateway({
|
||||
getUserDataPath: () => userData,
|
||||
getMemberEvent: () => ({ id: 'different-event', roomId: 'room@chatroom' })
|
||||
})
|
||||
const result = await gateway.execute({
|
||||
origin: 'member_monitor',
|
||||
purpose: 'member_left_notification',
|
||||
triggerType: 'automation',
|
||||
sourceId: 'event-1',
|
||||
recipient: { type: 'group', id: 'room@chatroom' },
|
||||
content: { type: 'text', text: '张三已退出群聊' }
|
||||
})
|
||||
|
||||
expect(result).toMatchObject({
|
||||
status: 'blocked',
|
||||
decision: 'block',
|
||||
errorCode: 'INVALID_REQUEST'
|
||||
})
|
||||
expect(mocks.sender.send).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('returns a structured capability failure without sending', async () => {
|
||||
const gateway = createGateway()
|
||||
mocks.capability.getPersonalWechatSendCapability.mockResolvedValueOnce({
|
||||
@@ -199,7 +230,7 @@ describe('WechatActionGateway', () => {
|
||||
capabilities: { text: false, image: false, voice: false },
|
||||
message: '当前微信发送能力不可用'
|
||||
})
|
||||
const result = await memberAction(gateway)
|
||||
const result = await leaveNotificationAction(gateway)
|
||||
|
||||
expect(result).toMatchObject({
|
||||
status: 'failed',
|
||||
@@ -226,7 +257,7 @@ describe('WechatActionGateway', () => {
|
||||
it('converts a transport throw into SEND_FAILED', async () => {
|
||||
const gateway = createGateway()
|
||||
mocks.sender.send.mockRejectedValueOnce(new Error('connector timeout'))
|
||||
const result = await memberAction(gateway)
|
||||
const result = await leaveNotificationAction(gateway)
|
||||
|
||||
expect(result).toMatchObject({
|
||||
status: 'failed',
|
||||
@@ -287,17 +318,10 @@ describe('WechatActionGateway', () => {
|
||||
if (sentAt.length === 1) throw new Error('first failed')
|
||||
return { success: true, status: {} }
|
||||
})
|
||||
const first = memberAction(gateway)
|
||||
const first = leaveNotificationAction(gateway)
|
||||
await vi.advanceTimersByTimeAsync(0)
|
||||
gateway.registerMemberEvent({ id: 'event-2', roomId: 'room@chatroom' })
|
||||
const second = gateway.execute({
|
||||
origin: 'member_monitor',
|
||||
purpose: 'member_left_notification',
|
||||
triggerType: 'automation',
|
||||
sourceId: 'event-2',
|
||||
recipient: { type: 'group', id: 'room@chatroom' },
|
||||
content: { type: 'text', text: '李四已退出群聊' }
|
||||
})
|
||||
// 第二条用不同的 eventId → 不同的幂等键,才会真的进队列。
|
||||
const second = leaveNotificationAction(gateway, { type: 'group', id: 'room@chatroom' }, 'event-2')
|
||||
|
||||
await vi.advanceTimersByTimeAsync(AUTOMATION_SEND_INTERVAL_MS)
|
||||
const results = await Promise.all([first, second])
|
||||
@@ -407,7 +431,7 @@ describe('WechatActionGateway', () => {
|
||||
.mockResolvedValueOnce({ ...readyCapability, ready: false })
|
||||
.mockResolvedValueOnce(readyCapability)
|
||||
|
||||
await expect(memberAction(gateway)).resolves.toMatchObject({
|
||||
await expect(leaveNotificationAction(gateway)).resolves.toMatchObject({
|
||||
status: 'failed',
|
||||
errorCode: 'SEND_CAPABILITY_UNAVAILABLE'
|
||||
})
|
||||
|
||||
Reference in new issue
Block a user