feat: 新增拓展中心功能, 提供 关键词回复 去水印模板

This commit is contained in:
Wxw-Gu committed 2026-11-13 17:54:37 +08:00
1 parent aca103cb96
commit b9ad4e1d71
85 files changed
+14750 -106

No files matched your search

@@ -0,0 +1,272 @@
import fs from 'fs-extra'
import path from 'node:path'
import { describe, expect, it, vi } from 'vitest'
const root = vi.hoisted(() => {
// eslint-disable-next-line @typescript-eslint/no-require-imports
const fs = require('node:fs') as typeof import('node:fs')
// eslint-disable-next-line @typescript-eslint/no-require-imports
const os = require('node:os') as typeof import('node:os')
// eslint-disable-next-line @typescript-eslint/no-require-imports
const path = require('node:path') as typeof import('node:path')
return fs.mkdtempSync(path.join(os.tmpdir(), 'tm-extension-automation-'))
})
vi.mock('electron', () => ({
app: { getPath: () => root },
safeStorage: {
isEncryptionAvailable: () => false,
encryptString: (value: string) => Buffer.from(value, 'utf8'),
decryptString: (value: Buffer) => value.toString('utf8')
},
BrowserWindow: { getAllWindows: () => [] }
}))
import {
createDefaultDailyReportRule,
describeRuleActions,
normalizeRuleDraft,
type AutomationRule
} from '../../src/shared/automation'
import type { WechatActionRequest, WechatActionResult } from '../../src/shared/wechat-action'
import { AutomationActionRunner } from '../../src/main/services/automation-action-runner'
import { AutomationRuleStore } from '../../src/main/services/automation-rule-store'
const sent: WechatActionResult = {
actionId: 'action-1',
status: 'sent',
decision: 'allow',
startedAt: '2026-01-01T00:00:00.000Z',
finishedAt: '2026-01-01T00:00:01.000Z'
}
function extensionRule(): AutomationRule {
return {
...createDefaultDailyReportRule(0),
id: 'rule-with-extension',
name: '关键词回复',
conditions: {
requireMentionMe: false,
keyword: '你好',
keywordMatchMode: 'contains',
conversationIds: [],
ignoreSelf: true
},
actions: [
{
type: 'extensionAction',
enabled: true,
extensionId: 'com.example.keyword-bot',
actionId: 'keyword.reply'
}
]
}
}
function runner(dependencies: {
reply?: { type: 'text'; text: string }
canSend?: boolean
fail?: boolean
}): {
instance: AutomationActionRunner
executeAction: ReturnType<
typeof vi.fn<(request: WechatActionRequest) => Promise<WechatActionResult>>
>
} {
const executeAction = vi.fn(async (request: WechatActionRequest) => {
void request
return sent
})
const instance = new AutomationActionRunner({
executeAction,
invokeExtensionAction: async () => {
if (dependencies.fail) throw new Error('扩展崩溃')
return {
success: true,
output: { matched: true },
...(dependencies.reply ? { reply: dependencies.reply } : {})
}
},
canExtensionSendText: () => dependencies.canSend !== false,
delay: async () => undefined,
now: () => 1_000
})
return { instance, executeAction }
}
const message = {
eventId: 'message:1',
accountId: 'wxid_self',
conversationId: 'fixture-room@chatroom',
messageId: '9001',
senderId: 'wxid_peer',
senderName: '张三',
isGroup: true,
isSelf: false,
type: 'text' as const,
text: '你好',
mentionsMe: false,
timestamp: 1_700_000_000_000
}
describe('extension automation action', () => {
it('扩展返回 reply 后由宿主经 Gateway 发送', async () => {
const { instance, executeAction } = runner({ reply: { type: 'text', text: '你好呀!' } })
const result = await instance.run({
executionId: 'exec-1',
rule: extensionRule(),
conversationId: 'fixture-room@chatroom',
isGroup: true,
sourceDisplayName: '测试群',
message
})
expect(result.status).toBe('success')
expect(result.steps.map((step) => step.key)).toEqual([
'received',
'matched',
'extension_action',
'reply',
'report',
'send'
])
expect(executeAction).toHaveBeenCalledTimes(1)
const request = executeAction.mock.calls[0][0]
expect(request.origin).toBe('extension')
expect(request.purpose).toBe('extension_action')
expect(request.triggerType).toBe('automation')
expect(request.idempotencyKey).toBe('extension_action:exec-1')
expect(request.recipient).toMatchObject({ type: 'group', id: 'fixture-room@chatroom' })
expect(request.content).toEqual({ type: 'text', text: '你好呀!' })
expect((request.metadata as { extensionId: string }).extensionId).toBe(
'com.example.keyword-bot'
)
})
it('扩展没有发送权限时拒绝发送,且不调用 Gateway', async () => {
const { instance, executeAction } = runner({
reply: { type: 'text', text: '你好呀!' },
canSend: false
})
const result = await instance.run({
executionId: 'exec-2',
rule: extensionRule(),
conversationId: 'fixture-room@chatroom',
isGroup: true,
sourceDisplayName: '测试群',
message
})
expect(result.status).toBe('failed')
expect(result.errorSummary).toContain('wechat.send.text')
expect(executeAction).not.toHaveBeenCalled()
const reply = result.steps.find((step) => step.key === 'reply')
expect(reply?.status).toBe('failed')
})
it('扩展动作失败时后续步骤全部跳过', async () => {
const { instance, executeAction } = runner({ fail: true })
const result = await instance.run({
executionId: 'exec-3',
rule: extensionRule(),
conversationId: 'fixture-room@chatroom',
isGroup: true,
sourceDisplayName: '测试群',
message
})
expect(result.status).toBe('failed')
expect(result.steps.find((step) => step.key === 'extension_action')?.status).toBe('failed')
expect(result.steps.filter((step) => step.status === 'skipped')).toHaveLength(3)
expect(executeAction).not.toHaveBeenCalled()
})
it('未配置扩展动作时步骤列表保持原样', async () => {
const { instance } = runner({})
const rule: AutomationRule = {
...createDefaultDailyReportRule(0),
actions: [{ type: 'replyText', enabled: true, text: '收到' }]
}
const result = await instance.run({
executionId: 'exec-4',
rule,
conversationId: 'fixture-room@chatroom',
isGroup: true,
sourceDisplayName: '测试群',
message
})
expect(result.steps.map((step) => step.key)).toEqual([
'received',
'matched',
'reply',
'report',
'send'
])
})
})
describe('extension action persistence', () => {
it('规则保存后仍保留扩展动作,缺少扩展/动作 id 的草稿会被丢弃', () => {
const store = new AutomationRuleStore({ userDataPath: () => path.join(root, 'rules') })
const created = store.createRule({
name: '扩展规则',
enabled: true,
ruleType: 'daily_report',
scope: 'group',
conditions: { keyword: '你好', keywordMatchMode: 'contains' },
cooldownSeconds: 30,
replyDelaySeconds: 0,
actions: [
{
type: 'extensionAction',
enabled: true,
extensionId: 'com.example.keyword-bot',
actionId: 'keyword.reply'
},
{ type: 'extensionAction', enabled: true }
]
})
expect(created.actions).toHaveLength(1)
expect(created.actions[0]).toMatchObject({
type: 'extensionAction',
extensionId: 'com.example.keyword-bot',
actionId: 'keyword.reply'
})
const reloaded = new AutomationRuleStore({
userDataPath: () => path.join(root, 'rules')
}).getRule(created.id)
expect(reloaded?.actions[0].extensionId).toBe('com.example.keyword-bot')
expect(describeRuleActions(reloaded!)).toBe('执行扩展动作')
})
it('input 只接受 JSON 对象,超限丢弃', () => {
const normalized = normalizeRuleDraft({
actions: [
{
type: 'extensionAction',
enabled: true,
extensionId: 'com.example.keyword-bot',
actionId: 'keyword.reply',
input: { url: 'https://example.com', nested: { ok: true } }
}
]
})
expect(normalized.actions[0].input).toEqual({
url: 'https://example.com',
nested: { ok: true }
})
const tooBig = normalizeRuleDraft({
actions: [
{
type: 'extensionAction',
enabled: true,
extensionId: 'com.example.keyword-bot',
actionId: 'keyword.reply',
input: { blob: 'x'.repeat(5_000) }
}
]
})
expect(tooBig.actions[0].input).toBeUndefined()
})
})
process.on('exit', () => {
fs.removeSync(root)
})
@@ -0,0 +1,328 @@
import fs from 'fs-extra'
import os from 'node:os'
import path from 'node:path'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { ExtensionManager } from '../../src/main/extensions/extension-manager'
import { createExtensionPaths } from '../../src/main/extensions/extension-paths'
import { EXTENSION_HOST_PROTOCOL_VERSION } from '../../src/shared/extensions/rpc'
import type {
ExtensionHostChild,
ExtensionHostSpawnOptions
} from '../../src/main/extensions/extension-host'
import type { PersonalWechatSendCapability } from '../../src/shared/personal-wechat'
import type { WechatActionResult } from '../../src/shared/wechat-action'
const MANIFEST = {
manifestVersion: 1,
id: 'com.example.fixture-bot',
name: 'Fixture Bot',
version: '1.0.0',
apiVersion: '1',
minAppVersion: '2.6.0',
permissions: ['messages.subscribe', 'wechat.send.text', 'storage', 'automation.action', 'contacts.list'],
entrypoints: { page: 'ui/index.html', background: 'background/index.js' },
subscriptions: {
messageTypes: ['text'],
conversationIds: [],
requireMentionMe: false,
includeSelf: false
},
contributions: {
pages: [{ id: 'settings', title: '配置' }],
automationActions: [{ id: 'keyword.reply', title: '关键词回复' }]
}
}
const capability = {
supported: true,
ready: true,
status: 'ready',
capabilities: { text: true, image: true, voice: false },
senderStatus: {},
message: '已就绪'
} as unknown as PersonalWechatSendCapability
const sentResult: WechatActionResult = {
actionId: 'action-1',
status: 'sent',
decision: 'allow',
startedAt: '2026-01-01T00:00:00.000Z',
finishedAt: '2026-01-01T00:00:01.000Z'
}
type Listener = (...args: unknown[]) => void
class FakeChild implements ExtensionHostChild {
readonly sent: Array<Record<string, unknown>> = []
private readonly listeners = new Map<string, Listener[]>()
send(message: unknown): void {
const payload = message as Record<string, unknown>
this.sent.push(payload)
if (payload.type === 'activate') {
queueMicrotask(() => {
this.emit('message', {
type: 'activated',
version: EXTENSION_HOST_PROTOCOL_VERSION,
ok: true
})
this.emit('message', {
type: 'register-action',
version: EXTENSION_HOST_PROTOCOL_VERSION,
action: { id: 'keyword.reply', title: '关键词回复', hasInputSchema: true }
})
})
}
if (payload.type === 'invoke-action') {
queueMicrotask(() =>
this.emit('message', {
type: 'action-result',
version: EXTENSION_HOST_PROTOCOL_VERSION,
requestId: payload.requestId,
ok: true,
output: { success: true, reply: { type: 'text', text: '你好呀!' } }
})
)
}
if (payload.type === 'shutdown') {
queueMicrotask(() => this.emit('exit', 0, null))
}
}
kill(): void {
this.emit('exit', 1, null)
}
on(event: 'message', listener: (message: unknown) => void): void
on(event: 'exit', listener: (code: number | null, signal: string | null) => void): void
on(event: 'error', listener: (error: Error) => void): void
on(event: string, listener: (...args: never[]) => void): void {
const list = this.listeners.get(event) ?? []
list.push(listener as unknown as Listener)
this.listeners.set(event, list)
}
once(event: string, listener: Listener): void {
this.on(event as 'message', listener as (message: unknown) => void)
}
emit(event: string, ...args: unknown[]): void {
for (const listener of this.listeners.get(event) ?? []) listener(...args)
}
events(): Array<Record<string, unknown>> {
return this.sent.filter((message) => message.type === 'event')
}
}
const roots: string[] = []
let userData: string
function createSourceExtension(): string {
const parent = fs.mkdtempSync(path.join(os.tmpdir(), 'tm-extension-src-'))
roots.push(parent)
const source = path.join(parent, 'extension')
fs.ensureDirSync(path.join(source, 'ui'))
fs.ensureDirSync(path.join(source, 'background'))
fs.writeJsonSync(path.join(source, 'manifest.json'), MANIFEST)
fs.writeFileSync(path.join(source, 'ui', 'index.html'), '<!doctype html><title>fixture</title>')
fs.writeFileSync(path.join(source, 'background', 'index.js'), 'module.exports = () => {}')
return source
}
function createManager(): {
manager: ExtensionManager
paths: ReturnType<typeof createExtensionPaths>
children: FakeChild[]
executeAction: ReturnType<typeof vi.fn>
} {
const paths = createExtensionPaths(userData)
const children: FakeChild[] = []
const executeAction = vi.fn(async () => sentResult)
const manager = new ExtensionManager({
paths,
appVersion: '2.6.0',
spawn: (options: ExtensionHostSpawnOptions) => {
void options
const child = new FakeChild()
children.push(child)
return child
},
getCapability: async () => capability,
checkEntitlement: async () => ({ ok: true, message: '授权有效', source: 'mac_license' }),
executeAction,
queryMessages: async () => [],
listGroups: async () => [{ id: 'fixture-room@chatroom', name: '测试群' }],
aiChat: async () => ({ text: '' }),
getAccountId: () => 'wxid_self',
getSelfUsernames: () => ['wxid_self'],
isDatabaseReady: () => true,
now: () => 1_000
})
return { manager, paths, children, executeAction }
}
async function tick(): Promise<void> {
await new Promise((resolve) => setTimeout(resolve, 0))
}
beforeEach(() => {
userData = fs.mkdtempSync(path.join(os.tmpdir(), 'tm-extension-manager-'))
roots.push(userData)
})
afterEach(() => {
for (const root of roots.splice(0)) fs.removeSync(root)
})
describe('extension lifecycle', () => {
it('安装 → 页面读写配置 → 启用 → 事件 → 动作 → 发送 → 停用 → 卸载', async () => {
const { manager, paths, children, executeAction } = createManager()
await manager.initialize()
const source = createSourceExtension()
const installed = await manager.installFromDirectory(source)
expect(installed.success).toBe(true)
expect(installed.extension?.enabled).toBe(false)
// 安装只自动授予低风险权限。
expect(installed.extension?.grantedPermissions).toEqual(['storage'])
const page = manager.pageUrl('com.example.fixture-bot')
expect(page.url).toBe('tm-extension://com.example.fixture-bot/ui/index.html')
const saved = await manager.pageRequest('com.example.fixture-bot', 'storage.set', {
key: 'greeting',
value: '你好'
})
expect(saved.ok).toBe(true)
expect(
(await manager.pageRequest('com.example.fixture-bot', 'storage.get', { key: 'greeting' }))
.result
).toBe('你好')
// 页面不能发送微信消息。
expect((await manager.pageRequest('com.example.fixture-bot', 'wechat.send.text', {})).ok).toBe(
false
)
// 页面可以读取群列表(manifest 已声明 contacts.list)。
const groups = await manager.pageRequest('com.example.fixture-bot', 'contacts.listGroups', {})
expect(groups.ok).toBe(true)
expect(groups.result).toEqual({
groups: [{ id: 'fixture-room@chatroom', name: '测试群' }]
})
const enabled = await manager.setEnabled('com.example.fixture-bot', true)
expect(enabled.success).toBe(true)
await tick()
const child = children[0]
expect(manager.get('com.example.fixture-bot')?.runtime.state).toBe('active')
expect(manager.get('com.example.fixture-bot')?.automationActions[0]).toMatchObject({
id: 'keyword.reply',
registered: true
})
manager.handleMessage({
sessionId: 'fixture-room@chatroom',
localId: '1001',
serverId: '9001',
createTime: 1_700_000_000,
messageType: 1,
isSelf: false,
senderId: 'wxid_peer',
senderNickname: '张三',
content: '@我 你好',
isGroup: true,
mentionTargets: ['wxid_self']
})
const event = child.events()[0]
expect(event).toBeTruthy()
const envelope = event.envelope as { event: { mentionsMe: boolean; text: string } }
expect(envelope.event.mentionsMe).toBe(true)
expect(envelope.event.text).toBe('@我 你好')
// 同一条消息重复投递不会再分发。
manager.handleMessage({
sessionId: 'fixture-room@chatroom',
localId: '1001',
createTime: 1_700_000_000,
messageType: 1,
isSelf: false,
content: '@我 你好',
isGroup: true,
mentionTargets: ['wxid_self']
})
expect(child.events()).toHaveLength(1)
const output = await manager.invokeAutomationAction(
'com.example.fixture-bot',
'keyword.reply',
{ text: '你好' }
)
expect(output.reply).toEqual({ type: 'text', text: '你好呀!' })
// 后台主动发送:宿主填 origin/purpose,扩展只描述收件人与内容。
child.emit('message', {
type: 'call',
version: EXTENSION_HOST_PROTOCOL_VERSION,
callId: 'call-1',
method: 'wechat.send.text',
params: { to: 'fixture-room@chatroom', text: '你好呀!' }
})
await tick()
const callResult = child.sent.find(
(message) => message.type === 'call-result' && message.callId === 'call-1'
)
expect(callResult?.ok).toBe(true)
expect(executeAction).toHaveBeenCalledTimes(1)
expect(executeAction.mock.calls[0][0]).toMatchObject({
origin: 'extension',
purpose: 'extension_send',
triggerType: 'automation',
recipient: { type: 'group', id: 'fixture-room@chatroom' },
content: { type: 'text', text: '你好呀!' }
})
const disabled = await manager.setEnabled('com.example.fixture-bot', false)
expect(disabled.success).toBe(true)
expect(manager.get('com.example.fixture-bot')?.grantedPermissions).toEqual(['storage'])
manager.handleMessage({
sessionId: 'fixture-room@chatroom',
localId: '1002',
createTime: 1_700_000_100,
messageType: 1,
isSelf: false,
content: '还在吗',
isGroup: true,
mentionTargets: []
})
expect(child.events()).toHaveLength(1)
const removed = await manager.uninstall('com.example.fixture-bot', true)
expect(removed.success).toBe(true)
expect(fs.existsSync(paths.installDir('com.example.fixture-bot'))).toBe(false)
expect(fs.existsSync(paths.extensionDataDir('com.example.fixture-bot'))).toBe(true)
expect(manager.list()).toEqual([])
})
it('不兼容的扩展安装被拒绝', async () => {
const { manager } = createManager()
await manager.initialize()
const source = createSourceExtension()
fs.writeJsonSync(path.join(source, 'manifest.json'), { ...MANIFEST, minAppVersion: '9.9.0' })
const result = await manager.installFromDirectory(source)
expect(result.success).toBe(false)
expect(result.error?.code).toBe('EXTENSION_INCOMPATIBLE')
})
it('停用状态下页面仍可打开与保存配置', async () => {
const { manager } = createManager()
await manager.initialize()
const source = createSourceExtension()
await manager.installFromDirectory(source)
const page = manager.pageUrl('com.example.fixture-bot', 'settings')
expect(page.pageId).toBe('settings')
const result = await manager.pageRequest('com.example.fixture-bot', 'storage.set', {
key: 'draft',
value: 1
})
expect(result.ok).toBe(true)
})
})