feat: 扩展中心支持多模态消息、HTML 渲染、一级导航与应用内通知

This commit is contained in:
Wxw-Gu committed 2026-12-01 14:49:41 +08:00
1 parent b20e514c90
commit 4ea73c3414
63 files changed
+8360 -644

No files matched your search

@@ -0,0 +1,524 @@
import fs from 'fs-extra'
import os from 'node:os'
import path from 'node:path'
import { createRequire } from 'node:module'
import { afterEach, describe, expect, it, vi } from 'vitest'
import { createExtensionPaths } from '../../src/main/extensions/extension-paths'
import { ExtensionManager } from '../../src/main/extensions/extension-manager'
import {
ExtensionMediaGateway,
paginateQueriedMessages,
type ResolvedExtensionMediaMessage
} from '../../src/main/extensions/extension-media-gateway'
import { HtmlRenderService, type RenderWindowAdapter } from '../../src/main/services/html-render-service'
import { encodeExtensionMessageRef } from '../../src/shared/extensions/media'
import type { ExtensionQueriedMessage } from '../../src/shared/extensions/rpc'
import type { ExtensionHostChild } from '../../src/main/extensions/extension-host'
import { EXTENSION_HOST_PROTOCOL_VERSION } from '../../src/shared/extensions/rpc'
import type { PersonalWechatSendCapability } from '../../src/shared/personal-wechat'
import type { WechatActionRequest, WechatActionResult } from '../../src/shared/wechat-action'
const require = createRequire(import.meta.url)
const tempDirs: string[] = []
function makeTempDir(): string {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'tm-ext-phase2-'))
tempDirs.push(dir)
return dir
}
afterEach(() => {
for (const dir of tempDirs.splice(0)) fs.removeSync(dir)
})
function createMockRenderWindow(): RenderWindowAdapter {
let destroyed = false
let ready: (() => void) | null = null
let resized: (() => void) | null = null
let size: [number, number] = [460, 800]
return {
loadFile: async () => {
ready?.()
},
onceReadyToShow: (cb) => {
ready = cb
},
onceResize: (cb) => {
resized = cb
},
getContentSize: () => size,
setContentSize: (w, h) => {
size = [w, h]
resized?.()
},
executeJavaScript: async (code) => {
if (code.includes('scrollWidth')) return { width: 460, height: 1120 }
return undefined
},
capturePage: async () => Buffer.alloc(2048, 0x89),
installRequestFilter: () => undefined,
clearRequestFilter: () => undefined,
isDestroyed: () => destroyed,
destroy: () => {
destroyed = true
}
}
}
function createSilentChild(): ExtensionHostChild {
const listeners = new Map<string, Array<(...args: unknown[]) => void>>()
const emit = (event: string, ...args: unknown[]): void => {
for (const fn of listeners.get(event) ?? []) fn(...args)
}
const child: ExtensionHostChild = {
send(message: unknown) {
const payload = message as Record<string, unknown>
if (payload.type === 'activate') {
queueMicrotask(() =>
emit('message', {
type: 'activated',
version: EXTENSION_HOST_PROTOCOL_VERSION,
ok: true
})
)
} else if (payload.type === 'shutdown') {
queueMicrotask(() => emit('exit', 0, null))
}
},
kill() {
emit('exit', 0, null)
},
on(event: string, listener: (...args: never[]) => void) {
const list = listeners.get(event) ?? []
list.push(listener as (...args: unknown[]) => void)
listeners.set(event, list)
},
once(event: string, listener: () => void) {
child.on(event as 'exit', listener as never)
}
}
queueMicrotask(() => emit('message', { type: 'ready', version: EXTENSION_HOST_PROTOCOL_VERSION }))
return child
}
describe('第二阶段端到端集成(AI 晨报、群聊机器人媒体解析、v1 兼容)', () => {
it('AI 晨报完整串联分页查询、媒体批处理、AI 总结、HTML 长图渲染、通知与默认禁发微信', async () => {
const root = makeTempDir()
const userData = path.join(root, 'userData')
const paths = createExtensionPaths(userData)
const accountId = 'wxid_fixture_self'
const groupId = 'fixture-group@chatroom'
const now = Date.now()
const imgRef = encodeExtensionMessageRef({
accountId,
conversationId: groupId,
messageId: 'm-img',
localId: '2',
timestamp: now - 30_000
})
const voiceRef = encodeExtensionMessageRef({
accountId,
conversationId: groupId,
messageId: 'm-voice',
localId: '3',
timestamp: now - 20_000
})
const allMessages: ExtensionQueriedMessage[] = [
{
messageId: 'm-text-1',
messageRef: encodeExtensionMessageRef({
accountId,
conversationId: groupId,
messageId: 'm-text-1',
timestamp: now - 40_000
}),
conversationId: groupId,
senderName: '张三',
isSelf: false,
type: 'text',
text: '明早十点同步发布节奏',
timestamp: now - 40_000
},
{
messageId: 'm-img',
messageRef: imgRef,
conversationId: groupId,
senderName: '李四',
isSelf: false,
type: 'image',
timestamp: now - 30_000
},
{
messageId: 'm-voice',
messageRef: voiceRef,
conversationId: groupId,
senderName: '王五',
isSelf: false,
type: 'voice',
timestamp: now - 20_000
}
]
const resolvedMedia: Record<string, ResolvedExtensionMediaMessage> = {
'm-img': {
messageId: 'm-img',
localId: 2,
serverId: 'm-img',
conversationId: groupId,
senderName: '李四',
type: 'image',
createTimeSeconds: Math.floor((now - 30_000) / 1000),
image: { md5: 'c'.repeat(32) }
},
'm-voice': {
messageId: 'm-voice',
localId: 3,
serverId: 'm-voice',
conversationId: groupId,
senderName: '王五',
type: 'voice',
createTimeSeconds: Math.floor((now - 20_000) / 1000),
voice: { durationSeconds: 5 }
}
}
const renderService = new HtmlRenderService({
tempDir: path.join(root, 'render-tmp'),
createWindow: () => createMockRenderWindow()
})
const executeAction = vi.fn(
async (_request: WechatActionRequest): Promise<WechatActionResult> => ({
actionId: 'act-1',
status: 'sent',
decision: 'allow',
startedAt: '2026-01-01T00:00:00.000Z',
finishedAt: '2026-01-01T00:00:01.000Z'
})
)
const manager = new ExtensionManager({
paths,
appVersion: '2.7.0',
spawn: () => createSilentChild(),
getCapability: async () =>
({
supported: true,
ready: true,
status: 'ready',
capabilities: { text: true, image: true, voice: true },
senderStatus: {},
message: ''
}) as unknown as PersonalWechatSendCapability,
checkEntitlement: async () => ({ ok: true, message: '授权有效', source: 'mac_license' }),
executeAction,
queryMessages: async (req) => paginateQueriedMessages(allMessages, req),
createMediaGateway: ({ hasPermission, getExtensionDataRoot }) =>
new ExtensionMediaGateway({
isDatabaseReady: () => true,
getAccountId: () => accountId,
getExtensionDataRoot,
hasPermission,
resolveMessage: async (ref) => resolvedMedia[ref.messageId] ?? null,
readImageData: async () => ({
buffer: Buffer.from('fixture-png'),
mimeType: 'image/png',
imageHash: 'hash-1',
quality: 'original'
}),
readVoiceData: async () => ({ wavBuffer: Buffer.from('RIFF'), durationMs: 5000 }),
readVideoAsset: async () => null,
recognizeOcr: async () => ({
success: true,
text: '版本发布检查清单',
language: 'zh-Hans',
engine: 'apple-vision'
}),
transcribeVoice: async () => ({
state: 'transcribed',
transcript: '测试环境已经准备好了',
cached: false,
durationMs: 5000
}),
analyzeImage: async () => ({ description: '检查清单截图', cached: false })
}),
renderHtmlToImage: (_extId, dataRoot, req) =>
renderService.renderExtensionHtmlToPng({
html: req.html,
css: req.css,
extensionDataRoot: dataRoot,
fileName: req.fileName,
width: req.width
}),
listGroups: async () => [{ id: groupId, name: '产品测试群' }],
aiChat: async () => ({
text: JSON.stringify({
headline: '发布前准备就绪',
highlights: ['明早十点同步发布节奏', '图片清单与语音确认测试环境就绪'],
actionItems: ['张三主持明早十点同步'],
groupBriefs: [{ groupName: '产品测试群', summary: '确认测试环境与发布清单。' }]
})
}),
getAccountId: () => accountId,
getSelfUsernames: () => [accountId],
isDatabaseReady: () => true,
secretCipher: {
isAvailable: () => false,
encrypt: () => Buffer.alloc(0),
decrypt: () => ''
}
})
await manager.initialize()
const digestSource = path.resolve(process.cwd(), 'examples/extensions/morning-digest')
const installed = await manager.installFromDirectory(digestSource)
expect(installed.success).toBe(true)
expect((await manager.setEnabled('com.example.morning-digest', true)).success).toBe(true)
// 模拟在子进程内直接激活 morning-digest 后台并接到 manager 的真实网关。
const activateDigest = require(path.join(digestSource, 'background/index.js'))
const pageHandlers = new Map<string, (params: Record<string, unknown>) => Promise<unknown>>()
const storageMap = new Map<string, unknown>()
const extId = 'com.example.morning-digest'
const extPerms = manager.get(extId)?.grantedPermissions ?? []
const mediaGateway = new ExtensionMediaGateway({
isDatabaseReady: () => true,
getAccountId: () => accountId,
getExtensionDataRoot: (id) => paths.extensionDataDir(id),
hasPermission: (_id, perm) => extPerms.includes(perm),
resolveMessage: async (ref) => resolvedMedia[ref.messageId] ?? null,
readImageData: async () => ({
buffer: Buffer.from('fixture-png'),
mimeType: 'image/png',
imageHash: 'hash-1',
quality: 'original'
}),
readVoiceData: async () => ({ wavBuffer: Buffer.from('RIFF'), durationMs: 5000 }),
readVideoAsset: async () => null,
recognizeOcr: async () => ({
success: true,
text: '版本发布检查清单',
language: 'zh-Hans',
engine: 'apple-vision'
}),
transcribeVoice: async () => ({
state: 'transcribed',
transcript: '测试环境已经准备好了',
cached: false,
durationMs: 5000
}),
analyzeImage: async () => ({ description: '检查清单截图', cached: false })
})
const sdkShim = {
extension: { id: extId, dataDir: paths.extensionDataDir(extId), permissions: extPerms },
page: {
onRequest: (method: string, fn: (params: Record<string, unknown>) => Promise<unknown>) =>
pageHandlers.set(method, fn)
},
storage: {
get: async (k: string) => storageMap.get(k) ?? null,
set: async (k: string, v: unknown) => void storageMap.set(k, v)
},
messages: {
query: async (req: Parameters<typeof paginateQueriedMessages>[1]) =>
paginateQueriedMessages(allMessages, { ...req, limit: 2 })
},
media: {
batch: (req: Parameters<ExtensionMediaGateway['batch']>[1]) => mediaGateway.batch(extId, req)
},
ai: {
chat: async () => ({
text: JSON.stringify({
headline: '发布前准备就绪',
highlights: ['明早十点同步发布节奏'],
actionItems: ['张三主持同步'],
groupBriefs: [{ groupName: '产品测试群', summary: '确认测试环境与清单。' }]
})
})
},
render: {
htmlToImage: (req: { html: string; css?: string; fileName?: string; width?: number }) =>
renderService.renderExtensionHtmlToPng({
...req,
extensionId: extId,
extensionDataRoot: paths.extensionDataDir(extId)
})
},
notifications: {
create: async (req: Parameters<ExtensionManager['createNotification']>[1]) =>
manager.createNotification(extId, req)
},
wechat: {
send: async (req: { type: 'image'; to: string; path: string }) => {
await executeAction({
origin: 'extension',
purpose: 'extension_send',
to: req.to,
content: { type: 'image', path: req.path }
} as never)
return { actionId: 'act-1', status: 'sent' as const }
}
},
automation: { registerAction: vi.fn() },
log: { info: vi.fn(), warn: vi.fn(), error: vi.fn() }
}
activateDigest(sdkShim)
const generate = pageHandlers.get('generateDigest')!
const result = (await generate({
groupIds: [groupId],
groupNames: { [groupId]: '产品测试群' },
windowHours: 24,
enableImageOcr: true,
enableVoiceTranscribe: true,
autoSendWechat: false
})) as Record<string, unknown>
expect(result.headline).toBe('发布前准备就绪')
expect(result.totalMessages).toBe(3)
expect(result.totalMediaResolved).toBe(2)
expect(result.sentToWechat).toBe(false)
expect(fs.existsSync(String(result.imagePath))).toBe(true)
expect(String(result.previewUrl || '')).toMatch(
/^tm-extension:\/\/com\.example\.morning-digest\/_data\/rendered\/morning-digest-/
)
// 默认禁止自动发微信。
expect(executeAction).not.toHaveBeenCalled()
// 已写入宿主通知中心。
expect(manager.listNotifications(extId)).toHaveLength(1)
expect(manager.getNotificationSummary().unpinnedUnread).toBe(1)
// 人工显式点击手动发送,经 Gateway 发送。
const sendLast = pageHandlers.get('sendLastDigest')!
await sendLast({ to: groupId })
expect(executeAction).toHaveBeenCalledTimes(1)
// 验证旧 v1 扩展(keyword-bot)向后兼容安装与启用。
const legacySource = path.resolve(process.cwd(), 'examples/extensions/keyword-bot')
expect((await manager.installFromDirectory(legacySource)).success).toBe(true)
expect((await manager.setEnabled('com.example.keyword-bot', true)).success).toBe(true)
await manager.dispose()
})
it('群聊机器人升级模板按需解析图片 OCR 与语音转写,无权限时安全降级', async () => {
const botPath = path.resolve(process.cwd(), 'examples/extensions/group-chat-bot/background/index.js')
const botActivate = require(botPath)
const resolveIncomingMediaText = botActivate.resolveIncomingMediaText as (
tm: unknown,
event: Record<string, unknown>,
options?: Record<string, unknown>
) => Promise<{ text: string; source: string } | null>
const mockTm = {
extension: { permissions: ['media.ocr', 'media.transcribe'] },
media: {
ocrImage: vi.fn(async () => ({ text: '周末爬山集合点' })),
transcribeVoice: vi.fn(async () => ({ state: 'transcribed', transcript: '我带水壶' }))
}
}
const imgRes = await resolveIncomingMediaText(mockTm, {
type: 'image',
messageRef: 'tmref1_img'
})
expect(imgRes).toEqual({ text: '[图片文字] 周末爬山集合点', source: 'image_ocr' })
const voiceRes = await resolveIncomingMediaText(mockTm, {
type: 'voice',
messageRef: 'tmref1_voice'
})
expect(voiceRes).toEqual({ text: '[语音转文字] 我带水壶', source: 'voice_transcript' })
// 缺少权限时返回 null,不发起调用。
const noPermTm = { extension: { permissions: [] }, media: { ocrImage: vi.fn() } }
expect(
await resolveIncomingMediaText(noPermTm, { type: 'image', messageRef: 'tmref1_img' })
).toBeNull()
expect(noPermTm.media.ocrImage).not.toHaveBeenCalled()
})
it('扩展升级新增权限需重新确认后方可生效,旧权限继续保留', async () => {
const root = makeTempDir()
const userData = path.join(root, 'userData')
const extV1 = path.join(root, 'ext-v1')
const extV2 = path.join(root, 'ext-v2')
const makeVersion = (dir: string, version: string, permissions: string[]): void => {
fs.ensureDirSync(path.join(dir, 'background'))
fs.writeJsonSync(path.join(dir, 'manifest.json'), {
manifestVersion: 1,
id: 'com.example.upgrade-guard',
name: '升级权限测试',
version,
apiVersion: '1',
entrypoints: { background: 'background/index.js' },
permissions
})
fs.writeFileSync(path.join(dir, 'background', 'index.js'), 'module.exports = () => {}')
}
makeVersion(extV1, '1.0.0', ['storage'])
makeVersion(extV2, '1.1.0', ['storage', 'notifications.create', 'media.read'])
const manager = new ExtensionManager({
paths: createExtensionPaths(userData),
appVersion: '2.7.0',
spawn: () => createSilentChild(),
getCapability: async () =>
({
supported: false,
ready: false,
status: 'unsupported',
capabilities: { text: false, image: false, video: false, voice: false },
senderStatus: {},
message: 'off'
}) as unknown as PersonalWechatSendCapability,
checkEntitlement: async () => ({ ok: false, message: 'off', source: 'mac_license' }),
executeAction: async (): Promise<WechatActionResult> => ({
actionId: 'a',
status: 'sent',
decision: 'allow',
startedAt: '2026-01-01T00:00:00.000Z',
finishedAt: '2026-01-01T00:00:01.000Z',
reason: 'off'
}),
queryMessages: async () => ({ messages: [], hasMore: false }),
listGroups: async () => [],
aiChat: async () => ({ text: '' }),
getAccountId: () => 'wxid_upgrade',
getSelfUsernames: () => [],
isDatabaseReady: () => true,
secretCipher: {
isAvailable: () => false,
encrypt: () => Buffer.alloc(0),
decrypt: () => ''
}
})
await manager.initialize()
expect((await manager.installFromDirectory(extV1)).success).toBe(true)
expect((await manager.setEnabled('com.example.upgrade-guard', true)).success).toBe(true)
// 升级到 v2:新增 notifications.create 与 media.read,必须处于 pendingPermissions 且不可用。
const upgraded = await manager.installFromDirectory(extV2)
expect(upgraded.success).toBe(true)
const detail = manager.get('com.example.upgrade-guard')
expect(detail?.grantedPermissions).toEqual(['storage'])
expect(detail?.pendingPermissions).toEqual(['notifications.create', 'media.read'])
expect(() =>
manager.createNotification('com.example.upgrade-guard', { title: '未确认权限不得写入' })
).toThrowError(/notifications\.create/)
// 用户显式重新确认授权后立即可用。
expect(
(await manager.grantPermissions('com.example.upgrade-guard', ['notifications.create'])).success
).toBe(true)
expect(
manager.createNotification('com.example.upgrade-guard', { title: '授权后允许写入' }).deduped
).toBe(false)
await manager.dispose()
})
})