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

+111 -107
View File
@@ -8,7 +8,7 @@
| `id` | 是 | 反向域名,小写;禁止 `com.tracememo.` / `tracememo.` / `tm.` 前缀 |
| `name` | 是 | 展示名,≤ 64 字 |
| `version` | 是 | `x.y.z`(可带 prerelease) |
| `apiVersion` | 是 | 必须为 `1` |
| `apiVersion` | 是 | 必须为 `1`(向后兼容所有 v1 扩展) |
| `minAppVersion` | 否 | 低于该版本拒绝安装 |
| `description` / `author` / `homepage` | 否 | 展示用;homepage 仅接受 http(s) |
| `permissions` | 是 | 见权限表;未知权限直接判 manifest 非法 |
@@ -16,6 +16,7 @@
| `entrypoints.background` | 二选一 | 后台入口相对路径 |
| `subscriptions` | 条件 | 申请 `messages.subscribe` 时必填 |
| `contributions.pages` | 否 | `[{ id, title, entry? }]`,`id` 形如 `settings` |
| `contributions.navigation` | 否 | `{ label, icon?, pageId?, order? }`,供用户「固定到一级菜单」;`icon` 仅支持内置安全图标集 `spark / bot / digest / bell / media / puzzle / compass / message` |
| `contributions.automationActions` | 否 | `[{ id, title, description? }]`,有此项必须提供 background |
路径规则:相对路径、不允许 `..`、反斜杠、盘符、控制字符、Windows 保留名;
@@ -26,24 +27,31 @@
| 权限 | 风险 | 能力 |
| --- | --- | --- |
| `messages.subscribe` | 高 | 接收 `message.received` |
| `messages.query` | 高 | `tm.messages.query` |
| `messages.query` | 高 | `tm.messages.query`(支持游标分页与类型过滤) |
| `media.read` | 高 | `tm.media.readImage` / `readVoice` / `readVideo`(按需解密并写入扩展私有缓存目录) |
| `media.ocr` | 中 | `tm.media.ocrImage`(纯本地系统 OCR,优先复用既有索引缓存) |
| `media.transcribe` | 中 | `tm.media.transcribeVoice`(复用 `VoiceTranscriptionGateway` 与转写缓存) |
| `contacts.list` | 中 | 配置页读取群列表(`contacts.listGroups`),不含聊天内容 |
| `wechat.send.text` | 高 | `tm.wechat.send`(文本)与自动化 `reply` |
| `wechat.send.image` | 高 | `tm.wechat.send({ type: 'image' })` |
| `wechat.send.video` | 高 | `tm.wechat.send({ type: 'video' })`,原生 Host 走 `/SendMsg` video |
| `wechat.send.voice` | 高 | `tm.wechat.send({ type: 'voice' })`,支持传入 `text` 用宿主 TTS 音色合成发送或传入音频 `path` |
| `ai.chat` | 中 | `tm.ai.chat` |
| `ai.vision` | 中 | `tm.media.analyzeImage` / `tm.ai.analyzeImage`(复用已配置的视觉 AI Provider) |
| `render.html` | 低 | `tm.render.htmlToImage`(离线隔离渲染静态 HTML/CSS 为 PNG 长图) |
| `notifications.create` | 中 | `tm.notifications.create`(写入扩展通知中心与未读角标) |
| `storage` | 低 | `tm.storage.*` 与页面存储 |
| `automation.action` | 中 | `tm.automation.registerAction` |
| `secrets` | 中 | `tm.secrets.*`(经系统安全存储加密保存私有凭据) |
安装时只自动授予**低风险**权限;其余在「启用」确认后授予。停用后回落到低风险集合。
安装时只自动授予**低风险**权限;其余在「启用」确认后授予。停用后回落到低风险集合。所有权限均由主进程独立校验,不依赖 SDK 侧检查。
## 后台 API
### tm.extension
- `id: string`
- `dataDir: string`(扩展私有数据目录,媒体文件写这里才能通过发送校验)
- `dataDir: string`(扩展私有数据目录,媒体与渲染产物落盘于此)
- `permissions: string[]`(当前已授予)
### tm.events
@@ -51,109 +59,114 @@
- `on('message.received', handler): () => void`
- `off('message.received', handler): void`
事件字段见 `TraceMemoMessageEvent`:`eventId / accountId / conversationId / messageId /
senderId? / senderName? / isGroup / isSelf / type / text? / mentionsMe / timestamp(ms)`。
事件字段见 `TraceMemoMessageEvent`:`eventId / messageRef / accountId / conversationId / messageId / senderId? / senderName? / isGroup / isSelf / type / text? / mentionsMe / timestamp(ms)`。
其中 `messageRef` 与 `tm.messages.query` 返回的 `messageRef` 格式完全统一,包含账号、会话与消息身份隔离校验。
### tm.messages.query
```ts
await tm.messages.query({ conversationId, startTime?, endTime?, limit? })
// → { messages: [{ messageId, conversationId, senderId?, senderName?, isSelf, type, text?, timestamp }] }
await tm.messages.query({
conversationId,
startTime?,
endTime?,
limit?,
cursor?,
order?, // 'asc' | 'desc';省略时保持 v1 默认最新一页语义并支持向更早历史续页
types? // 如 ['text', 'image', 'voice']
})
// → { messages: [{ messageId, messageRef, conversationId, senderId?, senderName?, isSelf, type, text?, timestamp }], nextCursor?, hasMore }
```
- 时间参数是 **epoch 毫秒**;默认最近 24 小时。
- 单次窗口最多 7 天,`limit` 上限 200。
- 时间参数是 **epoch 毫秒**;默认最近 24 小时,单次最大 35 天,`limit` 上限 500。
- 游标以 `(timestamp, messageId)` 为确定性边界,同时间戳多条消息分页不遗漏、不重复。
- 数据库未连接时抛 `DATABASE_NOT_READY`。
### tm.media(扩展媒体 Gateway)
```ts
// 按需读取媒体副本(写入扩展私有目录,不暴露原始微信数据库路径与密钥)
await tm.media.readImage({ messageRef, quality?: 'original' | 'thumbnail' })
await tm.media.readVoice({ messageRef })
await tm.media.readVideo({ messageRef })
// 本地 OCR / 语音转写 / AI 图片理解(自动复用主程序缓存与并发限制)
await tm.media.ocrImage({ messageRef, language?, force? })
await tm.media.transcribeVoice({ messageRef, force?, waitMs? })
await tm.media.analyzeImage({ messageRef, prompt?, force? })
// 批量按需处理(单次最多 20 项,并发上限 4,单项失败隔离返回)
await tm.media.batch({
concurrency: 2,
items: [
{ op: 'ocrImage', messageRef: imgRef },
{ op: 'transcribeVoice', messageRef: voiceRef }
]
})
```
- 跨账号 `messageRef` 触发 `ACCOUNT_MISMATCH`;消息类型不匹配触发 `MEDIA_UNSUPPORTED`;缺失文件触发 `MEDIA_NOT_FOUND`;并发满载触发 `CONCURRENCY_LIMITED`。
- `tm.ai.analyzeImage` 是 `tm.media.analyzeImage` 的等价别名,均要求 `ai.vision` 权限。
### tm.render.htmlToImage
```ts
await tm.render.htmlToImage({
html: '<main><h1>晨报</h1></main>',
css: 'main { padding: 20px; }',
fileName: 'morning-2026-12-01.png', // 可选,仅接受安全相对路径
width: 460,
maxHeight: 16000,
backgroundColor: '#ffffff',
timeoutMs: 20000
})
// → { path, previewUrl, width, height, pixelWidth, pixelHeight, deviceScaleFactor, bytes, mimeType: 'image/png', sha256 }
```
- 与官方群聊日报共用同一 `HtmlRenderService` 离线渲染引擎。
- 仅接受静态 HTML/CSS:自动拦截 `<script>`、`<iframe>`、内联事件、`javascript:`、`srcset`/`xlink:href` 与外链资源,独立窗口 + 临时 Session + 严格 CSP,输出至 `<dataDir>/rendered/`;生成路径可直接交给 `tm.wechat.send({ type: 'image', to, path })`,`previewUrl`(`tm-extension://<extensionId>/_data/rendered/...`)可直接用于扩展沙箱页面 `<img>` 预览。
### tm.notifications
```ts
await tm.notifications.create({
title: '今日晨报已生成',
body: '覆盖 3 个群聊,共提炼 5 条重点',
level: 'success', // 'info' | 'success' | 'warning' | 'error'
dedupeKey: 'morning-2026-12-01',
pageId: 'digest'
})
// → { id, deduped, createdAt }
const ownItems = await tm.notifications.list()
const { changed } = await tm.notifications.markRead({ id: ownItems[0]?.id })
```
- 由宿主持久化管理;同扩展相同 `dedupeKey` 仅更新内容不重复累加未读数,并受滑动窗口防刷屏限频保护(超限抛 `CONCURRENCY_LIMITED`)。
- `list` 与 `markRead` 强绑定调用方 `extensionId`,只能读写本扩展自己的通知。
- 已固定到一级菜单的扩展在固定入口显示独立未读角标;未固定扩展聚合到「扩展」导航的未读角标,与红色 `!` 发送能力异常提示严格区分。
- 停用扩展拒绝写入新通知(`EXTENSION_DISABLED`);卸载扩展自动清理其全部通知状态。
### tm.wechat.send
```ts
// 文本
await tm.wechat.send({ to, text, at?, dedupeKey? })
// 图片
await tm.wechat.send({ type: 'image', to, path: '/abs/path/cover.png', dedupeKey? })
// 视频(原生 Host 以 {toWxid, type:'video', msg:<路径>} 提交)
await tm.wechat.send({ type: 'video', to, path: '/abs/path/clip.mp4', dedupeKey? })
// 语音(传 text 由宿主用已配置的 TTS 音色合成发送,或传 path 发送音频文件)
await tm.wechat.send({ type: 'voice', to, text: '你好呀', voiceId?, dedupeKey? })
// → { actionId, status: 'sent' }
```
按顺序检查:权限 → 参数(文本 ≤ 2000 字)→ manifest 会话范围 → 频率
(同扩展 2 秒一条、每分钟 10 条)→ 本机发送能力 → 授权校验 → Gateway。
任何一步不通过都抛带错误码的异常,不会「静默丢弃」。
按顺序检查:权限 → 参数 → manifest 会话范围 → 频率 → 本机发送能力 → Pro 授权校验 → Action Gateway。任何一步不通过都抛带错误码的异常。
媒体路径额外约束:
### tm.ai.chat / tm.storage / tm.secrets / tm.automation / tm.capabilities / tm.log
- 必须是**绝对路径**的普通文件,realpath 后仍位于**扩展数据目录**或**系统临时目录**;
- 大小 1B–100MB;
- 图片扩展名:jpg/jpeg/png/gif/webp/bmp;视频扩展名:mp4/mov/m4v;
- 视频走 `type: 'video'`,不复用图片通道;发送失败不会降级成图片。
### tm.ai.chat
```ts
await tm.ai.chat([{ role: 'user', content: '...' }])
// → { text }
```
使用 TraceMemo 已配置的 AI Provider;扩展拿不到 API Key。
### tm.storage
```ts
await tm.storage.set('config', { ... })
await tm.storage.get('config')
await tm.storage.remove('config')
await tm.storage.list()
```
键:`[A-Za-z0-9._-]{1,64}`;单值 ≤ 256KB,总量 ≤ 1MB;只接受 JSON 值。
### tm.automation.registerAction
```ts
tm.automation.registerAction({ id, title, description?, inputSchema?, handler })
```
`id`:`[a-z0-9][a-z0-9._-]{1,63}`。`handler` 返回:
```ts
{ success: boolean, output?: object, reply?: { type: 'text', text, at? }, error?: string }
```
`inputSchema` 只支持 `object` + `string|number|boolean` 属性的浅校验;必填项缺失会直接拒绝。
执行超时默认 15 秒(宿主可配,最大 60 秒),超时返回 `ACTION_TIMEOUT`。
### tm.capabilities.get
返回只读快照:`enabled / permissions / platform / databaseReady / send{...} / ai{...}`。
### tm.log
`info / warn / error`,写入扩展日志(详情页可见,最多保留 200 条,单行 ≤ 500 字)。
## 页面桥
页面 → 宿主:
```ts
{ source: 'tracememo-extension-page', extensionId, requestId, method, params }
```
宿主 → 页面:
```ts
{ source: 'tracememo-extension-host', requestId, ok: true, result }
{ source: 'tracememo-extension-host', requestId, ok: false, error: { code, message } }
```
页面方法白名单:`storage.get|set|remove|list`、`capabilities.get`、`contacts.listGroups`、`extension.info`。
页面不能发送微信消息、不能查询消息、不能调用 AI。
- `tm.ai.chat(messages)`:调用 TraceMemo 已配置的 AI Provider,不暴露 API Key。
- `tm.storage.{get,set,remove,list}`:键 `[A-Za-z0-9._-]{1,64}`,单值 ≤ 256KB,总量 ≤ 1MB。
- `tm.secrets.{get,set,delete,has}`:系统安全存储加密凭据。
- `tm.automation.registerAction({ id, title, description?, inputSchema?, handler })`:注册自动化动作。
- `tm.page.onRequest(method, handler)`:注册页面到同扩展后台的受限请求处理器(响应 ≤ 64KB 纯 JSON)。
- `tm.capabilities.get()`:返回只读环境能力快照。
- `tm.log.{info,warn,error}`:写入扩展日志(最多保留 200 条,单行 ≤ 500 字)。
## 错误码
@@ -163,29 +176,20 @@ tm.automation.registerAction({ id, title, description?, inputSchema?, handler })
| `EXTENSION_DISABLED` | 扩展未启用 |
| `EXTENSION_INCOMPATIBLE` | apiVersion 或 minAppVersion 不满足 |
| `EXTENSION_INVALID_MANIFEST` | manifest 不合法 |
| `EXTENSION_INVALID_PATH` | 入口 / 资源路径越界 |
| `EXTENSION_INVALID_PATH` | 入口或输出路径越界 |
| `EXTENSION_HOST_UNAVAILABLE` | 后台进程未运行 |
| `PERMISSION_DENIED` | 未授予权限,或超出声明范围 |
| `CAPABILITY_UNAVAILABLE` | 本机能力不具备(未绑定 / 未就绪) |
| `LICENSE_REQUIRED` | 无有效授权 |
| `PERMISSION_DENIED` | 未授予权限或超出声明范围 |
| `CAPABILITY_UNAVAILABLE` | 本机能力不具备或未配置 |
| `LICENSE_REQUIRED` | 无有效 Pro 授权 |
| `DATABASE_NOT_READY` | 微信数据库未连接 |
| `SEND_NOT_SUPPORTED` | 当前平台或内容类型不支持 |
| `MEDIA_NOT_FOUND` | 找不到消息对应的本地媒体文件 |
| `MEDIA_UNSUPPORTED` | 该消息类型不支持所请求的媒体操作 |
| `ACCOUNT_MISMATCH` | `messageRef` 不属于当前已连接账号 |
| `CONCURRENCY_LIMITED` | 媒体解析或渲染并发达到上限 |
| `RENDER_FAILED` | 离线 HTML 渲染失败 |
| `ACTION_TIMEOUT` | 处理超时 |
| `ACTION_FAILED` | 执行失败 |
| `RATE_LIMITED` | 触发频率限制 |
| `INVALID_REQUEST` | 参数非法 |
| `STORAGE_LIMIT_EXCEEDED` | 存储超限 |
## 自动化动作输入
规则里保存的静态 `input` 会与宿主注入字段合并,同名键以宿主为准:
```json
{
"url": "https://example.com/video",
"conversationId": "xxx@chatroom",
"isGroup": true,
"accountId": "wxid_self",
"message": { "eventId": "message:...", "text": "...", "mentionsMe": false }
}
```
| `INVALID_REQUEST` | 参数非法或恶意输入被拒绝 |
| `STORAGE_LIMIT_EXCEEDED` | 存储或产出文件体积超限 |
+43 -73
View File
@@ -1,9 +1,8 @@
# 扩展中心架构(v1)
# 扩展中心架构
## 目标
把用户二次开发从官方源码里剥离:扩展装在自己的目录、走稳定的 SDK、由宿主做权限与能力检查。
官方升级只替换应用本体,不触碰扩展目录与数据目录。
将二次开发能力以稳定、可演进的 SDK 暴露给扩展,同时复用 TraceMemo 主程序既有的消息监听、媒体解密、语音转写、系统 OCR、视觉模型、HTML 离线渲染与发送网关,不维护第二套平行实现。
## 分层
@@ -12,88 +11,59 @@ TraceMemo Core(Electron 主进程 / 渲染层)
│
ExtensionManager ─── ExtensionRegistry(启用状态 / 授权集合)
│ ExtensionInstaller(目录 / ZIP 安装,原子替换)
│ ExtensionLogStore(日志)
│ ExtensionActionRegistry(自动化动作)
│ ExtensionEventBus(消息事件分发)
│ ExtensionNavigationStore(固定到一级菜单的状态与排序)
│ ExtensionNotificationStore(通知持久化、去重与未读汇总)
│ ExtensionLogStore / ExtensionActionRegistry / ExtensionEventBus
│
ExtensionHost(每个扩展一个 Node 子进程)
ExtensionHost(每个扩展一个独立 Node 子进程)
│ require(background/index.js),注入 tm
│
tm.* ── 白名单 RPC ──▶ 宿主能力
├─ storage → extensions-data/<id>
├─ messages.query→ chat-service(有界窗口)
├─ wechat.send → ExtensionSendGateway → WechatActionGateway
├─ ai.chat → AIProviderService
└─ capabilities → 只读快照
tm.* ── 白名单 RPC(主进程独立权限校验)──▶ 宿主能力
├─ storage / secrets → extensions-data/<id> / safeStorage
├─ messages.query → chat-service(游标分页 + 统一 messageRef)
├─ media.* → ExtensionMediaGateway
│ ├─ ImageDecryptService / VoiceService / VideoAssetService
│ ├─ SystemOcrService + imageTextIndexService 缓存
│ ├─ VoiceTranscriptionGateway
│ └─ ImageInsightService / AIProviderService
├─ render.htmlToImage → HtmlRenderService(与官方群聊日报共用)
├─ notifications → ExtensionNotificationStore → 一级导航角标 & 通知中心
├─ wechat.send → ExtensionSendGateway → WechatActionGateway
├─ ai.chat / vision → AIProviderService
└─ capabilities → 只读快照
```
关键边界:
- **主进程从不 `require` 扩展代码**;扩展只在子进程里加载。
- 扩展不 import 官方业务模块,只通过 JSON RPC 申请能力。
- 发送、消息读取、AI 调用全部复用既有服务,没有第二套监听或发送实现。
## 目录
## 目录与宿主状态
```text
<userData>/
extensions/<id>/ 代码(manifest.json / ui / background)
extensions-data/<id>/ 扩展私有数据(storage.json)
extensions-state/ 宿主状态
registry.json 启用状态与已授予权限
logs/<id>.jsonl 运行日志(轮转一份 .1)
extensions-staging/ 安装临时目录(成功后原子改名)
extensions/<id>/ 扩展代码(manifest.json / ui / background)
extensions-data/<id>/ 扩展私有数据
storage.json JSON 键值存储
media-cache/{images,voices,videos}/ 按需解密的媒体副本缓存
rendered/ tm.render.htmlToImage 生成的 PNG 长图
extensions-state/ 宿主管理状态
registry.json 启用状态与已授予权限
pinned-navigation.json 用户固定到一级导航的扩展顺序
notifications.json 扩展通知中心持久化记录
logs/<id>.jsonl 运行日志
extensions-staging/ 安装临时目录
```
三者分离的原因:
## 统一 messageRef 与按需媒体流水线
| 场景 | 结果 |
| --- | --- |
| 官方应用升级 | `userData` 不变,扩展与配置原样保留 |
| 扩展升级(同 id 新版本) | 只替换 `extensions/<id>`,`extensions-data` 不动 |
| 卸载并选择保留数据 | 删除代码目录,保留 `extensions-data` |
| 卸载并清除数据 | 同时删除数据目录与日志 |
- 实时事件 `ExtensionMessageEvent` 与历史查询 `ExtensionQueriedMessage` 输出同一套 `tmref1_*` 编码的 `messageRef`,内含 `accountId / conversationId / messageId / localId? / timestamp?`。
- 扩展通过 `messageRef` 按需请求媒体与派生解析;`ExtensionMediaGateway` 强制校验当前账号一致、权限充足、并发与超时上限,并将文件副本隔离写入该扩展自己的 `extensions-data/<id>/media-cache/`。
- 本地 OCR、语音转写与图片视觉理解优先复用主程序已有缓存,避免重复解密或重复调用模型。
## 生命周期
## 通用 HTML 渲染服务
```text
install → 校验 manifest / 入口 → 临时目录 → 原子替换 → 登记(默认未启用)
enable → 授予 manifest 声明的权限 → 启动子进程 → activate 握手 → active
message → ExtensionEventBus 去重 → 按 subscriptions 过滤 → 投递给子进程
action → 自动化 runner → ExtensionHost.invokeAction → 返回 reply / output
disable → 停止子进程 → 撤销高风险权限(仅保留 storage)→ inactive
upgrade → 停进程 → 替换目录 → 保留 enabled 与授权 → 重启
```
- `src/main/services/html-render-service.ts` 统一承接官方群聊日报截图(`group-report-service.ts`)与扩展 `tm.render.htmlToImage`。
- 每次渲染创建独立隐藏 `BrowserWindow` 与临时 `Session` 分区,限制网络请求仅放行目标 HTML 文件,校验静态 HTML 与输出尺寸/体积/并发/超时,并在 `finally` 中保证销毁窗口并删除临时文件。
崩溃处理:子进程异常退出时按 1s / 2s / 4s 退避重启,5 分钟内超过 3 次标记为
`crashed` 并停止自动重启,等用户手动停用再启用。
## 动态一级导航与通知聚合
## 消息事件
- 事件来源只有 `MessageListenerService` 的规范化结果,不直连数据库。
- `eventId = message:<sha1(sessionId:localId)>`,同一条消息稳定不变。
- `mentionsMe` 来自 `source.atuserlist` ∩ 当前账号 username;拿不到自身身份时为 `false`。
- 分发前做 manifest 级过滤(消息类型 / 会话范围 / 是否 @我 / 是否包含自己)。
- 子进程侧有令牌桶(容量 100,按 60/秒补充);超出时丢弃并记一条 warn,
不让扩展拖慢主进程监听循环。
**已知降级**:旧 Native Runtime 的事件不带 `sessionId`,监听层只能回读「最近活跃会话」。
事件总线不掩盖这一点,自动化状态与扩展能力快照都按「降级」标记。
## 发送链路
```text
tm.wechat.send
→ ExtensionHost(权限检查)→ ExtensionSendGateway(权限 / 范围 / 频率 / 能力 / 授权校验)
→ WechatActionGateway.executeFromExtension(origin=extension, purpose=extension_send)
→ WechatSendGateway → Windows / macOS sender
```
自动化动作返回的 `reply` 走同一条 Gateway,但 purpose 是 `extension_action`,
幂等键由 `executionId` 派生。扩展无法传入 `origin` / `purpose` / `triggerType`。
## 与自动化的关系
- 扩展注册动作,自动化负责触发、过滤、冷却、幂等、执行日志。
- 自动化规则里的 `extensionAction` 只保存 `extensionId + actionId + 静态 input`;
卸载扩展后规则**保留**,执行时明确报 `EXTENSION_NOT_FOUND`,不会静默删除用户配置。
- 扩展可在 `manifest.json` 声明 `contributions.navigation`(安全内置图标 + 标签 + 默认页);用户在扩展详情页主动选择「固定到一级菜单 / 取消固定 / 上移 / 下移」。
- 固定入口渲染在左侧一级导航「设置」上方,点击直接复用同一个 `ExtensionPageHost` 打开扩展页面,不新建第二套页面容器。
- 已固定扩展的未读通知显示在对应固定入口角标;未固定扩展的未读通知聚合到「扩展」导航的蓝色数字角标,与红色 `!` 发送能力异常提示严格区分。
- 卸载扩展时宿主自动清理其固定导航项与全部通知记录。
+64 -114
View File
@@ -1,27 +1,19 @@
# 扩展开发入门
从克隆源码到创建独立扩展的完整流程见[克隆 TraceMemo 后开发自己的扩展](./clone-and-customize.md)。本页保留 API 用法速查。
从克隆源码到创建独立扩展的完整流程见[克隆 TraceMemo 后开发自己的扩展](./clone-and-customize.md)。本页提供第二阶段新增能力与基础 API 的快速上手。
## 1. 安装示例
## 1. 官方模板一览
1. 打开 TraceMemo,左侧一级导航点「扩展」。
2. 点「安装目录」,选择 `examples/extensions/keyword-bot`。
3. 列表里出现 **关键词回复机器人**,状态为「已停用」。
4. 点「启用」→「打开页面」;页面顶部的「启用机器人」默认关闭,打开后修改规则并保存。
5. 完全退出并重启 TraceMemo,配置仍在。
在 TraceMemo 左侧点击「扩展」→「官方模板」可一键安装以下示例:
`examples/extensions/douyin-sender` 用同样的方式安装;它依赖本机 `python3`、Chrome 和抖音解析脚本,先看它自己的 README。
| 模板 | 演示能力 |
| --- | --- |
| `keyword-bot` | 消息事件订阅、关键词回复、Gateway 发送、自动化动作 |
| `group-chat-bot` | 多套群聊人格、长短期记忆、文字/语音回复、按需图片 OCR/视觉与语音转写 |
| `morning-digest` | 分页消息查询、批量媒体解析、AI 总结、离线 HTML 长图渲染、扩展通知、一级导航固定与可选微信发送 |
| `douyin-sender` | 外部 Python 脚本协作、视频下载与发送 |
## 2. 最小扩展
```text
my-extension/
manifest.json
ui/index.html
background/index.js
```
`manifest.json`:
## 2. 最小扩展与固定到一级菜单
```json
{
@@ -30,112 +22,70 @@ my-extension/
"name": "我的扩展",
"version": "1.0.0",
"apiVersion": "1",
"minAppVersion": "2.6.0",
"permissions": ["storage"],
"minAppVersion": "2.7.0",
"permissions": ["storage", "notifications.create"],
"entrypoints": { "page": "ui/index.html", "background": "background/index.js" },
"contributions": { "pages": [{ "id": "settings", "title": "设置" }] }
}
```
`background/index.js`:
```js
module.exports = function activate(tm) {
tm.log.info('我的扩展已启动')
}
```
`ui/index.html` 里不能直接用 `window.api`。页面通过 postMessage 与宿主通信:
```js
const requestId = `req-${Date.now()}`
parent.postMessage(
{
source: 'tracememo-extension-page',
extensionId: 'com.example.my-extension',
requestId,
method: 'storage.get',
params: { key: 'greeting' }
},
'*'
)
window.addEventListener('message', (event) => {
const data = event.data
if (!data || data.source !== 'tracememo-extension-host' || data.requestId !== requestId) return
console.log(data.ok ? data.result : data.error)
})
```
页面可调用的方法只有:`storage.get` / `storage.set` / `storage.remove` / `storage.list` /
`capabilities.get` / `extension.info`。
## 3. 订阅消息
manifest 必须同时声明权限与订阅:
```json
{
"permissions": ["messages.subscribe"],
"subscriptions": {
"messageTypes": ["text"],
"conversationIds": [],
"requireMentionMe": false,
"includeSelf": false
"contributions": {
"pages": [{ "id": "main", "title": "我的扩展" }],
"navigation": { "label": "我的工具", "icon": "spark", "pageId": "main" }
}
}
```
用户在扩展详情页点击「固定到一级菜单」后,该入口会出现在左侧「设置」上方;点击可直接打开扩展页面。
## 3. 按需分页读取消息与解析图片/语音
```js
module.exports = function activate(tm) {
tm.events.on('message.received', async (event) => {
if (event.isSelf) return
if (!event.mentionsMe) return
await tm.wechat.send({
to: event.conversationId,
text: '收到',
dedupeKey: event.eventId
tm.page.onRequest('runDigest', async ({ conversationId }) => {
const endTime = Date.now()
const startTime = endTime - 24 * 60 * 60 * 1000
const messages = []
let cursor
do {
const page = await tm.messages.query({
conversationId,
startTime,
endTime,
order: 'asc',
limit: 100,
cursor
})
messages.push(...page.messages)
cursor = page.nextCursor
if (!page.hasMore) break
} while (cursor)
const items = messages
.filter((m) => m.type === 'image' || m.type === 'voice')
.slice(-6)
.map((m) => ({
op: m.type === 'image' ? 'ocrImage' : 'transcribeVoice',
messageRef: m.messageRef
}))
const media = items.length ? await tm.media.batch({ items, concurrency: 2 }) : { results: [] }
const rendered = await tm.render.htmlToImage({
html: `<main><h1>今日速览</h1><p>共 ${messages.length} 条消息</p></main>`,
css: 'main{padding:24px;font-family:-apple-system,sans-serif;}',
width: 460
})
await tm.notifications.create({
title: '今日速览已生成',
body: `分析 ${messages.length} 条消息,解析 ${media.results.length} 条媒体`,
level: 'success',
dedupeKey: `digest-${new Date().toISOString().slice(0, 10)}`,
pageId: 'main'
})
return { count: messages.length, imagePath: rendered.path }
})
}
```
`dedupeKey` 建议直接用 `event.eventId`:同一条消息重复投递时,Gateway 会按审计记录短路。
## 4. 开发调试与安全约定
## 4. 注册自动化动作
```js
tm.automation.registerAction({
id: 'douyin.process',
title: '抖音视频处理',
description: '处理指定视频链接',
inputSchema: {
type: 'object',
properties: { url: { type: 'string' } },
required: ['url']
},
async handler(input) {
return {
success: true,
output: { url: input.url },
reply: { type: 'text', text: '已收到链接' }
}
}
})
```
扩展中心会展示动作声明与运行时注册状态。当前自动化规则编辑器尚未提供扩展动作选择入口,因此暂时不能从界面配置该动作。宿主侧执行契约与输入结构见[扩展 API 参考](./api-reference.md#自动化动作输入)。
扩展动作返回的 `reply` 由宿主经 Gateway 发送;扩展本身不调用发送接口也能完成回复。
## 5. 开发与调试
- TraceMemo 会把扩展复制到用户数据目录;改完源码后先在扩展中心重新安装同一目录,更新已安装的文件。需要时再「停用 → 启用」重启后台进程。
- 页面资源更新后重新打开或刷新扩展页面。
- 日志在扩展详情页底部,`宿主` 表示生命周期与错误,`扩展` 表示 `tm.log.*` 写入的内容。
- 想看完整后台输出,可以在终端启动 `pnpm dev`,子进程 stderr 会进主进程日志。
## 6. 升级与保留
- 扩展升级只替换代码目录;`storage` 数据与启用状态保留。
- 官方 TraceMemo 升级不触碰 `extensions/`、`extensions-data/`、`extensions-state/`。
- 卸载默认保留数据(v1 界面只提供「保留数据」这一条路径;`keepData: false` 已在 IPC 中实现,界面暂未暴露)。
- 后台进程属于受信任本地代码;涉及敏感权限(读取消息/媒体、发微信、写通知)均由主进程独立校验,请按最小权限原则声明。
- 涉及微信发送的扩展默认应关闭自动发送,先通过离线渲染与预览确认内容后再由用户手动触发测试发送。
- 修改源码后可通过「二次开发 → 链接本地项目 + 重载」快速验证,无需反复重新打包安装。
+29 -71
View File
@@ -1,86 +1,44 @@
# 扩展安全模型(v1)
# 扩展安全模型
## 信任分级
## 信任分级与进程边界
| 类型 | 说明 | 本版支持 |
| 类型 | 说明 | 支持状态 |
| --- | --- | --- |
| 声明式 UI 扩展 | 只有页面,使用白名单存储 / 能力查询 | 是 |
| 受信任本地代码扩展 | 后台是任意 Node 代码,可读写本机文件 | 是(安装即视为信任) |
| 声明式 UI 扩展 | 仅页面,经 `postMessage` 白名单访问存储与能力查询 | 支持 |
| 受信任本地代码扩展 | 后台为独立 Node 子进程(`ELECTRON_RUN_AS_NODE`),具备当前系统用户的 Node 权限 | 支持(安装即视为受信任本地代码) |
**独立进程不等于强沙箱。** 后台子进程(`ELECTRON_RUN_AS_NODE`)拥有运行用户的全部
Node 能力,因此扩展作者可以读写本机文件、发起网络请求。本版不声称限制了这些——
它限制的是**TraceMemo 内部能力**:
**明确边界:独立 Node 子进程属于受信任本地代码,不构成强安全沙箱。** 我们不夸大进程隔离的安全性——子进程未受操作系统级 sandbox(如 seatbelt / AppContainer)约束。宿主边界保护的是 **TraceMemo 内部敏感资产与受控网关**:
- 拿不到数据库句柄、数据库密钥、授权凭据、Native Runtime 句柄;
- 不能直接调用原生发送接口(dylib / 底层端口);
- 不能 `require` 官方主进程模块;
- 不能伪造宿主可信元数据(`origin` / `purpose` / `triggerType` / 幂等键)。
- 扩展无法获取微信数据库句柄、数据库解密密钥、图片 AES/XOR 密钥、AI/TTS API Key 明文或原生发送 Runtime 句柄;
- 扩展不能 `require` 主进程模块,也不能伪造宿主可信字段(`origin` / `purpose` / `triggerType` / 幂等键);
- 扩展的后台代码崩溃、死循环或挂死不会拖垮主进程(具备启动超时、调用超时、退避重启与连续崩溃熔断)。
## 进程与权限
## 主进程独立权限校验
```text
主进程 ── fork ──▶ 扩展子进程(每扩展一个)
│ 只注入 tm
▼
白名单 RPC(method + params)
│
宿主再次校验权限
```
子进程 SDK 侧的 `requirePermission` 仅用于提前给出可读错误提示;**所有 RPC 方法在主进程 `ExtensionHost`、`ExtensionManager`、`ExtensionMediaGateway` 与 `ExtensionSendGateway` 均独立校验权限、启用状态与暂停状态**,绝不信任子进程上报的数据。
两侧都检查权限:子进程提前失败给出明确错误码,宿主侧才是权威判定。
子进程崩溃 / 挂死不影响主进程:宿主有启动超时、调用超时、退避重启与熔断。
## 媒体 Gateway 安全与隔离
## 发送安全
- **账号身份与签名防伪造**:实时事件与历史查询签发的 `messageRef` 均由主进程附加运行期 HMAC-SHA256 签名与账号世代标识;未签名伪造、篡改、跨账号(`ACCOUNT_MISMATCH`)或账号切换前的旧引用一律拒绝;若扩展声明了 `subscriptions.conversationIds`,查询与媒体读取同样强制校验会话范围(`PERMISSION_DENIED`)。
- **跨扩展与跨账号缓存隔离**:图片、语音、视频副本严格落盘到 `<extensions-data>/<extensionId>/media-cache/<accountHash>/`,写入前经 `isPathInside` 与 `realpath` 双重校验,绝不返回微信原始目录或数据库路径。
- **错误脱敏**:底层异常中的本地绝对路径与密钥键名在返回扩展前自动脱敏。
- **资源保护**:全局并发上限、单扩展并发上限、单次批量项数上限(≤ 20)及单项超时(`ACTION_TIMEOUT`)防止扩展拖垮本地 OCR、语音转写队列或主进程 I/O。
```text
扩展声明「发什么」
↓
宿主填 origin=extension / purpose=extension_send / recipient 类型 / 幂等键
↓
ExtensionSendGateway:权限 → 会话范围 → 频率 → 本机能力 → 授权校验
↓
WechatActionGateway:用途白名单 + `extension_*` 必须来自 origin=extension
↓
WechatSendGateway:真实发送 + Send Log
```
## 离线 HTML 渲染安全
- 扩展不能在请求里指定 `purpose`,因此无法借用 `manual_*` / `api_*` 等用途绕过白名单。
- 自动化草稿里的 `extensionAction` 只保存扩展 id、动作 id 与静态输入;
发送内容由扩展返回,发送动作由 runner 发起,幂等键由 `executionId` 派生。
- 授权只在主进程判定:macOS 读 Native license(要求 `authorized === true`),
Windows 探测 `/license/status` 只接受 `LICENSE_OK`。UI 上的 `ready` 不作为授权依据。
- 扩展调用 `tm.render.htmlToImage` 仅允许静态 HTML/CSS:入口即拒绝 `<script>`、`<iframe>`、`<object>`、`<embed>`、`<meta http-equiv="refresh">`、内联事件(`on*=`)、`javascript:` 协议及任何 `http(s)/ws/ftp/file` 外链。
- 渲染窗口强制 `sandbox: true`、`contextIsolation: true`、`nodeIntegration: false`、独立随机 `partition`、`will-navigate` 拦截、弹窗拒绝、严格响应头 CSP(`default-src 'none'; script-src 'none'; img-src data:; style-src 'unsafe-inline'`)与 `webRequest.onBeforeRequest` 单文件白名单。
- 强制限制 HTML 体积、输出宽高、PNG 体积、渲染并发数与执行超时;无论成功或失败都在 `finally` 中销毁窗口、注销过滤器并删除临时 HTML 文件。
- 输出文件名经 `isSafeRelativeEntryPath`、`isPathInside` 与 `realpath` 校验,杜绝 `../` 路径穿越与符号链接逃逸。
## 页面安全
## 发送与授权安全
- 自定义协议 `tm-extension://<id>/<path>`,每次请求 realpath 复核目录归属;
- iframe `sandbox="allow-scripts"`:无 same-origin、无 Node、无 preload、无 `window.api`;
- 响应头 CSP:`default-src 'self'`、`script-src 'self'`、`connect-src 'none'`、
`object-src 'none'`、`base-uri 'none'`、`form-action 'none'`;
- 页面只能调用 `storage.*` / `capabilities.get` / `contacts.listGroups` / `extension.info`;
`contacts.listGroups` 只返回群名称与会话 id,且要求 manifest 声明 `contacts.list`。
- 所有扩展发送(文本、图片、视频、语音)均经 `ExtensionSendGateway` → `WechatActionGateway` → `WechatSendGateway`,不可绕过 Pro entitlement、频率限制、会话范围与 Action Audit。
- 真实微信测试默认禁止自动发送;官方模板(如「AI 晨报」)默认关闭自动发送微信开关,仅在用户人工确认并显式开启或点击测试发送时才调用发送链路。
## 安装安全
## 页面、导航与通知安全
ZIP 安装校验:
1. 包大小 ≤ 100MB、文件数 ≤ 2000、单文件 ≤ 20MB、解压总量 ≤ 50MB;
2. 条目路径规范化后判重(大小写不敏感),拒绝 `..`、绝对路径、盘符、保留名;
3. 拒绝 `SymbolicLink` 与非常规条目;
4. 先解压到 `extensions-staging`,校验 manifest 与入口存在后才原子改名;
5. 目标已存在时先改名备份,替换失败自动回滚。
目录安装同样拒绝符号链接与非普通文件,并遵守同样的体积 / 数量上限。
## 隐私
- 宿主日志只记录生命周期、错误摘要与数量,不写聊天正文、昵称、wxid、群名、路径;
- `message.received` 只在扩展声明 `messages.subscribe` 且用户启用后才投递;
- 扩展自己写 `tm.log.*` 的内容会落盘并展示,作者需自行遵守隐私约定;
- 扩展存储按 id 隔离,路径来自已校验的 id,不接受任意目录。
## 已知边界(v1 未解决)
- 后台代码的文件 / 网络权限未做系统级限制(无 seatbelt / AppContainer);
- 页面与后台共享 `storage`,因此页面能读到后台写入的任何配置;
- 没有签名校验与来源可信度分级,安装来源完全依赖用户选择;
- 事件投递是「至多一次」:进程重启或过载时可能丢事件,扩展需要用 `eventId` 自行幂等。
- 扩展页面运行在 `tm-extension://<id>/<path>` 自定义协议与 `sandbox="allow-scripts"` iframe 中,固定到一级导航后仍复用同一个 `ExtensionPageHost`,不暴露 `window.api` 或 Node。
- 扩展私有媒体预览仅开放 `tm-extension://<id>/_data/{rendered,media-cache}/` 白名单媒体扩展名(图片/音频/视频),禁止访问 `storage.json`、其他目录、符号链接与脚本/HTML 类型,不向扩展页面开放本地文件系统。
- `contributions.navigation.icon` 仅允许预定义安全图标枚举,不加载扩展提供的原始 SVG 到主进程/主界面 DOM。
- 停用扩展拒绝写入新通知;单扩展通知受滑动窗口限频保护防刷屏;卸载扩展自动清理固定导航项与通知持久化状态。
+3 -2
View File
@@ -1,11 +1,12 @@
# 扩展示例
三个可直接安装的官方模板示例,用来验证扩展中心从安装到发送的完整链路。
四个可直接安装的官方模板示例,覆盖扩展中心从安装、媒体解析、离线渲染、通知中心到受控发送的完整链路。
| 目录 | 用途 | 申请权限 |
| --- | --- | --- |
| `keyword-bot/` | 消息事件、关键词匹配、Gateway 发送、自动化动作 | `messages.subscribe`、`contacts.list`、`wechat.send.text`、`storage`、`automation.action` |
| `group-chat-bot/` | 多套群聊人格、单群长期与短期记忆、结合 TraceMemo 音色随机回复文字或发送语音 | `messages.subscribe`、`messages.query`、`contacts.list`、`wechat.send.text`、`wechat.send.voice`、`ai.chat`、`storage` |
| `group-chat-bot/` | 多套群聊人格、单群长期与短期记忆、按需解析图片与语音、随机回复文字或语音 | `messages.subscribe`、`messages.query`、`media.ocr`、`media.transcribe`、`ai.vision`、`contacts.list`、`wechat.send.text`、`wechat.send.voice`、`ai.chat`、`notifications.create`、`storage` |
| `morning-digest/` | AI 晨报:分页查询消息、批量媒体解析、AI 总结、离线 HTML 长图渲染、扩展通知与可选微信发送 | `messages.query`、`media.ocr`、`media.transcribe`、`ai.chat`、`ai.vision`、`render.html`、`notifications.create`、`contacts.list`、`wechat.send.image`、`automation.action`、`storage` |
| `douyin-sender/` | @我 发抖音链接 → 解析 → 下载 → 发回视频;配置页可测试发送 | `messages.subscribe`、`contacts.list`、`wechat.send.video`、`wechat.send.text`、`storage` |
## 安装
+14 -21
View File
@@ -1,37 +1,30 @@
# 群聊机器人 (`com.example.group-chat-bot`)
> **这是模板壳,不是完整运行包。** 本目录的 `lib/bot-engine.js` 只含纯函数,不含
> `activateBotRuntime` 运行时。直接把本目录打成 ZIP 安装,后台会走
> `background/index.js` 的 fallback,预览与测试发送都会提示「当前功能暂不可用」。
> 可安装的完整包必须包含带运行时的 `lib/bot-engine.js`;不要把本目录当成品分发。
> **这是模板壳,不是完整运行包。** 本目录不含 `lib/bot-engine.js` 运行时核心。直接把本目录打成 ZIP 安装,后台会走 `background/index.js` 的静默壳逻辑,页面可预览配置但不会执行自动回复。
TraceMemo 官方扩展模板。结合 TraceMemo 已配置的 AI 模型与文字转语音(TTS)音色,在指定微信群聊中按角色设定自然接话,支持单群长期记忆与随机回复文字 / 随机发送语音。
TraceMemo 官方扩展模板。结合 TraceMemo 已配置的 AI 模型、文字转语音(TTS)音色、本地系统 OCR、AI 视觉理解与语音转写能力,在指定微信群聊中按角色设定自然接话,支持单群长期记忆、按需解析图片与语音内容,以及随机回复文字 / 发送语音。
## 核心特性
1. **多套群聊人格(Persona)**:内置「日常群友」「技术搭子」「温柔捧场王」「幽默气氛组」四套预设人格,支持新建、修改或删除自定义人格(独立配置人设背景、说话风格、字数上限与追问约束),并可为不同微信群绑定不同人格。
2. **短期上下文 + 单群长期记忆(Memory)**:
- **短期记忆**:接话时自动读取本群最近 N 条文本消息作为多轮对话上下文。
- **长期记忆**:按群独立维护「固定背景记忆(手动置顶的群规、群友称呼偏好)」与「AI 自动提炼的互动摘要(常聊话题、近期约定)」。可按对话轮数自动更新,也可在配置页随时手动触发 AI 提炼或修订。
3. **自然群聊节奏控制**:支持「仅 @我」「命中唤醒词」「@我 或唤醒词」「自然活跃接话(@我必回 + 普通群消息按概率随机搭话)」四种触发模式,区分直接唤醒冷却与环境闲聊冷却,并支持重复表达抑制。
4. **随机回复文字 / 随机发送语音 + TraceMemo 音色同步展示**:
- 配置页直接展示 TraceMemo「设置 → 文字转语音」中当前选定的音色(名称、ID、标签、合成模型与样本试听)。
- 支持「随机混合(按概率随机回复文字或发送语音)」「仅回复文字」「仅发送语音」三种模式,单群可独立覆盖;当语音未就绪或发送失败时支持自动降级为发送文字。
1. **多套群聊人格(Persona)**:内置四套预设人格并支持自定义编辑,可按群绑定不同人格。
2. **短期上下文 + 单群长期记忆(Memory)**:按群维护固定备注与 AI 提炼的互动摘要。
3. **按需图片与语音理解(v1.1 新增)**:
- 订阅范围已扩展至 `text` / `image` / `voice`,通过统一的 `messageRef` 按需调用 `tm.media.ocrImage`、`tm.media.analyzeImage` 与 `tm.media.transcribeVoice`。
- 图片优先走本地系统 OCR(零联网消耗),按需降级/切换视觉模型;语音复用主程序转写队列与缓存。
4. **随机回复文字 / 发送语音 + 动态一级导航**:声明 `contributions.navigation`,支持在扩展详情页一键「固定到一级菜单」。
## 申请权限
| 权限 | 用途 |
| --- | --- |
| `messages.subscribe` | 接收微信群聊新文本消息事件 |
| `messages.query` | 读取触发群聊最近的上下文消息 |
| `messages.subscribe` | 接收微信群聊文本、图片与语音新消息事件 |
| `messages.query` | 分页读取触发群聊最近的上下文消息 |
| `media.ocr` | 按需识别群聊图片中的文字(纯本地,不联网) |
| `media.transcribe` | 按需将群聊语音转为文字(复用主程序转写缓存) |
| `ai.vision` | 按需调用已配置的视觉模型理解图片内容 |
| `contacts.list` | 在配置页读取群聊列表供勾选生效范围 |
| `wechat.send.text` | 经 TraceMemo Gateway 发送群聊文字回复 |
| `wechat.send.voice` | 经 TraceMemo 文字转语音服务与 Gateway 发送群聊语音气泡 |
| `ai.chat` | 调用 TraceMemo 已配置的 AI Provider 进行思考回复与记忆提炼 |
| `notifications.create` | 在扩展通知中心汇报关键状态 |
| `storage` | 保存机器人配置、单群长期记忆与今日统计 |
## 测试
```bash
node --test examples/extensions/group-chat-bot/tests/bot-engine.test.mjs
```
@@ -1,6 +1,6 @@
'use strict'
/** 群聊机器人后台入口壳:核心逻辑由 lib/bot-engine 承载,缺失时保持静默空操作且不报错。 */
/** 群聊机器人后台入口壳:核心逻辑由 lib/bot-engine 承载,并内置按需图片/语音解析适配。 */
let engine = null
try {
@@ -9,6 +9,86 @@ try {
engine = null
}
function hasGrantedPermission(tm, permission) {
const perms = tm && tm.extension && Array.isArray(tm.extension.permissions)
? tm.extension.permissions
: []
return perms.includes(permission)
}
/** 按需将图片或语音消息解析为可供机器人理解的纯文本摘要,缺权限或失败时安全降级为 null。 */
async function resolveIncomingMediaText(tm, event, options = {}) {
if (!event || typeof event !== 'object') return null
if (event.type === 'text') {
const text = String(event.text || '').trim()
return text ? { text, source: 'text' } : null
}
const messageRef = String(event.messageRef || '').trim()
if (!messageRef || !tm || !tm.media) return null
if (event.type === 'image') {
const imageMode = options.imageMode || 'ocr'
if (imageMode === 'off') return null
if (imageMode === 'vision' && hasGrantedPermission(tm, 'ai.vision')) {
try {
const analyzed = await tm.media.analyzeImage({ messageRef })
const parts = [analyzed && analyzed.description, analyzed && analyzed.ocrText]
.map((item) => String(item || '').trim())
.filter(Boolean)
if (parts.length > 0) {
return { text: `[图片内容] ${parts.join(';')}`, source: 'image_vision' }
}
} catch {
// 视觉理解失败时降级到本地 OCR。
}
}
if (hasGrantedPermission(tm, 'media.ocr')) {
try {
const ocr = await tm.media.ocrImage({ messageRef })
const ocrText = String((ocr && ocr.text) || '').trim()
if (ocrText) {
return { text: `[图片文字] ${ocrText}`, source: 'image_ocr' }
}
} catch {
// 本地 OCR 不可用时继续尝试可选视觉回退。
}
}
if (options.visionFallback === true && hasGrantedPermission(tm, 'ai.vision')) {
try {
const analyzed = await tm.media.analyzeImage({ messageRef })
const desc = String((analyzed && analyzed.description) || '').trim()
if (desc) return { text: `[图片内容] ${desc}`, source: 'image_vision' }
} catch {
return null
}
}
return null
}
if (event.type === 'voice') {
if (options.voiceTranscribeEnabled === false) return null
if (!hasGrantedPermission(tm, 'media.transcribe')) return null
try {
const result = await tm.media.transcribeVoice({
messageRef,
waitMs: Number(options.voiceWaitMs) > 0 ? Number(options.voiceWaitMs) : 12_000
})
if (result && result.state === 'transcribed' && String(result.transcript || '').trim()) {
return {
text: `[语音转文字] ${String(result.transcript).trim()}`,
source: 'voice_transcript'
}
}
} catch {
return null
}
}
return null
}
function registerFallbackHandlers(tm) {
if (!tm || !tm.page || typeof tm.page.onRequest !== 'function') return
const unavailable = async () => {
@@ -19,9 +99,9 @@ function registerFallbackHandlers(tm) {
tm.page.onRequest('testSend', unavailable)
}
module.exports = function activate(api) {
function activate(api) {
if (engine && typeof engine.activateBotRuntime === 'function') {
engine.activateBotRuntime(api)
engine.activateBotRuntime(api, { resolveIncomingMediaText })
} else {
registerFallbackHandlers(api)
}
@@ -29,3 +109,6 @@ module.exports = function activate(api) {
api.log.info('群聊机器人已启动')
}
}
activate.resolveIncomingMediaText = resolveIncomingMediaText
module.exports = activate
@@ -2,18 +2,22 @@
"manifestVersion": 1,
"id": "com.example.group-chat-bot",
"name": "群聊机器人 - 模板(如需使用请找授权你的人",
"version": "1.0.0",
"version": "1.1.0",
"apiVersion": "1",
"minAppVersion": "2.6.0",
"description": "支持多套群聊人格设定、群聊长期与短期记忆、自然接话节奏,并可结合 TraceMemo 音色随机回复文字或发送语音。",
"minAppVersion": "2.7.0",
"description": "支持多套群聊人格设定、群聊长期与短期记忆、按需解析图片与语音内容,并可结合 TraceMemo 音色随机回复文字或发送语音。",
"author": "TraceMemo Examples",
"permissions": [
"messages.subscribe",
"messages.query",
"media.ocr",
"media.transcribe",
"contacts.list",
"wechat.send.text",
"wechat.send.voice",
"ai.chat",
"ai.vision",
"notifications.create",
"storage"
],
"entrypoints": {
@@ -22,7 +26,9 @@
},
"subscriptions": {
"messageTypes": [
"text"
"text",
"image",
"voice"
],
"conversationIds": [],
"requireMentionMe": false,
@@ -34,6 +40,11 @@
"id": "settings",
"title": "群聊机器人设置"
}
]
],
"navigation": {
"label": "群聊机器人",
"icon": "bot",
"pageId": "settings"
}
}
}
@@ -0,0 +1,10 @@
# AI 晨报 (`com.example.morning-digest`)
TraceMemo 官方示例模板,完整演示扩展系统第二阶段全链路能力:
1. **分页消息查询**:使用 `tm.messages.query({ order: 'asc', cursor, limit })` 稳定翻页读取多群历史记录。
2. **按需媒体解析**:使用 `tm.media.batch` 按需触发图片本地 OCR、可选 AI 视觉理解与语音转写,自动复用主程序缓存。
3. **AI 总结**:经 `tm.ai.chat` 提炼今日重点、待办事项与各群速览。
4. **通用 HTML 长图渲染**:经 `tm.render.htmlToImage` 在隔离离线窗口中输出 PNG 长图至扩展私有目录。
5. **扩展通知中心 & 一级导航固定**:声明 `contributions.navigation` 支持固定到左侧一级导航;生成完成后通过 `tm.notifications.create` 写入去重通知。
6. **可选微信发送**:默认关闭自动发送,用户确认生成效果后可手动选择测试群聊发送长图,全链路仍经 TraceMemo Gateway 与授权校验。
@@ -0,0 +1,240 @@
'use strict'
/** AI 晨报后台:串联分页消息读取、批量媒体解析、AI 总结、离线长图渲染、通知中心与可选微信发送。 */
const {
DIGEST_CSS,
normalizeConfig,
selectMediaBatchItems,
buildDigestPromptMessages,
parseDigestSummary,
buildDigestHtml
} = require('../lib/digest-builder')
const CONFIG_KEY = 'config'
const LAST_DIGEST_KEY = 'lastDigest'
function localDateKey(timestamp = Date.now()) {
const date = new Date(timestamp)
const month = String(date.getMonth() + 1).padStart(2, '0')
const day = String(date.getDate()).padStart(2, '0')
return `${date.getFullYear()}-${month}-${day}`
}
async function queryAllGroupMessages(tm, conversationId, startTime, endTime, maxMessages) {
const collected = []
let cursor = undefined
const pageSize = Math.min(100, maxMessages)
for (let pageIndex = 0; pageIndex < 20 && collected.length < maxMessages; pageIndex += 1) {
const page = await tm.messages.query({
conversationId,
startTime,
endTime,
order: 'asc',
limit: Math.min(pageSize, maxMessages - collected.length),
...(cursor ? { cursor } : {})
})
const batch = Array.isArray(page && page.messages) ? page.messages : []
collected.push(...batch)
if (!page || !page.hasMore || !page.nextCursor) break
cursor = page.nextCursor
}
return collected
}
async function generateMorningDigest(tm, overrideConfig = null) {
const stored = await tm.storage.get(CONFIG_KEY).catch(() => null)
const config = normalizeConfig(overrideConfig ? { ...(stored || {}), ...overrideConfig } : stored)
if (config.groupIds.length === 0) {
throw new Error('请先在 AI 晨报配置页至少选择一个群聊')
}
const now = Date.now()
const startTime = now - config.windowHours * 60 * 60 * 1000
const dateLabel = localDateKey(now)
const grantedPermissions = (tm.extension && tm.extension.permissions) || []
const groupReports = []
let totalMessages = 0
let totalMediaResolved = 0
for (const groupId of config.groupIds) {
const messages = await queryAllGroupMessages(
tm,
groupId,
startTime,
now,
config.maxMessagesPerGroup
)
totalMessages += messages.length
const mediaByRef = new Map()
const batchItems = selectMediaBatchItems(messages, config, grantedPermissions)
if (batchItems.length > 0 && tm.media && typeof tm.media.batch === 'function') {
try {
const batchResult = await tm.media.batch({ items: batchItems, concurrency: 2 })
for (const entry of (batchResult && batchResult.results) || []) {
if (!entry || !entry.ok || !entry.result) continue
if (entry.op === 'ocrImage' && entry.result.text) {
mediaByRef.set(entry.messageRef, `[图片文字] ${entry.result.text}`)
totalMediaResolved += 1
} else if (entry.op === 'analyzeImage' && entry.result.description) {
mediaByRef.set(entry.messageRef, `[图片理解] ${entry.result.description}`)
totalMediaResolved += 1
} else if (
entry.op === 'transcribeVoice' &&
entry.result.state === 'transcribed' &&
entry.result.transcript
) {
mediaByRef.set(entry.messageRef, `[语音转文字] ${entry.result.transcript}`)
totalMediaResolved += 1
}
}
} catch (error) {
tm.log.warn(`AI 晨报:媒体按需解析降级跳过(${error instanceof Error ? error.message : '未知错误'})`)
}
}
const lines = []
for (const msg of messages) {
const sender = msg.senderName || (msg.isSelf ? '我' : '群友')
if (msg.text && msg.text.trim()) {
lines.push(`${sender}:${msg.text.trim().slice(0, 180)}`)
} else if (msg.messageRef && mediaByRef.has(msg.messageRef)) {
lines.push(`${sender}:${String(mediaByRef.get(msg.messageRef)).slice(0, 180)}`)
}
}
groupReports.push({
groupId,
name: config.groupNames[groupId] || groupId,
messageCount: messages.length,
mediaResolvedCount: mediaByRef.size,
lines
})
}
let summaryText = ''
if (grantedPermissions.includes('ai.chat')) {
const promptMessages = buildDigestPromptMessages({ dateLabel, groups: groupReports })
const aiResp = await tm.ai.chat(promptMessages)
summaryText = String((aiResp && aiResp.text) || '')
}
const summary = parseDigestSummary(summaryText, groupReports)
const html = buildDigestHtml({
dateLabel,
headline: summary.headline,
highlights: summary.highlights,
actionItems: summary.actionItems,
groupBriefs: summary.groupBriefs,
totalMessages,
totalMediaResolved,
groupCount: groupReports.length
})
const rendered = await tm.render.htmlToImage({
html,
css: DIGEST_CSS,
fileName: `morning-digest-${dateLabel}.png`,
width: config.renderWidth
})
const record = {
dateLabel,
generatedAt: now,
headline: summary.headline,
highlights: summary.highlights,
actionItems: summary.actionItems,
groupBriefs: summary.groupBriefs,
totalMessages,
totalMediaResolved,
groupCount: groupReports.length,
imagePath: rendered.path,
previewUrl: rendered.previewUrl || '',
width: rendered.width,
height: rendered.height,
pixelWidth: rendered.pixelWidth || rendered.width,
pixelHeight: rendered.pixelHeight || rendered.height,
deviceScaleFactor: rendered.deviceScaleFactor || 1,
bytes: rendered.bytes
}
await tm.storage.set(LAST_DIGEST_KEY, record)
if (grantedPermissions.includes('notifications.create')) {
try {
await tm.notifications.create({
title: `AI 晨报已生成 · ${dateLabel}`,
body: `${summary.headline}(${groupReports.length} 个群 / ${totalMessages} 条消息)`,
level: 'success',
dedupeKey: `morning-digest:${dateLabel}`,
pageId: 'digest'
})
} catch (error) {
tm.log.warn(`AI 晨报:通知写入失败(${error instanceof Error ? error.message : '未知错误'})`)
}
}
let sentToWechat = false
if (
config.autoSendWechat &&
config.wechatTargetGroupId &&
grantedPermissions.includes('wechat.send.image')
) {
await tm.wechat.send({
type: 'image',
to: config.wechatTargetGroupId,
path: rendered.path,
dedupeKey: `morning-digest-send:${dateLabel}:${config.wechatTargetGroupId}`
})
sentToWechat = true
}
tm.log.info(
`AI 晨报已生成:${groupReports.length} 个群,${totalMessages} 条消息,解析媒体 ${totalMediaResolved} 条`
)
return { ...record, sentToWechat }
}
module.exports = function activate(tm) {
if (tm.page && typeof tm.page.onRequest === 'function') {
tm.page.onRequest('generateDigest', async (params) => {
return generateMorningDigest(tm, params && typeof params === 'object' ? params : null)
})
tm.page.onRequest('sendLastDigest', async (params) => {
const target = String((params && params.to) || '').trim()
if (!target) throw new Error('请先选择发送目标群聊')
const last = await tm.storage.get(LAST_DIGEST_KEY)
if (!last || !last.imagePath) throw new Error('请先生成今日晨报长图')
const sent = await tm.wechat.send({
type: 'image',
to: target,
path: last.imagePath,
dedupeKey: `morning-digest-manual:${last.dateLabel}:${target}:${Date.now()}`
})
return { ok: true, actionId: sent.actionId, to: target }
})
}
if (
tm.automation &&
typeof tm.automation.registerAction === 'function' &&
tm.extension &&
Array.isArray(tm.extension.permissions) &&
tm.extension.permissions.includes('automation.action')
) {
tm.automation.registerAction({
id: 'morning-digest.generate',
title: '生成 AI 晨报',
description: '汇总已配置群聊消息并渲染晨报长图',
handler: async () => {
const result = await generateMorningDigest(tm)
return { success: true, output: { headline: result.headline, imagePath: result.imagePath } }
}
})
}
tm.log.info('AI 晨报已启动')
}
@@ -0,0 +1,285 @@
'use strict'
/** AI 晨报纯逻辑模块:配置收敛、媒体批次编排、AI 摘要提示词与严格静态 HTML 渲染构建。 */
const DEFAULT_CONFIG = {
groupIds: [],
groupNames: {},
windowHours: 24,
maxMessagesPerGroup: 300,
enableImageOcr: true,
enableImageVision: false,
enableVoiceTranscribe: true,
maxMediaPerGroup: 6,
renderWidth: 460,
/** 默认禁止自动发微信,需用户显式开启或手动点击发送。 */
autoSendWechat: false,
wechatTargetGroupId: ''
}
function clampInt(value, fallback, min, max) {
const num = Number(value)
if (!Number.isFinite(num)) return fallback
return Math.max(min, Math.min(max, Math.round(num)))
}
function normalizeConfig(raw) {
const src = raw && typeof raw === 'object' && !Array.isArray(raw) ? raw : {}
const groupIds = Array.isArray(src.groupIds)
? Array.from(
new Set(
src.groupIds
.map((item) => String(item || '').trim())
.filter(Boolean)
.slice(0, 10)
)
)
: []
const groupNames = {}
if (src.groupNames && typeof src.groupNames === 'object' && !Array.isArray(src.groupNames)) {
for (const [id, name] of Object.entries(src.groupNames)) {
const cleanId = String(id || '').trim()
const cleanName = String(name || '').trim().slice(0, 64)
if (cleanId && cleanName) groupNames[cleanId] = cleanName
}
}
return {
groupIds,
groupNames,
windowHours: clampInt(src.windowHours, DEFAULT_CONFIG.windowHours, 1, 168),
maxMessagesPerGroup: clampInt(
src.maxMessagesPerGroup,
DEFAULT_CONFIG.maxMessagesPerGroup,
20,
1000
),
enableImageOcr: src.enableImageOcr !== false,
enableImageVision: src.enableImageVision === true,
enableVoiceTranscribe: src.enableVoiceTranscribe !== false,
maxMediaPerGroup: clampInt(src.maxMediaPerGroup, DEFAULT_CONFIG.maxMediaPerGroup, 0, 15),
renderWidth: clampInt(src.renderWidth, DEFAULT_CONFIG.renderWidth, 320, 960),
autoSendWechat: src.autoSendWechat === true,
wechatTargetGroupId: String(src.wechatTargetGroupId || '').trim().slice(0, 128)
}
}
function escapeHtml(value) {
return String(value ?? '')
.replace(/&/g, '&amp;')
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;')
.replace(/"/g, '&quot;')
.replace(/'/g, '&#39;')
}
/** 挑选待按需解析的图片与语音消息引用,单群总量受限以避免慢任务拖垮晨报生成。 */
function selectMediaBatchItems(messages, config, grantedPermissions = []) {
const limit = clampInt(config.maxMediaPerGroup, 6, 0, 15)
if (limit === 0 || !Array.isArray(messages) || messages.length === 0) return []
const perms = new Set(Array.isArray(grantedPermissions) ? grantedPermissions : [])
const items = []
const recent = [...messages].reverse()
for (const msg of recent) {
if (items.length >= limit) break
const messageRef = String((msg && msg.messageRef) || '').trim()
if (!messageRef) continue
if (msg.type === 'image') {
if (config.enableImageVision && perms.has('ai.vision')) {
items.push({ op: 'analyzeImage', messageRef })
} else if (config.enableImageOcr && perms.has('media.ocr')) {
items.push({ op: 'ocrImage', messageRef })
}
} else if (msg.type === 'voice') {
if (config.enableVoiceTranscribe && perms.has('media.transcribe')) {
items.push({ op: 'transcribeVoice', messageRef, options: { waitMs: 10_000 } })
}
}
}
return items
}
function buildDigestPromptMessages(input) {
const dateLabel = String(input.dateLabel || '').trim() || new Date().toISOString().slice(0, 10)
const sections = (input.groups || []).map((group) => {
const lines = (group.lines || []).slice(0, 120).join('\n')
return `【群聊:${group.name}】(共 ${group.messageCount} 条消息,解析媒体 ${group.mediaResolvedCount} 条)\n${lines || '(暂无有效内容)'}`
})
return [
{
role: 'system',
content: [
'你是一名简洁高效的中文晨报编辑,负责根据多个微信群最近一天的聊天记录与图片/语音解析结果整理一份结构化「AI 晨报」。',
'请严格输出纯 JSON,不要包含 Markdown 代码块包裹:',
'{"headline":"一句话总览(<=28字)","highlights":["重点1","重点2"],"actionItems":["待办或约定1"],"groupBriefs":[{"groupName":"群名","summary":"该群简述(<=80字)"}]}'
].join('\n')
},
{
role: 'user',
content: `日期:${dateLabel}\n\n${sections.join('\n\n')}`
}
]
}
function parseDigestSummary(rawText, fallbackGroups = []) {
const cleaned = String(rawText || '')
.trim()
.replace(/^```(?:json)?\s*/i, '')
.replace(/\s*```$/i, '')
.trim()
try {
const parsed = JSON.parse(cleaned)
if (parsed && typeof parsed === 'object') {
const headline = String(parsed.headline || '今日群聊晨报').trim().slice(0, 60)
const highlights = Array.isArray(parsed.highlights)
? parsed.highlights.map((x) => String(x || '').trim()).filter(Boolean).slice(0, 6)
: []
const actionItems = Array.isArray(parsed.actionItems)
? parsed.actionItems.map((x) => String(x || '').trim()).filter(Boolean).slice(0, 6)
: []
const groupBriefs = Array.isArray(parsed.groupBriefs)
? parsed.groupBriefs
.filter((item) => item && typeof item === 'object')
.map((item) => ({
groupName: String(item.groupName || '群聊').trim().slice(0, 48),
summary: String(item.summary || '').trim().slice(0, 200)
}))
.filter((item) => item.summary)
.slice(0, 10)
: []
if (headline || highlights.length > 0 || groupBriefs.length > 0) {
return { headline, highlights, actionItems, groupBriefs }
}
}
} catch {
// 非 JSON 文本回退为单条摘要展示,不中断渲染。
}
return {
headline: '今日群聊晨报',
highlights: cleaned ? [cleaned.slice(0, 240)] : ['最近周期内暂无重点讨论'],
actionItems: [],
groupBriefs: fallbackGroups.map((g) => ({
groupName: g.name,
summary: `共采集 ${g.messageCount} 条消息,解析媒体 ${g.mediaResolvedCount} 条。`
}))
}
}
const DIGEST_CSS = `
* { box-sizing: border-box; }
body {
margin: 0;
padding: 20px;
background: #f4f6f9;
color: #18212f;
font-family: -apple-system, BlinkMacSystemFont, "PingFang SC", "Microsoft YaHei", sans-serif;
}
.digest-card {
background: #ffffff;
border-radius: 16px;
padding: 24px;
border: 1px solid #e5e9f0;
}
.digest-kicker {
font-size: 12px;
letter-spacing: 0.08em;
color: #2563eb;
font-weight: 700;
margin-bottom: 6px;
}
.digest-title {
margin: 0 0 8px;
font-size: 22px;
line-height: 1.35;
}
.digest-meta {
font-size: 12px;
color: #64748b;
margin-bottom: 18px;
}
.digest-section {
margin-top: 18px;
padding-top: 16px;
border-top: 1px solid #edf0f5;
}
.digest-section h2 {
margin: 0 0 10px;
font-size: 15px;
color: #0f172a;
}
.digest-list {
margin: 0;
padding-left: 18px;
line-height: 1.65;
font-size: 14px;
}
.digest-group {
background: #f8fafc;
border-radius: 10px;
padding: 12px 14px;
margin-bottom: 10px;
}
.digest-group-name {
font-size: 13px;
font-weight: 700;
color: #1e293b;
margin-bottom: 4px;
}
.digest-group-summary {
margin: 0;
font-size: 13px;
line-height: 1.6;
color: #334155;
}
.digest-footer {
margin-top: 18px;
padding-top: 12px;
border-top: 1px dashed #e2e8f0;
font-size: 11px;
color: #94a3b8;
}
`
/** 构建纯静态、无脚本、无外链的晨报 HTML,满足 HtmlRenderService 的严格安全校验。 */
function buildDigestHtml(data) {
const dateLabel = escapeHtml(data.dateLabel || '')
const headline = escapeHtml(data.headline || '今日群聊晨报')
const totalMessages = Number(data.totalMessages) || 0
const totalMedia = Number(data.totalMediaResolved) || 0
const groupCount = Number(data.groupCount) || 0
const highlightsHtml = (data.highlights || [])
.map((item) => `<li>${escapeHtml(item)}</li>`)
.join('')
const actionsHtml = (data.actionItems || [])
.map((item) => `<li>${escapeHtml(item)}</li>`)
.join('')
const briefsHtml = (data.groupBriefs || [])
.map(
(item) =>
`<div class="digest-group"><div class="digest-group-name">${escapeHtml(item.groupName)}</div><p class="digest-group-summary">${escapeHtml(item.summary)}</p></div>`
)
.join('')
return `<main class="digest-card">
<div class="digest-kicker">TRACEMEMO AI 晨报 · ${dateLabel}</div>
<h1 class="digest-title">${headline}</h1>
<div class="digest-meta">覆盖 ${groupCount} 个群聊 · 采样 ${totalMessages} 条消息 · 解析 ${totalMedia} 条图片/语音</div>
${highlightsHtml ? `<section class="digest-section"><h2>今日重点</h2><ul class="digest-list">${highlightsHtml}</ul></section>` : ''}
${actionsHtml ? `<section class="digest-section"><h2>待办与约定</h2><ul class="digest-list">${actionsHtml}</ul></section>` : ''}
${briefsHtml ? `<section class="digest-section"><h2>各群速览</h2>${briefsHtml}</section>` : ''}
<footer class="digest-footer">由 TraceMemo 扩展「AI 晨报」离线生成</footer>
</main>`
}
module.exports = {
DEFAULT_CONFIG,
DIGEST_CSS,
normalizeConfig,
escapeHtml,
selectMediaBatchItems,
buildDigestPromptMessages,
parseDigestSummary,
buildDigestHtml
}
@@ -0,0 +1,48 @@
{
"manifestVersion": 1,
"id": "com.example.morning-digest",
"name": "AI 晨报",
"version": "1.0.0",
"apiVersion": "1",
"minAppVersion": "2.7.0",
"description": "分页拉取指定群聊最近消息,按需解析图片与语音并经 AI 总结,离线渲染为晨报 PNG 长图、发送应用内通知,并支持人工确认后可选发送到微信。",
"author": "TraceMemo Examples",
"permissions": [
"messages.query",
"media.ocr",
"media.transcribe",
"ai.chat",
"ai.vision",
"render.html",
"notifications.create",
"contacts.list",
"wechat.send.image",
"automation.action",
"storage"
],
"entrypoints": {
"page": "ui/index.html",
"background": "background/index.js"
},
"contributions": {
"pages": [
{
"id": "digest",
"title": "AI 晨报"
}
],
"navigation": {
"label": "AI 晨报",
"icon": "digest",
"pageId": "digest",
"order": 10
},
"automationActions": [
{
"id": "morning-digest.generate",
"title": "生成 AI 晨报",
"description": "汇总已配置群聊的文字、图片与语音消息并渲染晨报长图"
}
]
}
}
@@ -0,0 +1,56 @@
import test from 'node:test'
import assert from 'node:assert/strict'
import { createRequire } from 'node:module'
const require = createRequire(import.meta.url)
const {
normalizeConfig,
selectMediaBatchItems,
parseDigestSummary,
buildDigestHtml
} = require('../lib/digest-builder.js')
test('normalizeConfig 默认关闭自动发微信并收敛数值边界', () => {
const cfg = normalizeConfig({ windowHours: 999, renderWidth: 100, groupIds: ['g1@chatroom', 'g1@chatroom'] })
assert.equal(cfg.autoSendWechat, false)
assert.equal(cfg.windowHours, 168)
assert.equal(cfg.renderWidth, 320)
assert.deepEqual(cfg.groupIds, ['g1@chatroom'])
})
test('selectMediaBatchItems 按权限筛选图片 OCR/视觉与语音转写批次', () => {
const messages = [
{ type: 'text', messageRef: 'ref-1', text: '早安' },
{ type: 'image', messageRef: 'ref-img' },
{ type: 'voice', messageRef: 'ref-voice' }
]
const items = selectMediaBatchItems(
messages,
normalizeConfig({ enableImageOcr: true, enableVoiceTranscribe: true, maxMediaPerGroup: 5 }),
['media.ocr', 'media.transcribe']
)
assert.equal(items.length, 2)
assert.equal(items[0].op, 'transcribeVoice')
assert.equal(items[1].op, 'ocrImage')
})
test('buildDigestHtml 转义 HTML 特殊字符且不包含脚本或外链', () => {
const summary = parseDigestSummary(
JSON.stringify({
headline: '今日<script>alert(1)</script>焦点',
highlights: ['项目评审通过'],
actionItems: ['张三跟进上线'],
groupBriefs: [{ groupName: '产品测试群', summary: '讨论了发布排期' }]
})
)
const html = buildDigestHtml({
dateLabel: '2026-12-01',
...summary,
totalMessages: 42,
totalMediaResolved: 3,
groupCount: 1
})
assert.equal(/<script/i.test(html), false)
assert.equal(html.includes('&lt;script&gt;'), true)
assert.equal(html.includes('产品测试群'), true)
})
@@ -0,0 +1,251 @@
'use strict'
const EXTENSION_ID = 'com.example.morning-digest'
const PAGE_SOURCE = 'tracememo-extension-page'
const HOST_SOURCE = 'tracememo-extension-host'
const CONFIG_KEY = 'config'
const LAST_DIGEST_KEY = 'lastDigest'
const pending = new Map()
let seq = 0
let groups = []
let lastDigest = null
let config = {
groupIds: [],
groupNames: {},
windowHours: 24,
enableImageOcr: true,
enableImageVision: false,
enableVoiceTranscribe: true,
maxMediaPerGroup: 6,
renderWidth: 460,
autoSendWechat: false,
wechatTargetGroupId: ''
}
function callHost(method, params) {
return new Promise((resolve, reject) => {
const requestId = `req-${++seq}`
pending.set(requestId, { resolve, reject })
window.parent.postMessage(
{ source: PAGE_SOURCE, extensionId: EXTENSION_ID, requestId, method, params: params || {} },
'*'
)
})
}
window.addEventListener('message', (event) => {
const data = event.data
if (!data || data.source !== HOST_SOURCE) return
const item = pending.get(data.requestId)
if (!item) return
pending.delete(data.requestId)
if (data.ok) item.resolve(data.result)
else item.reject(new Error((data.error && data.error.message) || '请求失败'))
})
function setBanner(text, tone) {
const el = document.getElementById('banner')
el.textContent = text
el.dataset.tone = tone || ''
}
function renderGroupList() {
const keyword = document.getElementById('group-search').value.trim().toLowerCase()
const container = document.getElementById('group-list')
container.textContent = ''
const filtered = groups.filter((g) => !keyword || g.name.toLowerCase().includes(keyword))
if (filtered.length === 0) {
const empty = document.createElement('div')
empty.className = 'group-item'
empty.textContent = groups.length === 0 ? '暂无可选群聊(请先连接微信数据库)' : '没有匹配的群聊'
container.appendChild(empty)
return
}
const selectedSet = new Set(config.groupIds)
for (const group of filtered) {
const label = document.createElement('label')
label.className = 'group-item'
const input = document.createElement('input')
input.type = 'checkbox'
input.checked = selectedSet.has(group.id)
input.addEventListener('change', () => {
if (input.checked) {
if (!config.groupIds.includes(group.id) && config.groupIds.length < 10) {
config.groupIds.push(group.id)
config.groupNames[group.id] = group.name
} else {
input.checked = false
}
} else {
config.groupIds = config.groupIds.filter((id) => id !== group.id)
}
})
const span = document.createElement('span')
span.textContent = group.name
label.appendChild(input)
label.appendChild(span)
container.appendChild(label)
}
}
function renderTargetSelect() {
const select = document.getElementById('wechat-target')
select.textContent = ''
const none = document.createElement('option')
none.value = ''
none.textContent = '不自动发送'
select.appendChild(none)
for (const group of groups) {
const opt = document.createElement('option')
opt.value = group.id
opt.textContent = group.name
select.appendChild(opt)
}
select.value = config.wechatTargetGroupId || ''
}
function syncForm() {
document.getElementById('window-hours').value = String(config.windowHours || 24)
document.getElementById('enable-ocr').checked = config.enableImageOcr !== false
document.getElementById('enable-vision').checked = config.enableImageVision === true
document.getElementById('enable-voice').checked = config.enableVoiceTranscribe !== false
document.getElementById('max-media').value = String(config.maxMediaPerGroup ?? 6)
document.getElementById('render-width').value = String(config.renderWidth ?? 460)
document.getElementById('auto-send').checked = config.autoSendWechat === true
renderGroupList()
renderTargetSelect()
}
function collectForm() {
config.windowHours = Number(document.getElementById('window-hours').value) || 24
config.enableImageOcr = document.getElementById('enable-ocr').checked
config.enableImageVision = document.getElementById('enable-vision').checked
config.enableVoiceTranscribe = document.getElementById('enable-voice').checked
config.maxMediaPerGroup = Number(document.getElementById('max-media').value) || 0
config.renderWidth = Number(document.getElementById('render-width').value) || 460
config.wechatTargetGroupId = document.getElementById('wechat-target').value
config.autoSendWechat = document.getElementById('auto-send').checked
}
function renderDigestResult(record) {
const el = document.getElementById('digest-result')
const sendBtn = document.getElementById('send-last-btn')
const previewWrap = document.getElementById('digest-preview-wrap')
const previewImg = document.getElementById('digest-preview-img')
const previewCaption = document.getElementById('digest-preview-caption')
if (!record || !record.headline) {
el.className = 'result-body empty'
el.textContent = '尚未生成晨报,勾选群聊后点击右上角「立即生成今日晨报」。'
previewWrap.hidden = true
previewImg.removeAttribute('src')
sendBtn.disabled = true
return
}
el.className = 'result-body'
const pixelMeta =
record.pixelWidth && record.pixelHeight
? `(实际像素 ${record.pixelWidth}×${record.pixelHeight}px,${record.deviceScaleFactor || 1}x)`
: ''
const lines = [
`【标题】${record.headline}(${record.dateLabel})`,
`【统计】覆盖 ${record.groupCount} 个群 · ${record.totalMessages} 条消息 · 解析 ${record.totalMediaResolved} 条媒体`,
`【长图】逻辑 ${record.width}×${record.height}px${pixelMeta} · ${(Number(record.bytes || 0) / 1024).toFixed(1)}KB`,
`【输出文件】${record.imagePath}`
]
if (Array.isArray(record.highlights) && record.highlights.length > 0) {
lines.push('', '【今日重点】', ...record.highlights.map((item, idx) => `${idx + 1}. ${item}`))
}
if (Array.isArray(record.actionItems) && record.actionItems.length > 0) {
lines.push('', '【待办与约定】', ...record.actionItems.map((item, idx) => `${idx + 1}. ${item}`))
}
el.textContent = lines.join('\n')
if (record.previewUrl) {
previewWrap.hidden = false
previewCaption.textContent = `长图实时预览(受控扩展私有媒体协议):${record.previewUrl}`
previewImg.src = `${record.previewUrl}?t=${record.generatedAt || Date.now()}`
} else {
previewWrap.hidden = true
previewImg.removeAttribute('src')
}
sendBtn.disabled = false
}
document.getElementById('group-search').addEventListener('input', renderGroupList)
document.getElementById('save-btn').addEventListener('click', async () => {
collectForm()
try {
await callHost('storage.set', { key: CONFIG_KEY, value: config })
setBanner('配置已保存。', 'ok')
} catch (error) {
setBanner(`保存失败:${error.message}`, 'error')
}
})
document.getElementById('generate-btn').addEventListener('click', async () => {
collectForm()
if (config.groupIds.length === 0) {
setBanner('请先勾选至少一个群聊。', 'error')
return
}
const btn = document.getElementById('generate-btn')
btn.disabled = true
setBanner('正在分页拉取消息、按需解析图片/语音并离线渲染长图…')
try {
await callHost('storage.set', { key: CONFIG_KEY, value: config })
const result = await callHost('extension.request', {
method: 'generateDigest',
params: config
})
lastDigest = result
renderDigestResult(result)
setBanner(
result.sentToWechat
? '今日晨报已生成、写入通知中心并已发送至目标群聊。'
: '今日晨报已生成并写入扩展通知中心。',
'ok'
)
} catch (error) {
setBanner(`生成失败:${error.message}`, 'error')
} finally {
btn.disabled = false
}
})
document.getElementById('send-last-btn').addEventListener('click', async () => {
collectForm()
if (!config.wechatTargetGroupId) {
setBanner('请先在「发送目标群聊」下拉框中选择一个群聊。', 'error')
return
}
try {
await callHost('extension.request', {
method: 'sendLastDigest',
params: { to: config.wechatTargetGroupId }
})
setBanner('已通过 TraceMemo Gateway 发送晨报长图。', 'ok')
} catch (error) {
setBanner(`发送失败:${error.message}`, 'error')
}
})
async function init() {
const [savedConfig, savedDigest, roster] = await Promise.all([
callHost('storage.get', { key: CONFIG_KEY }).catch(() => null),
callHost('storage.get', { key: LAST_DIGEST_KEY }).catch(() => null),
callHost('contacts.listGroups', {}).catch(() => ({ groups: [] }))
])
if (savedConfig && typeof savedConfig === 'object') {
config = { ...config, ...savedConfig }
}
groups = Array.isArray(roster && roster.groups) ? roster.groups : []
lastDigest = savedDigest
syncForm()
renderDigestResult(lastDigest)
setBanner('AI 晨报已就绪。建议先点击「立即生成今日晨报」离线预览。')
}
init().catch((error) => {
setBanner(`初始化失败:${error.message}`, 'error')
})
@@ -0,0 +1,96 @@
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>AI 晨报</title>
<link rel="stylesheet" href="./style.css">
</head>
<body>
<div class="page">
<header class="hero">
<div>
<div class="kicker">TraceMemo 官方模板 · com.example.morning-digest</div>
<h1>AI 晨报</h1>
<p class="subtitle">分页拉取群聊记录、按需解析图片与语音、AI 总结并离线生成 PNG 长图,支持通知提醒与可选微信发送。</p>
</div>
<div class="hero-actions">
<button id="generate-btn" class="btn primary" type="button">立即生成今日晨报</button>
<button id="save-btn" class="btn" type="button">保存配置</button>
</div>
</header>
<div id="banner" class="banner" role="status">正在加载配置与群聊列表…</div>
<div class="grid">
<section class="card">
<h2>1. 选择采集群聊与时间窗</h2>
<div class="field">
<label for="window-hours">采集范围(小时)</label>
<select id="window-hours">
<option value="24">最近 24 小时</option>
<option value="48">最近 48 小时</option>
<option value="72">最近 72 小时</option>
</select>
</div>
<div class="field">
<label for="group-search">搜索并勾选目标群聊(最多 10 个)</label>
<input id="group-search" type="search" placeholder="按群名筛选…">
<div id="group-list" class="group-list"></div>
</div>
</section>
<section class="card">
<h2>2. 按需媒体解析与长图渲染</h2>
<label class="check-row">
<input id="enable-ocr" type="checkbox" checked>
<span>图片本地 OCR 文字识别(纯本地,优先复用索引缓存)</span>
</label>
<label class="check-row">
<input id="enable-vision" type="checkbox">
<span>图片 AI 视觉理解(需配置视觉模型)</span>
</label>
<label class="check-row">
<input id="enable-voice" type="checkbox" checked>
<span>语音本地转文字(复用本机语音转写服务)</span>
</label>
<div class="field-row">
<div class="field">
<label for="max-media">每群最多解析媒体数</label>
<input id="max-media" type="number" min="0" max="15" value="6">
</div>
<div class="field">
<label for="render-width">长图宽度(px)</label>
<input id="render-width" type="number" min="320" max="960" value="460">
</div>
</div>
<h3>3. 可选微信发送(默认关闭)</h3>
<div class="field">
<label for="wechat-target">发送目标群聊</label>
<select id="wechat-target">
<option value="">不自动发送</option>
</select>
</div>
<label class="check-row">
<input id="auto-send" type="checkbox">
<span>生成后自动发送晨报长图到所选目标群(默认关闭,建议先预览)</span>
</label>
</section>
</div>
<section class="card result-card">
<div class="result-head">
<h2>最近一次晨报结果</h2>
<button id="send-last-btn" class="btn" type="button" disabled>手动发送长图到目标群</button>
</div>
<div id="digest-result" class="result-body empty">尚未生成晨报,勾选群聊后点击右上角「立即生成今日晨报」。</div>
<div id="digest-preview-wrap" class="preview-wrap" hidden>
<div class="preview-caption" id="digest-preview-caption"></div>
<img id="digest-preview-img" class="preview-img" alt="晨报长图预览">
</div>
</section>
</div>
<script src="./app.js"></script>
</body>
</html>
@@ -0,0 +1,225 @@
* {
box-sizing: border-box;
}
body {
margin: 0;
padding: 24px;
font-family: -apple-system, BlinkMacSystemFont, "PingFang SC", "Microsoft YaHei", sans-serif;
background: #f5f7fa;
color: #18212f;
}
.page {
max-width: 960px;
margin: 0 auto;
display: flex;
flex-direction: column;
gap: 16px;
}
.hero {
display: flex;
justify-content: space-between;
align-items: flex-start;
gap: 16px;
background: #ffffff;
border: 1px solid #e5e9f0;
border-radius: 14px;
padding: 20px;
}
.kicker {
font-size: 12px;
color: #2563eb;
font-weight: 600;
margin-bottom: 4px;
}
.hero h1 {
margin: 0 0 6px;
font-size: 22px;
}
.subtitle {
margin: 0;
font-size: 13px;
color: #64748b;
}
.hero-actions {
display: flex;
gap: 8px;
flex-shrink: 0;
}
.btn {
padding: 8px 14px;
border-radius: 8px;
border: 1px solid #cbd5e1;
background: #ffffff;
color: #1e293b;
font-size: 13px;
cursor: pointer;
}
.btn.primary {
background: #2563eb;
border-color: #2563eb;
color: #ffffff;
}
.btn:disabled {
opacity: 0.5;
cursor: not-allowed;
}
.banner {
padding: 10px 14px;
border-radius: 10px;
font-size: 13px;
background: #eff6ff;
color: #1d4ed8;
border: 1px solid #bfdbfe;
}
.banner[data-tone="error"] {
background: #fef2f2;
color: #b91c1c;
border-color: #fecaca;
}
.banner[data-tone="ok"] {
background: #f0fdf4;
color: #15803d;
border-color: #bbf7d0;
}
.grid {
display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr));
gap: 16px;
}
.card {
background: #ffffff;
border: 1px solid #e5e9f0;
border-radius: 14px;
padding: 18px;
display: flex;
flex-direction: column;
gap: 12px;
}
.card h2 {
margin: 0;
font-size: 15px;
}
.card h3 {
margin: 8px 0 0;
font-size: 14px;
}
.field {
display: flex;
flex-direction: column;
gap: 6px;
font-size: 13px;
}
.field input,
.field select {
padding: 8px 10px;
border-radius: 8px;
border: 1px solid #cbd5e1;
font-size: 13px;
}
.field-row {
display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr));
gap: 10px;
}
.check-row {
display: flex;
align-items: center;
gap: 8px;
font-size: 13px;
cursor: pointer;
}
.group-list {
max-height: 220px;
overflow: auto;
border: 1px solid #e2e8f0;
border-radius: 8px;
padding: 6px;
display: flex;
flex-direction: column;
gap: 4px;
}
.group-item {
display: flex;
align-items: center;
gap: 8px;
padding: 6px 8px;
border-radius: 6px;
font-size: 13px;
cursor: pointer;
}
.group-item:hover {
background: #f8fafc;
}
.result-head {
display: flex;
justify-content: space-between;
align-items: center;
gap: 12px;
}
.result-body {
font-size: 13px;
line-height: 1.65;
white-space: pre-wrap;
background: #f8fafc;
border-radius: 10px;
padding: 14px;
}
.result-body.empty {
color: #64748b;
}
.preview-wrap {
margin-top: 14px;
padding: 12px;
border-radius: 12px;
background: #f8fafc;
border: 1px solid #e2e8f0;
display: flex;
flex-direction: column;
align-items: center;
gap: 8px;
}
.preview-caption {
font-size: 12px;
color: #64748b;
word-break: break-all;
align-self: flex-start;
}
.preview-img {
max-width: 100%;
width: 460px;
height: auto;
border-radius: 10px;
border: 1px solid #cbd5e1;
box-shadow: 0 6px 20px rgba(15, 23, 42, 0.08);
background: #ffffff;
}
+8
View File
@@ -17,6 +17,10 @@
"sha256": "eb672f076710619dc363756d854319a8ded9b8f6a4833c258c1493c57bb89629",
"bytes": 25231
},
"group-chat-bot@1.1.0": {
"sha256": "be1fb28a2b8a20c95fccd19f6e2229f7166abfffefcf120309febcf3c882f437",
"bytes": 25947
},
"keyword-bot@1.0.0": {
"sha256": "3d8e5453e7ae6de7e29c16eb3c9e718a98bae27e9ed2edfd10399fb158e1c87d",
"bytes": 19121
@@ -24,6 +28,10 @@
"keyword-bot@1.0.1": {
"sha256": "ae379a10dac553b60cc8c823186734d917b604b6dff27e2e7d2d62f5cf5e4d41",
"bytes": 19517
},
"morning-digest@1.0.0": {
"sha256": "3336d3c7739aad0d40919546ca7884581aaaf7e3487db5428041d6bc0f6bd992",
"bytes": 14556
}
}
}
+239 -9
View File
@@ -1,4 +1,4 @@
/** TraceMemo 扩展 SDK v1:仅类型定义,运行期由宿主注入全局 tm。 */
/** TraceMemo 扩展 SDK v1(兼容扩展):仅类型定义,运行期由宿主注入全局 tm。 */
export type ExtensionMessageType =
| 'text'
@@ -11,9 +11,23 @@ export type ExtensionMessageType =
| 'system'
| 'other'
export type ExtensionNavigationIcon =
| 'spark'
| 'bot'
| 'digest'
| 'bell'
| 'media'
| 'puzzle'
| 'compass'
| 'message'
export type ExtensionNotificationLevel = 'info' | 'success' | 'warning' | 'error'
export interface TraceMemoMessageEvent {
/** 同一条微信消息稳定不变:`message:<sha1(sessionId:localId)>`。 */
eventId: string
/** 跨实时事件与历史查询统一的不透明消息引用,可直接传给 tm.media.* 接口。 */
messageRef: string
accountId: string
conversationId: string
messageId: string
@@ -31,6 +45,8 @@ export interface TraceMemoMessageEvent {
export interface TraceMemoQueriedMessage {
messageId: string
/** 跨实时事件与历史查询统一的不透明消息引用,可直接传给 tm.media.* 接口。 */
messageRef: string
conversationId: string
senderId?: string
senderName?: string
@@ -41,6 +57,175 @@ export interface TraceMemoQueriedMessage {
timestamp: number
}
export interface TraceMemoMessagesQueryRequest {
conversationId: string
/** epoch 毫秒;默认最近 24 小时。 */
startTime?: number
/** epoch 毫秒;默认现在。 */
endTime?: number
limit?: number
/** 上一页返回的 opaque 游标;同时间戳多条消息不漏不重。 */
cursor?: string
order?: 'asc' | 'desc'
types?: ExtensionMessageType[]
}
export interface TraceMemoMessagesQueryResult {
messages: TraceMemoQueriedMessage[]
nextCursor?: string
hasMore: boolean
}
export interface TraceMemoMediaReadImageResult {
messageRef: string
mimeType: string
bytes: number
sha256: string
/** 扩展私有数据目录内的可读副本路径。 */
path: string
/** 扩展沙箱页面可直接加载的受控只读预览 URL。 */
previewUrl?: string
quality: 'original' | 'thumbnail'
cached: boolean
}
export interface TraceMemoMediaReadVoiceResult {
messageRef: string
mimeType: 'audio/wav'
bytes: number
sha256: string
durationMs?: number
path: string
previewUrl?: string
cached: boolean
}
export interface TraceMemoMediaReadVideoResult {
messageRef: string
mimeType: 'video/mp4'
bytes: number
sha256: string
path: string
previewUrl?: string
posterPath?: string
posterPreviewUrl?: string
durationMs?: number
width?: number
height?: number
cached: boolean
}
export interface TraceMemoMediaOcrImageResult {
messageRef: string
text: string
language: string | null
engine: string
cached: boolean
}
export interface TraceMemoMediaTranscribeVoiceResult {
messageRef: string
state: 'transcribed' | 'pending' | 'failed'
transcript?: string
durationMs?: number
cached: boolean
error?: string
}
export interface TraceMemoMediaAnalyzeImageResult {
messageRef: string
description: string
ocrText?: string
tags?: string[]
category?: string
model?: string
cached: boolean
}
export type TraceMemoMediaBatchOperation =
| 'readImage'
| 'readVoice'
| 'readVideo'
| 'ocrImage'
| 'transcribeVoice'
| 'analyzeImage'
export interface TraceMemoMediaBatchItem {
op: TraceMemoMediaBatchOperation
messageRef: string
options?: Record<string, unknown>
}
export interface TraceMemoMediaBatchItemResult {
index: number
op: TraceMemoMediaBatchOperation
messageRef: string
ok: boolean
result?:
| TraceMemoMediaReadImageResult
| TraceMemoMediaReadVoiceResult
| TraceMemoMediaReadVideoResult
| TraceMemoMediaOcrImageResult
| TraceMemoMediaTranscribeVoiceResult
| TraceMemoMediaAnalyzeImageResult
error?: { code: string; message: string }
}
export interface TraceMemoRenderHtmlRequest {
html: string
css?: string
/** 可选相对文件名(输出到扩展私有目录的 rendered/ 下)。 */
fileName?: string
width?: number
maxHeight?: number
backgroundColor?: string
timeoutMs?: number
}
export interface TraceMemoRenderHtmlResult {
path: string
/** 扩展沙箱页面可直接加载的受控只读预览 URL。 */
previewUrl?: string
width: number
height: number
pixelWidth?: number
pixelHeight?: number
deviceScaleFactor?: number
bytes: number
mimeType: 'image/png'
sha256: string
}
export interface TraceMemoNotificationCreateRequest {
title: string
body?: string
level?: ExtensionNotificationLevel
/** 扩展内去重键;相同键更新既有通知而不重复叠加未读数。 */
dedupeKey?: string
/** 点击通知后跳转的本扩展页面 id。 */
pageId?: string
}
export interface TraceMemoNotificationCreateResult {
id: string
deduped: boolean
createdAt: number
}
export interface TraceMemoNotificationItem {
id: string
extensionId: string
extensionName: string
title: string
body?: string
level: ExtensionNotificationLevel
dedupeKey?: string
pageId?: string
read: boolean
createdAt: number
updatedAt: number
}
export interface TraceMemoSendTextRequest {
/** 缺省为 text。 */
type?: 'text'
@@ -147,6 +332,18 @@ export interface TraceMemoApi {
readonly dataDir: string
readonly permissions: string[]
}
page: {
onRequest(
method: string,
handler: (params: Record<string, unknown>) => unknown | Promise<unknown>
): void
}
secrets: {
get(key: string): Promise<string | null>
set(key: string, value: string): Promise<void>
delete(key: string): Promise<void>
has(key: string): Promise<boolean>
}
events: {
on(
name: 'message.received',
@@ -158,20 +355,53 @@ export interface TraceMemoApi {
): void
}
messages: {
query(request: {
conversationId: string
/** epoch 毫秒;默认最近 24 小时。 */
startTime?: number
/** epoch 毫秒;默认现在。 */
endTime?: number
limit?: number
}): Promise<{ messages: TraceMemoQueriedMessage[] }>
query(request: TraceMemoMessagesQueryRequest): Promise<TraceMemoMessagesQueryResult>
}
media: {
readImage(request: {
messageRef: string
quality?: 'original' | 'thumbnail'
}): Promise<TraceMemoMediaReadImageResult>
readVoice(request: { messageRef: string }): Promise<TraceMemoMediaReadVoiceResult>
readVideo(request: { messageRef: string }): Promise<TraceMemoMediaReadVideoResult>
ocrImage(request: {
messageRef: string
language?: string
force?: boolean
}): Promise<TraceMemoMediaOcrImageResult>
transcribeVoice(request: {
messageRef: string
force?: boolean
waitMs?: number
}): Promise<TraceMemoMediaTranscribeVoiceResult>
analyzeImage(request: {
messageRef: string
prompt?: string
force?: boolean
}): Promise<TraceMemoMediaAnalyzeImageResult>
batch(request: {
items: TraceMemoMediaBatchItem[]
concurrency?: number
}): Promise<{ results: TraceMemoMediaBatchItemResult[] }>
}
render: {
htmlToImage(request: TraceMemoRenderHtmlRequest): Promise<TraceMemoRenderHtmlResult>
}
notifications: {
create(request: TraceMemoNotificationCreateRequest): Promise<TraceMemoNotificationCreateResult>
list(): Promise<TraceMemoNotificationItem[]>
markRead(request?: { id?: string; all?: boolean }): Promise<{ changed: number }>
}
wechat: {
send(request: TraceMemoSendRequest): Promise<{ actionId: string; status: 'sent' }>
}
ai: {
chat(messages: Array<{ role: string; content: string }>): Promise<{ text: string }>
analyzeImage(request: {
messageRef: string
prompt?: string
force?: boolean
}): Promise<TraceMemoMediaAnalyzeImageResult>
}
storage: {
get(key: string): Promise<unknown>
+10
View File
@@ -33,6 +33,16 @@ const TEMPLATE_SPECS = [
},
platforms: ['darwin', 'win32']
},
{
id: 'morning-digest',
dir: 'morning-digest',
requires: {
python: false,
chrome: false,
externalScript: false
},
platforms: ['darwin', 'win32']
},
{
id: 'douyin-sender',
dir: 'douyin-sender',
+21 -15
View File
@@ -6,6 +6,7 @@ import {
shouldDeliverExtensionEvent,
type ExtensionMessageEvent
} from '../../shared/extensions/events'
import type { ExtensionMessageRef } from '../../shared/extensions/media'
import type { ExtensionSubscriptions } from '../../shared/extensions/manifest'
import type { NormalizedIncomingMessage } from '../services/message-listener-service'
@@ -22,6 +23,7 @@ export interface ExtensionEventBusDependencies {
listSubscribers: () => ExtensionEventSubscriber[]
getAccountId: () => string
getSelfUsernames: () => string[]
encodeMessageRef?: (ref: ExtensionMessageRef) => string
now?: () => number
onDelivered?: (extensionId: string, event: ExtensionMessageEvent) => void
}
@@ -71,21 +73,25 @@ export class ExtensionEventBus {
return
}
const selfUsernames = new Set(this.dependencies.getSelfUsernames())
const event = buildExtensionMessageEvent({
eventId,
accountId: this.accountId,
conversationId: message.sessionId,
messageId: message.serverId || message.localId,
...(message.senderId ? { senderId: message.senderId } : {}),
...(message.senderNickname ? { senderName: message.senderNickname } : {}),
isGroup: message.isGroup,
isSelf: message.isSelf,
messageType: message.messageType,
...(message.content !== undefined ? { content: message.content } : {}),
// 只有 source 里真实出现当前账号 username 才算 @我;拿不到自身身份时一律 false。
mentionsMe: message.mentionTargets.some((target) => selfUsernames.has(target)),
createTimeSeconds: message.createTime
})
const event = buildExtensionMessageEvent(
{
eventId,
accountId: this.accountId,
conversationId: message.sessionId,
messageId: message.serverId || message.localId,
localId: message.localId,
...(message.senderId ? { senderId: message.senderId } : {}),
...(message.senderNickname ? { senderName: message.senderNickname } : {}),
isGroup: message.isGroup,
isSelf: message.isSelf,
messageType: message.messageType,
...(message.content !== undefined ? { content: message.content } : {}),
// 只有 source 里真实出现当前账号 username 才算 @我;拿不到自身身份时一律 false。
mentionsMe: message.mentionTargets.some((target) => selfUsernames.has(target)),
createTimeSeconds: message.createTime
},
this.dependencies.encodeMessageRef
)
const envelope: ExtensionEventEnvelope = {
version: EXTENSION_EVENT_PROTOCOL_VERSION,
kind: 'message.received',
+189 -9
View File
@@ -4,7 +4,6 @@ import { existsSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { killProcessTree, type ProcessTreeKillResult } from '../process-tree'
import { ExtensionError, toExtensionErrorPayload } from '../../shared/extensions/errors'
import type { ExtensionRuntimeSnapshot } from '../../shared/extensions/types'
import {
sortPermissionsByRisk,
type ExtensionPermission
@@ -18,15 +17,42 @@ import {
type ExtensionHostInboundMessage,
type ExtensionHostOutboundMessage,
type ExtensionMessagesQueryRequest,
type ExtensionMessagesQueryResult,
type ExtensionNotificationCreateRequest,
type ExtensionNotificationCreateResult,
type ExtensionNotificationMarkReadRequest,
type ExtensionNotificationMarkReadResult,
type ExtensionQueriedMessage,
type ExtensionRenderHtmlToImageRequest,
type ExtensionRenderHtmlToImageResult,
type ExtensionSendImageRequest,
type ExtensionSendTextRequest,
type ExtensionSendTextResult,
type ExtensionSendVideoRequest,
type ExtensionSendVoiceRequest
} from '../../shared/extensions/rpc'
import type {
ExtensionMediaAnalyzeImageRequest,
ExtensionMediaAnalyzeImageResult,
ExtensionMediaBatchRequest,
ExtensionMediaBatchResult,
ExtensionMediaOcrImageRequest,
ExtensionMediaOcrImageResult,
ExtensionMediaReadImageRequest,
ExtensionMediaReadImageResult,
ExtensionMediaReadVideoRequest,
ExtensionMediaReadVideoResult,
ExtensionMediaReadVoiceRequest,
ExtensionMediaReadVoiceResult,
ExtensionMediaTranscribeVoiceRequest,
ExtensionMediaTranscribeVoiceResult
} from '../../shared/extensions/media'
import type { ExtensionEventEnvelope } from '../../shared/extensions/events'
import type { ExtensionCapabilitySnapshot } from '../../shared/extensions/types'
import type {
ExtensionCapabilitySnapshot,
ExtensionNotificationItem,
ExtensionRuntimeSnapshot
} from '../../shared/extensions/types'
import {
parseActionInputSchema,
type ExtensionActionInputSchema
@@ -95,6 +121,8 @@ export interface ExtensionHostDependencies {
/** 扩展私有数据目录;媒体文件只允许从这里或临时目录发送。 */
dataDir: string
permissions: ExtensionPermission[]
/** 实时权限检查(回查主进程最新状态),未提供时回退到启动快照 permissions。 */
hasPermission?: (permission: ExtensionPermission) => boolean
storage: ExtensionStorage
secrets?: ExtensionSecretStore
spawn: (options: ExtensionHostSpawnOptions) => ExtensionHostChild
@@ -104,7 +132,48 @@ export interface ExtensionHostDependencies {
queryMessages?: (
extensionId: string,
request: ExtensionMessagesQueryRequest
) => Promise<ExtensionQueriedMessage[]>
) => Promise<ExtensionQueriedMessage[] | ExtensionMessagesQueryResult>
mediaReadImage?: (
extensionId: string,
request: ExtensionMediaReadImageRequest
) => Promise<ExtensionMediaReadImageResult>
mediaReadVoice?: (
extensionId: string,
request: ExtensionMediaReadVoiceRequest
) => Promise<ExtensionMediaReadVoiceResult>
mediaReadVideo?: (
extensionId: string,
request: ExtensionMediaReadVideoRequest
) => Promise<ExtensionMediaReadVideoResult>
mediaOcrImage?: (
extensionId: string,
request: ExtensionMediaOcrImageRequest
) => Promise<ExtensionMediaOcrImageResult>
mediaTranscribeVoice?: (
extensionId: string,
request: ExtensionMediaTranscribeVoiceRequest
) => Promise<ExtensionMediaTranscribeVoiceResult>
mediaAnalyzeImage?: (
extensionId: string,
request: ExtensionMediaAnalyzeImageRequest
) => Promise<ExtensionMediaAnalyzeImageResult>
mediaBatch?: (
extensionId: string,
request: ExtensionMediaBatchRequest
) => Promise<ExtensionMediaBatchResult>
renderHtmlToImage?: (
extensionId: string,
request: ExtensionRenderHtmlToImageRequest
) => Promise<ExtensionRenderHtmlToImageResult>
createNotification?: (
extensionId: string,
request: ExtensionNotificationCreateRequest
) => Promise<ExtensionNotificationCreateResult> | ExtensionNotificationCreateResult
listNotifications?: (extensionId: string) => Promise<ExtensionNotificationItem[]> | ExtensionNotificationItem[]
markNotificationsRead?: (
extensionId: string,
request: ExtensionNotificationMarkReadRequest
) => Promise<ExtensionNotificationMarkReadResult> | ExtensionNotificationMarkReadResult
sendText?: (
extensionId: string,
request: ExtensionSendTextRequest
@@ -311,6 +380,7 @@ export class ExtensionHost {
this.settleActivation(new ExtensionError('EXTENSION_HOST_UNAVAILABLE', '扩展已停止'))
this.failPendingActions(new ExtensionError('EXTENSION_HOST_UNAVAILABLE', '扩展已停止'))
this.failPendingTests(new ExtensionError('EXTENSION_HOST_UNAVAILABLE', '扩展已停止'))
this.failPendingPageRequests(new ExtensionError('EXTENSION_HOST_UNAVAILABLE', '扩展已停止'))
this.actions.clear()
if (!child) {
this.setState('inactive')
@@ -592,6 +662,9 @@ export class ExtensionHost {
new ExtensionError('EXTENSION_HOST_UNAVAILABLE', `扩展进程已退出(${code ?? 'unknown'})`)
)
this.failPendingTests(new ExtensionError('EXTENSION_HOST_UNAVAILABLE', '扩展进程已退出'))
this.failPendingPageRequests(
new ExtensionError('EXTENSION_HOST_UNAVAILABLE', `扩展进程已退出(${code ?? 'unknown'})`)
)
if (this.stopping) {
this.setState('inactive')
return
@@ -775,12 +848,108 @@ export class ExtensionHost {
case 'messages.query': {
this.requirePermission('messages.query')
if (!this.dependencies.queryMessages) throw new ExtensionError('CAPABILITY_UNAVAILABLE')
return {
messages: await this.dependencies.queryMessages(
extensionId,
params as unknown as ExtensionMessagesQueryRequest
)
const queried = await this.dependencies.queryMessages(
extensionId,
params as unknown as ExtensionMessagesQueryRequest
)
if (Array.isArray(queried)) {
return { messages: queried, hasMore: false }
}
return queried
}
case 'media.readImage': {
this.requirePermission('media.read')
if (!this.dependencies.mediaReadImage) throw new ExtensionError('CAPABILITY_UNAVAILABLE')
return this.dependencies.mediaReadImage(
extensionId,
params as unknown as ExtensionMediaReadImageRequest
)
}
case 'media.readVoice': {
this.requirePermission('media.read')
if (!this.dependencies.mediaReadVoice) throw new ExtensionError('CAPABILITY_UNAVAILABLE')
return this.dependencies.mediaReadVoice(
extensionId,
params as unknown as ExtensionMediaReadVoiceRequest
)
}
case 'media.readVideo': {
this.requirePermission('media.read')
if (!this.dependencies.mediaReadVideo) throw new ExtensionError('CAPABILITY_UNAVAILABLE')
return this.dependencies.mediaReadVideo(
extensionId,
params as unknown as ExtensionMediaReadVideoRequest
)
}
case 'media.ocrImage': {
this.requirePermission('media.ocr')
if (!this.dependencies.mediaOcrImage) throw new ExtensionError('CAPABILITY_UNAVAILABLE')
return this.dependencies.mediaOcrImage(
extensionId,
params as unknown as ExtensionMediaOcrImageRequest
)
}
case 'media.transcribeVoice': {
this.requirePermission('media.transcribe')
if (!this.dependencies.mediaTranscribeVoice) {
throw new ExtensionError('CAPABILITY_UNAVAILABLE')
}
return this.dependencies.mediaTranscribeVoice(
extensionId,
params as unknown as ExtensionMediaTranscribeVoiceRequest
)
}
case 'media.analyzeImage': {
this.requirePermission('ai.vision')
if (!this.dependencies.mediaAnalyzeImage) throw new ExtensionError('CAPABILITY_UNAVAILABLE')
return this.dependencies.mediaAnalyzeImage(
extensionId,
params as unknown as ExtensionMediaAnalyzeImageRequest
)
}
case 'media.batch': {
if (!this.dependencies.mediaBatch) throw new ExtensionError('CAPABILITY_UNAVAILABLE')
return this.dependencies.mediaBatch(
extensionId,
params as unknown as ExtensionMediaBatchRequest
)
}
case 'render.htmlToImage': {
this.requirePermission('render.html')
if (!this.dependencies.renderHtmlToImage) {
throw new ExtensionError('CAPABILITY_UNAVAILABLE')
}
return this.dependencies.renderHtmlToImage(
extensionId,
params as unknown as ExtensionRenderHtmlToImageRequest
)
}
case 'notifications.create': {
this.requirePermission('notifications.create')
if (!this.dependencies.createNotification) {
throw new ExtensionError('CAPABILITY_UNAVAILABLE')
}
return this.dependencies.createNotification(
extensionId,
params as unknown as ExtensionNotificationCreateRequest
)
}
case 'notifications.list': {
this.requirePermission('notifications.create')
if (!this.dependencies.listNotifications) {
throw new ExtensionError('CAPABILITY_UNAVAILABLE')
}
return { items: await this.dependencies.listNotifications(extensionId) }
}
case 'notifications.markRead': {
this.requirePermission('notifications.create')
if (!this.dependencies.markNotificationsRead) {
throw new ExtensionError('CAPABILITY_UNAVAILABLE')
}
return this.dependencies.markNotificationsRead(
extensionId,
params as unknown as ExtensionNotificationMarkReadRequest
)
}
case 'wechat.send.text': {
this.requirePermission('wechat.send.text')
@@ -838,7 +1007,10 @@ export class ExtensionHost {
}
private requirePermission(permission: ExtensionPermission): void {
if (!this.dependencies.permissions.includes(permission)) {
const allowed = this.dependencies.hasPermission
? this.dependencies.hasPermission(permission)
: this.dependencies.permissions.includes(permission)
if (!allowed) {
throw new ExtensionError('PERMISSION_DENIED', `扩展没有 ${permission} 权限`)
}
}
@@ -867,6 +1039,14 @@ export class ExtensionHost {
}
}
private failPendingPageRequests(error: Error): void {
for (const [requestId, pending] of this.pendingPageRequests) {
clearTimeout(pending.timer)
this.pendingPageRequests.delete(requestId)
pending.reject(error)
}
}
private refillTokens(): void {
const now = this.now()
const elapsed = Math.max(0, now - this.eventTokensAt)
+78 -1
View File
@@ -7,11 +7,14 @@ import type {
ExtensionInstallResult,
ExtensionProjectResult,
ExtensionLogEntry,
ExtensionNotificationItem,
ExtensionNotificationSummary,
ExtensionOperationResult,
ExtensionPageDescriptor,
ExtensionPageRequest,
ExtensionPageResponse,
InstalledExtension
InstalledExtension,
PinnedExtensionNavItem
} from '../../shared/extensions/types'
import type { ExtensionManager } from './extension-manager'
import type { ExtensionPaths } from './extension-paths'
@@ -368,6 +371,80 @@ export function registerExtensionIpc(options: ExtensionIpcOptions): void {
return error ? { success: false, error } : { success: true }
})
)
ipcMain.handle(
EXTENSION_IPC.pinnedNavigation,
guard((): PinnedExtensionNavItem[] => manager().listPinnedNavigation())
)
ipcMain.handle(
EXTENSION_IPC.pinNavigation,
guard((payload: unknown): ExtensionOperationResult => {
const input = (payload ?? {}) as { id?: unknown; pageId?: unknown }
const pageId =
typeof input.pageId === 'string' && input.pageId.trim() ? input.pageId.trim() : undefined
return manager().pinNavigation(requireId(input.id), pageId)
})
)
ipcMain.handle(
EXTENSION_IPC.unpinNavigation,
guard((extensionId: unknown): ExtensionOperationResult =>
manager().unpinNavigation(requireId(extensionId))
)
)
ipcMain.handle(
EXTENSION_IPC.reorderNavigation,
guard((extensionIds: unknown): ExtensionOperationResult => {
const ids = Array.isArray(extensionIds)
? extensionIds.filter((item): item is string => typeof item === 'string')
: []
return manager().reorderPinnedNavigation(ids)
})
)
ipcMain.handle(
EXTENSION_IPC.notificationsList,
guard((extensionId?: unknown): ExtensionNotificationItem[] => {
const id =
typeof extensionId === 'string' && extensionId.trim() ? requireId(extensionId) : undefined
return manager().listNotifications(id)
})
)
ipcMain.handle(
EXTENSION_IPC.notificationsSummary,
guard((): ExtensionNotificationSummary => manager().getNotificationSummary())
)
ipcMain.handle(
EXTENSION_IPC.notificationsMarkRead,
guard((payload: unknown): { changed: number } => {
const input = (payload ?? {}) as { id?: unknown; extensionId?: unknown; all?: unknown }
const id = typeof input.id === 'string' && input.id.trim() ? input.id.trim() : undefined
const extensionId =
typeof input.extensionId === 'string' && input.extensionId.trim()
? requireId(input.extensionId)
: undefined
return {
changed: manager().markNotificationsRead({
...(id ? { id } : {}),
...(extensionId ? { extensionId } : {}),
all: input.all === true
})
}
})
)
ipcMain.handle(
EXTENSION_IPC.notificationsClear,
guard((extensionId?: unknown): { removed: number } => {
const id =
typeof extensionId === 'string' && extensionId.trim() ? requireId(extensionId) : undefined
return { removed: manager().clearNotifications(id) }
})
)
}
function requireId(value: unknown): string {
+388 -6
View File
@@ -24,6 +24,8 @@ import type {
ExtensionCapabilitySnapshot,
ExtensionInstallResult,
ExtensionLogEntry,
ExtensionNotificationItem,
ExtensionNotificationSummary,
ExtensionOperationResult,
ExtensionPageDescriptor,
ExtensionPageMethod,
@@ -32,18 +34,45 @@ import type {
ExtensionProjectResult,
ExtensionSystemHealth,
ExtensionTtsCapabilitySnapshot,
InstalledExtension
InstalledExtension,
PinnedExtensionNavItem
} from '../../shared/extensions/types'
import type {
ExtensionAutomationActionOutput,
ExtensionMessagesQueryRequest,
ExtensionMessagesQueryResult,
ExtensionNotificationCreateRequest,
ExtensionNotificationCreateResult,
ExtensionNotificationMarkReadRequest,
ExtensionNotificationMarkReadResult,
ExtensionQueriedMessage,
ExtensionRenderHtmlToImageRequest,
ExtensionRenderHtmlToImageResult,
ExtensionSendImageRequest,
ExtensionSendTextRequest,
ExtensionSendTextResult,
ExtensionSendVideoRequest,
ExtensionSendVoiceRequest
} from '../../shared/extensions/rpc'
import type {
ExtensionMediaAnalyzeImageRequest,
ExtensionMediaAnalyzeImageResult,
ExtensionMediaBatchRequest,
ExtensionMediaBatchResult,
ExtensionMediaOcrImageRequest,
ExtensionMediaOcrImageResult,
ExtensionMediaReadImageRequest,
ExtensionMediaReadImageResult,
ExtensionMediaReadVideoRequest,
ExtensionMediaReadVideoResult,
ExtensionMediaReadVoiceRequest,
ExtensionMediaReadVoiceResult,
ExtensionMediaTranscribeVoiceRequest,
ExtensionMediaTranscribeVoiceResult,
ExtensionMessageRef
} from '../../shared/extensions/media'
import type { ExtensionMediaGateway } from './extension-media-gateway'
import { buildExtensionPrivateMediaPreviewUrl } from './extension-protocol'
import type { PersonalWechatSendCapability } from '../../shared/personal-wechat'
import type { WechatActionRequest, WechatActionResult } from '../../shared/wechat-action'
import type { NormalizedIncomingMessage } from '../services/message-listener-service'
@@ -67,6 +96,8 @@ import {
type ExtensionTemplateStatus
} from './extension-template-catalog'
import { ExtensionLogStore } from './extension-log'
import { ExtensionNavigationStore } from './extension-navigation-store'
import { ExtensionNotificationStore } from './extension-notification-store'
import { ExtensionRegistry, type ExtensionRegistryRecord } from './extension-registry'
import { ExtensionSendGateway } from './extension-send-gateway'
import { ExtensionStorage } from './extension-storage'
@@ -80,7 +111,26 @@ export interface ExtensionManagerDependencies {
getCapability: () => Promise<PersonalWechatSendCapability>
checkEntitlement: () => Promise<ExtensionEntitlementResult>
executeAction: (request: WechatActionRequest) => Promise<WechatActionResult>
queryMessages: (request: ExtensionMessagesQueryRequest) => Promise<ExtensionQueriedMessage[]>
queryMessages: (
request: ExtensionMessagesQueryRequest
) => Promise<ExtensionQueriedMessage[] | ExtensionMessagesQueryResult>
/** 可选媒体网关工厂:在主进程独立校验权限与会话范围后按需读取/解析媒体。 */
createMediaGateway?: (context: {
hasPermission: (extensionId: string, permission: ExtensionPermission) => boolean
isConversationAllowed: (extensionId: string, conversationId: string) => boolean
getExtensionDataRoot: (extensionId: string) => string
}) => ExtensionMediaGateway
mediaGateway?: ExtensionMediaGateway
/** 可选 messageRef 主进程签名函数;配置后事件总线与历史查询共用签名机制。 */
encodeMessageRef?: (ref: ExtensionMessageRef) => string
/** 账号切换回调,用于刷新 messageRef 签名世代。 */
onAccountChanged?: (accountId: string) => void
/** 离线静态 HTML 渲染实现(复用通用 HtmlRenderService)。 */
renderHtmlToImage?: (
extensionId: string,
extensionDataRoot: string,
request: ExtensionRenderHtmlToImageRequest
) => Promise<ExtensionRenderHtmlToImageResult>
/** 群列表(id + 显示名);用于扩展配置页选择发送目标。 */
listGroups: () => Promise<Array<{ id: string; name: string }>>
aiChat: (messages: Array<{ role: string; content: string }>) => Promise<{ text: string }>
@@ -103,7 +153,15 @@ export interface ExtensionManagerDependencies {
now?: () => number
onChange?: (
extensionId: string,
reason: 'installed' | 'enabled' | 'disabled' | 'uninstalled' | 'runtime' | 'actions'
reason:
| 'installed'
| 'enabled'
| 'disabled'
| 'uninstalled'
| 'runtime'
| 'actions'
| 'navigation'
| 'notifications'
) => void
}
@@ -129,8 +187,11 @@ export class ExtensionManager {
private readonly installer: ExtensionInstaller
private readonly storage: ExtensionStorage
private readonly logs: ExtensionLogStore
private readonly navigationStore: ExtensionNavigationStore
private readonly notificationStore: ExtensionNotificationStore
private readonly actions = new ExtensionActionRegistry()
private readonly sendGateway: ExtensionSendGateway
private readonly mediaGateway: ExtensionMediaGateway | null
private readonly hosts = new Map<string, ExtensionHost>()
private readonly manifests = new Map<string, ExtensionManifest | null>()
private readonly eventBus: ExtensionEventBus
@@ -183,6 +244,8 @@ export class ExtensionManager {
onHealthChange: (extensionId, health) => this.handleStorageHealthChange(extensionId, health)
})
this.logs = new ExtensionLogStore(this.paths.logsDir)
this.navigationStore = new ExtensionNavigationStore(this.paths.pinnedNavigationFile, this.now)
this.notificationStore = new ExtensionNotificationStore(this.paths.notificationsFile, this.now)
this.sendGateway = new ExtensionSendGateway({
getCapability: dependencies.getCapability,
checkEntitlement: dependencies.checkEntitlement,
@@ -197,8 +260,19 @@ export class ExtensionManager {
listSubscribers: () => this.listEventSubscribers(),
getAccountId: dependencies.getAccountId,
getSelfUsernames: dependencies.getSelfUsernames,
...(dependencies.encodeMessageRef ? { encodeMessageRef: dependencies.encodeMessageRef } : {}),
now: this.now
})
this.mediaGateway =
dependencies.mediaGateway ??
dependencies.createMediaGateway?.({
hasPermission: (extensionId, permission) =>
this.hasActivePermission(extensionId, permission),
isConversationAllowed: (extensionId, conversationId) =>
this.isConversationAllowed(extensionId, conversationId),
getExtensionDataRoot: (extensionId) => this.paths.extensionDataDir(extensionId)
}) ??
null
}
/** 建立目录、加载状态、拉起已启用的扩展。单个扩展失败不影响其他扩展。 */
@@ -633,6 +707,8 @@ export class ExtensionManager {
}
} else {
this.registry.remove(extensionId)
this.navigationStore.remove(extensionId)
this.notificationStore.removeByExtension(extensionId)
}
} catch (error) {
return failure(toExtensionErrorPayload(error) as unknown as ExtensionError)
@@ -1058,10 +1134,176 @@ export class ExtensionManager {
return failure(toExtensionErrorPayload(error) as unknown as ExtensionError)
}
if (!keepData) this.logs.remove(extensionId)
this.navigationStore.remove(extensionId)
this.notificationStore.removeByExtension(extensionId)
this.dependencies.onChange?.(extensionId, 'uninstalled')
return { success: true }
}
/** 返回用户固定到一级导航的扩展条目(自动过滤已卸载或无页面扩展)。 */
listPinnedNavigation(): PinnedExtensionNavItem[] {
const records = this.navigationStore.list()
const result: PinnedExtensionNavItem[] = []
for (const pinned of records) {
const record = this.registry.get(pinned.extensionId)
if (!record) continue
const manifest = this.readManifest(pinned.extensionId)
if (!manifest || !manifest.entrypoints.page) continue
const nav = manifest.contributions.navigation
const defaultPageId = nav?.pageId || manifest.contributions.pages[0]?.id
const pageId = pinned.pageId || defaultPageId
result.push({
extensionId: record.id,
extensionName: manifest.name,
label: nav?.label || manifest.name,
icon: nav?.icon || 'puzzle',
...(pageId ? { pageId } : {}),
order: pinned.order,
enabled: record.enabled
})
}
return result
}
pinNavigation(extensionId: string, pageId?: string): ExtensionOperationResult {
const record = this.registry.get(extensionId)
if (!record) return failure(new ExtensionError('EXTENSION_NOT_FOUND'))
const manifest = this.readManifest(extensionId)
if (!manifest || !manifest.entrypoints.page) {
return failure(new ExtensionError('INVALID_REQUEST', '该扩展没有可固定的页面入口'))
}
const targetPageId = pageId || manifest.contributions.navigation?.pageId || manifest.contributions.pages[0]?.id
if (
targetPageId &&
manifest.contributions.pages.length > 0 &&
!manifest.contributions.pages.some((page) => page.id === targetPageId)
) {
return failure(new ExtensionError('INVALID_REQUEST', `扩展页面不存在:${targetPageId}`))
}
try {
this.navigationStore.pin(extensionId, targetPageId)
this.dependencies.onChange?.(extensionId, 'navigation')
return { success: true }
} catch (error) {
return failure(toExtensionErrorPayload(error) as unknown as ExtensionError)
}
}
unpinNavigation(extensionId: string): ExtensionOperationResult {
this.navigationStore.unpin(extensionId)
this.dependencies.onChange?.(extensionId, 'navigation')
return { success: true }
}
reorderPinnedNavigation(extensionIds: string[]): ExtensionOperationResult {
const sanitized = Array.isArray(extensionIds)
? extensionIds.map((id) => String(id || '').trim()).filter((id) => isValidExtensionId(id))
: []
this.navigationStore.reorder(sanitized)
this.dependencies.onChange?.(sanitized[0] || '', 'navigation')
return { success: true }
}
createNotification(
extensionId: string,
request: ExtensionNotificationCreateRequest
): ExtensionNotificationCreateResult {
const record = this.registry.get(extensionId)
if (!record) throw new ExtensionError('EXTENSION_NOT_FOUND')
if (!record.enabled) throw new ExtensionError('EXTENSION_DISABLED', '扩展已停用,拒绝写入新通知')
if (this.isSuspended(extensionId)) {
throw new ExtensionError('EXTENSION_STORAGE_CORRUPTED', '扩展已暂停,拒绝写入新通知')
}
if (!hasExtensionPermission(record.grantedPermissions, 'notifications.create')) {
throw new ExtensionError('PERMISSION_DENIED', '扩展没有 notifications.create 权限')
}
const manifest = this.readManifest(extensionId)
const extensionName = manifest?.name || record.id
const targetPageId = request?.pageId
? String(request.pageId).trim()
: manifest?.contributions.navigation?.pageId || manifest?.contributions.pages[0]?.id
if (
request?.pageId &&
manifest &&
manifest.contributions.pages.length > 0 &&
!manifest.contributions.pages.some((page) => page.id === targetPageId)
) {
throw new ExtensionError('INVALID_REQUEST', `通知跳转页面不存在:${targetPageId}`)
}
const created = this.notificationStore.create(extensionId, extensionName, {
...request,
...(targetPageId ? { pageId: targetPageId } : {})
})
this.dependencies.onChange?.(extensionId, 'notifications')
return created
}
listNotifications(extensionId?: string): ExtensionNotificationItem[] {
return this.notificationStore.list(extensionId)
}
/** 扩展后台查询自身通知(强绑定调用方 extensionId,绝不跨扩展读取)。 */
private listOwnNotifications(extensionId: string): ExtensionNotificationItem[] {
const record = this.registry.get(extensionId)
if (!record) throw new ExtensionError('EXTENSION_NOT_FOUND')
if (!record.enabled) throw new ExtensionError('EXTENSION_DISABLED')
if (this.isSuspended(extensionId)) {
throw new ExtensionError('EXTENSION_STORAGE_CORRUPTED', '扩展已暂停')
}
if (!hasExtensionPermission(record.grantedPermissions, 'notifications.create')) {
throw new ExtensionError('PERMISSION_DENIED', '扩展没有 notifications.create 权限')
}
return this.notificationStore.list(extensionId)
}
/** 扩展后台标记自身通知已读(强绑定调用方 extensionId,禁止修改其他扩展通知)。 */
private markOwnNotificationsRead(
extensionId: string,
request: ExtensionNotificationMarkReadRequest
): ExtensionNotificationMarkReadResult {
const record = this.registry.get(extensionId)
if (!record) throw new ExtensionError('EXTENSION_NOT_FOUND')
if (!record.enabled) throw new ExtensionError('EXTENSION_DISABLED')
if (this.isSuspended(extensionId)) {
throw new ExtensionError('EXTENSION_STORAGE_CORRUPTED', '扩展已暂停')
}
if (!hasExtensionPermission(record.grantedPermissions, 'notifications.create')) {
throw new ExtensionError('PERMISSION_DENIED', '扩展没有 notifications.create 权限')
}
const id = typeof request?.id === 'string' && request.id.trim() ? request.id.trim() : undefined
const all = request?.all === true || !id
const changed = this.notificationStore.markRead({
extensionId,
...(id ? { id } : {}),
...(all ? { all: true } : {})
})
if (changed > 0) {
this.dependencies.onChange?.(extensionId, 'notifications')
}
return { changed }
}
getNotificationSummary(): ExtensionNotificationSummary {
const pinnedIds = new Set(this.listPinnedNavigation().map((item) => item.extensionId))
return this.notificationStore.summary(pinnedIds)
}
markNotificationsRead(options: { id?: string; extensionId?: string; all?: boolean }): number {
const changed = this.notificationStore.markRead(options)
if (changed > 0) {
this.dependencies.onChange?.(options.extensionId || '', 'notifications')
}
return changed
}
clearNotifications(extensionId?: string): number {
const removed = this.notificationStore.clear(extensionId)
if (removed > 0) {
this.dependencies.onChange?.(extensionId || '', 'notifications')
}
return removed
}
/** 页面地址。停用的扩展也允许打开自己的配置页(否则用户无法先配置再启用)。 */
pageUrl(extensionId: string, pageId?: string): ExtensionPageDescriptor {
const record = this.registry.get(extensionId)
@@ -1176,12 +1418,15 @@ export class ExtensionManager {
}
handleMessage(message: NormalizedIncomingMessage): void {
this.eventBus.setAccountId(this.dependencies.getAccountId())
const accountId = this.dependencies.getAccountId()
this.eventBus.setAccountId(accountId)
this.dependencies.onAccountChanged?.(accountId)
this.eventBus.handleMessage(message)
}
setAccountId(accountId: string): void {
this.eventBus.setAccountId(accountId)
this.dependencies.onAccountChanged?.(accountId)
}
/** 自动化动作执行入口。由 `AutomationActionRunner` 调用。 */
@@ -1380,6 +1625,7 @@ export class ExtensionManager {
extensionDir: resolvedRoot.root,
dataDir: this.paths.extensionDataDir(extensionId),
permissions: this.registry.get(extensionId)?.grantedPermissions ?? [],
hasPermission: (permission) => this.hasActivePermission(extensionId, permission),
storage: this.storage,
secrets: this.secrets,
spawn: this.dependencies.spawn ?? this.defaultSpawn(),
@@ -1393,6 +1639,17 @@ export class ExtensionManager {
this.dependencies.onChange?.(extensionId, 'actions')
},
queryMessages: (id, request) => this.queryMessages(id, request),
mediaReadImage: (id, request) => this.mediaReadImage(id, request),
mediaReadVoice: (id, request) => this.mediaReadVoice(id, request),
mediaReadVideo: (id, request) => this.mediaReadVideo(id, request),
mediaOcrImage: (id, request) => this.mediaOcrImage(id, request),
mediaTranscribeVoice: (id, request) => this.mediaTranscribeVoice(id, request),
mediaAnalyzeImage: (id, request) => this.mediaAnalyzeImage(id, request),
mediaBatch: (id, request) => this.mediaBatch(id, request),
renderHtmlToImage: (id, request) => this.renderHtmlToImage(id, request),
createNotification: (id, request) => this.createNotification(id, request),
listNotifications: (id) => this.listOwnNotifications(id),
markNotificationsRead: (id, request) => this.markOwnNotificationsRead(id, request),
sendText: (id, request) => this.sendText(id, request),
sendImage: (id, request) => this.sendImage(id, request),
sendVideo: (id, request) => this.sendVideo(id, request),
@@ -1459,10 +1716,112 @@ export class ExtensionManager {
return subscribers
}
private hasActivePermission(extensionId: string, permission: ExtensionPermission): boolean {
const record = this.registry.get(extensionId)
if (!record?.enabled || this.isSuspended(extensionId)) return false
return hasExtensionPermission(record.grantedPermissions, permission)
}
/** 若 manifest.subscriptions.conversationIds 非空,则限制扩展只能访问声明范围内的会话。 */
private isConversationAllowed(extensionId: string, conversationId: string): boolean {
const manifest = this.readManifest(extensionId)
const scope = manifest?.subscriptions?.conversationIds ?? []
if (scope.length === 0) return true
return scope.includes(conversationId)
}
private requireMediaGateway(extensionId: string): ExtensionMediaGateway {
const record = this.registry.get(extensionId)
if (!record) throw new ExtensionError('EXTENSION_NOT_FOUND')
if (!record.enabled) throw new ExtensionError('EXTENSION_DISABLED')
if (this.isSuspended(extensionId)) {
throw new ExtensionError('EXTENSION_STORAGE_CORRUPTED', '扩展已暂停,媒体调用被拒绝')
}
if (!this.mediaGateway) {
throw new ExtensionError('CAPABILITY_UNAVAILABLE', '当前环境未启用扩展媒体能力')
}
return this.mediaGateway
}
private async mediaReadImage(
extensionId: string,
request: ExtensionMediaReadImageRequest
): Promise<ExtensionMediaReadImageResult> {
return this.requireMediaGateway(extensionId).readImage(extensionId, request)
}
private async mediaReadVoice(
extensionId: string,
request: ExtensionMediaReadVoiceRequest
): Promise<ExtensionMediaReadVoiceResult> {
return this.requireMediaGateway(extensionId).readVoice(extensionId, request)
}
private async mediaReadVideo(
extensionId: string,
request: ExtensionMediaReadVideoRequest
): Promise<ExtensionMediaReadVideoResult> {
return this.requireMediaGateway(extensionId).readVideo(extensionId, request)
}
private async mediaOcrImage(
extensionId: string,
request: ExtensionMediaOcrImageRequest
): Promise<ExtensionMediaOcrImageResult> {
return this.requireMediaGateway(extensionId).ocrImage(extensionId, request)
}
private async mediaTranscribeVoice(
extensionId: string,
request: ExtensionMediaTranscribeVoiceRequest
): Promise<ExtensionMediaTranscribeVoiceResult> {
return this.requireMediaGateway(extensionId).transcribeVoice(extensionId, request)
}
private async mediaAnalyzeImage(
extensionId: string,
request: ExtensionMediaAnalyzeImageRequest
): Promise<ExtensionMediaAnalyzeImageResult> {
return this.requireMediaGateway(extensionId).analyzeImage(extensionId, request)
}
private async mediaBatch(
extensionId: string,
request: ExtensionMediaBatchRequest
): Promise<ExtensionMediaBatchResult> {
return this.requireMediaGateway(extensionId).batch(extensionId, request)
}
private async renderHtmlToImage(
extensionId: string,
request: ExtensionRenderHtmlToImageRequest
): Promise<ExtensionRenderHtmlToImageResult> {
const record = this.registry.get(extensionId)
if (!record) throw new ExtensionError('EXTENSION_NOT_FOUND')
if (!record.enabled) throw new ExtensionError('EXTENSION_DISABLED')
if (this.isSuspended(extensionId)) {
throw new ExtensionError('EXTENSION_STORAGE_CORRUPTED', '扩展已暂停,渲染调用被拒绝')
}
if (!hasExtensionPermission(record.grantedPermissions, 'render.html')) {
throw new ExtensionError('PERMISSION_DENIED', '扩展没有 render.html 权限')
}
if (!this.dependencies.renderHtmlToImage) {
throw new ExtensionError('CAPABILITY_UNAVAILABLE', '当前环境未启用 HTML 渲染能力')
}
const dataRoot = this.paths.extensionDataDir(extensionId)
const rendered = await this.dependencies.renderHtmlToImage(extensionId, dataRoot, request)
const previewUrl =
rendered.previewUrl ?? buildExtensionPrivateMediaPreviewUrl(extensionId, dataRoot, rendered.path)
return {
...rendered,
...(previewUrl ? { previewUrl } : {})
}
}
private async queryMessages(
extensionId: string,
request: ExtensionMessagesQueryRequest
): Promise<ExtensionQueriedMessage[]> {
): Promise<ExtensionQueriedMessage[] | ExtensionMessagesQueryResult> {
if (!this.dependencies.isDatabaseReady()) {
throw new ExtensionError('DATABASE_NOT_READY')
}
@@ -1481,11 +1840,30 @@ export class ExtensionManager {
}
const record = this.registry.get(extensionId)
if (!record?.enabled) throw new ExtensionError('EXTENSION_DISABLED')
if (this.isSuspended(extensionId)) {
throw new ExtensionError('EXTENSION_STORAGE_CORRUPTED', '扩展已暂停,查询被拒绝')
}
if (!hasExtensionPermission(record.grantedPermissions, 'messages.query')) {
throw new ExtensionError('PERMISSION_DENIED', '扩展没有 messages.query 权限')
}
if (!this.isConversationAllowed(extensionId, conversationId)) {
throw new ExtensionError('PERMISSION_DENIED', '目标会话超出扩展声明的访问范围')
}
const order = request?.order === 'asc' || request?.order === 'desc' ? request.order : undefined
const cursor = typeof request?.cursor === 'string' && request.cursor.trim()
? request.cursor.trim()
: undefined
const types = Array.isArray(request?.types)
? request.types.map((item) => String(item || '').trim()).filter(Boolean).slice(0, 16)
: undefined
return this.dependencies.queryMessages({
conversationId,
startTime,
endTime,
limit
limit,
...(cursor ? { cursor } : {}),
...(order ? { order } : {}),
...(types?.length ? { types } : {})
})
}
@@ -1678,6 +2056,10 @@ export class ExtensionManager {
id: page.id,
title: page.title
})),
...(manifest?.contributions.navigation
? { navigation: manifest.contributions.navigation }
: {}),
pinnedToNav: this.navigationStore.isPinned(record.id),
automationActions: this.actions.summariesFor(record.id),
filesPresent: Boolean(manifest),
storage: {
@@ -0,0 +1,935 @@
import fs from 'fs-extra'
import path from 'node:path'
import { createHash } from 'node:crypto'
import { ExtensionError, toExtensionErrorPayload } from '../../shared/extensions/errors'
import type { ExtensionPermission } from '../../shared/extensions/permissions'
import {
decodeExtensionMessageRef,
decodeMessagesQueryCursor,
encodeMessagesQueryCursor,
type ExtensionMediaAnalyzeImageRequest,
type ExtensionMediaAnalyzeImageResult,
type ExtensionMediaBatchItem,
type ExtensionMediaBatchItemResult,
type ExtensionMediaBatchOperation,
type ExtensionMediaBatchRequest,
type ExtensionMediaBatchResult,
type ExtensionMediaOcrImageRequest,
type ExtensionMediaOcrImageResult,
type ExtensionMediaReadImageRequest,
type ExtensionMediaReadImageResult,
type ExtensionMediaReadVideoRequest,
type ExtensionMediaReadVideoResult,
type ExtensionMediaReadVoiceRequest,
type ExtensionMediaReadVoiceResult,
type ExtensionMediaTranscribeVoiceRequest,
type ExtensionMediaTranscribeVoiceResult,
type ExtensionMessageRef
} from '../../shared/extensions/media'
import type {
ExtensionMessagesQueryRequest,
ExtensionMessagesQueryResult,
ExtensionQueriedMessage
} from '../../shared/extensions/rpc'
import type { VoiceMessageReference } from '../../shared/voice-recognition'
import type { VoiceTranscriptionOutcome } from '../voice-pipeline/voice-transcription-gateway'
import { isPathInside } from './extension-paths'
import { buildExtensionPrivateMediaPreviewUrl } from './extension-protocol'
const DEFAULT_GLOBAL_CONCURRENCY = 4
const DEFAULT_PER_EXTENSION_CONCURRENCY = 2
const DEFAULT_MAX_BATCH_ITEMS = 20
const DEFAULT_MAX_VIDEO_BYTES = 100 * 1024 * 1024
const DEFAULT_CACHE_ENTRIES = 128
const DEFAULT_CACHE_TTL_MS = 10 * 60 * 1000
const DEFAULT_TRANSCRIBE_WAIT_MS = 12_000
const MAX_TRANSCRIBE_WAIT_MS = 25_000
const DEFAULT_TIMEOUTS_MS: Record<ExtensionMediaBatchOperation, number> = {
readImage: 15_000,
readVoice: 20_000,
readVideo: 30_000,
ocrImage: 25_000,
transcribeVoice: 30_000,
analyzeImage: 60_000
}
const OP_REQUIRED_PERMISSION: Record<ExtensionMediaBatchOperation, ExtensionPermission> = {
readImage: 'media.read',
readVoice: 'media.read',
readVideo: 'media.read',
ocrImage: 'media.ocr',
transcribeVoice: 'media.transcribe',
analyzeImage: 'ai.vision'
}
export interface ResolvedExtensionMediaMessage {
messageId: string
localId?: number
serverId?: string
conversationId: string
senderName?: string
type: 'image' | 'voice' | 'video' | 'other'
/** epoch 秒。 */
createTimeSeconds: number
image?: { md5?: string; datName?: string }
voice?: { durationSeconds?: number }
video?: {
hashes: string[]
byteLength?: number
duration?: number
width?: number
height?: number
}
}
export interface ExtensionMediaGatewayDependencies {
isDatabaseReady: () => boolean
getAccountId: () => string
getExtensionDataRoot: (extensionId: string) => string
hasPermission: (extensionId: string, permission: ExtensionPermission) => boolean
/** 校验扩展是否允许访问目标会话(manifest.subscriptions.conversationIds 约束)。 */
isConversationAllowed?: (extensionId: string, conversationId: string) => boolean
/** messageRef 验签;不配置就退化为只解码不校验,伪造与切号前旧引用都会放行。 */
verifySignedRef?: (rawRef: unknown, expectedAccountId: string) => ExtensionMessageRef | null
resolveMessage: (ref: ExtensionMessageRef) => Promise<ResolvedExtensionMediaMessage | null>
readImageData: (
message: ResolvedExtensionMediaMessage,
quality: 'original' | 'thumbnail'
) => Promise<{
buffer: Buffer
mimeType: string
imageHash?: string
quality: 'original' | 'thumbnail'
} | null>
readVoiceData: (
message: ResolvedExtensionMediaMessage
) => Promise<{ wavBuffer: Buffer; durationMs?: number } | null>
readVideoAsset: (message: ResolvedExtensionMediaMessage) => Promise<{
filePath: string
posterPath?: string
durationMs?: number
width?: number
height?: number
} | null>
getCachedOcr?: (
conversationId: string,
messageId: string
) => { text: string; language?: string | null; engine?: string } | null
recognizeOcr: (
imageDataUrl: string,
language?: string
) => Promise<{
success: boolean
text: string
language: string | null
engine: string
error?: string
}>
transcribeVoice: (
reference: VoiceMessageReference,
options: { force?: boolean; waitMs: number }
) => Promise<VoiceTranscriptionOutcome | null>
analyzeImage: (input: {
messageId: string
conversationId: string
senderName: string
sentAt: number
imageHash: string
imageDataUrl: string
prompt?: string
force?: boolean
}) => Promise<{
description: string
ocrText?: string
tags?: string[]
category?: string
model?: string
cached?: boolean
}>
maxGlobalConcurrent?: number
maxPerExtensionConcurrent?: number
maxBatchItems?: number
maxVideoBytes?: number
cacheTtlMs?: number
timeoutsMs?: Partial<Record<ExtensionMediaBatchOperation, number>>
now?: () => number
}
interface CacheEntry<T> {
value: T
at: number
}
function sha256Hex(buffer: Buffer): string {
return createHash('sha256').update(buffer).digest('hex')
}
function extensionForImageMime(mimeType: string): string {
const normalized = mimeType.toLowerCase()
if (normalized.includes('png')) return '.png'
if (normalized.includes('webp')) return '.webp'
if (normalized.includes('gif')) return '.gif'
if (normalized.includes('bmp')) return '.bmp'
return '.jpg'
}
/** 避免底层异常把本机目录或密钥原样回传给扩展。 */
function sanitizeMediaErrorMessage(message: string): string {
return String(message || '媒体处理失败')
.replace(/[A-Za-z]:\\[^\s'"]+/g, '<path>')
.replace(/\/(?:Users|home|var|tmp|private|Library|Volumes)\/[^\s'"]+/g, '<path>')
.replace(/\b(aesKey|xorKey|apiKey|token|secret)\s*[:=]\s*\S+/gi, '$1=***')
.slice(0, 200)
}
function withTimeout<T>(promise: Promise<T>, timeoutMs: number): Promise<T> {
return new Promise<T>((resolve, reject) => {
const timer = setTimeout(() => {
reject(new ExtensionError('ACTION_TIMEOUT', '媒体处理超时'))
}, timeoutMs)
promise.then(
(value) => {
clearTimeout(timer)
resolve(value)
},
(error) => {
clearTimeout(timer)
reject(error)
}
)
})
}
/**
* 扩展媒体与按需解析入口:账号隔离、权限、缓存边界与并发上限一律在主进程校验,
* 底层复用主程序已有的图片解密、语音转写、系统 OCR 与视觉模型。
*/
export class ExtensionMediaGateway {
private readonly maxGlobal: number
private readonly maxPerExtension: number
private readonly maxBatchItems: number
private readonly maxVideoBytes: number
private readonly cacheTtlMs: number
private readonly timeouts: Record<ExtensionMediaBatchOperation, number>
private readonly now: () => number
private activeGlobal = 0
private readonly activeByExtension = new Map<string, number>()
private readonly inFlight = new Map<string, Promise<unknown>>()
private readonly ocrCache = new Map<string, CacheEntry<Omit<ExtensionMediaOcrImageResult, 'messageRef' | 'cached'>>>()
private readonly visionCache = new Map<
string,
CacheEntry<Omit<ExtensionMediaAnalyzeImageResult, 'messageRef' | 'cached'>>
>()
private lastAccountId = ''
constructor(private readonly deps: ExtensionMediaGatewayDependencies) {
this.maxGlobal = Math.max(1, deps.maxGlobalConcurrent ?? DEFAULT_GLOBAL_CONCURRENCY)
this.maxPerExtension = Math.max(
1,
deps.maxPerExtensionConcurrent ?? DEFAULT_PER_EXTENSION_CONCURRENCY
)
this.maxBatchItems = Math.max(1, deps.maxBatchItems ?? DEFAULT_MAX_BATCH_ITEMS)
this.maxVideoBytes = Math.max(1024, deps.maxVideoBytes ?? DEFAULT_MAX_VIDEO_BYTES)
this.cacheTtlMs = Math.max(1_000, deps.cacheTtlMs ?? DEFAULT_CACHE_TTL_MS)
this.timeouts = { ...DEFAULT_TIMEOUTS_MS, ...(deps.timeoutsMs ?? {}) }
this.now = deps.now ?? (() => Date.now())
}
async readImage(
extensionId: string,
request: ExtensionMediaReadImageRequest
): Promise<ExtensionMediaReadImageResult> {
this.assertPermission(extensionId, 'media.read')
const { ref, accountId } = this.verifyRef(extensionId, request?.messageRef)
const quality: 'original' | 'thumbnail' =
request?.quality === 'thumbnail' ? 'thumbnail' : 'original'
const dedupeKey = `${accountId}:${extensionId}:readImage:${ref.conversationId}:${ref.messageId}:${quality}`
return this.runGuarded(extensionId, 'readImage', dedupeKey, async () => {
const message = await this.requireTypedMessage(ref, 'image')
const data = await this.deps.readImageData(message, quality)
if (!data || data.buffer.length === 0) {
throw new ExtensionError('MEDIA_NOT_FOUND', '找不到该图片消息的本地文件')
}
const sha256 = sha256Hex(data.buffer)
const shortHash = sha256.slice(0, 32)
const ext = extensionForImageMime(data.mimeType)
const written = await this.writeCachedMediaFile(
extensionId,
accountId,
'images',
`${shortHash}_${data.quality}${ext}`,
data.buffer
)
const previewUrl = buildExtensionPrivateMediaPreviewUrl(
extensionId,
this.deps.getExtensionDataRoot(extensionId),
written.filePath
)
return {
messageRef: request.messageRef,
mimeType: data.mimeType,
bytes: data.buffer.length,
sha256,
path: written.filePath,
...(previewUrl ? { previewUrl } : {}),
quality: data.quality,
cached: written.cached
}
})
}
async readVoice(
extensionId: string,
request: ExtensionMediaReadVoiceRequest
): Promise<ExtensionMediaReadVoiceResult> {
this.assertPermission(extensionId, 'media.read')
const { ref, accountId } = this.verifyRef(extensionId, request?.messageRef)
const dedupeKey = `${accountId}:${extensionId}:readVoice:${ref.conversationId}:${ref.messageId}`
return this.runGuarded(extensionId, 'readVoice', dedupeKey, async () => {
const message = await this.requireTypedMessage(ref, 'voice')
const voice = await this.deps.readVoiceData(message)
if (!voice || voice.wavBuffer.length === 0) {
throw new ExtensionError('MEDIA_NOT_FOUND', '找不到该语音消息的音频数据')
}
const sha256 = sha256Hex(voice.wavBuffer)
const shortHash = sha256.slice(0, 32)
const written = await this.writeCachedMediaFile(
extensionId,
accountId,
'voices',
`${shortHash}.wav`,
voice.wavBuffer
)
const previewUrl = buildExtensionPrivateMediaPreviewUrl(
extensionId,
this.deps.getExtensionDataRoot(extensionId),
written.filePath
)
const durationMs =
voice.durationMs ??
(message.voice?.durationSeconds ? Math.round(message.voice.durationSeconds * 1000) : undefined)
return {
messageRef: request.messageRef,
mimeType: 'audio/wav',
bytes: voice.wavBuffer.length,
sha256,
...(durationMs !== undefined ? { durationMs } : {}),
path: written.filePath,
...(previewUrl ? { previewUrl } : {}),
cached: written.cached
}
})
}
async readVideo(
extensionId: string,
request: ExtensionMediaReadVideoRequest
): Promise<ExtensionMediaReadVideoResult> {
this.assertPermission(extensionId, 'media.read')
const { ref, accountId } = this.verifyRef(extensionId, request?.messageRef)
const dedupeKey = `${accountId}:${extensionId}:readVideo:${ref.conversationId}:${ref.messageId}`
return this.runGuarded(extensionId, 'readVideo', dedupeKey, async () => {
const message = await this.requireTypedMessage(ref, 'video')
const asset = await this.deps.readVideoAsset(message)
if (!asset?.filePath || !(await fs.pathExists(asset.filePath))) {
throw new ExtensionError('MEDIA_NOT_FOUND', '本地未找到该视频文件')
}
const stat = await fs.stat(asset.filePath)
if (!stat.isFile() || stat.size <= 0) {
throw new ExtensionError('MEDIA_NOT_FOUND', '本地视频文件无效')
}
if (stat.size > this.maxVideoBytes) {
throw new ExtensionError('STORAGE_LIMIT_EXCEEDED', '视频体积超出单文件上限')
}
const videoBuffer = await fs.readFile(asset.filePath)
const sha256 = sha256Hex(videoBuffer)
const shortHash = sha256.slice(0, 32)
const written = await this.writeCachedMediaFile(
extensionId,
accountId,
'videos',
`${shortHash}.mp4`,
videoBuffer
)
const dataRoot = this.deps.getExtensionDataRoot(extensionId)
const previewUrl = buildExtensionPrivateMediaPreviewUrl(extensionId, dataRoot, written.filePath)
let posterPath: string | undefined
let posterPreviewUrl: string | undefined
if (asset.posterPath && (await fs.pathExists(asset.posterPath))) {
try {
const posterBuffer = await fs.readFile(asset.posterPath)
if (posterBuffer.length > 0 && posterBuffer.length <= 10 * 1024 * 1024) {
const posterWritten = await this.writeCachedMediaFile(
extensionId,
accountId,
'videos',
`${shortHash}_poster.jpg`,
posterBuffer
)
posterPath = posterWritten.filePath
posterPreviewUrl = buildExtensionPrivateMediaPreviewUrl(
extensionId,
dataRoot,
posterWritten.filePath
)
}
} catch {
posterPath = undefined
posterPreviewUrl = undefined
}
}
const durationMs =
asset.durationMs ??
(message.video?.duration ? Math.round(message.video.duration * 1000) : undefined)
return {
messageRef: request.messageRef,
mimeType: 'video/mp4',
bytes: videoBuffer.length,
sha256,
path: written.filePath,
...(previewUrl ? { previewUrl } : {}),
...(posterPath ? { posterPath } : {}),
...(posterPreviewUrl ? { posterPreviewUrl } : {}),
...(durationMs !== undefined ? { durationMs } : {}),
...(asset.width ?? message.video?.width ? { width: asset.width ?? message.video?.width } : {}),
...(asset.height ?? message.video?.height
? { height: asset.height ?? message.video?.height }
: {}),
cached: written.cached
}
})
}
async ocrImage(
extensionId: string,
request: ExtensionMediaOcrImageRequest
): Promise<ExtensionMediaOcrImageResult> {
this.assertPermission(extensionId, 'media.ocr')
const { ref, accountId } = this.verifyRef(extensionId, request?.messageRef)
const language = typeof request?.language === 'string' ? request.language.trim().slice(0, 32) : ''
const force = request?.force === true
const cacheKey = `${accountId}:${ref.conversationId}:${ref.messageId}:${language || 'auto'}`
if (!force) {
const memHit = this.readCache(this.ocrCache, cacheKey)
if (memHit) {
return { messageRef: request.messageRef, ...memHit, cached: true }
}
}
const dedupeKey = `${accountId}:ocrImage:${ref.conversationId}:${ref.messageId}:${language || 'auto'}:${force ? '1' : '0'}`
return this.runGuarded(extensionId, 'ocrImage', dedupeKey, async () => {
const message = await this.requireTypedMessage(ref, 'image')
if (!force && !language && this.deps.getCachedOcr) {
const indexed = this.deps.getCachedOcr(message.conversationId, message.messageId)
if (indexed && typeof indexed.text === 'string') {
const payload = {
text: indexed.text,
language: indexed.language ?? null,
engine: indexed.engine || 'system-ocr'
}
this.writeCache(this.ocrCache, cacheKey, payload)
return {
messageRef: request.messageRef,
...payload,
cached: true
}
}
}
const data = await this.deps.readImageData(message, 'original')
if (!data || data.buffer.length === 0) {
throw new ExtensionError('MEDIA_NOT_FOUND', '找不到该图片消息的本地文件')
}
const dataUrl = `data:${data.mimeType};base64,${data.buffer.toString('base64')}`
const ocr = await this.deps.recognizeOcr(dataUrl, language || undefined)
if (!ocr.success) {
throw new ExtensionError(
'CAPABILITY_UNAVAILABLE',
sanitizeMediaErrorMessage(ocr.error || '本地图片文字识别失败')
)
}
const payload = {
text: ocr.text,
language: ocr.language,
engine: ocr.engine
}
this.writeCache(this.ocrCache, cacheKey, payload)
return {
messageRef: request.messageRef,
...payload,
cached: false
}
})
}
async transcribeVoice(
extensionId: string,
request: ExtensionMediaTranscribeVoiceRequest
): Promise<ExtensionMediaTranscribeVoiceResult> {
this.assertPermission(extensionId, 'media.transcribe')
const { ref, accountId } = this.verifyRef(extensionId, request?.messageRef)
const force = request?.force === true
const waitMs = Math.max(
0,
Math.min(
Number.isFinite(Number(request?.waitMs))
? Math.trunc(Number(request.waitMs))
: DEFAULT_TRANSCRIBE_WAIT_MS,
MAX_TRANSCRIBE_WAIT_MS
)
)
const dedupeKey = `${accountId}:transcribeVoice:${ref.conversationId}:${ref.messageId}:${force ? '1' : '0'}`
return this.runGuarded(extensionId, 'transcribeVoice', dedupeKey, async () => {
const message = await this.requireTypedMessage(ref, 'voice')
const localId =
message.localId ?? (ref.localId && /^\d+$/.test(ref.localId) ? Number(ref.localId) : 0)
const voiceRef: VoiceMessageReference = {
sessionId: message.conversationId,
localId,
createTime: message.createTimeSeconds,
...(message.serverId ? { svrId: message.serverId } : {}),
...(message.voice?.durationSeconds
? { durationSeconds: message.voice.durationSeconds }
: {})
}
const outcome = await this.deps.transcribeVoice(voiceRef, { force, waitMs })
if (!outcome) {
throw new ExtensionError('CONCURRENCY_LIMITED', '语音转写队列已满,请稍后再试')
}
if (outcome.state === 'transcribed') {
return {
messageRef: request.messageRef,
state: 'transcribed',
transcript: outcome.transcript,
...(outcome.durationMs !== undefined ? { durationMs: outcome.durationMs } : {}),
cached: outcome.cached
}
}
if (outcome.state === 'pending') {
return {
messageRef: request.messageRef,
state: 'pending',
cached: false
}
}
return {
messageRef: request.messageRef,
state: 'failed',
cached: false,
error: sanitizeMediaErrorMessage(outcome.error)
}
})
}
async analyzeImage(
extensionId: string,
request: ExtensionMediaAnalyzeImageRequest
): Promise<ExtensionMediaAnalyzeImageResult> {
this.assertPermission(extensionId, 'ai.vision')
const { ref, accountId } = this.verifyRef(extensionId, request?.messageRef)
const prompt = typeof request?.prompt === 'string' ? request.prompt.trim().slice(0, 1000) : ''
const force = request?.force === true
const promptHash = prompt ? createHash('sha256').update(prompt).digest('hex').slice(0, 16) : 'default'
const cacheKey = `${accountId}:${ref.conversationId}:${ref.messageId}:${promptHash}`
if (!force) {
const memHit = this.readCache(this.visionCache, cacheKey)
if (memHit) {
return { messageRef: request.messageRef, ...memHit, cached: true }
}
}
const dedupeKey = `${accountId}:analyzeImage:${ref.conversationId}:${ref.messageId}:${promptHash}:${force ? '1' : '0'}`
return this.runGuarded(extensionId, 'analyzeImage', dedupeKey, async () => {
const message = await this.requireTypedMessage(ref, 'image')
const data = await this.deps.readImageData(message, 'original')
if (!data || data.buffer.length === 0) {
throw new ExtensionError('MEDIA_NOT_FOUND', '找不到该图片消息的本地文件')
}
const imageHash = data.imageHash || `sha256:${sha256Hex(data.buffer).slice(0, 32)}`
const imageDataUrl = `data:${data.mimeType};base64,${data.buffer.toString('base64')}`
const analyzed = await this.deps.analyzeImage({
messageId: message.messageId,
conversationId: message.conversationId,
senderName: message.senderName || '联系人',
sentAt: Math.round(message.createTimeSeconds * 1000),
imageHash,
imageDataUrl,
...(prompt ? { prompt } : {}),
force
})
const payload = {
description: analyzed.description,
...(analyzed.ocrText ? { ocrText: analyzed.ocrText } : {}),
...(analyzed.tags?.length ? { tags: analyzed.tags } : {}),
...(analyzed.category ? { category: analyzed.category } : {}),
...(analyzed.model ? { model: analyzed.model } : {})
}
this.writeCache(this.visionCache, cacheKey, payload)
return {
messageRef: request.messageRef,
...payload,
cached: analyzed.cached === true
}
})
}
async batch(
extensionId: string,
request: ExtensionMediaBatchRequest
): Promise<ExtensionMediaBatchResult> {
const items = Array.isArray(request?.items) ? request.items : null
if (!items || items.length === 0) {
throw new ExtensionError('INVALID_REQUEST', 'batch.items 不能为空')
}
if (items.length > this.maxBatchItems) {
throw new ExtensionError(
'INVALID_REQUEST',
`单次批量处理最多支持 ${this.maxBatchItems} 项`
)
}
const requestedConcurrency = Number(request?.concurrency)
const workerLimit = Math.max(
1,
Math.min(
Number.isFinite(requestedConcurrency) ? Math.trunc(requestedConcurrency) : 2,
this.maxPerExtension,
4
)
)
const results: ExtensionMediaBatchItemResult[] = new Array(items.length)
let cursor = 0
const worker = async (): Promise<void> => {
while (cursor < items.length) {
const index = cursor
cursor += 1
const item = items[index]
results[index] = await this.executeBatchItem(extensionId, index, item)
}
}
await Promise.all(
Array.from({ length: Math.min(workerLimit, items.length) }, () => worker())
)
return { results }
}
private async executeBatchItem(
extensionId: string,
index: number,
item: ExtensionMediaBatchItem
): Promise<ExtensionMediaBatchItemResult> {
const op = item?.op
const messageRef = typeof item?.messageRef === 'string' ? item.messageRef : ''
const options =
item?.options && typeof item.options === 'object' && !Array.isArray(item.options)
? item.options
: {}
if (!op || !(op in OP_REQUIRED_PERMISSION)) {
return {
index,
op: (op || 'readImage') as ExtensionMediaBatchOperation,
messageRef,
ok: false,
error: { code: 'INVALID_REQUEST', message: '不支持的批量媒体操作类型' }
}
}
try {
let result: ExtensionMediaBatchItemResult['result']
switch (op) {
case 'readImage':
result = await this.readImage(extensionId, {
messageRef,
quality: options.quality === 'thumbnail' ? 'thumbnail' : 'original'
})
break
case 'readVoice':
result = await this.readVoice(extensionId, { messageRef })
break
case 'readVideo':
result = await this.readVideo(extensionId, { messageRef })
break
case 'ocrImage':
result = await this.ocrImage(extensionId, {
messageRef,
...(typeof options.language === 'string' ? { language: options.language } : {}),
force: options.force === true
})
break
case 'transcribeVoice':
result = await this.transcribeVoice(extensionId, {
messageRef,
force: options.force === true,
...(typeof options.waitMs === 'number' ? { waitMs: options.waitMs } : {})
})
break
case 'analyzeImage':
result = await this.analyzeImage(extensionId, {
messageRef,
...(typeof options.prompt === 'string' ? { prompt: options.prompt } : {}),
force: options.force === true
})
break
}
return { index, op, messageRef, ok: true, result }
} catch (error) {
return {
index,
op,
messageRef,
ok: false,
error: toExtensionErrorPayload(error)
}
}
}
private assertPermission(extensionId: string, permission: ExtensionPermission): void {
if (!this.deps.hasPermission(extensionId, permission)) {
throw new ExtensionError('PERMISSION_DENIED', `扩展没有 ${permission} 权限`)
}
}
private verifyRef(
extensionId: string,
rawRef: unknown
): { ref: ExtensionMessageRef; accountId: string } {
if (!this.deps.isDatabaseReady()) {
throw new ExtensionError('DATABASE_NOT_READY', '微信数据库尚未连接')
}
const accountId = String(this.deps.getAccountId() || '').trim()
if (!accountId) {
throw new ExtensionError('DATABASE_NOT_READY', '当前未连接到有效微信账号')
}
if (this.lastAccountId && this.lastAccountId !== accountId) {
this.ocrCache.clear()
this.visionCache.clear()
}
this.lastAccountId = accountId
const ref = this.deps.verifySignedRef
? this.deps.verifySignedRef(rawRef, accountId)
: decodeExtensionMessageRef(rawRef)
if (!ref) {
// 保留跨账号明确错误码:若结构有效但账号不匹配,返回 ACCOUNT_MISMATCH。
const parsed = decodeExtensionMessageRef(rawRef)
if (parsed && parsed.accountId && parsed.accountId !== accountId) {
throw new ExtensionError('ACCOUNT_MISMATCH', '消息引用不属于当前已连接账号')
}
throw new ExtensionError('INVALID_REQUEST', 'messageRef 无效、未签名或已失效')
}
if (!ref.accountId || ref.accountId !== accountId) {
throw new ExtensionError('ACCOUNT_MISMATCH', '消息引用不属于当前已连接账号')
}
if (this.deps.isConversationAllowed && !this.deps.isConversationAllowed(extensionId, ref.conversationId)) {
throw new ExtensionError('PERMISSION_DENIED', '消息所属会话超出扩展声明的访问范围')
}
return { ref, accountId }
}
private async requireTypedMessage(
ref: ExtensionMessageRef,
expectedType: 'image' | 'voice' | 'video'
): Promise<ResolvedExtensionMediaMessage> {
const resolved = await this.deps.resolveMessage(ref)
if (!resolved) {
throw new ExtensionError('MEDIA_NOT_FOUND', '找不到对应的消息记录')
}
if (resolved.conversationId !== ref.conversationId) {
throw new ExtensionError('ACCOUNT_MISMATCH', '消息所属会话与引用不一致')
}
if (resolved.type !== expectedType) {
throw new ExtensionError('MEDIA_UNSUPPORTED', `该消息类型为 ${resolved.type},不支持此操作`)
}
return resolved
}
private async runGuarded<T>(
extensionId: string,
op: ExtensionMediaBatchOperation,
dedupeKey: string,
task: () => Promise<T>
): Promise<T> {
const existing = this.inFlight.get(dedupeKey)
if (existing) return (await existing) as T
const extCount = this.activeByExtension.get(extensionId) ?? 0
if (this.activeGlobal >= this.maxGlobal || extCount >= this.maxPerExtension) {
throw new ExtensionError('CONCURRENCY_LIMITED', '媒体处理并发已达上限,请稍后再试')
}
this.activeGlobal += 1
this.activeByExtension.set(extensionId, extCount + 1)
const timeoutMs = this.timeouts[op]
const promise = withTimeout(task(), timeoutMs)
.catch((error) => {
if (error instanceof ExtensionError) throw error
throw new ExtensionError(
'ACTION_FAILED',
sanitizeMediaErrorMessage(error instanceof Error ? error.message : String(error))
)
})
.finally(() => {
this.inFlight.delete(dedupeKey)
this.activeGlobal = Math.max(0, this.activeGlobal - 1)
const current = this.activeByExtension.get(extensionId) ?? 1
if (current <= 1) this.activeByExtension.delete(extensionId)
else this.activeByExtension.set(extensionId, current - 1)
})
this.inFlight.set(dedupeKey, promise)
return promise
}
/** 始终落盘到扩展私有数据目录且按账号哈希分桶,禁止跨扩展与跨账号共享缓存路径。 */
private async writeCachedMediaFile(
extensionId: string,
accountId: string,
bucket: 'images' | 'voices' | 'videos',
fileName: string,
data: Buffer
): Promise<{ filePath: string; cached: boolean }> {
const dataRoot = path.resolve(this.deps.getExtensionDataRoot(extensionId))
const accountScope = createHash('sha256').update(accountId).digest('hex').slice(0, 16)
const cacheDir = path.join(dataRoot, 'media-cache', accountScope, bucket)
const filePath = path.join(cacheDir, fileName)
if (!isPathInside(dataRoot, filePath)) {
throw new ExtensionError('EXTENSION_INVALID_PATH', '媒体缓存路径越界')
}
await fs.ensureDir(cacheDir)
const realRoot = await fs.realpath(dataRoot)
const realDir = await fs.realpath(cacheDir)
if (!isPathInside(realRoot, realDir)) {
throw new ExtensionError('EXTENSION_INVALID_PATH', '媒体缓存目录存在非法符号链接')
}
if (await fs.pathExists(filePath)) {
const stat = await fs.lstat(filePath)
if (!stat.isSymbolicLink() && stat.isFile() && stat.size === data.length) {
return { filePath, cached: true }
}
}
const tempPath = `${filePath}.${Date.now().toString(36)}.tmp`
await fs.writeFile(tempPath, data)
await fs.move(tempPath, filePath, { overwrite: true })
return { filePath, cached: false }
}
private readCache<T>(map: Map<string, CacheEntry<T>>, key: string): T | null {
const entry = map.get(key)
if (!entry) return null
if (this.now() - entry.at > this.cacheTtlMs) {
map.delete(key)
return null
}
return entry.value
}
private writeCache<T>(map: Map<string, CacheEntry<T>>, key: string, value: T): void {
map.set(key, { value, at: this.now() })
if (map.size > DEFAULT_CACHE_ENTRIES) {
const oldest = map.keys().next().value
if (oldest) map.delete(oldest)
}
}
}
function compareCodePoint(left: string, right: string): number {
if (left === right) return 0
return left < right ? -1 : 1
}
/** 确定性游标分页:按 (timestamp, messageId) 排序,同时间戳多条消息不漏不重。 */
export function paginateQueriedMessages(
allMessages: ExtensionQueriedMessage[],
request: ExtensionMessagesQueryRequest
): ExtensionMessagesQueryResult {
const limit = Math.max(1, Math.min(Number(request.limit) || 50, 500))
const cursor = request.cursor ? decodeMessagesQueryCursor(request.cursor) : null
if (request.cursor && !cursor) {
throw new ExtensionError('INVALID_REQUEST', '分页游标无效')
}
if (cursor && request.order && cursor.order !== request.order) {
throw new ExtensionError('INVALID_REQUEST', '分页游标与排序方向不一致')
}
if (cursor && request.order === undefined && cursor.order !== 'desc') {
throw new ExtensionError('INVALID_REQUEST', '默认分页模式仅接受向更早历史续页的游标')
}
const allowedTypes =
Array.isArray(request.types) && request.types.length > 0
? new Set(request.types.map((item) => String(item).trim()).filter(Boolean))
: null
const filtered = allMessages.filter((item) => {
if (allowedTypes && !allowedTypes.has(item.type)) return false
if (request.startTime !== undefined && item.timestamp < request.startTime) return false
if (request.endTime !== undefined && item.timestamp > request.endTime) return false
return true
})
const ascSorted = [...filtered].sort((left, right) => {
const timeDelta = left.timestamp - right.timestamp
return timeDelta !== 0 ? timeDelta : compareCodePoint(left.messageId, right.messageId)
})
// 未显式指定 order 时保持 v1 默认语义(返回最新一页并按时间升序排列),同时支持向更早历史续页。
if (request.order === undefined) {
const olderPool = cursor
? ascSorted.filter((item) => {
const timeDelta = item.timestamp - cursor.timestamp
const cmp = timeDelta !== 0 ? timeDelta : compareCodePoint(item.messageId, cursor.messageId)
return cmp < 0
})
: ascSorted
const hasMore = olderPool.length > limit
const page = olderPool.slice(-limit)
const oldest = page[0]
return {
messages: page,
...(hasMore && oldest
? {
nextCursor: encodeMessagesQueryCursor({
order: 'desc',
timestamp: oldest.timestamp,
messageId: oldest.messageId
})
}
: {}),
hasMore
}
}
const order: 'asc' | 'desc' = request.order === 'desc' ? 'desc' : 'asc'
const sorted = order === 'desc' ? [...ascSorted].reverse() : ascSorted
const afterCursor = cursor
? sorted.filter((item) => {
const timeDelta = item.timestamp - cursor.timestamp
const cmp = timeDelta !== 0 ? timeDelta : compareCodePoint(item.messageId, cursor.messageId)
return order === 'desc' ? cmp < 0 : cmp > 0
})
: sorted
const hasMore = afterCursor.length > limit
const page = afterCursor.slice(0, limit)
const last = page[page.length - 1]
return {
messages: page,
...(hasMore && last
? {
nextCursor: encodeMessagesQueryCursor({
order,
timestamp: last.timestamp,
messageId: last.messageId
})
}
: {}),
hasMore
}
}
@@ -0,0 +1,73 @@
import { createHmac, randomBytes, timingSafeEqual } from 'node:crypto'
import {
decodeExtensionMessageRef,
encodeExtensionMessageRef,
type ExtensionMessageRef
} from '../../shared/extensions/media'
const SIGNATURE_BYTES = 16
/**
* messageRef 用运行期密钥 + 账号世代签名,防止扩展伪造引用;
* 世代随账号切换递增,切号前签发的旧引用必须全部失效。
*/
export class ExtensionMessageRefSigner {
private readonly secret: Buffer
private generation = 1
private currentAccountId = ''
constructor(secret?: Buffer) {
this.secret = secret && secret.length >= 16 ? secret : randomBytes(32)
}
/** 账号变化时递增世代,让切号前签发的所有 messageRef 失效。 */
syncAccount(accountId: string): void {
const normalized = String(accountId || '').trim()
if (!normalized) return
if (this.currentAccountId && this.currentAccountId !== normalized) {
this.generation += 1
}
this.currentAccountId = normalized
}
sign(ref: ExtensionMessageRef): string {
this.syncAccount(ref.accountId)
const unsigned = encodeExtensionMessageRef(ref)
const mac = this.computeMac(unsigned, this.generation)
return `${unsigned}.${mac}`
}
verify(rawRef: unknown, expectedAccountId: string): ExtensionMessageRef | null {
if (typeof rawRef !== 'string') return null
const trimmed = rawRef.trim()
const dotIndex = trimmed.lastIndexOf('.')
if (dotIndex <= 0 || dotIndex === trimmed.length - 1) return null
const unsigned = trimmed.slice(0, dotIndex)
const providedSig = trimmed.slice(dotIndex + 1)
if (!/^[A-Za-z0-9_-]{16,64}$/.test(providedSig)) return null
const normalizedAccount = String(expectedAccountId || '').trim()
if (!normalizedAccount) return null
this.syncAccount(normalizedAccount)
const expectedSig = this.computeMac(unsigned, this.generation)
const providedBuf = Buffer.from(providedSig, 'utf8')
const expectedBuf = Buffer.from(expectedSig, 'utf8')
if (providedBuf.length !== expectedBuf.length || !timingSafeEqual(providedBuf, expectedBuf)) {
return null
}
const decoded = decodeExtensionMessageRef(unsigned)
if (!decoded || decoded.accountId !== normalizedAccount) return null
return decoded
}
private computeMac(unsigned: string, generation: number): string {
return createHmac('sha256', this.secret)
.update(`${generation}:${unsigned}`)
.digest()
.subarray(0, SIGNATURE_BYTES)
.toString('base64url')
}
}
@@ -0,0 +1,144 @@
import fs from 'fs-extra'
import path from 'node:path'
import { isValidExtensionId } from '../../shared/extensions/manifest'
export interface PinnedNavigationRecord {
extensionId: string
pageId?: string
order: number
pinnedAt: number
}
interface PinnedNavigationFile {
version: number
items: PinnedNavigationRecord[]
}
const STORE_VERSION = 1
const MAX_PINNED_ITEMS = 12
/** 宿主管理的一级导航固定项存储;独立于扩展自身配置,重启可恢复、卸载自动清理。 */
export class ExtensionNavigationStore {
private items: PinnedNavigationRecord[] = []
constructor(
private readonly filePath: string,
private readonly now: () => number = () => Date.now()
) {
this.items = this.load()
}
list(): PinnedNavigationRecord[] {
return [...this.items].sort((left, right) => {
if (left.order !== right.order) return left.order - right.order
return left.pinnedAt - right.pinnedAt
})
}
isPinned(extensionId: string): boolean {
return this.items.some((item) => item.extensionId === extensionId)
}
pin(extensionId: string, pageId?: string): PinnedNavigationRecord[] {
const existing = this.items.find((item) => item.extensionId === extensionId)
if (existing) {
if (pageId !== undefined) existing.pageId = pageId || undefined
this.save()
return this.list()
}
if (this.items.length >= MAX_PINNED_ITEMS) {
throw new Error(`最多固定 ${MAX_PINNED_ITEMS} 个扩展到一级导航`)
}
const maxOrder = this.items.reduce((acc, item) => Math.max(acc, item.order), -1)
this.items.push({
extensionId,
...(pageId ? { pageId } : {}),
order: maxOrder + 1,
pinnedAt: this.now()
})
this.save()
return this.list()
}
unpin(extensionId: string): PinnedNavigationRecord[] {
const before = this.items.length
this.items = this.items.filter((item) => item.extensionId !== extensionId)
if (this.items.length !== before) {
this.reindex()
this.save()
}
return this.list()
}
remove(extensionId: string): boolean {
const before = this.items.length
this.items = this.items.filter((item) => item.extensionId !== extensionId)
if (this.items.length === before) return false
this.reindex()
this.save()
return true
}
reorder(extensionIds: string[]): PinnedNavigationRecord[] {
const byId = new Map(this.items.map((item) => [item.extensionId, item]))
const ordered: PinnedNavigationRecord[] = []
for (const id of extensionIds) {
const found = byId.get(id)
if (!found) continue
ordered.push(found)
byId.delete(id)
}
for (const remaining of byId.values()) {
ordered.push(remaining)
}
this.items = ordered.map((item, index) => ({ ...item, order: index }))
this.save()
return this.list()
}
private reindex(): void {
this.items = this.list().map((item, index) => ({ ...item, order: index }))
}
private load(): PinnedNavigationRecord[] {
if (!fs.existsSync(this.filePath)) return []
try {
const parsed = fs.readJsonSync(this.filePath) as Partial<PinnedNavigationFile>
if (!parsed || Number(parsed.version) !== STORE_VERSION || !Array.isArray(parsed.items)) {
return []
}
const result: PinnedNavigationRecord[] = []
const seen = new Set<string>()
for (const item of parsed.items) {
if (!item || typeof item !== 'object') continue
const extensionId = String(item.extensionId || '').trim()
if (!isValidExtensionId(extensionId) || seen.has(extensionId)) continue
seen.add(extensionId)
const pageId =
typeof item.pageId === 'string' && item.pageId.trim()
? item.pageId.trim().slice(0, 32)
: undefined
const order = Number.isFinite(Number(item.order)) ? Math.round(Number(item.order)) : result.length
const pinnedAt =
Number.isFinite(Number(item.pinnedAt)) && Number(item.pinnedAt) > 0
? Math.round(Number(item.pinnedAt))
: this.now()
result.push({ extensionId, ...(pageId ? { pageId } : {}), order, pinnedAt })
}
return result.sort((left, right) => left.order - right.order).slice(0, MAX_PINNED_ITEMS)
} catch {
return []
}
}
private save(): void {
fs.ensureDirSync(path.dirname(this.filePath))
const temp = `${this.filePath}.${process.pid}.${Date.now().toString(36)}.tmp`
const payload: PinnedNavigationFile = {
version: STORE_VERSION,
items: this.list()
}
fs.writeJsonSync(temp, payload, { spaces: 2 })
fs.moveSync(temp, this.filePath, { overwrite: true })
}
}
@@ -0,0 +1,268 @@
import fs from 'fs-extra'
import path from 'node:path'
import { randomUUID } from 'node:crypto'
import { ExtensionError } from '../../shared/extensions/errors'
import { isValidExtensionId } from '../../shared/extensions/manifest'
import type {
ExtensionNotificationCreateRequest,
ExtensionNotificationCreateResult,
ExtensionNotificationLevel
} from '../../shared/extensions/rpc'
import type {
ExtensionNotificationItem,
ExtensionNotificationSummary
} from '../../shared/extensions/types'
interface NotificationFile {
version: number
items: ExtensionNotificationItem[]
}
const STORE_VERSION = 1
const MAX_TOTAL_NOTIFICATIONS = 200
const MAX_PER_EXTENSION_NOTIFICATIONS = 50
const RATE_WINDOW_MS = 60_000
const DEFAULT_MAX_NEW_PER_WINDOW = 20
const DEFAULT_MAX_UPDATES_PER_WINDOW = 60
const VALID_LEVELS: readonly ExtensionNotificationLevel[] = ['info', 'success', 'warning', 'error']
export interface ExtensionNotificationStoreOptions {
maxNewPerWindow?: number
maxUpdatesPerWindow?: number
rateWindowMs?: number
}
function normalizeLevel(value: unknown): ExtensionNotificationLevel {
return typeof value === 'string' && (VALID_LEVELS as readonly string[]).includes(value)
? (value as ExtensionNotificationLevel)
: 'info'
}
/** 宿主管理的扩展通知中心持久化存储;支持扩展内去重、限频防刷屏、分级、未读统计与卸载清理。 */
export class ExtensionNotificationStore {
private items: ExtensionNotificationItem[] = []
private readonly maxNewPerWindow: number
private readonly maxUpdatesPerWindow: number
private readonly rateWindowMs: number
private readonly newHistory = new Map<string, number[]>()
private readonly updateHistory = new Map<string, number[]>()
constructor(
private readonly filePath: string,
private readonly now: () => number = () => Date.now(),
options: ExtensionNotificationStoreOptions = {}
) {
this.maxNewPerWindow = Math.max(1, options.maxNewPerWindow ?? DEFAULT_MAX_NEW_PER_WINDOW)
this.maxUpdatesPerWindow = Math.max(1, options.maxUpdatesPerWindow ?? DEFAULT_MAX_UPDATES_PER_WINDOW)
this.rateWindowMs = Math.max(1_000, options.rateWindowMs ?? RATE_WINDOW_MS)
this.items = this.load()
}
create(
extensionId: string,
extensionName: string,
request: ExtensionNotificationCreateRequest
): ExtensionNotificationCreateResult {
const title = String(request?.title || '')
.trim()
.slice(0, 80)
if (!title) {
throw new ExtensionError('INVALID_REQUEST', '通知标题不能为空')
}
const body =
typeof request?.body === 'string' && request.body.trim()
? request.body.trim().slice(0, 300)
: undefined
const level = normalizeLevel(request?.level)
const dedupeKey =
typeof request?.dedupeKey === 'string' && request.dedupeKey.trim()
? request.dedupeKey.trim().slice(0, 128)
: undefined
const pageId =
typeof request?.pageId === 'string' && request.pageId.trim()
? request.pageId.trim().slice(0, 32)
: undefined
const at = this.now()
if (dedupeKey) {
const existing = this.items.find(
(item) => item.extensionId === extensionId && item.dedupeKey === dedupeKey
)
if (existing) {
this.assertRateLimit(this.updateHistory, extensionId, this.maxUpdatesPerWindow, at)
existing.extensionName = extensionName
existing.title = title
existing.body = body
existing.level = level
existing.pageId = pageId
existing.updatedAt = at
this.save()
return { id: existing.id, deduped: true, createdAt: existing.createdAt }
}
}
this.assertRateLimit(this.newHistory, extensionId, this.maxNewPerWindow, at)
const record: ExtensionNotificationItem = {
id: `ext-ntf-${randomUUID()}`,
extensionId,
extensionName,
title,
...(body ? { body } : {}),
level,
...(dedupeKey ? { dedupeKey } : {}),
...(pageId ? { pageId } : {}),
read: false,
createdAt: at,
updatedAt: at
}
this.items.unshift(record)
this.prune(extensionId)
this.save()
return { id: record.id, deduped: false, createdAt: record.createdAt }
}
list(extensionId?: string): ExtensionNotificationItem[] {
const filtered = extensionId
? this.items.filter((item) => item.extensionId === extensionId)
: this.items
return [...filtered]
.sort((left, right) => right.updatedAt - left.updatedAt)
.map((item) => ({ ...item }))
}
summary(pinnedExtensionIds: ReadonlySet<string>): ExtensionNotificationSummary {
let totalUnread = 0
let unpinnedUnread = 0
const unreadByExtension: Record<string, number> = {}
for (const item of this.items) {
if (item.read) continue
totalUnread += 1
unreadByExtension[item.extensionId] = (unreadByExtension[item.extensionId] ?? 0) + 1
if (!pinnedExtensionIds.has(item.extensionId)) {
unpinnedUnread += 1
}
}
return { totalUnread, unpinnedUnread, unreadByExtension }
}
markRead(options: { id?: string; extensionId?: string; all?: boolean }): number {
let changed = 0
for (const item of this.items) {
if (item.read) continue
if (options.extensionId && item.extensionId !== options.extensionId) {
continue
}
if (options.all) {
item.read = true
changed += 1
} else if (options.id && item.id === options.id) {
item.read = true
changed += 1
} else if (!options.id && options.extensionId && item.extensionId === options.extensionId) {
item.read = true
changed += 1
}
}
if (changed > 0) this.save()
return changed
}
private assertRateLimit(
bucket: Map<string, number[]>,
extensionId: string,
limit: number,
at: number
): void {
const recent = (bucket.get(extensionId) ?? []).filter((ts) => at - ts < this.rateWindowMs)
if (recent.length >= limit) {
bucket.set(extensionId, recent)
throw new ExtensionError('CONCURRENCY_LIMITED', '通知写入过于频繁,请稍后再试')
}
recent.push(at)
bucket.set(extensionId, recent)
}
clear(extensionId?: string): number {
const before = this.items.length
this.items = extensionId
? this.items.filter((item) => item.extensionId !== extensionId)
: []
const removed = before - this.items.length
if (removed > 0) this.save()
return removed
}
removeByExtension(extensionId: string): number {
return this.clear(extensionId)
}
private prune(extensionId: string): void {
const perExt = this.items.filter((item) => item.extensionId === extensionId)
if (perExt.length > MAX_PER_EXTENSION_NOTIFICATIONS) {
const keepIds = new Set(
perExt
.sort((a, b) => b.updatedAt - a.updatedAt)
.slice(0, MAX_PER_EXTENSION_NOTIFICATIONS)
.map((item) => item.id)
)
this.items = this.items.filter(
(item) => item.extensionId !== extensionId || keepIds.has(item.id)
)
}
if (this.items.length > MAX_TOTAL_NOTIFICATIONS) {
this.items.sort((a, b) => b.updatedAt - a.updatedAt)
this.items = this.items.slice(0, MAX_TOTAL_NOTIFICATIONS)
}
}
private load(): ExtensionNotificationItem[] {
if (!fs.existsSync(this.filePath)) return []
try {
const parsed = fs.readJsonSync(this.filePath) as Partial<NotificationFile>
if (!parsed || Number(parsed.version) !== STORE_VERSION || !Array.isArray(parsed.items)) {
return []
}
const result: ExtensionNotificationItem[] = []
const seen = new Set<string>()
for (const raw of parsed.items) {
if (!raw || typeof raw !== 'object') continue
const id = String(raw.id || '').trim()
const extensionId = String(raw.extensionId || '').trim()
const title = String(raw.title || '').trim().slice(0, 80)
if (!id || seen.has(id) || !isValidExtensionId(extensionId) || !title) continue
seen.add(id)
const createdAt = Number.isFinite(Number(raw.createdAt)) ? Number(raw.createdAt) : this.now()
const updatedAt = Number.isFinite(Number(raw.updatedAt)) ? Number(raw.updatedAt) : createdAt
result.push({
id,
extensionId,
extensionName: String(raw.extensionName || extensionId).slice(0, 64),
title,
...(typeof raw.body === 'string' && raw.body.trim()
? { body: raw.body.trim().slice(0, 300) }
: {}),
level: normalizeLevel(raw.level),
...(typeof raw.dedupeKey === 'string' && raw.dedupeKey.trim()
? { dedupeKey: raw.dedupeKey.trim().slice(0, 128) }
: {}),
...(typeof raw.pageId === 'string' && raw.pageId.trim()
? { pageId: raw.pageId.trim().slice(0, 32) }
: {}),
read: raw.read === true,
createdAt,
updatedAt
})
}
return result.sort((a, b) => b.updatedAt - a.updatedAt).slice(0, MAX_TOTAL_NOTIFICATIONS)
} catch {
return []
}
}
private save(): void {
fs.ensureDirSync(path.dirname(this.filePath))
const temp = `${this.filePath}.${process.pid}.${Date.now().toString(36)}.tmp`
fs.writeJsonSync(temp, { version: STORE_VERSION, items: this.items }, { spaces: 2 })
fs.moveSync(temp, this.filePath, { overwrite: true })
}
}
+4
View File
@@ -22,6 +22,8 @@ export interface ExtensionPaths {
stateDir: string
stagingDir: string
registryFile: string
pinnedNavigationFile: string
notificationsFile: string
logsDir: string
installDir: (extensionId: string) => string
extensionDataDir: (extensionId: string) => string
@@ -42,6 +44,8 @@ export function createExtensionPaths(userData: string): ExtensionPaths {
stateDir,
stagingDir,
registryFile: path.join(stateDir, 'registry.json'),
pinnedNavigationFile: path.join(stateDir, 'pinned-navigation.json'),
notificationsFile: path.join(stateDir, 'notifications.json'),
logsDir,
installDir: (extensionId) => path.join(extensionsDir, extensionId),
extensionDataDir: (extensionId) => path.join(dataDir, extensionId),
+137 -33
View File
@@ -5,6 +5,9 @@ import { isSafeRelativeEntryPath } from '../../shared/extensions/manifest'
import { isPathInside, type ExtensionPaths } from './extension-paths'
export const EXTENSION_SCHEME = 'tm-extension'
export const EXTENSION_PRIVATE_DATA_PREFIX = '_data/'
const ALLOWED_PRIVATE_DATA_DIRS = ['rendered/', 'media-cache/'] as const
const MIME_TYPES: Record<string, string> = {
'.html': 'text/html; charset=utf-8',
@@ -25,6 +28,135 @@ const MIME_TYPES: Record<string, string> = {
'.wasm': 'application/wasm'
}
/** 扩展私有预览只放行静态媒体文件,禁止读取脚本、HTML 或 storage.json。 */
const PRIVATE_MEDIA_MIME_TYPES: Record<string, string> = {
'.png': 'image/png',
'.jpg': 'image/jpeg',
'.jpeg': 'image/jpeg',
'.gif': 'image/gif',
'.webp': 'image/webp',
'.bmp': 'image/bmp',
'.wav': 'audio/wav',
'.mp3': 'audio/mpeg',
'.m4a': 'audio/mp4',
'.mp4': 'video/mp4'
}
const MAX_CODE_FILE_BYTES = 20 * 1024 * 1024
const MAX_PRIVATE_IMAGE_AUDIO_BYTES = 25 * 1024 * 1024
const MAX_PRIVATE_VIDEO_BYTES = 100 * 1024 * 1024
const PAGE_CSP = [
"default-src 'self'",
"script-src 'self'",
"style-src 'self' 'unsafe-inline'",
"img-src 'self' data: https:",
"media-src 'self' data: https:",
"font-src 'self' data:",
"connect-src 'none'",
"object-src 'none'",
"base-uri 'none'",
"form-action 'none'"
].join('; ')
const PRIVATE_MEDIA_CSP = "default-src 'none'; sandbox"
/** 为位于扩展私有目录 rendered/ 或 media-cache/ 下的媒体文件构造受控预览 URL。 */
export function buildExtensionPrivateMediaPreviewUrl(
extensionId: string,
extensionDataRoot: string,
filePath: string
): string | undefined {
const id = String(extensionId || '').trim().toLowerCase()
if (!/^[a-z0-9.-]{3,128}$/.test(id)) return undefined
const root = path.resolve(extensionDataRoot)
const target = path.resolve(filePath)
if (!isPathInside(root, target)) return undefined
const relative = path.relative(root, target).replace(/\\/g, '/')
if (!isSafeRelativeEntryPath(relative)) return undefined
if (!ALLOWED_PRIVATE_DATA_DIRS.some((prefix) => relative.startsWith(prefix))) return undefined
const ext = path.extname(relative).toLowerCase()
if (!(ext in PRIVATE_MEDIA_MIME_TYPES)) return undefined
const encodedPath = relative
.split('/')
.map((segment) => encodeURIComponent(segment))
.join('/')
return `${EXTENSION_SCHEME}://${id}/${EXTENSION_PRIVATE_DATA_PREFIX}${encodedPath}`
}
export interface ResolvedExtensionProtocolFile {
realFile: string
contentType: string
csp: string
size: number
isPrivateMedia: boolean
}
/** 扩展协议统一解析器:支持扩展代码文件与受控的 `_data/{rendered,media-cache}/` 媒体只读预览。 */
export async function resolveExtensionProtocolFile(
requestUrl: string,
dependencies: ExtensionProtocolDependencies
): Promise<ResolvedExtensionProtocolFile | null> {
const url = new URL(requestUrl)
if (url.protocol !== `${EXTENSION_SCHEME}:`) return null
const extensionId = url.hostname.toLowerCase()
if (!/^[a-z0-9.-]{3,128}$/.test(extensionId)) return null
const relative = decodeURIComponent(url.pathname).replace(/^\/+/, '')
if (!isSafeRelativeEntryPath(relative)) return null
const isPrivateMedia = relative.startsWith(EXTENSION_PRIVATE_DATA_PREFIX)
if (isPrivateMedia) {
// 只有已安装的扩展允许解析私有预览文件。
if (!dependencies.resolveRoot(extensionId)) return null
const subPath = relative.slice(EXTENSION_PRIVATE_DATA_PREFIX.length)
if (!isSafeRelativeEntryPath(subPath)) return null
if (!ALLOWED_PRIVATE_DATA_DIRS.some((prefix) => subPath.startsWith(prefix))) return null
const ext = path.extname(subPath).toLowerCase()
const contentType = PRIVATE_MEDIA_MIME_TYPES[ext]
if (!contentType) return null
const dataRoot = dependencies.paths.extensionDataDir(extensionId)
const resolved = path.resolve(dataRoot, subPath)
if (!isPathInside(dataRoot, resolved)) return null
const lstat = await fs.lstat(resolved).catch(() => null)
if (!lstat || lstat.isSymbolicLink() || !lstat.isFile()) return null
const realRoot = await fs.realpath(dataRoot).catch(() => null)
const realFile = await fs.realpath(resolved).catch(() => null)
if (!realRoot || !realFile || !isPathInside(realRoot, realFile)) return null
const maxBytes = ext === '.mp4' ? MAX_PRIVATE_VIDEO_BYTES : MAX_PRIVATE_IMAGE_AUDIO_BYTES
if (lstat.size <= 0 || lstat.size > maxBytes) return null
return {
realFile,
contentType,
csp: PRIVATE_MEDIA_CSP,
size: lstat.size,
isPrivateMedia: true
}
}
const root = dependencies.resolveRoot(extensionId)
if (!root) return null
const resolved = path.resolve(root, relative)
if (!isPathInside(root, resolved)) return null
const realRoot = await fs.realpath(root).catch(() => null)
const realFile = await fs.realpath(resolved).catch(() => null)
if (!realRoot || !realFile || !isPathInside(realRoot, realFile)) return null
const stat = await fs.stat(realFile).catch(() => null)
if (!stat || !stat.isFile() || stat.size > MAX_CODE_FILE_BYTES) return null
const contentType =
MIME_TYPES[path.extname(realFile).toLowerCase()] || 'application/octet-stream'
return {
realFile,
contentType,
csp: PAGE_CSP,
size: stat.size,
isPrivateMedia: false
}
}
/** 扩展页面协议:只接受 `tm-extension://<extensionId>/<path>`,realpath 必须仍在。 */
export function registerExtensionScheme(): void {
protocol.registerSchemesAsPrivileged([
@@ -50,42 +182,14 @@ export interface ExtensionProtocolDependencies {
export function installExtensionProtocolHandler(dependencies: ExtensionProtocolDependencies): void {
protocol.handle(EXTENSION_SCHEME, async (request) => {
try {
const url = new URL(request.url)
const extensionId = url.hostname.toLowerCase()
if (!/^[a-z0-9.-]{3,128}$/.test(extensionId)) return notFound()
const relative = decodeURIComponent(url.pathname).replace(/^\/+/, '')
if (!isSafeRelativeEntryPath(relative)) return notFound()
const root = dependencies.resolveRoot(extensionId)
if (!root) return notFound()
const resolved = path.resolve(root, relative)
if (!isPathInside(root, resolved)) return notFound()
const realRoot = await fs.realpath(root).catch(() => null)
const realFile = await fs.realpath(resolved).catch(() => null)
if (!realRoot || !realFile) return notFound()
if (!isPathInside(realRoot, realFile)) return notFound()
const stat = await fs.stat(realFile)
if (!stat.isFile() || stat.size > 20 * 1024 * 1024) return notFound()
const body = await fs.readFile(realFile)
const contentType =
MIME_TYPES[path.extname(realFile).toLowerCase()] || 'application/octet-stream'
const resolved = await resolveExtensionProtocolFile(request.url, dependencies)
if (!resolved) return notFound()
const body = await fs.readFile(resolved.realFile)
return new Response(body, {
status: 200,
headers: {
'Content-Type': contentType,
'Content-Security-Policy': [
"default-src 'self'",
"script-src 'self'",
"style-src 'self' 'unsafe-inline'",
"img-src 'self' data: https:",
"media-src 'self' data: https:",
"font-src 'self' data:",
"connect-src 'none'",
"object-src 'none'",
"base-uri 'none'",
"form-action 'none'"
].join('; '),
'Content-Type': resolved.contentType,
'Content-Security-Policy': resolved.csp,
'X-Content-Type-Options': 'nosniff',
'Cache-Control': 'no-store'
}
+397 -14
View File
@@ -1,4 +1,5 @@
import { app, safeStorage } from 'electron'
import { createHash } from 'node:crypto'
import path from 'node:path'
import { AIProviderService } from '../services/ai-provider-service'
import {
@@ -7,18 +8,37 @@ import {
isReady,
listContacts,
listMessagesAsync,
resolveMd5
resolveMd5,
type FormattedMessage
} from '../services/chat-service'
import { imageInsightService } from '../services/image-insight-service'
import { ImageKeyConfigService } from '../services/image-key-config-service'
import { imageTextIndexService } from '../services/image-text-index-service'
import { personalWechatCapabilityService } from '../services/personal-wechat-capability-service'
import { htmlRenderService } from '../services/html-render-service'
import { loadSettings } from '../services/settings-store'
import { systemOcrService } from '../services/system-ocr-service'
import { TextToSpeechSettingsService } from '../services/text-to-speech-settings-service'
import { wechatActionGateway } from '../services/wechat-action-gateway'
import { ImageDecryptService } from '../image-decrypt-service'
import { VideoAssetService } from '../video-asset-service'
import { VoiceService } from '../voice-service'
import type { VoiceTranscriptionGateway } from '../voice-pipeline/voice-transcription-gateway'
import { ExtensionError } from '../../shared/extensions/errors'
import type { ExtensionMessageRef } from '../../shared/extensions/media'
import type {
ExtensionMessagesQueryRequest,
ExtensionMessagesQueryResult,
ExtensionQueriedMessage
} from '../../shared/extensions/rpc'
import { checkExtensionSendEntitlement } from './extension-entitlement'
import { ExtensionManager } from './extension-manager'
import {
ExtensionMediaGateway,
paginateQueriedMessages,
type ResolvedExtensionMediaMessage
} from './extension-media-gateway'
import { ExtensionMessageRefSigner } from './extension-message-ref-signer'
import { getExtensionPaths } from './extension-paths'
let manager: ExtensionManager | null = null
@@ -34,19 +54,281 @@ function resolveTemplateRoot(): string {
export interface ExtensionSystemOptions {
appVersion: string
onChange: (extensionId: string, reason: string) => void
getImageDecryptService?: () => ImageDecryptService | null
voiceTranscriptionGateway?: Pick<VoiceTranscriptionGateway, 'transcribe' | 'snapshot'>
}
function decodeBase64DataUrl(value: string): { buffer: Buffer; mimeType: string } | null {
const match = /^data:(image\/[a-z0-9.+-]+);base64,([a-z0-9+/=]+)$/i.exec(value)
if (!match) return null
return { mimeType: match[1].toLowerCase(), buffer: Buffer.from(match[2], 'base64') }
}
/** 扩展系统的主进程接线。 */
export async function initExtensionSystem(options: ExtensionSystemOptions): Promise<void> {
if (manager) return
const ttsService = new TextToSpeechSettingsService()
let fallbackImageService: ImageDecryptService | null = null
let fallbackImageKey = ''
let fallbackImageClient: ReturnType<
NonNullable<ReturnType<typeof getChatDb>>['getWcdb4Client']
> | null = null
let cachedVoiceService: {
client: ReturnType<NonNullable<ReturnType<typeof getChatDb>>['getWcdb4Client']>
service: VoiceService
} | null = null
let cachedVideoService: {
client: ReturnType<NonNullable<ReturnType<typeof getChatDb>>['getWcdb4Client']>
service: VideoAssetService
} | null = null
const resolveImageDecryptService = (): ImageDecryptService | null => {
const injected = options.getImageDecryptService?.()
if (injected) return injected
const imageConfig = new ImageKeyConfigService().getConfig()
const aesKey = imageConfig.aesKey || ''
const xorKey = imageConfig.xorKey || '0x40'
if (!aesKey) return null
const client = getChatDb()?.getWcdb4Client() || null
const key = `${xorKey}:${aesKey}`
if (
!fallbackImageService ||
fallbackImageKey !== key ||
fallbackImageClient !== client
) {
fallbackImageService = new ImageDecryptService(xorKey, aesKey, client, loadSettings().dbRoot)
fallbackImageKey = key
fallbackImageClient = client
}
return fallbackImageService
}
const resolveVoiceService = (): VoiceService | null => {
const client = getChatDb()?.getWcdb4Client()
if (!client) return null
if (!cachedVoiceService || cachedVoiceService.client !== client) {
cachedVoiceService = { client, service: new VoiceService(client) }
}
return cachedVoiceService.service
}
const resolveVideoService = (): VideoAssetService | null => {
const client = getChatDb()?.getWcdb4Client()
if (!client) return null
if (!cachedVideoService || cachedVideoService.client !== client) {
cachedVideoService = { client, service: new VideoAssetService(client) }
}
return cachedVideoService.service
}
const getAccountId = (): string => String(getSelfAccountInfo()?.wxid || '')
const messageRefSigner = new ExtensionMessageRefSigner()
manager = new ExtensionManager({
paths: getExtensionPaths(),
appVersion: options.appVersion,
getCapability: () => personalWechatCapabilityService.getPersonalWechatSendCapability(),
checkEntitlement: () => checkExtensionSendEntitlement(),
executeAction: (request) => wechatActionGateway.execute(request),
queryMessages: queryConversationMessages,
encodeMessageRef: (ref) => messageRefSigner.sign(ref),
onAccountChanged: (accountId) => messageRefSigner.syncAccount(accountId),
queryMessages: (request) =>
queryConversationMessages(request, getAccountId(), (ref) => messageRefSigner.sign(ref)),
createMediaGateway: ({ hasPermission, isConversationAllowed, getExtensionDataRoot }) =>
new ExtensionMediaGateway({
isDatabaseReady: () => {
try {
return isReady()
} catch {
return false
}
},
getAccountId,
getExtensionDataRoot,
hasPermission,
isConversationAllowed,
verifySignedRef: (rawRef, expectedAccountId) =>
messageRefSigner.verify(rawRef, expectedAccountId),
resolveMessage: resolveMediaMessageByRef,
readImageData: async (message, quality) => {
const service = resolveImageDecryptService()
if (!service) {
throw new ExtensionError('CAPABILITY_UNAVAILABLE', '尚未配置图片解密密钥')
}
const primaryPath = await service.findImageFileAsync(
message.image?.md5,
message.image?.datName,
{
allowThumbnail: quality === 'thumbnail',
sessionId: message.conversationId,
createTime: message.createTimeSeconds
}
)
const resolvedQuality: 'original' | 'thumbnail' = primaryPath
? quality
: 'thumbnail'
const filePath =
primaryPath ||
(quality === 'original'
? await service.findImageFileAsync(message.image?.md5, message.image?.datName, {
allowThumbnail: true,
sessionId: message.conversationId,
createTime: message.createTimeSeconds
})
: null)
if (!filePath) return null
const decoded = await service.decryptImageToBase64WithFallbackAsync(filePath, true)
if (!decoded?.data) return null
const parsed = decodeBase64DataUrl(decoded.data)
if (!parsed) return null
return {
buffer: parsed.buffer,
mimeType: parsed.mimeType,
...(message.image?.md5 ? { imageHash: message.image.md5.toLowerCase() } : {}),
quality: resolvedQuality
}
},
readVoiceData: async (message) => {
const service = resolveVoiceService()
if (!service) {
throw new ExtensionError('DATABASE_NOT_READY', '微信数据库尚未连接')
}
const resolved = await service.resolveVoice(
message.conversationId,
message.localId ?? 0,
message.createTimeSeconds,
message.serverId
)
if (!resolved.success || !resolved.data) return null
return {
wavBuffer: Buffer.from(resolved.data, 'base64'),
...(message.voice?.durationSeconds
? { durationMs: Math.round(message.voice.durationSeconds * 1000) }
: {})
}
},
readVideoAsset: async (message) => {
const service = resolveVideoService()
if (!service) {
throw new ExtensionError('DATABASE_NOT_READY', '微信数据库尚未连接')
}
const resolved = await service.resolve(message.video?.hashes ?? [], {
createTime: message.createTimeSeconds,
byteLength: message.video?.byteLength,
duration: message.video?.duration,
width: message.video?.width,
height: message.video?.height
})
if (!resolved.success || !resolved.url) return null
const filePath = service.pathForUrl(resolved.url)
if (!filePath) return null
const posterPath = resolved.poster ? service.pathForUrl(resolved.poster) : undefined
return {
filePath,
...(posterPath ? { posterPath } : {}),
...(message.video?.duration
? { durationMs: Math.round(message.video.duration * 1000) }
: {}),
...(message.video?.width ? { width: message.video.width } : {}),
...(message.video?.height ? { height: message.video.height } : {})
}
},
getCachedOcr: (conversationId, messageId) => {
const entry = imageTextIndexService.getConversationOcr(conversationId).get(messageId)
if (!entry) return null
return { text: entry.text, language: null, engine: 'system-ocr' }
},
recognizeOcr: async (imageDataUrl, language) => {
const result = await systemOcrService.recognize({
imageDataUrl,
...(language ? { language } : {})
})
return {
success: result.success,
text: result.text,
language: result.language,
engine: result.engine,
...(result.error ? { error: result.error } : {})
}
},
transcribeVoice: async (reference, opts) => {
if (!options.voiceTranscriptionGateway) {
throw new ExtensionError('CAPABILITY_UNAVAILABLE', '语音转写服务尚未初始化')
}
const outcomes = await options.voiceTranscriptionGateway.transcribe([reference], opts)
if (!outcomes) return null
return outcomes[0] ?? null
},
analyzeImage: async (input) => {
const accountScope = createHash('sha256')
.update(getAccountId() || 'unknown')
.digest('hex')
.slice(0, 12)
if (!input.prompt) {
const response = await imageInsightService.analyze({
messageId: input.messageId,
imageHash: `${accountScope}:${input.imageHash}`,
imageDataUrl: input.imageDataUrl,
sender: input.senderName,
sentAt: input.sentAt,
sessionId: input.conversationId,
force: input.force
})
if (!response.success || !response.insight) {
throw new ExtensionError(
'CAPABILITY_UNAVAILABLE',
response.error || 'AI 图片理解调用失败'
)
}
return {
description: response.insight.description,
...(response.insight.ocrText ? { ocrText: response.insight.ocrText } : {}),
...(response.insight.tags?.length ? { tags: response.insight.tags } : {}),
...(response.insight.category ? { category: response.insight.category } : {}),
...(response.insight.model ? { model: response.insight.model } : {}),
cached: response.fromCache === true
}
}
const provider = new AIProviderService()
const runtime = provider.getVisionRuntimeConfig()
if (!runtime.configured || !runtime.providerId || !runtime.model) {
throw new ExtensionError('CAPABILITY_UNAVAILABLE', '尚未配置支持图片理解的 AI 模型')
}
const result = await provider.analyzeImage(
[
{
role: 'user',
content: [
{ type: 'text', text: input.prompt },
{ type: 'image', dataUrl: input.imageDataUrl }
]
}
],
{ providerId: runtime.providerId, modelId: runtime.model }
)
if (!result.success || !result.data) {
throw new ExtensionError('CAPABILITY_UNAVAILABLE', result.error || 'AI 图片理解调用失败')
}
return {
description: result.data.trim(),
model: runtime.modelName || runtime.model,
cached: false
}
}
}),
renderHtmlToImage: (extensionId, extensionDataRoot, request) =>
htmlRenderService.renderExtensionHtmlToPng({
extensionId,
html: request.html,
css: request.css,
extensionDataRoot,
fileName: request.fileName,
width: request.width,
maxHeight: request.maxHeight,
backgroundColor: request.backgroundColor,
timeoutMs: request.timeoutMs
}),
listGroups: async () => {
try {
return listContacts()
@@ -109,7 +391,7 @@ export async function initExtensionSystem(options: ExtensionSystemOptions): Prom
cleanupVoice: (filePath) => {
ttsService.removeGeneratedAudio(filePath)
},
getAccountId: () => String(getSelfAccountInfo()?.wxid || ''),
getAccountId,
getSelfUsernames: () => {
try {
return (getChatDb()?.getWcdb4Client()?.getMyUsernameCandidates?.() ?? []).filter(Boolean)
@@ -169,24 +451,114 @@ function normalizeQueriedMessageType(rawType: string | undefined): {
return { type: value || 'other', isTextLike: false }
}
function toResolvedMediaMessage(
conversationId: string,
message: FormattedMessage
): ResolvedExtensionMediaMessage {
const normalized = normalizeQueriedMessageType(message.type)
const contentData = message.contentData
const mediaType: ResolvedExtensionMediaMessage['type'] =
normalized.type === 'image' || contentData?.type === 'image'
? 'image'
: normalized.type === 'voice' || contentData?.type === 'voice'
? 'voice'
: normalized.type === 'video' || contentData?.type === 'video'
? 'video'
: 'other'
const videoHashes =
contentData?.type === 'video'
? [contentData.md5, contentData.newMd5, contentData.rawMd5]
.map((item) => String(item || '').trim())
.filter(Boolean)
: []
return {
messageId: message.serverId || String(message.localId ?? message.id),
...(message.localId !== undefined ? { localId: message.localId } : {}),
...(message.serverId ? { serverId: message.serverId } : {}),
conversationId,
...(message.name ? { senderName: message.name } : {}),
type: mediaType,
createTimeSeconds: message.createTime ?? 0,
...(contentData?.type === 'image'
? { image: { md5: contentData.md5, datName: contentData.datName } }
: {}),
...(mediaType === 'voice'
? {
voice: {
durationSeconds:
message.voiceDuration ??
(contentData?.type === 'voice' ? contentData.duration : undefined)
}
}
: {}),
...(contentData?.type === 'video'
? {
video: {
hashes: videoHashes,
byteLength: contentData.byteLength,
duration: contentData.duration,
width: contentData.width,
height: contentData.height
}
}
: {})
}
}
function matchesRef(message: FormattedMessage, ref: ExtensionMessageRef): boolean {
const canonicalId = message.serverId || String(message.localId ?? message.id)
if (canonicalId === ref.messageId) return true
if (message.serverId && message.serverId === ref.messageId) return true
if (ref.localId && message.localId !== undefined && String(message.localId) === ref.localId) {
return true
}
if (message.localId !== undefined && String(message.localId) === ref.messageId) return true
return message.id === ref.messageId
}
/** 结合 messageRef 的时间戳先查窄窗口,未命中再回退宽窗口,避免扫描整个会话。 */
async function resolveMediaMessageByRef(
ref: ExtensionMessageRef
): Promise<ResolvedExtensionMediaMessage | null> {
const contact = resolveMd5(ref.conversationId)
if (!contact?.md5) return null
const nowSec = Math.floor(Date.now() / 1000)
const centerSec = ref.timestamp ? Math.floor(ref.timestamp / 1000) : nowSec
const windows: Array<[number, number]> = ref.timestamp
? [
[Math.max(0, centerSec - 15), centerSec + 15],
[Math.max(0, centerSec - 300), centerSec + 300]
]
: [[Math.max(0, nowSec - 86_400), nowSec + 60]]
for (const [startSec, endSec] of windows) {
const rows = await listMessagesAsync(contact.md5, startSec, endSec, undefined, '', 'unknown')
const matched = rows.find((item) => matchesRef(item, ref))
if (matched) return toResolvedMediaMessage(ref.conversationId, matched)
}
return null
}
async function queryConversationMessages(
request: ExtensionMessagesQueryRequest
): Promise<ExtensionQueriedMessage[]> {
request: ExtensionMessagesQueryRequest,
accountId: string,
encodeRef: (ref: ExtensionMessageRef) => string
): Promise<ExtensionMessagesQueryResult> {
const contact = resolveMd5(request.conversationId)
if (!contact?.md5) throw new ExtensionError('DATABASE_NOT_READY', '找不到该会话或数据库未连接')
const limit = Math.max(1, Math.min(Number(request.limit) || 50, 500))
const startMs = request.startTime ?? Date.now() - 86_400_000
const endMs = request.endTime ?? Date.now()
const rawMessages = await listMessagesAsync(
contact.md5,
Math.floor((request.startTime ?? Date.now() - 86_400_000) / 1000),
Math.floor((request.endTime ?? Date.now()) / 1000),
Math.floor(startMs / 1000),
Math.ceil(endMs / 1000),
undefined,
'',
'unknown'
)
const sorted = [...rawMessages]
.sort((left, right) => (left.createTime ?? 0) - (right.createTime ?? 0))
.slice(-limit)
return sorted.map((message) => {
const mapped: ExtensionQueriedMessage[] = rawMessages.map((message) => {
const normalizedType = normalizeQueriedMessageType(message.type)
const quoteText =
message.contentData &&
@@ -196,17 +568,28 @@ async function queryConversationMessages(
? message.contentData.content
: ''
const resolvedText = String(message.content || quoteText || '').trim()
const messageId = message.serverId || String(message.localId ?? message.id)
const timestamp = Math.round((message.createTime ?? 0) * 1000)
const messageRef = encodeRef({
accountId,
conversationId: request.conversationId,
messageId,
...(message.localId !== undefined ? { localId: String(message.localId) } : {}),
timestamp
})
return {
messageId: message.serverId || String(message.localId ?? message.id),
messageId,
messageRef,
conversationId: request.conversationId,
...(message.senderId ? { senderId: message.senderId } : {}),
...(message.name ? { senderName: message.name } : {}),
isSelf: message.isSender === true,
type: normalizedType.type,
...(normalizedType.isTextLike && resolvedText ? { text: resolvedText } : {}),
timestamp: Math.round((message.createTime ?? 0) * 1000)
timestamp
}
})
return paginateQueriedMessages(mapped, request)
}
async function chatWithConfiguredProvider(
+77 -1
View File
@@ -146,14 +146,86 @@ const tm = {
startTime?: number
endTime?: number
limit?: number
}): Promise<{ messages: unknown[] }> {
cursor?: string
order?: 'asc' | 'desc'
types?: string[]
}): Promise<{ messages: unknown[]; nextCursor?: string; hasMore?: boolean }> {
requirePermission('messages.query')
const result = (await callHost('messages.query', { ...request }, 25_000)) as {
messages: unknown[]
nextCursor?: string
hasMore?: boolean
}
return result
}
},
media: {
async readImage(request: { messageRef: string; quality?: 'original' | 'thumbnail' }) {
requirePermission('media.read')
return callHost('media.readImage', { ...request }, 20_000)
},
async readVoice(request: { messageRef: string }) {
requirePermission('media.read')
return callHost('media.readVoice', { ...request }, 25_000)
},
async readVideo(request: { messageRef: string }) {
requirePermission('media.read')
return callHost('media.readVideo', { ...request }, 35_000)
},
async ocrImage(request: { messageRef: string; language?: string; force?: boolean }) {
requirePermission('media.ocr')
return callHost('media.ocrImage', { ...request }, 30_000)
},
async transcribeVoice(request: { messageRef: string; force?: boolean; waitMs?: number }) {
requirePermission('media.transcribe')
return callHost('media.transcribeVoice', { ...request }, 35_000)
},
async analyzeImage(request: { messageRef: string; prompt?: string; force?: boolean }) {
requirePermission('ai.vision')
return callHost('media.analyzeImage', { ...request }, 65_000)
},
async batch(request: {
items: Array<{ op: string; messageRef: string; options?: Record<string, unknown> }>
concurrency?: number
}) {
return callHost('media.batch', { ...request }, 120_000)
}
},
render: {
async htmlToImage(request: {
html: string
css?: string
fileName?: string
width?: number
maxHeight?: number
backgroundColor?: string
timeoutMs?: number
}) {
requirePermission('render.html')
return callHost('render.htmlToImage', { ...request }, 50_000)
}
},
notifications: {
async create(request: {
title: string
body?: string
level?: 'info' | 'success' | 'warning' | 'error'
dedupeKey?: string
pageId?: string
}) {
requirePermission('notifications.create')
return callHost('notifications.create', { ...request }, 8_000)
},
async list() {
requirePermission('notifications.create')
const result = (await callHost('notifications.list', {}, 8_000)) as { items?: unknown[] }
return Array.isArray(result?.items) ? result.items : []
},
async markRead(request: { id?: string; all?: boolean } = {}) {
requirePermission('notifications.create')
return callHost('notifications.markRead', { ...request }, 8_000)
}
},
wechat: {
/** 发送文本、图片、视频或语音。 */
async send(request: {
@@ -222,6 +294,10 @@ const tm = {
async chat(messages: Array<{ role: string; content: string }>) {
requirePermission('ai.chat')
return (await callHost('ai.chat', { messages }, 60_000)) as { text: string }
},
async analyzeImage(request: { messageRef: string; prompt?: string; force?: boolean }) {
requirePermission('ai.vision')
return callHost('media.analyzeImage', { ...request }, 65_000)
}
},
storage: {
+12 -87
View File
@@ -1,10 +1,8 @@
import { app, BrowserWindow } from 'electron'
import crypto from 'node:crypto'
import { appendFileSync } from 'node:fs'
import fs from 'fs-extra'
import os from 'os'
import path from 'path'
import { fileURLToPath } from 'node:url'
import {
GroupReportExportRequest,
GroupReportExportResult,
@@ -23,6 +21,7 @@ import { getReportTemplate } from '../shared/report-templates'
import type { ReportTemplateRef } from '../shared/report-template-package'
import { injectReportTemplateFragmentContract } from '../shared/report-template-fragment-contract'
import { reportTemplateService, validateReportTemplateHtml } from './report-template-service'
import { htmlRenderService } from './services/html-render-service'
const LEGACY_TEMPLATE_FILES: Record<string, string> = {
v1: 'mobile_daily_report_v1.html',
@@ -1017,95 +1016,21 @@ const captureFullPage = async (
const maxCaptureWidth = LEGACY_TEMPLATE_FILES[templateId || ''] ? 1200 : template.maxCaptureWidth
const maxCaptureHeight = templateOverride?.maxCaptureHeight || 20000
console.log(`[GroupReport] capture begin html=${htmlPath}`)
const reportSessionPartition = `report-template-${crypto.randomUUID()}`
const reportWindow = new BrowserWindow({
show: false,
opacity: 0,
skipTaskbar: true,
const result = await htmlRenderService.renderFileToPng({
htmlPath,
pngPath,
width: captureWidth,
height: 800,
frame: false,
maxWidth: maxCaptureWidth,
minHeight: 800,
maxHeight: maxCaptureHeight,
backgroundColor: '#f3f5f7',
webPreferences: {
sandbox: true,
contextIsolation: true,
nodeIntegration: false,
partition: reportSessionPartition
minPngBytes: 1000,
onBlockedRequest: (details, reason) => {
recordBlockedTemplateRequest(details as Electron.OnBeforeRequestListenerDetails, reason)
}
})
const allowedDocumentPath = path.resolve(htmlPath)
const requestHandler = (
details: Electron.OnBeforeRequestListenerDetails,
callback: (response: { cancel: boolean }) => void
): void => {
if (details.url.startsWith('file:')) {
try {
const requestedPath = path.resolve(fileURLToPath(details.url))
if (requestedPath === allowedDocumentPath) {
callback({ cancel: false })
} else {
recordBlockedTemplateRequest(details, 'file-path-not-allowed')
callback({ cancel: true })
}
} catch {
recordBlockedTemplateRequest(details, 'invalid-file-url')
callback({ cancel: true })
}
return
}
recordBlockedTemplateRequest(details, 'scheme-not-allowed')
callback({ cancel: true })
}
reportWindow.webContents.session.webRequest.onBeforeRequest(
{ urls: ['http://*/*', 'https://*/*', 'ws://*/*', 'wss://*/*', 'file://*/*'] },
requestHandler
)
reportWindow.webContents.setWindowOpenHandler(() => ({ action: 'deny' }))
reportWindow.webContents.on('will-navigate', (event) => event.preventDefault())
try {
const readyToShow = new Promise<void>((resolve) => reportWindow.once('ready-to-show', resolve))
await reportWindow.loadFile(htmlPath)
await readyToShow
console.log('[GroupReport] capture loaded html')
await reportWindow.webContents.executeJavaScript(`Promise.all([
document.fonts.ready,
...Array.from(document.images).map((img) => img.complete ? Promise.resolve() : new Promise((resolve) => {
img.addEventListener('load', resolve, { once: true });
img.addEventListener('error', resolve, { once: true });
}))
])`)
console.log('[GroupReport] capture assets ready')
const metrics = (await reportWindow.webContents.executeJavaScript(`({
width: Math.ceil(Math.max(document.documentElement.scrollWidth, document.body.scrollWidth, ${captureWidth})),
height: Math.ceil(Math.max(document.documentElement.scrollHeight, document.body.scrollHeight, 800))
})`)) as { width: number; height: number }
const width = Math.max(captureWidth, Math.min(maxCaptureWidth, Math.ceil(metrics.width)))
const height = Math.max(800, Math.min(maxCaptureHeight, Math.ceil(metrics.height)))
const [currentWidth, currentHeight] = reportWindow.getContentSize()
if (currentWidth !== width || currentHeight !== height) {
const resized = new Promise<void>((resolve) => reportWindow.once('resize', resolve))
reportWindow.setContentSize(width, height)
await resized
}
await reportWindow.webContents.executeJavaScript(
'new Promise((resolve) => requestAnimationFrame(() => requestAnimationFrame(resolve)))'
)
await new Promise((resolve) => setTimeout(resolve, 100))
console.log(`[GroupReport] capture native page width=${width} height=${height}`)
const image = await reportWindow.webContents.capturePage(
{ x: 0, y: 0, width, height },
{ stayHidden: true }
)
const png = image.toPNG()
if (png.length < 1000) throw new Error('生成的日报图片为空')
await fs.writeFile(pngPath, png)
console.log(`[GroupReport] capture ok bytes=${png.length} png=${pngPath}`)
return `data:image/png;base64,${png.toString('base64')}`
} finally {
reportWindow.webContents.session.webRequest.onBeforeRequest(null)
reportWindow.destroy()
}
console.log(`[GroupReport] capture ok bytes=${result.bytes} png=${pngPath}`)
return result.imageDataUrl
}
export const exportGroupReport = async (
+2
View File
@@ -1737,6 +1737,8 @@ app.whenReady().then(async () => { if (isLegacyMigrationHelper) {
createWindow()
void initExtensionSystem({
appVersion: app.getVersion(),
getImageDecryptService: () => ensureImageDecryptService(),
voiceTranscriptionGateway,
onChange: (extensionId, reason) => {
for (const window of BrowserWindow.getAllWindows()) {
if (!window.isDestroyed()) {
+594
View File
@@ -0,0 +1,594 @@
import { BrowserWindow } from 'electron'
import crypto from 'node:crypto'
import fs from 'fs-extra'
import os from 'node:os'
import path from 'node:path'
import { fileURLToPath } from 'node:url'
import { ExtensionError } from '../../shared/extensions/errors'
import { isSafeRelativeEntryPath } from '../../shared/extensions/manifest'
import { isPathInside } from '../extensions/extension-paths'
import { buildExtensionPrivateMediaPreviewUrl } from '../extensions/extension-protocol'
const DEFAULT_WIDTH = 430
const MIN_WIDTH = 240
const DEFAULT_MAX_WIDTH = 1600
const DEFAULT_MIN_HEIGHT = 120
const DEFAULT_MAX_HEIGHT = 16_000
const DEFAULT_MAX_HTML_BYTES = 1024 * 1024
const DEFAULT_MAX_PNG_BYTES = 20 * 1024 * 1024
const DEFAULT_TIMEOUT_MS = 20_000
const DEFAULT_MAX_CONCURRENT = 2
const MIN_VALID_PNG_BYTES = 100
/** 禁止脚本、外链、表单与框架:只允许内联样式与 data: 图片/字体。 */
export const STATIC_RENDER_CSP =
"default-src 'none'; img-src data:; style-src 'unsafe-inline'; font-src data:; media-src 'none'; script-src 'none'; connect-src 'none'; frame-src 'none'; object-src 'none'; base-uri 'none'; form-action 'none';"
const FORBIDDEN_HTML_PATTERNS: Array<{ pattern: RegExp; reason: string }> = [
{ pattern: /<\s*script\b/i, reason: '不允许包含 script 标签' },
{ pattern: /<\s*(?:iframe|frame|frameset|object|embed|applet|base)\b/i, reason: '不允许包含外部嵌入或重定向标签' },
{ pattern: /<\s*meta\b[^>]*http-equiv\s*=\s*['"]?\s*refresh/i, reason: '不允许包含 meta refresh 跳转' },
{ pattern: /\bon[a-z]{2,32}\s*=/i, reason: '不允许包含内联事件处理属性' },
{ pattern: /\b(?:javascript|vbscript)\s*:/i, reason: '不允许包含脚本协议 URL' },
{ pattern: /\b(?:src|href|xlink:href|srcset|action|poster)\s*=\s*['"]?\s*(?:https?:|wss?:|ftp:|file:|\/\/)/i, reason: '不允许引用外部网络或本地文件资源' },
{ pattern: /@import\b/i, reason: '不允许在样式中使用 @import 加载外部资源' },
{ pattern: /url\(\s*['"]?\s*(?:https?:|wss?:|ftp:|file:|\/\/)/i, reason: '不允许在样式中引用外部网络或本地文件 URL' }
]
export interface RenderBlockedRequestDetails {
url: string
method: string
resourceType: string
}
export interface RenderWindowAdapter {
loadFile: (filePath: string) => Promise<void>
onceReadyToShow: (callback: () => void) => void
onceResize: (callback: () => void) => void
getContentSize: () => [number, number]
setContentSize: (width: number, height: number) => void
executeJavaScript: (code: string) => Promise<unknown>
capturePage: (rect: { x: number; y: number; width: number; height: number }) => Promise<Buffer>
installRequestFilter: (
handler: (
details: RenderBlockedRequestDetails,
callback: (response: { cancel: boolean }) => void
) => void
) => void
clearRequestFilter: () => void
isDestroyed: () => boolean
destroy: () => void
}
export interface RenderFileToPngOptions {
htmlPath: string
pngPath: string
width?: number
maxWidth?: number
minHeight?: number
maxHeight?: number
backgroundColor?: string
timeoutMs?: number
maxPngBytes?: number
minPngBytes?: number
/** 为 true 时在 HTTP 响应头追加严格 CSP,适合不可信静态 HTML。 */
enforceStaticCsp?: boolean
/** 捕获前的帧稳定等待(毫秒);真实 Electron 默认 100ms,单元测试注入窗口时为 0。 */
settleMs?: number
onBlockedRequest?: (details: RenderBlockedRequestDetails, reason: string) => void
}
export interface RenderFileToPngResult {
pngPath: string
width: number
height: number
pixelWidth?: number
pixelHeight?: number
deviceScaleFactor?: number
bytes: number
sha256: string
imageDataUrl: string
}
export interface RenderExtensionHtmlOptions {
extensionId?: string
html: string
css?: string
/** 扩展私有数据根目录;生成的 PNG 必须落在此目录内。 */
extensionDataRoot: string
/** 可选相对文件名(默认 `rendered/render-<timestamp>.png`)。 */
fileName?: string
width?: number
maxHeight?: number
backgroundColor?: string
timeoutMs?: number
}
export interface RenderExtensionHtmlResult {
path: string
previewUrl?: string
width: number
height: number
pixelWidth?: number
pixelHeight?: number
deviceScaleFactor?: number
bytes: number
mimeType: 'image/png'
sha256: string
}
export interface HtmlRenderServiceDependencies {
createWindow?: (options: {
width: number
height: number
backgroundColor: string
partition: string
enforceStaticCsp: boolean
}) => RenderWindowAdapter
maxConcurrent?: number
maxHtmlBytes?: number
maxPngBytes?: number
tempDir?: string
}
function clampInt(value: unknown, fallback: number, min: number, max: number): number {
const parsed = Number(value)
if (!Number.isFinite(parsed)) return fallback
return Math.max(min, Math.min(max, Math.round(parsed)))
}
function normalizeBackgroundColor(value: unknown): string {
const raw = String(value || '').trim()
if (/^#[0-9a-fA-F]{3,8}$/.test(raw)) return raw
return '#ffffff'
}
/** 静态 HTML 安全校验:在进入 BrowserWindow 之前阻断脚本、事件处理器和外链。 */
export function assertSafeStaticHtml(html: string, css = '', maxBytes = DEFAULT_MAX_HTML_BYTES): void {
const htmlText = String(html ?? '')
const cssText = String(css ?? '')
if (!htmlText.trim()) {
throw new ExtensionError('INVALID_REQUEST', 'html 内容不能为空')
}
const totalBytes = Buffer.byteLength(htmlText, 'utf8') + Buffer.byteLength(cssText, 'utf8')
if (totalBytes > maxBytes) {
throw new ExtensionError(
'INVALID_REQUEST',
`HTML 与 CSS 总大小不能超过 ${Math.floor(maxBytes / 1024)}KB`
)
}
if (cssText && /<\s*\/?\s*style\b/i.test(cssText)) {
throw new ExtensionError('INVALID_REQUEST', '静态 HTML 校验未通过:css 中不允许包含 style 标签')
}
for (const rule of FORBIDDEN_HTML_PATTERNS) {
if (rule.pattern.test(htmlText) || (cssText && rule.pattern.test(cssText))) {
throw new ExtensionError('INVALID_REQUEST', `静态 HTML 校验未通过:${rule.reason}`)
}
}
}
const PNG_MAGIC = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a])
function readPngPixelDimensions(png: Buffer): { pixelWidth: number; pixelHeight: number } | null {
if (png.length < 24) return null
if (!png.subarray(0, 8).equals(PNG_MAGIC)) return null
const pixelWidth = png.readUInt32BE(16)
const pixelHeight = png.readUInt32BE(20)
if (!pixelWidth || !pixelHeight) return null
return { pixelWidth, pixelHeight }
}
/** 构造带严格 CSP 与隔离样式的完整静态 HTML 文档。 */
export function buildIsolatedHtmlDocument(html: string, css = ''): string {
const cspTag = `<meta http-equiv="Content-Security-Policy" content="${STATIC_RENDER_CSP}">`
const styleTag = css.trim() ? `<style>${css}</style>` : ''
const trimmed = html.trim()
if (/<html\b/i.test(trimmed)) {
if (/<head\b[^>]*>/i.test(trimmed)) {
return trimmed.replace(/<head\b[^>]*>/i, (match) => `${match}\n${cspTag}\n${styleTag}`)
}
return trimmed.replace(/<html\b[^>]*>/i, (match) => `${match}\n<head>${cspTag}${styleTag}</head>`)
}
return `<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
${cspTag}
<style>html,body{margin:0;padding:0;box-sizing:border-box;}</style>
${styleTag}
</head>
<body>${trimmed}</body>
</html>`
}
function createElectronRenderWindow(options: {
width: number
height: number
backgroundColor: string
partition: string
enforceStaticCsp: boolean
}): RenderWindowAdapter {
const win = new BrowserWindow({
show: false,
opacity: 0,
skipTaskbar: true,
width: options.width,
height: options.height,
frame: false,
backgroundColor: options.backgroundColor,
webPreferences: {
sandbox: true,
contextIsolation: true,
nodeIntegration: false,
webSecurity: true,
allowRunningInsecureContent: false,
partition: options.partition
}
})
win.webContents.setWindowOpenHandler(() => ({ action: 'deny' }))
win.webContents.on('will-navigate', (event) => event.preventDefault())
if (options.enforceStaticCsp) {
win.webContents.session.webRequest.onHeadersReceived((details, callback) => {
callback({
responseHeaders: {
...(details.responseHeaders ?? {}),
'Content-Security-Policy': [STATIC_RENDER_CSP]
}
})
})
}
return {
loadFile: (filePath) => win.loadFile(filePath),
onceReadyToShow: (cb) => {
win.once('ready-to-show', cb)
},
onceResize: (cb) => {
win.once('resize', cb)
},
getContentSize: () => {
const [w, h] = win.getContentSize()
return [w, h]
},
setContentSize: (w, h) => win.setContentSize(w, h),
executeJavaScript: (code) => win.webContents.executeJavaScript(code),
capturePage: async (rect) => {
const image = await win.webContents.capturePage(rect, { stayHidden: true })
return image.toPNG()
},
installRequestFilter: (handler) => {
win.webContents.session.webRequest.onBeforeRequest(
{ urls: ['http://*/*', 'https://*/*', 'ws://*/*', 'wss://*/*', 'ftp://*/*', 'file://*/*'] },
(details, callback) => {
handler(
{
url: details.url,
method: details.method,
resourceType: details.resourceType
},
callback
)
}
)
},
clearRequestFilter: () => {
win.webContents.session.webRequest.onBeforeRequest(null)
if (options.enforceStaticCsp) {
win.webContents.session.webRequest.onHeadersReceived(null)
}
},
isDestroyed: () => win.isDestroyed(),
destroy: () => {
if (!win.isDestroyed()) win.destroy()
}
}
}
/** 构造文件级网络隔离拦截器:仅放行当前单个本地 HTML 文件,拒绝所有外链与其他 file:// 路径。 */
export function createDocumentIsolationHandler(
allowedDocumentPath: string,
onBlocked?: (details: RenderBlockedRequestDetails, reason: string) => void
): (
details: RenderBlockedRequestDetails,
callback: (response: { cancel: boolean }) => void
) => void {
const normalizedAllowed = path.resolve(allowedDocumentPath)
return (details, callback) => {
if (details.url.startsWith('file:')) {
try {
const requestedPath = path.resolve(fileURLToPath(details.url))
const same =
process.platform === 'win32'
? requestedPath.toLowerCase() === normalizedAllowed.toLowerCase()
: requestedPath === normalizedAllowed
if (same) {
callback({ cancel: false })
} else {
onBlocked?.(details, 'file-path-not-allowed')
callback({ cancel: true })
}
} catch {
onBlocked?.(details, 'invalid-file-url')
callback({ cancel: true })
}
return
}
onBlocked?.(details, 'scheme-not-allowed')
callback({ cancel: true })
}
}
function withTimeout<T>(promise: Promise<T>, timeoutMs: number): Promise<T> {
return new Promise<T>((resolve, reject) => {
const timer = setTimeout(() => {
reject(new ExtensionError('ACTION_TIMEOUT', 'HTML 渲染超时'))
}, timeoutMs)
promise.then(
(value) => {
clearTimeout(timer)
resolve(value)
},
(error) => {
clearTimeout(timer)
reject(error)
}
)
})
}
/**
* 官方群聊日报与扩展 `tm.render.htmlToImage` 共用本服务:
* 隔离窗口/Session、网络拦截、尺寸与并发上限必须两侧一致。
*/
export class HtmlRenderService {
private readonly createWindow: NonNullable<HtmlRenderServiceDependencies['createWindow']>
private readonly maxConcurrent: number
private readonly maxHtmlBytes: number
private readonly maxPngBytes: number
private readonly tempDir: string
private readonly defaultSettleMs: number
private activeCount = 0
constructor(deps: HtmlRenderServiceDependencies = {}) {
this.createWindow = deps.createWindow ?? createElectronRenderWindow
this.defaultSettleMs = deps.createWindow ? 0 : 100
this.maxConcurrent = Math.max(1, deps.maxConcurrent ?? DEFAULT_MAX_CONCURRENT)
this.maxHtmlBytes = Math.max(1024, deps.maxHtmlBytes ?? DEFAULT_MAX_HTML_BYTES)
this.maxPngBytes = Math.max(1024, deps.maxPngBytes ?? DEFAULT_MAX_PNG_BYTES)
this.tempDir = deps.tempDir ?? path.join(os.tmpdir(), 'tracememo-html-render')
}
get activeRenders(): number {
return this.activeCount
}
async renderFileToPng(options: RenderFileToPngOptions): Promise<RenderFileToPngResult> {
if (this.activeCount >= this.maxConcurrent) {
throw new ExtensionError('CONCURRENCY_LIMITED', '页面渲染并发已达上限,请稍后再试')
}
const captureWidth = clampInt(options.width, DEFAULT_WIDTH, MIN_WIDTH, 2400)
const maxCaptureWidth = Math.max(
captureWidth,
clampInt(options.maxWidth, Math.max(captureWidth, DEFAULT_MAX_WIDTH), captureWidth, 2400)
)
const minCaptureHeight = clampInt(options.minHeight, DEFAULT_MIN_HEIGHT, 64, 4000)
const maxCaptureHeight = Math.max(
minCaptureHeight,
clampInt(options.maxHeight, DEFAULT_MAX_HEIGHT, minCaptureHeight, 25_000)
)
const timeoutMs = clampInt(options.timeoutMs, DEFAULT_TIMEOUT_MS, 200, 60_000)
const maxPngBytes = Math.max(1024, options.maxPngBytes ?? this.maxPngBytes)
const minPngBytes = Math.max(1, options.minPngBytes ?? MIN_VALID_PNG_BYTES)
const backgroundColor = normalizeBackgroundColor(options.backgroundColor ?? '#f3f5f7')
this.activeCount += 1
let win: RenderWindowAdapter | null = null
let wroteOutput = false
let aborted = false
try {
const partition = `html-render-${crypto.randomUUID()}`
win = this.createWindow({
width: captureWidth,
height: Math.min(800, maxCaptureHeight),
backgroundColor,
partition,
enforceStaticCsp: options.enforceStaticCsp === true
})
const currentWin = win
const isolationHandler = createDocumentIsolationHandler(
options.htmlPath,
options.onBlockedRequest
)
currentWin.installRequestFilter(isolationHandler)
const run = async (): Promise<RenderFileToPngResult> => {
const readyToShow = new Promise<void>((resolve) => currentWin.onceReadyToShow(resolve))
await currentWin.loadFile(options.htmlPath)
await readyToShow
await currentWin.executeJavaScript(`Promise.all([
document.fonts ? document.fonts.ready : Promise.resolve(),
...Array.from(document.images || []).map((img) => img.complete ? Promise.resolve() : new Promise((resolve) => {
img.addEventListener('load', resolve, { once: true });
img.addEventListener('error', resolve, { once: true });
}))
])`)
const metrics = (await currentWin.executeJavaScript(`({
width: Math.ceil(Math.max(document.documentElement.scrollWidth, document.body ? document.body.scrollWidth : 0, ${captureWidth})),
height: Math.ceil(Math.max(document.documentElement.scrollHeight, document.body ? document.body.scrollHeight : 0, ${minCaptureHeight}))
})`)) as { width?: number; height?: number } | null
const width = Math.max(
captureWidth,
Math.min(maxCaptureWidth, Math.ceil(Number(metrics?.width) || captureWidth))
)
const height = Math.max(
minCaptureHeight,
Math.min(maxCaptureHeight, Math.ceil(Number(metrics?.height) || minCaptureHeight))
)
const [currentWidth, currentHeight] = currentWin.getContentSize()
if (currentWidth !== width || currentHeight !== height) {
const resized = new Promise<void>((resolve) => {
const fallback = setTimeout(resolve, 300)
currentWin.onceResize(() => {
clearTimeout(fallback)
resolve()
})
})
currentWin.setContentSize(width, height)
await resized
}
await currentWin.executeJavaScript(
'new Promise((resolve) => requestAnimationFrame(() => requestAnimationFrame(resolve)))'
)
const settleMs = options.settleMs ?? this.defaultSettleMs
if (settleMs > 0) {
await new Promise((resolve) => setTimeout(resolve, settleMs))
}
if (aborted) {
throw new ExtensionError('ACTION_TIMEOUT', 'HTML 渲染超时')
}
const png = await currentWin.capturePage({ x: 0, y: 0, width, height })
if (aborted) {
throw new ExtensionError('ACTION_TIMEOUT', 'HTML 渲染超时')
}
if (!png || png.length < minPngBytes) {
throw new ExtensionError('RENDER_FAILED', '渲染生成的 PNG 图片为空或过小')
}
if (png.length > maxPngBytes) {
throw new ExtensionError('STORAGE_LIMIT_EXCEEDED', '渲染生成的 PNG 图片超过体积上限')
}
await fs.ensureDir(path.dirname(options.pngPath))
if (aborted) {
throw new ExtensionError('ACTION_TIMEOUT', 'HTML 渲染超时')
}
await fs.writeFile(options.pngPath, png)
if (aborted) {
await fs.remove(options.pngPath).catch(() => undefined)
throw new ExtensionError('ACTION_TIMEOUT', 'HTML 渲染超时')
}
wroteOutput = true
const sha256 = crypto.createHash('sha256').update(png).digest('hex')
const pixelDims = readPngPixelDimensions(png)
const deviceScaleFactor =
pixelDims && width > 0 ? Number((pixelDims.pixelWidth / width).toFixed(2)) : undefined
return {
pngPath: options.pngPath,
width,
height,
...(pixelDims ? { pixelWidth: pixelDims.pixelWidth, pixelHeight: pixelDims.pixelHeight } : {}),
...(deviceScaleFactor ? { deviceScaleFactor } : {}),
bytes: png.length,
sha256,
imageDataUrl: `data:image/png;base64,${png.toString('base64')}`
}
}
return await withTimeout(run(), timeoutMs)
} catch (error) {
aborted = true
if (!wroteOutput) {
await fs.remove(options.pngPath).catch(() => undefined)
}
if (error instanceof ExtensionError) throw error
throw new ExtensionError(
'RENDER_FAILED',
error instanceof Error ? error.message.slice(0, 200) : '页面渲染失败'
)
} finally {
if (win) {
try {
win.clearRequestFilter()
} catch {
// 窗口已销毁时忽略清理钩子异常。
}
try {
win.destroy()
} catch {
// 忽略重复销毁异常。
}
}
this.activeCount = Math.max(0, this.activeCount - 1)
}
}
/** 为扩展渲染静态 HTML 长图,输出严格隔离在扩展私有数据目录中。 */
async renderExtensionHtmlToPng(
options: RenderExtensionHtmlOptions
): Promise<RenderExtensionHtmlResult> {
assertSafeStaticHtml(options.html, options.css, this.maxHtmlBytes)
const dataRoot = path.resolve(options.extensionDataRoot)
const relativeTarget = this.resolveExtensionOutputPath(options.fileName)
const targetPath = path.resolve(dataRoot, relativeTarget)
if (!isPathInside(dataRoot, targetPath)) {
throw new ExtensionError('EXTENSION_INVALID_PATH', '渲染输出路径越界')
}
await fs.ensureDir(dataRoot)
await fs.ensureDir(path.dirname(targetPath))
const realRoot = await fs.realpath(dataRoot)
const realParent = await fs.realpath(path.dirname(targetPath))
if (!isPathInside(realRoot, realParent)) {
throw new ExtensionError('EXTENSION_INVALID_PATH', '渲染输出目录包含非法符号链接')
}
await fs.ensureDir(this.tempDir)
const tempHtmlPath = path.join(this.tempDir, `ext-render-${crypto.randomUUID()}.html`)
const documentHtml = buildIsolatedHtmlDocument(options.html, options.css)
try {
await fs.writeFile(tempHtmlPath, documentHtml, 'utf8')
const rendered = await this.renderFileToPng({
htmlPath: tempHtmlPath,
pngPath: targetPath,
width: clampInt(options.width, DEFAULT_WIDTH, MIN_WIDTH, DEFAULT_MAX_WIDTH),
maxWidth: DEFAULT_MAX_WIDTH,
minHeight: DEFAULT_MIN_HEIGHT,
maxHeight: clampInt(options.maxHeight, DEFAULT_MAX_HEIGHT, DEFAULT_MIN_HEIGHT, DEFAULT_MAX_HEIGHT),
backgroundColor: options.backgroundColor ?? '#ffffff',
timeoutMs: clampInt(options.timeoutMs, DEFAULT_TIMEOUT_MS, 500, 45_000),
maxPngBytes: this.maxPngBytes,
enforceStaticCsp: true
})
const previewUrl = options.extensionId
? buildExtensionPrivateMediaPreviewUrl(options.extensionId, dataRoot, rendered.pngPath)
: undefined
return {
path: rendered.pngPath,
...(previewUrl ? { previewUrl } : {}),
width: rendered.width,
height: rendered.height,
...(rendered.pixelWidth !== undefined ? { pixelWidth: rendered.pixelWidth } : {}),
...(rendered.pixelHeight !== undefined ? { pixelHeight: rendered.pixelHeight } : {}),
...(rendered.deviceScaleFactor !== undefined
? { deviceScaleFactor: rendered.deviceScaleFactor }
: {}),
bytes: rendered.bytes,
mimeType: 'image/png',
sha256: rendered.sha256
}
} finally {
await fs.remove(tempHtmlPath).catch(() => undefined)
}
}
private resolveExtensionOutputPath(fileName: string | undefined): string {
const raw = String(fileName || '').trim()
if (!raw) {
return path.join('rendered', `render-${Date.now().toString(36)}-${crypto.randomBytes(4).toString('hex')}.png`)
}
const normalized = raw.replace(/\\/g, '/')
if (!isSafeRelativeEntryPath(normalized)) {
throw new ExtensionError('EXTENSION_INVALID_PATH', '输出文件名包含非法路径片段')
}
const withExt = normalized.toLowerCase().endsWith('.png') ? normalized : `${normalized}.png`
return withExt.startsWith('rendered/') ? withExt : `rendered/${withExt}`
}
}
export const htmlRenderService = new HtmlRenderService()
+16 -1
View File
@@ -7,13 +7,16 @@ import type {
import type {
ExtensionInstallResult,
ExtensionLogEntry,
ExtensionNotificationItem,
ExtensionNotificationSummary,
ExtensionOperationResult,
ExtensionPageDescriptor,
ExtensionPageResponse,
ExtensionActionInfo,
ExtensionProjectResult,
ExtensionSystemHealth,
InstalledExtension
InstalledExtension,
PinnedExtensionNavItem
} from '../shared/extensions/types'
import type { ExtensionTemplateStatus } from '../shared/extensions/templates'
import {
@@ -924,6 +927,18 @@ declare global {
) => Promise<ExtensionPageDescriptor>
extensionPageRequest: (request: ExtensionPageRequest) => Promise<ExtensionPageResponse>
openExtensionDataDir: (extensionId: string) => Promise<{ success: boolean; error?: string }>
listPinnedExtensionNav: () => Promise<PinnedExtensionNavItem[]>
pinExtensionNav: (extensionId: string, pageId?: string) => Promise<ExtensionOperationResult>
unpinExtensionNav: (extensionId: string) => Promise<ExtensionOperationResult>
reorderPinnedExtensionNav: (extensionIds: string[]) => Promise<ExtensionOperationResult>
listExtensionNotifications: (extensionId?: string) => Promise<ExtensionNotificationItem[]>
getExtensionNotificationSummary: () => Promise<ExtensionNotificationSummary>
markExtensionNotificationsRead: (payload: {
id?: string
extensionId?: string
all?: boolean
}) => Promise<{ changed: number }>
clearExtensionNotifications: (extensionId?: string) => Promise<{ removed: number }>
onExtensionChanged: (callback: (event: ExtensionChangedEvent) => void) => () => void
}
}
+23 -1
View File
@@ -147,6 +147,8 @@ import type { ExtensionChangedEvent } from '../shared/extensions/ipc'
import type {
ExtensionInstallResult,
ExtensionLogEntry,
ExtensionNotificationItem,
ExtensionNotificationSummary,
ExtensionOperationResult,
ExtensionPageDescriptor,
ExtensionPageRequest,
@@ -154,7 +156,8 @@ import type {
ExtensionActionInfo,
ExtensionProjectResult,
ExtensionSystemHealth,
InstalledExtension
InstalledExtension,
PinnedExtensionNavItem
} from '../shared/extensions/types'
import type { ExtensionTemplateStatus } from '../shared/extensions/templates'
@@ -375,6 +378,25 @@ const api = {
ipcRenderer.invoke('extension:pageRequest', request),
openExtensionDataDir: (extensionId: string): Promise<{ success: boolean; error?: string }> =>
ipcRenderer.invoke('extension:openDataDir', extensionId),
listPinnedExtensionNav: (): Promise<PinnedExtensionNavItem[]> =>
ipcRenderer.invoke('extension:pinnedNavigation'),
pinExtensionNav: (extensionId: string, pageId?: string): Promise<ExtensionOperationResult> =>
ipcRenderer.invoke('extension:pinNavigation', { id: extensionId, pageId }),
unpinExtensionNav: (extensionId: string): Promise<ExtensionOperationResult> =>
ipcRenderer.invoke('extension:unpinNavigation', extensionId),
reorderPinnedExtensionNav: (extensionIds: string[]): Promise<ExtensionOperationResult> =>
ipcRenderer.invoke('extension:reorderNavigation', extensionIds),
listExtensionNotifications: (extensionId?: string): Promise<ExtensionNotificationItem[]> =>
ipcRenderer.invoke('extension:notificationsList', extensionId),
getExtensionNotificationSummary: (): Promise<ExtensionNotificationSummary> =>
ipcRenderer.invoke('extension:notificationsSummary'),
markExtensionNotificationsRead: (payload: {
id?: string
extensionId?: string
all?: boolean
}): Promise<{ changed: number }> => ipcRenderer.invoke('extension:notificationsMarkRead', payload),
clearExtensionNotifications: (extensionId?: string): Promise<{ removed: number }> =>
ipcRenderer.invoke('extension:notificationsClear', extensionId),
onExtensionChanged: (callback: (event: ExtensionChangedEvent) => void) => {
const listener = (_event: Electron.IpcRendererEvent, payload: ExtensionChangedEvent): void =>
callback(payload)
+50 -1
View File
@@ -53,7 +53,12 @@ import {
type AutomationOpenRuleRequest
} from './features/automation/AutomationWorkspace'
import { ExtensionWorkspace } from './features/extensions/ExtensionWorkspace'
import type { ExtensionDeepLink } from '../../shared/extensions/types'
import { ExtensionPageHost } from './features/extensions/ExtensionPageHost'
import type {
ExtensionDeepLink,
ExtensionPageDescriptor,
PinnedExtensionNavItem
} from '../../shared/extensions/types'
import { selectContactAvatarRefreshUsernames } from './utils/contact-avatar'
import {
buildContactSearchIndex,
@@ -267,6 +272,10 @@ function App(): React.ReactElement {
const [activePage, setActivePage] = useState<AppPage>('archive')
/** 从其它页面跳到扩展中心时的定位目标;扩展中心消费后清空。 */
const [extensionDeepLink, setExtensionDeepLink] = useState<ExtensionDeepLink | null>(null)
/** 通过一级导航固定入口直接打开的扩展页面,复用同一个 ExtensionPageHost 容器。 */
const [pinnedExtensionPage, setPinnedExtensionPage] = useState<ExtensionPageDescriptor | null>(
null
)
/** 「退群监控 ⇄ 自动化」之间的跨页深链。 */
const [automationOpenRuleRequest, setAutomationOpenRuleRequest] =
React.useState<AutomationOpenRuleRequest | null>(null)
@@ -1604,11 +1613,36 @@ function App(): React.ReactElement {
/** 跳到扩展中心并带上定位目标(模板 / 扩展)。 */
const openExtensionDeepLink = (target: ExtensionDeepLink): void => {
setPinnedExtensionPage(null)
setExtensionDeepLink(target)
handlePageChange('extensions')
}
const openPinnedExtensionNav = (item: PinnedExtensionNavItem): void => {
void window.api.markExtensionNotificationsRead?.({ extensionId: item.extensionId }).catch(() => undefined)
void window.api
.getExtensionPageUrl(item.extensionId, item.pageId)
.then((descriptor) => {
setPinnedExtensionPage(descriptor)
})
.catch(() => {
setPinnedExtensionPage(null)
openExtensionDeepLink({ extensionId: item.extensionId })
})
}
React.useEffect(() => {
if (typeof window === 'undefined' || typeof window.api?.onExtensionChanged !== 'function') return
return window.api.onExtensionChanged((event) => {
if (event.reason !== 'uninstalled') return
setPinnedExtensionPage((current) =>
current && current.extensionId === event.extensionId ? null : current
)
})
}, [])
const handlePageChange = (page: AppPage): void => {
setPinnedExtensionPage(null)
setActivePage(page)
if (page === 'archive' && selectedContact) void handleSelectContact(selectedContact)
if (page === 'settings') setSettingsCategory('account-database')
@@ -2085,6 +2119,19 @@ function App(): React.ReactElement {
)
const renderCurrentWorkspace = (): React.ReactElement => {
if (pinnedExtensionPage) {
return (
<div className="extension-page-wrapper">
<ExtensionPageHost
descriptor={pinnedExtensionPage}
onBack={() => {
setPinnedExtensionPage(null)
setActivePage('extensions')
}}
/>
</div>
)
}
switch (activePage) {
case 'archive':
return renderArchiveWorkspace()
@@ -2382,6 +2429,8 @@ function App(): React.ReactElement {
dbReady={isDatabaseConnected}
dbConnecting={isDatabaseConnecting}
onPageChange={handlePageChange}
activePinnedExtensionId={pinnedExtensionPage?.extensionId ?? null}
onOpenPinnedExtension={openPinnedExtensionNav}
onOpenSettings={openSettings}
onOpenGuide={openFirstUseGuide}
appearanceTheme={appearanceSettings.theme}
@@ -2,6 +2,7 @@ import React from 'react'
import { AccountSummary } from '../account/AccountSummary'
import { PrimaryNavigation } from './PrimaryNavigation'
import { AppPage, PRIMARY_NAV_ITEMS } from './navigation'
import type { PinnedExtensionNavItem } from '../../../../shared/extensions/types'
import brandIcon from '../../assets/brand-icon.svg'
interface SelfInfo {
@@ -17,6 +18,8 @@ interface AppShellProps {
dbReady: boolean
dbConnecting?: boolean
onPageChange: (page: AppPage) => void
activePinnedExtensionId?: string | null
onOpenPinnedExtension?: (item: PinnedExtensionNavItem) => void
onOpenSettings: () => void
onOpenGuide: () => void
appearanceTheme?: 'system' | 'light' | 'dark'
@@ -38,6 +41,8 @@ export function AppShell({
dbReady,
dbConnecting = false,
onPageChange,
activePinnedExtensionId,
onOpenPinnedExtension,
onOpenSettings,
onOpenGuide,
appearanceTheme = 'system',
@@ -57,7 +62,12 @@ export function AppShell({
<div className={`app-shell theme-${appearanceTheme} ${compactMode ? 'is-compact' : ''}`}>
<aside className="app-primary-rail">
<BrandLogo />
<PrimaryNavigation activePage={activePage} onPageChange={onPageChange} />
<PrimaryNavigation
activePage={activePage}
onPageChange={onPageChange}
activePinnedExtensionId={activePinnedExtensionId}
onOpenPinnedExtension={onOpenPinnedExtension}
/>
<button
type="button"
className="app-guide-launcher"
@@ -1,6 +1,11 @@
import React from 'react'
import { AppPage, PRIMARY_NAV_ITEMS } from './navigation'
import type { GroupExitMonitorState } from '../../../../shared/group-exit-monitor'
import type { ExtensionNavigationIcon } from '../../../../shared/extensions/manifest'
import type {
ExtensionNotificationSummary,
PinnedExtensionNavItem
} from '../../../../shared/extensions/types'
interface NavIconProps {
page: AppPage
@@ -9,6 +14,76 @@ interface NavIconProps {
interface PrimaryNavigationProps {
activePage: AppPage
onPageChange: (page: AppPage) => void
/** 可选外部注入(便于测试);省略时自动从宿主加载并订阅变更。 */
pinnedExtensions?: PinnedExtensionNavItem[]
/** 可选外部注入(便于测试);省略时自动从宿主加载扩展通知汇总。 */
notificationSummary?: ExtensionNotificationSummary
activePinnedExtensionId?: string | null
onOpenPinnedExtension?: (item: PinnedExtensionNavItem) => void
}
function ExtensionNavIcon({ icon }: { icon: ExtensionNavigationIcon }): React.ReactElement {
switch (icon) {
case 'spark':
return (
<svg viewBox="0 0 24 24" aria-hidden="true" focusable="false">
<path d="M12 3.5 14.3 9.7 20.5 12l-6.2 2.3L12 20.5l-2.3-6.2L3.5 12l6.2-2.3L12 3.5Z" />
</svg>
)
case 'bot':
return (
<svg viewBox="0 0 24 24" aria-hidden="true" focusable="false">
<rect x="5" y="7.5" width="14" height="10.5" rx="3" />
<path d="M12 4.5v3" />
<circle cx="9.5" cy="12.5" r="1" />
<circle cx="14.5" cy="12.5" r="1" />
</svg>
)
case 'digest':
return (
<svg viewBox="0 0 24 24" aria-hidden="true" focusable="false">
<path d="M6 4.5h9l3 3v12H6z" />
<path d="M9 10h6" />
<path d="M9 13.5h6" />
<path d="M9 17h4" />
</svg>
)
case 'bell':
return (
<svg viewBox="0 0 24 24" aria-hidden="true" focusable="false">
<path d="M7 16.5h10l-1.2-2.2V10a3.8 3.8 0 0 0-7.6 0v4.3L7 16.5Z" />
<path d="M10.5 19a1.5 1.5 0 0 0 3 0" />
</svg>
)
case 'media':
return (
<svg viewBox="0 0 24 24" aria-hidden="true" focusable="false">
<rect x="4.5" y="6" width="15" height="12" rx="2" />
<circle cx="9.5" cy="10.5" r="1.4" />
<path d="m6.5 16 4-3.5 2.8 2.2 2.2-1.8 2 3.1" />
</svg>
)
case 'compass':
return (
<svg viewBox="0 0 24 24" aria-hidden="true" focusable="false">
<circle cx="12" cy="12" r="7.5" />
<path d="m14.8 9.2-1.8 4.6-4.6 1.8 1.8-4.6 4.6-1.8Z" />
</svg>
)
case 'message':
return (
<svg viewBox="0 0 24 24" aria-hidden="true" focusable="false">
<path d="M5 6.5h14v9H9.5L6 18.5v-3H5v-9Z" />
</svg>
)
case 'puzzle':
default:
return (
<svg viewBox="0 0 24 24" aria-hidden="true" focusable="false">
<path d="M9.5 4.5h5v2a1.5 1.5 0 1 0 3 0v-2h1.5v15h-15v-15H5.5v2a1.5 1.5 0 1 1-3 0v-2H5" />
</svg>
)
}
}
function NavIcon({ page }: NavIconProps): React.ReactElement {
@@ -47,7 +122,6 @@ function NavIcon({ page }: NavIconProps): React.ReactElement {
</svg>
)
case 'extensions':
// 拼图:扩展是「往现有能力上加一块」,与自动化的闪电区分开。
return (
<svg viewBox="0 0 24 24" aria-hidden="true" focusable="false">
<path d="M9.5 4.5h5v2a1.5 1.5 0 1 0 3 0v-2h1.5v15h-15v-15H5.5v2a1.5 1.5 0 1 1-3 0v-2H5" />
@@ -64,7 +138,6 @@ function NavIcon({ page }: NavIconProps): React.ReactElement {
</svg>
)
case 'automation':
// 闪电:强调「命中即自动执行」,与退群监控的箭头区分开。
return (
<svg viewBox="0 0 24 24" aria-hidden="true" focusable="false">
<path d="M13 4.5 7.5 13h4l-.5 6.5L16.5 11h-4z" />
@@ -110,10 +183,57 @@ const SEND_CAPABILITY_POLL_MS = 30 * 60 * 1000
export function PrimaryNavigation({
activePage,
onPageChange
onPageChange,
pinnedExtensions: pinnedOverride,
notificationSummary: notificationOverride,
activePinnedExtensionId,
onOpenPinnedExtension
}: PrimaryNavigationProps): React.ReactElement {
const [unreadExitCount, setUnreadExitCount] = React.useState(0)
const [sendUnavailable, setSendUnavailable] = React.useState(false)
const [loadedPinned, setLoadedPinned] = React.useState<PinnedExtensionNavItem[]>([])
const [loadedSummary, setLoadedSummary] = React.useState<ExtensionNotificationSummary>({
totalUnread: 0,
unpinnedUnread: 0,
unreadByExtension: {}
})
const pinnedExtensions = pinnedOverride ?? loadedPinned
const notificationSummary = notificationOverride ?? loadedSummary
React.useEffect(() => {
if (pinnedOverride && notificationOverride) return
const api = typeof window !== 'undefined' ? window.api : undefined
if (!api) return
let disposed = false
const refreshExtensionNavState = (): void => {
if (!pinnedOverride && typeof api.listPinnedExtensionNav === 'function') {
void api
.listPinnedExtensionNav()
.then((items) => {
if (!disposed && Array.isArray(items)) setLoadedPinned(items)
})
.catch(() => undefined)
}
if (!notificationOverride && typeof api.getExtensionNotificationSummary === 'function') {
void api
.getExtensionNotificationSummary()
.then((summary) => {
if (!disposed && summary) setLoadedSummary(summary)
})
.catch(() => undefined)
}
}
refreshExtensionNavState()
const unsubscribe =
typeof api.onExtensionChanged === 'function'
? api.onExtensionChanged(() => refreshExtensionNavState())
: null
return () => {
disposed = true
unsubscribe?.()
}
}, [pinnedOverride, notificationOverride])
React.useEffect(() => {
const api = typeof window !== 'undefined' ? window.api : undefined
@@ -129,7 +249,6 @@ export function PrimaryNavigation({
}
checkSendCapability()
const timer = window.setInterval(checkSendCapability, SEND_CAPABILITY_POLL_MS)
// 半小时才轮一次,红点会过期;窗口重新可见时补查一次,成本可忽略。
const onVisibilityChange = (): void => {
if (!document.hidden) checkSendCapability()
}
@@ -169,34 +288,91 @@ export function PrimaryNavigation({
void api.markGroupExitMonitorRead().catch(() => undefined)
}, [activePage])
const beforeSettings = PRIMARY_NAV_ITEMS.filter((item) => item.id !== 'settings')
const settingsItem = PRIMARY_NAV_ITEMS.find((item) => item.id === 'settings')
const renderBuiltInItem = (item: (typeof PRIMARY_NAV_ITEMS)[number]): React.ReactElement => {
const unpinnedUnread = item.id === 'extensions' ? notificationSummary.unpinnedUnread : 0
const titleParts = [item.label]
if (item.id === 'extensions' && sendUnavailable) titleParts.push('当前暂无发送能力')
if (unpinnedUnread > 0) titleParts.push(`${unpinnedUnread} 条未读扩展通知`)
return (
<button
key={item.id}
type="button"
className={`primary-nav-item ${!activePinnedExtensionId && activePage === item.id ? 'active' : ''}`}
onClick={() => onPageChange(item.id)}
title={titleParts.join(' · ')}
>
<span className="primary-nav-mark" aria-hidden>
<NavIcon page={item.id} />
{item.id === 'exit-monitor' && unreadExitCount > 0 && (
<span className="primary-nav-badge">{Math.min(unreadExitCount, 99)}</span>
)}
{item.id === 'extensions' && sendUnavailable && (
<span
className="primary-nav-badge primary-nav-badge-warn"
data-badge-kind="send-warning"
title="当前暂无发送能力"
>
!
</span>
)}
{unpinnedUnread > 0 && (
<span
className={`primary-nav-badge primary-nav-badge-notification ${sendUnavailable ? 'primary-nav-badge-bottom' : ''}`}
data-badge-kind="extension-unread"
title={`未固定扩展有 ${unpinnedUnread} 条未读通知`}
>
{Math.min(unpinnedUnread, 99)}
</span>
)}
</span>
<span className="primary-nav-label">{item.label}</span>
</button>
)
}
return (
<nav className="primary-navigation" aria-label="一级导航">
{PRIMARY_NAV_ITEMS.map((item) => (
<button
key={item.id}
type="button"
className={`primary-nav-item ${activePage === item.id ? 'active' : ''}`}
onClick={() => onPageChange(item.id)}
title={
item.id === 'extensions' && sendUnavailable
? `${item.label}(当前暂无发送能力)`
: item.label
}
>
<span className="primary-nav-mark" aria-hidden>
<NavIcon page={item.id} />
{item.id === 'exit-monitor' && unreadExitCount > 0 && (
<span className="primary-nav-badge">{Math.min(unreadExitCount, 99)}</span>
)}
{item.id === 'extensions' && sendUnavailable && (
<span className="primary-nav-badge" title="当前暂无发送能力">
!
</span>
)}
</span>
<span className="primary-nav-label">{item.label}</span>
</button>
))}
{beforeSettings.map(renderBuiltInItem)}
{pinnedExtensions.length > 0 && (
<>
<div className="primary-nav-divider" role="separator" aria-hidden />
{pinnedExtensions.map((item) => {
const isActive = activePinnedExtensionId === item.extensionId
const unread = notificationSummary.unreadByExtension[item.extensionId] ?? 0
return (
<button
key={`ext:${item.extensionId}`}
type="button"
data-pinned-extension-id={item.extensionId}
className={`primary-nav-item primary-nav-item-pinned ${isActive ? 'active' : ''}`}
onClick={() => onOpenPinnedExtension?.(item)}
title={
unread > 0
? `${item.label}(${unread} 条未读通知)`
: `${item.label}(已固定扩展)`
}
>
<span className="primary-nav-mark" aria-hidden>
<ExtensionNavIcon icon={item.icon} />
{unread > 0 && (
<span
className="primary-nav-badge primary-nav-badge-notification"
data-badge-kind="pinned-unread"
>
{Math.min(unread, 99)}
</span>
)}
</span>
<span className="primary-nav-label">{item.label}</span>
</button>
)
})}
</>
)}
{settingsItem && renderBuiltInItem(settingsItem)}
</nav>
)
}
@@ -6,9 +6,12 @@ import {
} from '../../../../shared/extensions/permissions'
import type {
ExtensionLogEntry,
ExtensionNotificationItem,
ExtensionNotificationSummary,
ExtensionPageDescriptor,
ExtensionSystemHealth,
InstalledExtension
InstalledExtension,
PinnedExtensionNavItem
} from '../../../../shared/extensions/types'
import type {
ExtensionTemplateEntry,
@@ -78,8 +81,10 @@ export function ExtensionWorkspace({
const [templates, setTemplates] = React.useState<ExtensionTemplateStatus[]>([])
const [templatesLoading, setTemplatesLoading] = React.useState(true)
const [installingTemplate, setInstallingTemplate] = React.useState<string | null>(null)
/** 右侧主区域:扩展列表 or 官方模板画廊。 */
const [view, setView] = React.useState<'extensions' | 'templates' | 'guide'>('extensions')
/** 右侧主区域:扩展列表、官方模板画廊、二次开发引导或通知中心。 */
const [view, setView] = React.useState<'extensions' | 'templates' | 'guide' | 'notifications'>(
'extensions'
)
/** 深链定位的模板:进入画廊时自动展开它。 */
const [focusedTemplateId, setFocusedTemplateId] = React.useState<string | null>(null)
/** 正在创建项目的模板;非空时显示创建对话框。 */
@@ -98,20 +103,51 @@ export function ExtensionWorkspace({
message?: string
} | null>(null)
const [sendMaskDismissed, setSendMaskDismissed] = React.useState(false)
const [pinnedNavItems, setPinnedNavItems] = React.useState<PinnedExtensionNavItem[]>([])
const [notifications, setNotifications] = React.useState<ExtensionNotificationItem[]>([])
const [notificationSummary, setNotificationSummary] =
React.useState<ExtensionNotificationSummary>({
totalUnread: 0,
unpinnedUnread: 0,
unreadByExtension: {}
})
const refresh = React.useCallback(async (): Promise<void> => {
const loadSendCap =
typeof window.api?.getPersonalWechatSendCapability === 'function'
? window.api.getPersonalWechatSendCapability().catch(() => null)
: Promise.resolve(null)
const [list, systemHealth, templateList, nextSendCap] = await Promise.all([
window.api.listExtensions(),
window.api.getExtensionHealth().catch(() => null),
window.api.listExtensionTemplates().catch(() => []),
loadSendCap
])
const loadPinnedNav =
typeof window.api?.listPinnedExtensionNav === 'function'
? window.api.listPinnedExtensionNav().catch(() => [])
: Promise.resolve([])
const loadNotifications =
typeof window.api?.listExtensionNotifications === 'function'
? window.api.listExtensionNotifications().catch(() => [])
: Promise.resolve([])
const loadNotificationSummary =
typeof window.api?.getExtensionNotificationSummary === 'function'
? window.api.getExtensionNotificationSummary().catch(() => ({
totalUnread: 0,
unpinnedUnread: 0,
unreadByExtension: {}
}))
: Promise.resolve({ totalUnread: 0, unpinnedUnread: 0, unreadByExtension: {} })
const [list, systemHealth, templateList, nextSendCap, nextPinnedNav, nextNotifications, nextSummary] =
await Promise.all([
window.api.listExtensions(),
window.api.getExtensionHealth().catch(() => null),
window.api.listExtensionTemplates().catch(() => []),
loadSendCap,
loadPinnedNav,
loadNotifications,
loadNotificationSummary
])
setExtensions(list)
setHealth(systemHealth)
setPinnedNavItems(nextPinnedNav)
setNotifications(nextNotifications)
setNotificationSummary(nextSummary)
setTemplates(templateList)
setSendCapability(nextSendCap)
setTemplatesLoading(false)
@@ -556,6 +592,86 @@ export function ExtensionWorkspace({
}
}
const togglePinNavigation = async (extension: InstalledExtension): Promise<void> => {
setBusy(true)
try {
const result = extension.pinnedToNav
? await window.api.unpinExtensionNav(extension.id)
: await window.api.pinExtensionNav(
extension.id,
extension.navigation?.pageId || extension.pages[0]?.id
)
if (!result.success) {
toast({
title: extension.pinnedToNav ? '取消固定失败' : '固定到一级菜单失败',
description: result.error?.message || '操作失败',
variant: 'destructive'
})
} else {
toast({
title: extension.pinnedToNav ? '已从一级菜单移除' : '已固定到一级菜单',
description: extension.pinnedToNav
? `${extension.name} 已取消固定`
: `${extension.name} 已显示在设置上方`
})
}
await refresh()
} finally {
setBusy(false)
}
}
const movePinnedNavigation = async (extensionId: string, delta: -1 | 1): Promise<void> => {
const ids = pinnedNavItems.map((item) => item.extensionId)
const index = ids.indexOf(extensionId)
const target = index + delta
if (index < 0 || target < 0 || target >= ids.length) return
const next = [...ids]
;[next[index], next[target]] = [next[target], next[index]]
setBusy(true)
try {
await window.api.reorderPinnedExtensionNav(next)
await refresh()
} finally {
setBusy(false)
}
}
const openNotificationTarget = async (item: ExtensionNotificationItem): Promise<void> => {
await window.api.markExtensionNotificationsRead?.({ id: item.id }).catch(() => undefined)
const targetExtension = extensions.find((ext) => ext.id === item.extensionId)
if (targetExtension && targetExtension.pages.length > 0) {
try {
const descriptor = await window.api.getExtensionPageUrl(
item.extensionId,
item.pageId || targetExtension.pages[0]?.id
)
setPage(descriptor)
void refresh().catch(() => undefined)
return
} catch {
// 页面不可用时退回该扩展详情。
}
}
setSelectedId(item.extensionId)
setView('extensions')
void refresh().catch(() => undefined)
}
const markAllNotificationsRead = async (): Promise<void> => {
await window.api.markExtensionNotificationsRead?.({ all: true }).catch(() => undefined)
await refresh()
}
const clearAllNotifications = async (): Promise<void> => {
await window.api.clearExtensionNotifications?.().catch(() => undefined)
await refresh()
}
const selectedPinnedIndex = selected
? pinnedNavItems.findIndex((item) => item.extensionId === selected.id)
: -1
if (page) {
return (
<div className="extension-page-wrapper">
@@ -657,6 +773,15 @@ export function ExtensionWorkspace({
>
二次开发
</Button>
<Button
size="sm"
variant={view === 'notifications' ? 'default' : 'outline'}
className="extension-template-entry"
onClick={() => setView(view === 'notifications' ? 'extensions' : 'notifications')}
>
扩展通知
{notificationSummary.totalUnread > 0 ? ` (${notificationSummary.totalUnread})` : ''}
</Button>
<Button
size="sm"
variant="outline"
@@ -784,7 +909,94 @@ export function ExtensionWorkspace({
</div>
</div>
)}
{view === 'guide' ? (
{view === 'notifications' ? (
<section className="extension-notifications-panel" aria-label="扩展通知中心">
<header className="extension-detail-header">
<div>
<h3>扩展通知中心</h3>
<p className="extension-detail-description">
汇总扩展主动发出的提醒;未固定到一级菜单的扩展未读数会自动聚合到左侧「扩展」角标。
</p>
</div>
<div className="extension-detail-actions">
<Button
size="sm"
variant="outline"
disabled={notificationSummary.totalUnread === 0}
onClick={() => void markAllNotificationsRead()}
>
全部标为已读
</Button>
<Button
size="sm"
variant="ghost"
disabled={notifications.length === 0}
onClick={() => void clearAllNotifications()}
>
清空通知
</Button>
</div>
</header>
{notifications.length === 0 ? (
<div className="extension-detail-empty">
<h3>暂无扩展通知</h3>
<p>扩展调用通知能力后,提醒会显示在这里并支持一键跳转到对应扩展页面。</p>
</div>
) : (
<ul className="extension-notification-list">
{notifications.map((item) => {
const levelLabel =
item.level === 'success'
? '成功'
: item.level === 'warning'
? '提醒'
: item.level === 'error'
? '异常'
: '信息'
return (
<li
key={item.id}
className={`extension-notification-item level-${item.level} ${item.read ? 'is-read' : 'is-unread'}`}
>
<div className="extension-notification-meta">
<span className={`extension-badge tone-${item.level === 'error' ? 'danger' : item.level === 'warning' ? 'warn' : item.level === 'success' ? 'ok' : 'neutral'}`}>
{levelLabel}
</span>
<strong>{item.title}</strong>
<span className="extension-muted">{item.extensionName}</span>
{!item.read && <span className="extension-notification-dot">未读</span>}
</div>
{item.body && <p className="extension-notification-body">{item.body}</p>}
<div className="extension-notification-actions">
<Button
size="sm"
variant="secondary"
onClick={() => void openNotificationTarget(item)}
>
查看页面
</Button>
{!item.read && (
<Button
size="sm"
variant="ghost"
onClick={() => {
void window.api
.markExtensionNotificationsRead?.({ id: item.id })
.then(() => refresh())
.catch(() => undefined)
}}
>
标记已读
</Button>
)}
</div>
</li>
)
})}
</ul>
)}
</section>
) : view === 'guide' ? (
<DevelopmentGuide
onBack={() => setView('extensions')}
onCreateProject={() => setView('templates')}
@@ -896,18 +1108,52 @@ export function ExtensionWorkspace({
{selected.enabled ? '停用' : '启用'}
</Button>
{selected.pages.length > 0 && (
<Button
size="sm"
variant="secondary"
onClick={() => {
void window.api
.getExtensionPageUrl(selected.id, selected.pages[0]?.id)
.then(setPage)
.catch(() => undefined)
}}
>
打开页面
</Button>
<>
<Button
size="sm"
variant="secondary"
onClick={() => {
void window.api
.getExtensionPageUrl(selected.id, selected.pages[0]?.id)
.then(setPage)
.catch(() => undefined)
}}
>
打开页面
</Button>
<Button
size="sm"
variant={selected.pinnedToNav ? 'outline' : 'ghost'}
disabled={busy}
onClick={() => void togglePinNavigation(selected)}
>
{selected.pinnedToNav ? '取消固定' : '固定到一级菜单'}
</Button>
{selected.pinnedToNav && pinnedNavItems.length > 1 && (
<>
<Button
size="sm"
variant="ghost"
disabled={busy || selectedPinnedIndex <= 0}
onClick={() => void movePinnedNavigation(selected.id, -1)}
>
上移
</Button>
<Button
size="sm"
variant="ghost"
disabled={
busy ||
selectedPinnedIndex < 0 ||
selectedPinnedIndex >= pinnedNavItems.length - 1
}
onClick={() => void movePinnedNavigation(selected.id, 1)}
>
下移
</Button>
</>
)}
</>
)}
<Button
size="sm"
+58
View File
@@ -1164,3 +1164,61 @@
border-color: color-mix(in srgb, currentColor 26%, transparent);
background: color-mix(in srgb, currentColor 6%, transparent);
}
.extension-notifications-panel {
display: flex;
flex-direction: column;
gap: 16px;
}
.extension-notification-list {
margin: 0;
padding: 0;
list-style: none;
display: flex;
flex-direction: column;
gap: 10px;
}
.extension-notification-item {
padding: 12px 14px;
border-radius: var(--wxex-radius-md, 10px);
border: 1px solid var(--wxex-border);
background: var(--wxex-bg-elevated, var(--wxex-bg-card));
display: flex;
flex-direction: column;
gap: 8px;
}
.extension-notification-item.is-unread {
border-color: color-mix(in srgb, var(--wxex-accent, #2563eb) 45%, var(--wxex-border));
}
.extension-notification-meta {
display: flex;
align-items: center;
gap: 8px;
flex-wrap: wrap;
}
.extension-notification-dot {
font-size: 11px;
padding: 1px 6px;
border-radius: 999px;
background: color-mix(in srgb, var(--wxex-accent, #2563eb) 14%, transparent);
color: var(--wxex-accent, #2563eb);
font-weight: 600;
}
.extension-notification-body {
margin: 0;
font-size: 13px;
line-height: 20px;
color: var(--wxex-text-secondary);
}
.extension-notification-actions {
display: flex;
align-items: center;
gap: 8px;
}
+8
View File
@@ -124,6 +124,14 @@ body {
}
}
.primary-nav-divider {
width: 28px;
height: 1px;
flex: 0 0 1px;
margin: 4px auto;
background: var(--border-subtle, rgba(0, 0, 0, 0.12));
}
.primary-nav-item {
width: 100%;
height: 58px;
@@ -20,6 +20,15 @@
text-align: center;
}
.primary-nav-badge-notification {
background: var(--wxex-accent, #2563eb);
}
.primary-nav-badge-bottom {
top: auto;
bottom: -6px;
}
.exit-monitor-page,
.exit-monitor-manage-page {
box-sizing: border-box;
+12 -2
View File
@@ -33,7 +33,12 @@ export const EXTENSION_ERROR_CODES = [
/** 目标目录已有文件 / 目标不可写;创建项目被拒绝。 */
'EXTENSION_PROJECT_EXISTS',
/** 检测到安装副本被用户修改,拒绝自动覆盖。 */
'EXTENSION_MODIFIED_LOCALLY'
'EXTENSION_MODIFIED_LOCALLY',
'MEDIA_NOT_FOUND',
'MEDIA_UNSUPPORTED',
'ACCOUNT_MISMATCH',
'CONCURRENCY_LIMITED',
'RENDER_FAILED'
] as const
export type ExtensionErrorCode = (typeof EXTENSION_ERROR_CODES)[number]
@@ -61,7 +66,12 @@ export const EXTENSION_ERROR_MESSAGES: Record<ExtensionErrorCode, string> = {
EXTENSION_STORAGE_CORRUPTED: '扩展配置已损坏',
EXTENSION_SOURCE_MISSING: '开发源码目录不可用',
EXTENSION_PROJECT_EXISTS: '目标项目目录不可用',
EXTENSION_MODIFIED_LOCALLY: '扩展代码已被本地修改'
EXTENSION_MODIFIED_LOCALLY: '扩展代码已被本地修改',
MEDIA_NOT_FOUND: '找不到该消息对应的媒体资源',
MEDIA_UNSUPPORTED: '该消息类型不支持当前媒体操作',
ACCOUNT_MISMATCH: '消息引用不属于当前已连接账号',
CONCURRENCY_LIMITED: '并发任务已达上限,请稍后再试',
RENDER_FAILED: '页面渲染失败'
}
export interface ExtensionErrorPayload {
+16 -2
View File
@@ -1,4 +1,5 @@
import type { ExtensionMessageType, ExtensionSubscriptions } from './manifest'
import { encodeExtensionMessageRef, type ExtensionMessageRef } from './media'
/**
* 投递给扩展的规范化消息事件。
@@ -11,6 +12,8 @@ import type { ExtensionMessageType, ExtensionSubscriptions } from './manifest'
*/
export interface ExtensionMessageEvent {
eventId: string
/** 跨实时事件与历史查询统一的消息引用,用于按需读取媒体与解析接口。 */
messageRef?: string
accountId: string
conversationId: string
messageId: string
@@ -67,6 +70,7 @@ export interface BuildExtensionMessageEventInput {
accountId: string
conversationId: string
messageId: string
localId?: string
senderId?: string
senderName?: string
isGroup: boolean
@@ -79,12 +83,22 @@ export interface BuildExtensionMessageEventInput {
}
export function buildExtensionMessageEvent(
input: BuildExtensionMessageEventInput
input: BuildExtensionMessageEventInput,
encodeRef: (ref: ExtensionMessageRef) => string = encodeExtensionMessageRef
): ExtensionMessageEvent {
const type = mapWechatMessageType(input.messageType)
const text = type === 'text' ? String(input.content ?? '') : ''
const timestamp = Math.round(input.createTimeSeconds * 1000)
const messageRef = encodeRef({
accountId: input.accountId,
conversationId: input.conversationId,
messageId: input.messageId,
...(input.localId ? { localId: input.localId } : {}),
timestamp
})
return {
eventId: input.eventId,
messageRef,
accountId: input.accountId,
conversationId: input.conversationId,
messageId: input.messageId,
@@ -95,7 +109,7 @@ export function buildExtensionMessageEvent(
type,
...(text ? { text } : {}),
mentionsMe: input.mentionsMe,
timestamp: Math.round(input.createTimeSeconds * 1000)
timestamp
}
}
+10
View File
@@ -34,6 +34,14 @@ export const EXTENSION_IPC = {
pageUrl: 'extension:getPageUrl',
pageRequest: 'extension:pageRequest',
openDataDir: 'extension:openDataDir',
pinnedNavigation: 'extension:pinnedNavigation',
pinNavigation: 'extension:pinNavigation',
unpinNavigation: 'extension:unpinNavigation',
reorderNavigation: 'extension:reorderNavigation',
notificationsList: 'extension:notificationsList',
notificationsSummary: 'extension:notificationsSummary',
notificationsMarkRead: 'extension:notificationsMarkRead',
notificationsClear: 'extension:notificationsClear',
changed: 'extension:changed'
} as const
@@ -44,6 +52,8 @@ export type ExtensionChangeReason =
| 'uninstalled'
| 'runtime'
| 'actions'
| 'navigation'
| 'notifications'
export interface ExtensionChangedEvent {
extensionId: string
+67 -3
View File
@@ -53,6 +53,27 @@ export interface ExtensionAutomationActionContribution {
description?: string
}
export const EXTENSION_NAVIGATION_ICONS = [
'spark',
'bot',
'digest',
'bell',
'media',
'puzzle',
'compass',
'message'
] as const
export type ExtensionNavigationIcon = (typeof EXTENSION_NAVIGATION_ICONS)[number]
export interface ExtensionNavigationContribution {
label: string
icon?: ExtensionNavigationIcon
/** 点击固定入口后打开的页面 id;省略时默认打开第一个页面。 */
pageId?: string
order?: number
}
export interface ExtensionSubscriptions {
messageTypes: ExtensionMessageType[]
/** 空数组 = 不按会话过滤。非空时只投递这些会话。 */
@@ -81,6 +102,7 @@ export interface ExtensionManifest {
contributions: {
pages: ExtensionPageContribution[]
automationActions: ExtensionAutomationActionContribution[]
navigation?: ExtensionNavigationContribution
}
}
@@ -281,6 +303,42 @@ function parseAutomationActions(input: unknown): ExtensionAutomationActionContri
return actions
}
function parseNavigation(
input: unknown,
pages: readonly ExtensionPageContribution[]
): ExtensionNavigationContribution | undefined | null {
if (input === undefined) return undefined
if (!input || typeof input !== 'object' || Array.isArray(input)) return null
const raw = input as Record<string, unknown>
const label = asTrimmedString(raw.label, 24)
if (!label) return null
let icon: ExtensionNavigationIcon | undefined
if (raw.icon !== undefined) {
const candidate = String(raw.icon).trim()
if (!(EXTENSION_NAVIGATION_ICONS as readonly string[]).includes(candidate)) return null
icon = candidate as ExtensionNavigationIcon
}
let pageId: string | undefined
if (raw.pageId !== undefined) {
const candidate = asTrimmedString(raw.pageId, 32)
if (!PAGE_ID_PATTERN.test(candidate)) return null
if (pages.length > 0 && !pages.some((page) => page.id === candidate)) return null
pageId = candidate
}
let order: number | undefined
if (raw.order !== undefined) {
const num = Number(raw.order)
if (!Number.isFinite(num) || num < -1000 || num > 1000) return null
order = Math.round(num)
}
return {
label,
...(icon ? { icon } : {}),
...(pageId ? { pageId } : {}),
...(order !== undefined ? { order } : {})
}
}
function fail(
message: string,
code: ManifestParseResult['code'] = 'EXTENSION_INVALID_MANIFEST'
@@ -359,9 +417,11 @@ export function parseExtensionManifest(
if (pages === null) return fail('contributions.pages 不合法')
const automationActions = parseAutomationActions(contributionsObject.automationActions)
if (automationActions === null) return fail('contributions.automationActions 不合法')
const navigation = parseNavigation(contributionsObject.navigation, pages)
if (navigation === null) return fail('contributions.navigation 不合法')
if (pages.length > 0 && !entrypoints.page) {
return fail('注册了页面但缺少 entrypoints.page')
if ((pages.length > 0 || navigation !== undefined) && !entrypoints.page) {
return fail('注册了页面或导航入口但缺少 entrypoints.page')
}
if ((subscriptions !== null || automationActions.length > 0) && !entrypoints.background) {
return fail('声明了消息订阅或自动化动作,必须提供 entrypoints.background')
@@ -391,7 +451,11 @@ export function parseExtensionManifest(
permissions,
entrypoints,
...(subscriptions ? { subscriptions } : {}),
contributions: { pages, automationActions }
contributions: {
pages,
automationActions,
...(navigation ? { navigation } : {})
}
}
if (options.appVersion) {
+293
View File
@@ -0,0 +1,293 @@
import type { ExtensionErrorPayload } from './errors'
const MESSAGE_REF_PREFIX = 'tmref1_'
const MESSAGE_REF_MAX_LENGTH = 1024
const CURSOR_PREFIX = 'tmcur1_'
const CURSOR_MAX_LENGTH = 512
export interface ExtensionMessageRef {
accountId: string
conversationId: string
messageId: string
localId?: string
/** epoch 毫秒;用于缩小媒体回查窗口与按月目录定位。 */
timestamp?: number
}
export interface ExtensionMessagesQueryCursor {
order: 'asc' | 'desc'
/** epoch 毫秒。 */
timestamp: number
messageId: string
}
function bytesToBase64Url(bytes: Uint8Array): string {
let binary = ''
for (let index = 0; index < bytes.length; index += 1) {
binary += String.fromCharCode(bytes[index])
}
return btoa(binary).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/g, '')
}
function base64UrlToBytes(value: string): Uint8Array | null {
if (!/^[A-Za-z0-9_-]+$/.test(value)) return null
const normalized = value.replace(/-/g, '+').replace(/_/g, '/')
const padded = normalized + '='.repeat((4 - (normalized.length % 4)) % 4)
try {
const binary = atob(padded)
const bytes = new Uint8Array(binary.length)
for (let index = 0; index < binary.length; index += 1) {
bytes[index] = binary.charCodeAt(index)
}
return bytes
} catch {
return null
}
}
function isSafeToken(value: unknown, maxLength: number): value is string {
if (typeof value !== 'string') return false
const trimmed = value.trim()
if (!trimmed || trimmed.length > maxLength) return false
for (let index = 0; index < trimmed.length; index += 1) {
if (trimmed.charCodeAt(index) < 32) return false
}
return true
}
/** 生成跨实时事件与历史查询统一的 opaque messageRef。 */
export function encodeExtensionMessageRef(input: ExtensionMessageRef): string {
const accountId = String(input.accountId || '').trim()
const conversationId = String(input.conversationId || '').trim()
const messageId = String(input.messageId || '').trim()
if (!conversationId || !messageId) {
throw new Error('消息引用缺少会话或消息标识')
}
const payload: Record<string, unknown> = {
v: 1,
a: accountId,
c: conversationId,
m: messageId
}
const localId = input.localId !== undefined ? String(input.localId).trim() : ''
if (localId) payload.l = localId
if (typeof input.timestamp === 'number' && Number.isFinite(input.timestamp) && input.timestamp > 0) {
payload.t = Math.round(input.timestamp)
}
const encoded = bytesToBase64Url(new TextEncoder().encode(JSON.stringify(payload)))
return `${MESSAGE_REF_PREFIX}${encoded}`
}
/** 还原 opaque messageRef;支持带宿主签名后缀的格式,篡改、超长或字段缺失一律返回 null。 */
export function decodeExtensionMessageRef(value: unknown): ExtensionMessageRef | null {
if (typeof value !== 'string') return null
const trimmed = value.trim()
if (!trimmed.startsWith(MESSAGE_REF_PREFIX) || trimmed.length > MESSAGE_REF_MAX_LENGTH) {
return null
}
const dotIndex = trimmed.indexOf('.')
const body = dotIndex > 0 ? trimmed.slice(MESSAGE_REF_PREFIX.length, dotIndex) : trimmed.slice(MESSAGE_REF_PREFIX.length)
if (dotIndex > 0) {
const suffix = trimmed.slice(dotIndex + 1)
if (!/^[A-Za-z0-9_-]{16,64}$/.test(suffix)) return null
}
const bytes = base64UrlToBytes(body)
if (!bytes) return null
try {
const parsed = JSON.parse(new TextDecoder().decode(bytes)) as Record<string, unknown>
if (!parsed || typeof parsed !== 'object' || parsed.v !== 1) return null
if (!isSafeToken(parsed.c, 160) || !isSafeToken(parsed.m, 160)) return null
const accountId = typeof parsed.a === 'string' ? parsed.a.trim() : ''
if (accountId.length > 160) return null
for (let index = 0; index < accountId.length; index += 1) {
if (accountId.charCodeAt(index) < 32) return null
}
const localId = isSafeToken(parsed.l, 120) ? parsed.l.trim() : undefined
const timestamp =
typeof parsed.t === 'number' && Number.isFinite(parsed.t) && parsed.t > 0
? Math.round(parsed.t)
: undefined
return {
accountId,
conversationId: parsed.c.trim(),
messageId: parsed.m.trim(),
...(localId ? { localId } : {}),
...(timestamp !== undefined ? { timestamp } : {})
}
} catch {
return null
}
}
/** 编码分页游标:以 (timestamp, messageId) 元组保证同秒多消息不漏不重。 */
export function encodeMessagesQueryCursor(cursor: ExtensionMessagesQueryCursor): string {
const payload = {
v: 1,
o: cursor.order === 'desc' ? 'desc' : 'asc',
t: Math.round(cursor.timestamp),
m: cursor.messageId
}
return `${CURSOR_PREFIX}${bytesToBase64Url(new TextEncoder().encode(JSON.stringify(payload)))}`
}
export function decodeMessagesQueryCursor(value: unknown): ExtensionMessagesQueryCursor | null {
if (typeof value !== 'string') return null
const trimmed = value.trim()
if (!trimmed.startsWith(CURSOR_PREFIX) || trimmed.length > CURSOR_MAX_LENGTH) return null
const bytes = base64UrlToBytes(trimmed.slice(CURSOR_PREFIX.length))
if (!bytes) return null
try {
const parsed = JSON.parse(new TextDecoder().decode(bytes)) as Record<string, unknown>
if (!parsed || typeof parsed !== 'object' || parsed.v !== 1) return null
if (parsed.o !== 'asc' && parsed.o !== 'desc') return null
if (typeof parsed.t !== 'number' || !Number.isFinite(parsed.t)) return null
if (!isSafeToken(parsed.m, 160)) return null
return {
order: parsed.o,
timestamp: Math.round(parsed.t),
messageId: parsed.m.trim()
}
} catch {
return null
}
}
export interface ExtensionMediaReadImageRequest {
messageRef: string
quality?: 'original' | 'thumbnail'
}
export interface ExtensionMediaReadImageResult {
messageRef: string
mimeType: string
bytes: number
sha256: string
/** 位于扩展私有数据目录内的可读副本路径,不暴露原始微信目录。 */
path: string
/** 扩展沙箱页面可直接加载的受控只读预览地址(tm-extension://)。 */
previewUrl?: string
quality: 'original' | 'thumbnail'
cached: boolean
}
export interface ExtensionMediaReadVoiceRequest {
messageRef: string
}
export interface ExtensionMediaReadVoiceResult {
messageRef: string
mimeType: 'audio/wav'
bytes: number
sha256: string
durationMs?: number
/** 位于扩展私有数据目录内的 WAV 副本路径。 */
path: string
/** 扩展沙箱页面可直接加载的受控只读预览地址(tm-extension://)。 */
previewUrl?: string
cached: boolean
}
export interface ExtensionMediaReadVideoRequest {
messageRef: string
}
export interface ExtensionMediaReadVideoResult {
messageRef: string
mimeType: 'video/mp4'
bytes: number
sha256: string
/** 位于扩展私有数据目录内的视频副本路径。 */
path: string
/** 扩展沙箱页面可直接加载的受控只读预览地址(tm-extension://)。 */
previewUrl?: string
posterPath?: string
posterPreviewUrl?: string
durationMs?: number
width?: number
height?: number
cached: boolean
}
export interface ExtensionMediaOcrImageRequest {
messageRef: string
language?: string
force?: boolean
}
export interface ExtensionMediaOcrImageResult {
messageRef: string
text: string
language: string | null
engine: string
cached: boolean
}
export interface ExtensionMediaTranscribeVoiceRequest {
messageRef: string
force?: boolean
/** 最多同步等待毫秒数,超时仍未完成时返回 `state: 'pending'`。 */
waitMs?: number
}
export interface ExtensionMediaTranscribeVoiceResult {
messageRef: string
state: 'transcribed' | 'pending' | 'failed'
transcript?: string
durationMs?: number
cached: boolean
error?: string
}
export interface ExtensionMediaAnalyzeImageRequest {
messageRef: string
prompt?: string
force?: boolean
}
export interface ExtensionMediaAnalyzeImageResult {
messageRef: string
description: string
ocrText?: string
tags?: string[]
category?: string
model?: string
cached: boolean
}
export type ExtensionMediaBatchOperation =
| 'readImage'
| 'readVoice'
| 'readVideo'
| 'ocrImage'
| 'transcribeVoice'
| 'analyzeImage'
export interface ExtensionMediaBatchItem {
op: ExtensionMediaBatchOperation
messageRef: string
options?: Record<string, unknown>
}
export interface ExtensionMediaBatchRequest {
items: ExtensionMediaBatchItem[]
concurrency?: number
}
export interface ExtensionMediaBatchItemResult {
index: number
op: ExtensionMediaBatchOperation
messageRef: string
ok: boolean
result?:
| ExtensionMediaReadImageResult
| ExtensionMediaReadVoiceResult
| ExtensionMediaReadVideoResult
| ExtensionMediaOcrImageResult
| ExtensionMediaTranscribeVoiceResult
| ExtensionMediaAnalyzeImageResult
error?: ExtensionErrorPayload
}
export interface ExtensionMediaBatchResult {
results: ExtensionMediaBatchItemResult[]
}
+37
View File
@@ -3,12 +3,18 @@
export const EXTENSION_PERMISSIONS = [
'messages.subscribe',
'messages.query',
'media.read',
'media.ocr',
'media.transcribe',
'contacts.list',
'wechat.send.text',
'wechat.send.image',
'wechat.send.video',
'wechat.send.voice',
'ai.chat',
'ai.vision',
'render.html',
'notifications.create',
'storage',
'automation.action',
'secrets'
@@ -42,6 +48,22 @@ export const EXTENSION_PERMISSION_INFO: Record<ExtensionPermission, ExtensionPer
description: '按会话与时间窗口读取有上限的历史消息,不能遍历全部会话。',
risk: 'high'
},
'media.read': {
label: '按需读取消息媒体',
description:
'通过 messageRef 按需读取指定消息关联的图片、语音或视频副本;原始数据库路径与密钥不会暴露给扩展。',
risk: 'high'
},
'media.ocr': {
label: '本地图片文字识别',
description: '对指定图片消息执行本机系统 OCR 识别,仅在本地运行,不上传原图。',
risk: 'medium'
},
'media.transcribe': {
label: '本地语音转文字',
description: '对指定语音消息执行本机语音识别并复用已有转写缓存。',
risk: 'medium'
},
'contacts.list': {
label: '读取群列表',
description: '读取本机通讯录中的群名称与会话 id,用于配置页选择发送目标;不包含聊天内容。',
@@ -75,6 +97,21 @@ export const EXTENSION_PERMISSION_INFO: Record<ExtensionPermission, ExtensionPer
description: '使用 TraceMemo 已配置的 AI Provider 发起对话;扩展拿不到 API Key 明文。',
risk: 'medium'
},
'ai.vision': {
label: '调用 AI 图片理解',
description: '使用 TraceMemo 已配置的视觉模型理解指定图片消息;扩展拿不到 API Key 明文。',
risk: 'medium'
},
'render.html': {
label: '渲染静态 HTML 长图',
description: '在隔离离线窗口中将静态 HTML/CSS 渲染为 PNG 长图,仅输出到该扩展自己的私有目录。',
risk: 'low'
},
'notifications.create': {
label: '发送应用内通知',
description: '向 TraceMemo 扩展通知中心写入带级别的通知,支持未读角标与跳转到本扩展页面。',
risk: 'medium'
},
storage: {
label: '扩展私有存储',
description: '读写本扩展独立的数据目录,不会接触其他扩展或官方数据。',
+73
View File
@@ -10,6 +10,17 @@ export type ExtensionHostCallMethod =
| 'storage.remove'
| 'storage.list'
| 'messages.query'
| 'media.readImage'
| 'media.readVoice'
| 'media.readVideo'
| 'media.ocrImage'
| 'media.transcribeVoice'
| 'media.analyzeImage'
| 'media.batch'
| 'render.htmlToImage'
| 'notifications.create'
| 'notifications.list'
| 'notifications.markRead'
| 'wechat.send.text'
| 'wechat.send.image'
| 'wechat.send.video'
@@ -187,10 +198,16 @@ export interface ExtensionMessagesQueryRequest {
/** epoch **毫秒**。 */
endTime?: number
limit?: number
/** 上一页返回的 opaque 游标;与 order 配合保证同时间戳消息不漏不重。 */
cursor?: string
order?: 'asc' | 'desc'
types?: string[]
}
export interface ExtensionQueriedMessage {
messageId: string
/** 跨实时事件与历史查询统一的消息引用,可直接传给 tm.media.* 接口。 */
messageRef?: string
conversationId: string
senderId?: string
senderName?: string
@@ -201,6 +218,12 @@ export interface ExtensionQueriedMessage {
timestamp: number
}
export interface ExtensionMessagesQueryResult {
messages: ExtensionQueriedMessage[]
nextCursor?: string
hasMore: boolean
}
export interface ExtensionSendTextRequest {
/** 群为 `xxx@chatroom`,私聊为 wxid。 */
to: string
@@ -239,3 +262,53 @@ export interface ExtensionSendTextResult {
actionId: string
status: 'sent'
}
export interface ExtensionRenderHtmlToImageRequest {
html: string
css?: string
/** 可选相对文件名(自动落盘至扩展私有目录的 rendered/ 下)。 */
fileName?: string
width?: number
maxHeight?: number
backgroundColor?: string
timeoutMs?: number
}
export interface ExtensionRenderHtmlToImageResult {
path: string
/** 扩展沙箱页面可直接加载的受控只读预览地址(tm-extension://)。 */
previewUrl?: string
width: number
height: number
pixelWidth?: number
pixelHeight?: number
deviceScaleFactor?: number
bytes: number
mimeType: 'image/png'
sha256: string
}
export type ExtensionNotificationLevel = 'info' | 'success' | 'warning' | 'error'
export interface ExtensionNotificationCreateRequest {
title: string
body?: string
level?: ExtensionNotificationLevel
dedupeKey?: string
pageId?: string
}
export interface ExtensionNotificationCreateResult {
id: string
deduped: boolean
createdAt: number
}
export interface ExtensionNotificationMarkReadRequest {
id?: string
all?: boolean
}
export interface ExtensionNotificationMarkReadResult {
changed: number
}
+39 -1
View File
@@ -1,4 +1,9 @@
import type { ExtensionCompatibility } from './manifest'
import type {
ExtensionCompatibility,
ExtensionNavigationContribution,
ExtensionNavigationIcon
} from './manifest'
import type { ExtensionNotificationLevel } from './rpc'
import type { ExtensionPermission } from './permissions'
import type { ExtensionErrorPayload } from './errors'
import type { ExtensionSource } from './source'
@@ -58,12 +63,45 @@ export interface InstalledExtension {
pendingPermissions: ExtensionPermission[]
runtime: ExtensionRuntimeSnapshot
pages: Array<{ id: string; title: string }>
navigation?: ExtensionNavigationContribution
pinnedToNav?: boolean
automationActions: ExtensionAutomationActionSummary[]
/** 扩展目录是否仍然存在;false 时 UI 必须显示为「文件缺失」而不是可启动。 */
filesPresent: boolean
storage: ExtensionStorageHealthSummary
}
export interface PinnedExtensionNavItem {
extensionId: string
extensionName: string
label: string
icon: ExtensionNavigationIcon
pageId?: string
order: number
enabled: boolean
}
export interface ExtensionNotificationItem {
id: string
extensionId: string
extensionName: string
title: string
body?: string
level: ExtensionNotificationLevel
dedupeKey?: string
pageId?: string
read: boolean
createdAt: number
updatedAt: number
}
export interface ExtensionNotificationSummary {
totalUnread: number
/** 未固定到一级导航的扩展未读总数,聚合展示在扩展中心入口。 */
unpinnedUnread: number
unreadByExtension: Record<string, number>
}
/** 从其它页面跳到扩展中心时的定位目标。 */
export interface ExtensionDeepLink {
/** 定位官方模板(打开模板画廊并展开该卡片)。 */
@@ -0,0 +1,59 @@
import { describe, expect, it, vi } from 'vitest'
import { fireEvent, render, screen } from '@testing-library/react'
import { PrimaryNavigation } from '../../src/renderer/src/components/layout/PrimaryNavigation'
import type { PinnedExtensionNavItem } from '../../src/shared/extensions/types'
describe('PrimaryNavigation 动态固定扩展入口', () => {
it('在「设置」上方按顺序渲染已固定扩展,点击后触发打开扩展回调', () => {
const onPageChange = vi.fn()
const onOpenPinnedExtension = vi.fn()
const pinned: PinnedExtensionNavItem[] = [
{
extensionId: 'com.example.digest',
extensionName: 'AI 晨报',
label: '晨报',
icon: 'digest',
pageId: 'main',
order: 0,
enabled: true
},
{
extensionId: 'com.example.group-chat-bot',
extensionName: '群聊机器人',
label: '机器人',
icon: 'bot',
pageId: 'main',
order: 1,
enabled: true
}
]
const { container } = render(
<PrimaryNavigation
activePage="archive"
onPageChange={onPageChange}
pinnedExtensions={pinned}
activePinnedExtensionId="com.example.digest"
onOpenPinnedExtension={onOpenPinnedExtension}
/>
)
const buttons = Array.from(container.querySelectorAll('button.primary-nav-item'))
const labels = buttons.map((btn) => btn.textContent?.trim())
const digestIndex = labels.indexOf('晨报')
const botIndex = labels.indexOf('机器人')
const settingsIndex = labels.indexOf('设置')
expect(digestIndex).toBeGreaterThan(-1)
expect(botIndex).toBe(digestIndex + 1)
expect(settingsIndex).toBeGreaterThan(botIndex)
// 当前打开的固定扩展高亮,且「档案」不再高亮。
expect(buttons[digestIndex].className).toContain('active')
expect(buttons[0].className).not.toContain('active')
fireEvent.click(screen.getByText('机器人'))
expect(onOpenPinnedExtension).toHaveBeenCalledWith(pinned[1])
expect(onPageChange).not.toHaveBeenCalled()
})
})
@@ -0,0 +1,55 @@
import { describe, expect, it, vi } from 'vitest'
import { render, waitFor } from '@testing-library/react'
import { PrimaryNavigation } from '../../src/renderer/src/components/layout/PrimaryNavigation'
import type {
ExtensionNotificationSummary,
PinnedExtensionNavItem
} from '../../src/shared/extensions/types'
describe('PrimaryNavigation 通知角标与发送异常提示区分', () => {
it('固定扩展显示独立未读角标,未固定扩展通知聚合至扩展中心且与发送异常 ! 区分显示', async () => {
const pinned: PinnedExtensionNavItem[] = [
{
extensionId: 'com.example.digest',
extensionName: 'AI 晨报',
label: '晨报',
icon: 'digest',
pageId: 'main',
order: 0,
enabled: true
}
]
const summary: ExtensionNotificationSummary = {
totalUnread: 5,
unpinnedUnread: 3,
unreadByExtension: {
'com.example.digest': 2,
'com.example.other': 3
}
}
;(window as unknown as { api?: Record<string, unknown> }).api = {
getPersonalWechatSendCapability: vi.fn(async () => ({ ready: false, message: '暂无发送能力' }))
}
const { container } = render(
<PrimaryNavigation
activePage="archive"
onPageChange={vi.fn()}
pinnedExtensions={pinned}
notificationSummary={summary}
/>
)
// 固定扩展角标显示 2。
const pinnedBadge = container.querySelector('[data-badge-kind="pinned-unread"]')
expect(pinnedBadge?.textContent).toBe('2')
// 扩展中心同时展示未固定通知聚合角标 (3) 与发送能力异常告警 (!),两者清晰区分。
await waitFor(() => {
expect(container.querySelector('[data-badge-kind="send-warning"]')?.textContent).toBe('!')
})
const extensionUnreadBadge = container.querySelector('[data-badge-kind="extension-unread"]')
expect(extensionUnreadBadge?.textContent).toBe('3')
})
})
@@ -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()
})
})
@@ -16,7 +16,7 @@ const packagedRoot = CANDIDATES.map((relative) => path.join(process.cwd(), relat
)
describe.skipIf(!packagedRoot)('打包后的模板资源', () => {
it('产物目录自带三个模板与索引', async () => {
it('产物目录自带四个模板与索引', async () => {
const catalog = new ExtensionTemplateCatalog({
templateRoot: packagedRoot as string,
getRecord: () => undefined,
@@ -30,7 +30,8 @@ describe.skipIf(!packagedRoot)('打包后的模板资源', () => {
expect(list.map((item) => item.template.templateId).sort()).toEqual([
'douyin-sender',
'group-chat-bot',
'keyword-bot'
'keyword-bot',
'morning-digest'
])
// 资源自包含:索引里的 zip 就在同一目录,且哈希匹配(damaged 会暴露不一致)。
expect(list.every((item) => item.state !== 'damaged')).toBe(true)
@@ -45,7 +46,7 @@ describe.skipIf(!packagedRoot)('打包后的模板资源', () => {
probePython: () => '/usr/bin/python3',
probeChrome: () => '/usr/bin/chrome'
})
for (const templateId of ['keyword-bot', 'group-chat-bot', 'douyin-sender']) {
for (const templateId of ['keyword-bot', 'group-chat-bot', 'morning-digest', 'douyin-sender']) {
const resolved = await catalog.resolveZip(templateId)
expect(fs.existsSync(resolved.path)).toBe(true)
expect(resolved.template.sha256).toMatch(/^[a-f0-9]{64}$/)
+4 -1
View File
@@ -25,9 +25,12 @@ describe('example extensions', () => {
const root = path.join(EXAMPLES_ROOT, directory)
const manifestPath = path.join(root, 'manifest.json')
expect(fs.existsSync(manifestPath), `${directory} 缺少 manifest.json`).toBe(true)
const pkg = JSON.parse(
fs.readFileSync(path.resolve(process.cwd(), 'package.json'), 'utf8')
) as { version?: string }
const parsed = parseExtensionManifest(
JSON.parse(fs.readFileSync(manifestPath, 'utf8')) as unknown,
{ appVersion: '2.6.0' }
{ appVersion: pkg.version || '2.7.0' }
)
expect(parsed.ok, `${directory}: ${parsed.message || ''}`).toBe(true)
const manifest = parsed.manifest
+560
View File
@@ -0,0 +1,560 @@
import fs from 'fs-extra'
import os from 'node:os'
import path from 'node:path'
import { afterEach, describe, expect, it, vi } from 'vitest'
import { buildExtensionMessageEvent } from '../../src/shared/extensions/events'
import {
decodeExtensionMessageRef,
encodeExtensionMessageRef
} from '../../src/shared/extensions/media'
import type { ExtensionPermission } from '../../src/shared/extensions/permissions'
import type { ExtensionQueriedMessage } from '../../src/shared/extensions/rpc'
import {
ExtensionMediaGateway,
paginateQueriedMessages,
type ResolvedExtensionMediaMessage
} from '../../src/main/extensions/extension-media-gateway'
import { ExtensionMessageRefSigner } from '../../src/main/extensions/extension-message-ref-signer'
const tempDirs: string[] = []
function makeTempDir(): string {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'tm-ext-media-'))
tempDirs.push(dir)
return dir
}
afterEach(() => {
for (const dir of tempDirs.splice(0)) fs.removeSync(dir)
})
function createHarness(overrides: {
accountId?: string
databaseReady?: boolean
permissionsByExtension?: Record<string, ExtensionPermission[]>
messages?: Record<string, ResolvedExtensionMediaMessage>
maxGlobalConcurrent?: number
maxPerExtensionConcurrent?: number
timeoutsMs?: Partial<Record<'readImage' | 'ocrImage', number>>
} = {}) {
const root = makeTempDir()
const rawVideoDir = path.join(root, 'wechat-private-root', 'msg', 'video', '2026-12')
fs.ensureDirSync(rawVideoDir)
const rawVideoPath = path.join(rawVideoDir, 'fixture-video.mp4')
const rawPosterPath = path.join(rawVideoDir, 'fixture-poster.jpg')
fs.writeFileSync(rawVideoPath, Buffer.from('fixture-mp4-binary-payload'))
fs.writeFileSync(rawPosterPath, Buffer.from('fixture-jpg-poster'))
let currentAccount = overrides.accountId ?? 'wxid_account_a'
const databaseReady = overrides.databaseReady ?? true
const permissionsByExtension = overrides.permissionsByExtension ?? {
'com.example.alpha': ['media.read', 'media.ocr', 'media.transcribe', 'ai.vision'],
'com.example.beta': ['media.read', 'media.ocr', 'media.transcribe', 'ai.vision']
}
const imageMessage: ResolvedExtensionMediaMessage = {
messageId: 'srv-img-1',
localId: 101,
serverId: 'srv-img-1',
conversationId: 'fixture-group@chatroom',
senderName: '张三',
type: 'image',
createTimeSeconds: 1_760_000_100,
image: { md5: 'a'.repeat(32), datName: 'img101' }
}
const voiceMessage: ResolvedExtensionMediaMessage = {
messageId: 'srv-voice-1',
localId: 102,
serverId: 'srv-voice-1',
conversationId: 'fixture-group@chatroom',
senderName: '李四',
type: 'voice',
createTimeSeconds: 1_760_000_200,
voice: { durationSeconds: 4 }
}
const videoMessage: ResolvedExtensionMediaMessage = {
messageId: 'srv-video-1',
localId: 103,
serverId: 'srv-video-1',
conversationId: 'fixture-group@chatroom',
senderName: '王五',
type: 'video',
createTimeSeconds: 1_760_000_300,
video: { hashes: ['b'.repeat(32)], duration: 12, width: 720, height: 1280 }
}
const messages: Record<string, ResolvedExtensionMediaMessage> = {
'srv-img-1': imageMessage,
'srv-voice-1': voiceMessage,
'srv-video-1': videoMessage,
...(overrides.messages ?? {})
}
const readImageData = vi.fn(async (_msg: ResolvedExtensionMediaMessage, quality: 'original' | 'thumbnail') => ({
buffer: Buffer.from(`png-bytes-${quality}`),
mimeType: 'image/png',
imageHash: 'hash-img-1',
quality
}))
const readVoiceData = vi.fn(async () => ({
wavBuffer: Buffer.from('RIFF-fixture-wav-data'),
durationMs: 4000
}))
const readVideoAsset = vi.fn(async () => ({
filePath: rawVideoPath,
posterPath: rawPosterPath,
durationMs: 12_000,
width: 720,
height: 1280
}))
const getCachedOcr = vi.fn<
(conversationId: string, messageId: string) => { text: string; language?: string | null; engine?: string } | null
>(() => null)
const recognizeOcr = vi.fn(async () => ({
success: true,
text: '测试图片识别文字',
language: 'zh-Hans',
engine: 'apple-vision'
}))
const transcribeVoice = vi.fn(async () => ({
state: 'transcribed' as const,
transcript: '明天上午十点开会',
cached: false,
durationMs: 4000
}))
const analyzeImage = vi.fn(async (input: { prompt?: string }) => ({
description: input.prompt ? `自定义分析:${input.prompt}` : '一张包含日程表的截图',
ocrText: '日程表',
tags: ['截图'],
category: 'screenshot',
model: 'fixture-vision',
cached: false
}))
const gateway = new ExtensionMediaGateway({
isDatabaseReady: () => databaseReady,
getAccountId: () => currentAccount,
getExtensionDataRoot: (extId) => path.join(root, 'extensions-data', extId),
hasPermission: (extId, perm) => (permissionsByExtension[extId] ?? []).includes(perm),
resolveMessage: async (ref) => messages[ref.messageId] ?? null,
readImageData,
readVoiceData,
readVideoAsset,
getCachedOcr,
recognizeOcr,
transcribeVoice,
analyzeImage,
maxGlobalConcurrent: overrides.maxGlobalConcurrent,
maxPerExtensionConcurrent: overrides.maxPerExtensionConcurrent,
timeoutsMs: overrides.timeoutsMs
})
return {
root,
rawVideoPath,
gateway,
setAccount: (next: string) => {
currentAccount = next
},
mocks: {
readImageData,
readVoiceData,
readVideoAsset,
getCachedOcr,
recognizeOcr,
transcribeVoice,
analyzeImage
}
}
}
describe('ExtensionMediaGateway 与统一 messageRef', () => {
it('实时事件与历史查询生成同一套可逆 messageRef,并拒绝篡改引用', () => {
const event = buildExtensionMessageEvent({
eventId: 'message:abc',
accountId: 'wxid_account_a',
conversationId: 'fixture-group@chatroom',
messageId: 'srv-img-1',
localId: '101',
isGroup: true,
isSelf: false,
messageType: 3,
mentionsMe: false,
createTimeSeconds: 1_760_000_100
})
const queryRef = encodeExtensionMessageRef({
accountId: 'wxid_account_a',
conversationId: 'fixture-group@chatroom',
messageId: 'srv-img-1',
localId: '101',
timestamp: 1_760_000_100_000
})
expect(event.messageRef).toBe(queryRef)
expect(decodeExtensionMessageRef(event.messageRef)).toEqual({
accountId: 'wxid_account_a',
conversationId: 'fixture-group@chatroom',
messageId: 'srv-img-1',
localId: '101',
timestamp: 1_760_000_100_000
})
expect(decodeExtensionMessageRef('invalid-ref')).toBeNull()
expect(decodeExtensionMessageRef('tmref1_!!!notbase64!!!')).toBeNull()
})
it('主进程独立拒绝未授权的媒体读取、OCR、转写与视觉理解调用', async () => {
const { gateway } = createHarness({
permissionsByExtension: { 'com.example.readonly': ['messages.query'] }
})
const imgRef = encodeExtensionMessageRef({
accountId: 'wxid_account_a',
conversationId: 'fixture-group@chatroom',
messageId: 'srv-img-1'
})
const voiceRef = encodeExtensionMessageRef({
accountId: 'wxid_account_a',
conversationId: 'fixture-group@chatroom',
messageId: 'srv-voice-1'
})
await expect(gateway.readImage('com.example.readonly', { messageRef: imgRef })).rejects.toMatchObject({
code: 'PERMISSION_DENIED'
})
await expect(gateway.ocrImage('com.example.readonly', { messageRef: imgRef })).rejects.toMatchObject({
code: 'PERMISSION_DENIED'
})
await expect(
gateway.transcribeVoice('com.example.readonly', { messageRef: voiceRef })
).rejects.toMatchObject({ code: 'PERMISSION_DENIED' })
await expect(gateway.analyzeImage('com.example.readonly', { messageRef: imgRef })).rejects.toMatchObject({
code: 'PERMISSION_DENIED'
})
})
it('跨账号 messageRef 被严格拒绝,切换账号后自动失效旧缓存', async () => {
const { gateway, setAccount, mocks } = createHarness()
const accountARef = encodeExtensionMessageRef({
accountId: 'wxid_account_a',
conversationId: 'fixture-group@chatroom',
messageId: 'srv-img-1'
})
const first = await gateway.ocrImage('com.example.alpha', { messageRef: accountARef })
expect(first.cached).toBe(false)
expect(mocks.recognizeOcr).toHaveBeenCalledTimes(1)
// 切换到账号 B 后,账号 A 的 messageRef 必须被拒绝。
setAccount('wxid_account_b')
await expect(
gateway.ocrImage('com.example.alpha', { messageRef: accountARef })
).rejects.toMatchObject({ code: 'ACCOUNT_MISMATCH' })
})
it('跨扩展媒体副本完全隔离在各自私有数据目录,不暴露原始微信路径', async () => {
const { gateway, rawVideoPath } = createHarness()
const imgRef = encodeExtensionMessageRef({
accountId: 'wxid_account_a',
conversationId: 'fixture-group@chatroom',
messageId: 'srv-img-1'
})
const videoRef = encodeExtensionMessageRef({
accountId: 'wxid_account_a',
conversationId: 'fixture-group@chatroom',
messageId: 'srv-video-1'
})
const alphaImg = await gateway.readImage('com.example.alpha', { messageRef: imgRef })
const betaImg = await gateway.readImage('com.example.beta', { messageRef: imgRef })
expect(alphaImg.path).toContain(path.join('extensions-data', 'com.example.alpha', 'media-cache'))
expect(betaImg.path).toContain(path.join('extensions-data', 'com.example.beta', 'media-cache'))
expect(alphaImg.path).not.toBe(betaImg.path)
// 同扩展二次读取命中磁盘缓存。
const alphaImgAgain = await gateway.readImage('com.example.alpha', { messageRef: imgRef })
expect(alphaImgAgain.cached).toBe(true)
const video = await gateway.readVideo('com.example.alpha', { messageRef: videoRef })
expect(video.path).not.toBe(rawVideoPath)
expect(video.path).not.toContain('wechat-private-root')
expect(video.path).toContain(path.join('extensions-data', 'com.example.alpha', 'media-cache'))
expect(fs.existsSync(video.path)).toBe(true)
expect(video.posterPath && fs.existsSync(video.posterPath)).toBe(true)
})
it('支持 OCR 索引缓存命中、语音转写复用与 AI 视觉理解缓存', async () => {
const { gateway, mocks } = createHarness()
const imgRef = encodeExtensionMessageRef({
accountId: 'wxid_account_a',
conversationId: 'fixture-group@chatroom',
messageId: 'srv-img-1'
})
const voiceRef = encodeExtensionMessageRef({
accountId: 'wxid_account_a',
conversationId: 'fixture-group@chatroom',
messageId: 'srv-voice-1'
})
// 命中既有图片文字索引缓存时不再触发 SystemOcr。
mocks.getCachedOcr.mockReturnValueOnce({ text: '索引已有 OCR', language: 'zh-Hans', engine: 'system-ocr' })
const cachedOcr = await gateway.ocrImage('com.example.alpha', { messageRef: imgRef })
expect(cachedOcr).toMatchObject({ text: '索引已有 OCR', cached: true })
expect(mocks.recognizeOcr).not.toHaveBeenCalled()
// force=true 时强制重新识别,并写入网关缓存。
const freshOcr = await gateway.ocrImage('com.example.alpha', { messageRef: imgRef, force: true })
expect(freshOcr).toMatchObject({ text: '测试图片识别文字', cached: false })
const secondOcr = await gateway.ocrImage('com.example.alpha', { messageRef: imgRef })
expect(secondOcr).toMatchObject({ text: '测试图片识别文字', cached: true })
expect(mocks.recognizeOcr).toHaveBeenCalledTimes(1)
// 语音读取与语音转写。
const voiceFile = await gateway.readVoice('com.example.alpha', { messageRef: voiceRef })
expect(voiceFile.mimeType).toBe('audio/wav')
expect(fs.existsSync(voiceFile.path)).toBe(true)
const transcript = await gateway.transcribeVoice('com.example.alpha', { messageRef: voiceRef })
expect(transcript).toMatchObject({ state: 'transcribed', transcript: '明天上午十点开会' })
// 视觉理解缓存命中,不同 prompt 隔离缓存键。
const vision1 = await gateway.analyzeImage('com.example.alpha', { messageRef: imgRef })
const vision2 = await gateway.analyzeImage('com.example.alpha', { messageRef: imgRef })
const visionCustom = await gateway.analyzeImage('com.example.alpha', {
messageRef: imgRef,
prompt: '提取价格'
})
expect(vision1.cached).toBe(false)
expect(vision2.cached).toBe(true)
expect(visionCustom.description).toBe('自定义分析:提取价格')
expect(mocks.analyzeImage).toHaveBeenCalledTimes(2)
})
it('并发限制、超时与批量部分失败隔离生效', async () => {
const { gateway, mocks } = createHarness({
maxGlobalConcurrent: 1,
maxPerExtensionConcurrent: 1,
timeoutsMs: { readImage: 60 }
})
let releaseFirst!: () => void
mocks.readImageData.mockImplementationOnce(
() =>
new Promise((resolve) => {
releaseFirst = () =>
resolve({
buffer: Buffer.from('slow-image'),
mimeType: 'image/png',
imageHash: 'hash-slow',
quality: 'original'
})
})
)
const imgRef = encodeExtensionMessageRef({
accountId: 'wxid_account_a',
conversationId: 'fixture-group@chatroom',
messageId: 'srv-img-1'
})
const voiceRef = encodeExtensionMessageRef({
accountId: 'wxid_account_a',
conversationId: 'fixture-group@chatroom',
messageId: 'srv-voice-1'
})
// 启动第一个慢任务占用唯一并发槽,第二个不同任务应命中 CONCURRENCY_LIMITED。
const slowTask = gateway.readImage('com.example.alpha', { messageRef: imgRef })
await expect(
gateway.readVoice('com.example.alpha', { messageRef: voiceRef })
).rejects.toMatchObject({ code: 'CONCURRENCY_LIMITED' })
// 等待超过 60ms,慢任务触发 ACTION_TIMEOUT。
await expect(slowTask).rejects.toMatchObject({ code: 'ACTION_TIMEOUT' })
releaseFirst()
// 批量调用中部分项类型不匹配不影响其他项成功。
const batch = await gateway.batch('com.example.alpha', {
concurrency: 1,
items: [
{ op: 'readImage', messageRef: imgRef },
{ op: 'readVoice', messageRef: imgRef },
{ op: 'transcribeVoice', messageRef: voiceRef }
]
})
expect(batch.results).toHaveLength(3)
expect(batch.results[0].ok).toBe(true)
expect(batch.results[1].ok).toBe(false)
expect(batch.results[1].error?.code).toBe('MEDIA_UNSUPPORTED')
expect(batch.results[2].ok).toBe(true)
})
it('游标分页在同时间戳多条消息下零遗漏、零重复,且兼容 v1 默认顺序', () => {
const dataset: ExtensionQueriedMessage[] = [
{ messageId: 'm1', messageRef: 'r1', conversationId: 'g1', isSelf: false, type: 'text', text: '1', timestamp: 1000 },
{ messageId: 'm2', messageRef: 'r2', conversationId: 'g1', isSelf: false, type: 'text', text: '2', timestamp: 2000 },
{ messageId: 'm3', messageRef: 'r3', conversationId: 'g1', isSelf: false, type: 'image', timestamp: 2000 },
{ messageId: 'm4', messageRef: 'r4', conversationId: 'g1', isSelf: false, type: 'text', text: '4', timestamp: 2000 },
{ messageId: 'm5', messageRef: 'r5', conversationId: 'g1', isSelf: false, type: 'voice', timestamp: 3000 }
]
// 升序分页:每页 2 条,走完刚好 5 条无遗漏无重复。
const collectedAsc: string[] = []
let cursor: string | undefined
for (let guard = 0; guard < 10; guard += 1) {
const page = paginateQueriedMessages(dataset, {
conversationId: 'g1',
order: 'asc',
limit: 2,
cursor
})
collectedAsc.push(...page.messages.map((item) => item.messageId))
if (!page.hasMore) break
cursor = page.nextCursor
}
expect(collectedAsc).toEqual(['m1', 'm2', 'm3', 'm4', 'm5'])
// 默认 v1 语义(不传 order):首屏返回最新 2 条,续页向更早历史翻页仍覆盖全部 5 条。
const firstDefault = paginateQueriedMessages(dataset, { conversationId: 'g1', limit: 2 })
expect(firstDefault.messages.map((item) => item.messageId)).toEqual(['m4', 'm5'])
expect(firstDefault.hasMore).toBe(true)
const secondDefault = paginateQueriedMessages(dataset, {
conversationId: 'g1',
limit: 2,
cursor: firstDefault.nextCursor
})
expect(secondDefault.messages.map((item) => item.messageId)).toEqual(['m2', 'm3'])
const thirdDefault = paginateQueriedMessages(dataset, {
conversationId: 'g1',
limit: 2,
cursor: secondDefault.nextCursor
})
expect(thirdDefault.messages.map((item) => item.messageId)).toEqual(['m1'])
expect(thirdDefault.hasMore).toBe(false)
// 按类型过滤。
const onlyMedia = paginateQueriedMessages(dataset, {
conversationId: 'g1',
order: 'asc',
types: ['image', 'voice'],
limit: 10
})
expect(onlyMedia.messages.map((item) => item.messageId)).toEqual(['m3', 'm5'])
// 默认模式不接受 asc 游标,避免反向错漏。
const ascFirst = paginateQueriedMessages(dataset, { conversationId: 'g1', order: 'asc', limit: 2 })
expect(() =>
paginateQueriedMessages(dataset, { conversationId: 'g1', limit: 2, cursor: ascFirst.nextCursor })
).toThrowError(/游标/)
})
it('签名校验拒绝伪造/篡改/切号旧引用、越权会话访问,且磁盘缓存按账号物理隔离', async () => {
const root = makeTempDir()
const signer = new ExtensionMessageRefSigner()
let currentAccount = 'wxid_account_a'
const imageMsg: ResolvedExtensionMediaMessage = {
messageId: 'srv-img-sec',
conversationId: 'allowed@chatroom',
type: 'image',
createTimeSeconds: 1700001000
}
const forbiddenMsg: ResolvedExtensionMediaMessage = {
messageId: 'srv-img-forbid',
conversationId: 'secret@chatroom',
type: 'image',
createTimeSeconds: 1700001000
}
const textMsg: ResolvedExtensionMediaMessage = {
messageId: 'srv-text-1',
conversationId: 'allowed@chatroom',
type: 'other',
createTimeSeconds: 1700001000
}
const gateway = new ExtensionMediaGateway({
isDatabaseReady: () => true,
getAccountId: () => currentAccount,
getExtensionDataRoot: (extId) => path.join(root, 'extensions-data', extId),
hasPermission: () => true,
isConversationAllowed: (_extId, conversationId) => conversationId === 'allowed@chatroom',
verifySignedRef: (rawRef, accountId) => signer.verify(rawRef, accountId),
resolveMessage: async (ref) => {
if (ref.messageId === 'srv-img-sec') return imageMsg
if (ref.messageId === 'srv-img-forbid') return forbiddenMsg
if (ref.messageId === 'srv-text-1') return textMsg
return null
},
readImageData: async () => ({
buffer: Buffer.from('same-image-bytes'),
mimeType: 'image/png',
quality: 'original'
}),
readVoiceData: async () => null,
readVideoAsset: async () => null,
getCachedOcr: () => ({ text: '不应该被非图片消息命中', engine: 'system-ocr' }),
recognizeOcr: async () => ({ success: true, text: 'ok', language: 'zh-Hans', engine: 'vision' }),
transcribeVoice: async () => null,
analyzeImage: async () => ({ description: 'ok' })
})
// 1. 未签名伪造的 tmref1_ 被拒绝。
const forgedRef = encodeExtensionMessageRef({
accountId: currentAccount,
conversationId: 'allowed@chatroom',
messageId: 'srv-img-sec'
})
await expect(
gateway.readImage('com.example.alpha', { messageRef: forgedRef })
).rejects.toMatchObject({ code: 'INVALID_REQUEST' })
// 2. 合法签发后正常读取,并返回受控 previewUrl。
const signedAllowed = signer.sign({
accountId: currentAccount,
conversationId: 'allowed@chatroom',
messageId: 'srv-img-sec'
})
const imgA = await gateway.readImage('com.example.alpha', { messageRef: signedAllowed })
expect(imgA.previewUrl).toMatch(/^tm-extension:\/\/com\.example\.alpha\/_data\/media-cache\//)
// 3. 篡改签发 token 任意字符被拒绝。
const tampered = `${signedAllowed.slice(0, -1)}${signedAllowed.endsWith('a') ? 'b' : 'a'}`
await expect(
gateway.readImage('com.example.alpha', { messageRef: tampered })
).rejects.toMatchObject({ code: 'INVALID_REQUEST' })
// 4. 超出声明会话范围被拒绝。
const signedForbidden = signer.sign({
accountId: currentAccount,
conversationId: 'secret@chatroom',
messageId: 'srv-img-forbid'
})
await expect(
gateway.readImage('com.example.alpha', { messageRef: signedForbidden })
).rejects.toMatchObject({ code: 'PERMISSION_DENIED' })
// 5. 非图片消息调用 ocrImage 不能误命中索引缓存。
const signedText = signer.sign({
accountId: currentAccount,
conversationId: 'allowed@chatroom',
messageId: 'srv-text-1'
})
await expect(
gateway.ocrImage('com.example.alpha', { messageRef: signedText })
).rejects.toMatchObject({ code: 'MEDIA_UNSUPPORTED' })
// 6. 切换账号到 B 后,磁盘缓存落在独立账号桶;再切回账号 A,旧世代签名引用已失效。
currentAccount = 'wxid_account_b'
const signedB = signer.sign({
accountId: currentAccount,
conversationId: 'allowed@chatroom',
messageId: 'srv-img-sec'
})
const imgB = await gateway.readImage('com.example.alpha', { messageRef: signedB })
expect(imgB.path).not.toBe(imgA.path)
expect(imgB.cached).toBe(false)
currentAccount = 'wxid_account_a'
await expect(
gateway.readImage('com.example.alpha', { messageRef: signedAllowed })
).rejects.toMatchObject({ code: 'INVALID_REQUEST' })
})
})
+202
View File
@@ -0,0 +1,202 @@
import fs from 'fs-extra'
import os from 'node:os'
import path from 'node:path'
import { afterEach, describe, expect, it } from 'vitest'
import { parseExtensionManifest } from '../../src/shared/extensions/manifest'
import { ExtensionNavigationStore } from '../../src/main/extensions/extension-navigation-store'
import { createExtensionPaths } from '../../src/main/extensions/extension-paths'
import { ExtensionManager } from '../../src/main/extensions/extension-manager'
import type { PersonalWechatSendCapability } from '../../src/shared/personal-wechat'
import type { WechatActionResult } from '../../src/shared/wechat-action'
const tempDirs: string[] = []
function makeTempDir(): string {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'tm-ext-nav-'))
tempDirs.push(dir)
return dir
}
afterEach(() => {
for (const dir of tempDirs.splice(0)) fs.removeSync(dir)
})
function writeSampleExtension(
dir: string,
id: string,
name: string,
navigation?: { label: string; icon?: string; pageId?: string }
): void {
fs.ensureDirSync(path.join(dir, 'ui'))
fs.writeFileSync(path.join(dir, 'ui', 'index.html'), '<!doctype html><html><body>hi</body></html>')
fs.writeJsonSync(path.join(dir, 'manifest.json'), {
manifestVersion: 1,
id,
name,
version: '1.0.0',
apiVersion: '1',
permissions: ['storage'],
entrypoints: { page: 'ui/index.html' },
contributions: {
pages: [{ id: 'main', title: name }],
automationActions: [],
...(navigation ? { navigation } : {})
}
})
}
describe('动态一级导航声明与持久化', () => {
it('manifest 校验 contributions.navigation 并兼容旧版无 navigation 清单', () => {
const valid = parseExtensionManifest({
manifestVersion: 1,
id: 'com.example.digest',
name: 'AI 晨报',
version: '1.0.0',
apiVersion: '1',
permissions: ['storage'],
entrypoints: { page: 'ui/index.html' },
contributions: {
pages: [{ id: 'main', title: '晨报' }],
navigation: { label: '晨报', icon: 'digest', pageId: 'main', order: 10 }
}
})
expect(valid.ok).toBe(true)
expect(valid.manifest?.contributions.navigation).toEqual({
label: '晨报',
icon: 'digest',
pageId: 'main',
order: 10
})
const legacy = parseExtensionManifest({
manifestVersion: 1,
id: 'com.example.legacy',
name: '旧扩展',
version: '1.0.0',
apiVersion: '1',
permissions: ['storage'],
entrypoints: { page: 'ui/index.html' }
})
expect(legacy.ok).toBe(true)
expect(legacy.manifest?.contributions.navigation).toBeUndefined()
const badIcon = parseExtensionManifest({
manifestVersion: 1,
id: 'com.example.bad',
name: '坏图标',
version: '1.0.0',
apiVersion: '1',
permissions: [],
entrypoints: { page: 'ui/index.html' },
contributions: {
pages: [{ id: 'main', title: '首页' }],
navigation: { label: '测试', icon: 'evil-svg' }
}
})
expect(badIcon.ok).toBe(false)
const missingPage = parseExtensionManifest({
manifestVersion: 1,
id: 'com.example.nopage',
name: '无页面',
version: '1.0.0',
apiVersion: '1',
permissions: [],
entrypoints: { background: 'bg.js' },
contributions: {
navigation: { label: '测试', icon: 'spark' }
}
})
expect(missingPage.ok).toBe(false)
})
it('固定、排序、重启恢复与卸载自动清理完整生效', async () => {
const root = makeTempDir()
const extADir = path.join(root, 'src-a')
const extBDir = path.join(root, 'src-b')
writeSampleExtension(extADir, 'com.example.alpha', '晨报助手', {
label: '晨报',
icon: 'digest',
pageId: 'main'
})
writeSampleExtension(extBDir, 'com.example.beta', '群聊机器人', {
label: '机器人',
icon: 'bot',
pageId: 'main'
})
const paths = createExtensionPaths(path.join(root, 'userData'))
const createManager = () =>
new ExtensionManager({
paths,
appVersion: '2.7.0',
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: async (): Promise<WechatActionResult> => ({
actionId: 'a1',
status: 'sent',
decision: 'allow',
startedAt: '2026-01-01T00:00:00.000Z',
finishedAt: '2026-01-01T00:00:01.000Z'
}),
queryMessages: async () => [],
listGroups: async () => [],
aiChat: async () => ({ text: 'ok' }),
getAccountId: () => 'wxid_fixture',
getSelfUsernames: () => ['wxid_fixture'],
isDatabaseReady: () => true,
secretCipher: {
isAvailable: () => false,
encrypt: () => Buffer.alloc(0),
decrypt: () => ''
}
})
const manager1 = createManager()
await manager1.initialize()
expect((await manager1.installFromDirectory(extADir)).success).toBe(true)
expect((await manager1.installFromDirectory(extBDir)).success).toBe(true)
expect(manager1.pinNavigation('com.example.alpha').success).toBe(true)
expect(manager1.pinNavigation('com.example.beta').success).toBe(true)
expect(manager1.listPinnedNavigation().map((item) => item.extensionId)).toEqual([
'com.example.alpha',
'com.example.beta'
])
// 调整排序。
manager1.reorderPinnedNavigation(['com.example.beta', 'com.example.alpha'])
expect(manager1.listPinnedNavigation().map((item) => item.extensionId)).toEqual([
'com.example.beta',
'com.example.alpha'
])
await manager1.dispose()
// 模拟应用重启:新建 Manager,固定项与顺序必须恢复。
const manager2 = createManager()
await manager2.initialize()
expect(manager2.listPinnedNavigation().map((item) => [item.extensionId, item.label, item.icon])).toEqual([
['com.example.beta', '机器人', 'bot'],
['com.example.alpha', '晨报', 'digest']
])
// 卸载扩展后自动从一级导航移除。
await manager2.uninstall('com.example.beta', true)
expect(manager2.listPinnedNavigation().map((item) => item.extensionId)).toEqual([
'com.example.alpha'
])
// 底层存储同步已清理。
const store = new ExtensionNavigationStore(paths.pinnedNavigationFile)
expect(store.list().map((item) => item.extensionId)).toEqual(['com.example.alpha'])
await manager2.dispose()
})
})
+195
View File
@@ -0,0 +1,195 @@
import fs from 'fs-extra'
import os from 'node:os'
import path from 'node:path'
import { afterEach, describe, expect, it } from 'vitest'
import { createExtensionPaths } from '../../src/main/extensions/extension-paths'
import { ExtensionManager } from '../../src/main/extensions/extension-manager'
import type { PersonalWechatSendCapability } from '../../src/shared/personal-wechat'
import type { WechatActionResult } from '../../src/shared/wechat-action'
const tempDirs: string[] = []
function makeTempDir(): string {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'tm-ext-notify-'))
tempDirs.push(dir)
return dir
}
afterEach(() => {
for (const dir of tempDirs.splice(0)) fs.removeSync(dir)
})
function writeExtension(dir: string, id: string, name: string, permissions: string[]): void {
fs.ensureDirSync(path.join(dir, 'ui'))
fs.writeFileSync(path.join(dir, 'ui', 'index.html'), '<!doctype html><html><body>ok</body></html>')
fs.writeJsonSync(path.join(dir, 'manifest.json'), {
manifestVersion: 1,
id,
name,
version: '1.0.0',
apiVersion: '1',
permissions,
entrypoints: { page: 'ui/index.html' },
contributions: {
pages: [{ id: 'main', title: name }],
navigation: { label: name, icon: 'bell', pageId: 'main' }
}
})
}
function makeManager(userData: string): ExtensionManager {
return new ExtensionManager({
paths: createExtensionPaths(userData),
appVersion: '2.7.0',
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: async (): Promise<WechatActionResult> => ({
actionId: 'a1',
status: 'sent',
decision: 'allow',
startedAt: '2026-01-01T00:00:00.000Z',
finishedAt: '2026-01-01T00:00:01.000Z'
}),
queryMessages: async () => [],
listGroups: async () => [],
aiChat: async () => ({ text: 'ok' }),
getAccountId: () => 'wxid_fixture',
getSelfUsernames: () => ['wxid_fixture'],
isDatabaseReady: () => true,
secretCipher: {
isAvailable: () => false,
encrypt: () => Buffer.alloc(0),
decrypt: () => ''
}
})
}
describe('ExtensionNotificationCenter 持久化、去重与生命周期', () => {
it('校验权限、拒绝停用扩展写入、支持 dedupeKey 去重与重启恢复,并在卸载后清理', async () => {
const root = makeTempDir()
const userData = path.join(root, 'userData')
const extA = path.join(root, 'ext-a')
const extB = path.join(root, 'ext-b')
writeExtension(extA, 'com.example.digest', '晨报', ['notifications.create'])
writeExtension(extB, 'com.example.bot', '机器人', ['notifications.create'])
const manager = makeManager(userData)
await manager.initialize()
await manager.installFromDirectory(extA)
await manager.installFromDirectory(extB)
// 未启用扩展必须拒绝写入新通知。
expect(() =>
manager.createNotification('com.example.digest', { title: '不应写入' })
).toThrowError(/停用/)
// 启用后若撤销 notifications.create 权限,主进程必须独立拒绝写入。
await manager.setEnabled('com.example.digest', true)
await manager.revokePermission('com.example.digest', 'notifications.create')
expect(() =>
manager.createNotification('com.example.digest', { title: '无权限' })
).toThrowError(/notifications\.create/)
// 重新授权后正常写入,并支持 dedupeKey 去重。
await manager.grantPermissions('com.example.digest', ['notifications.create'])
await manager.setEnabled('com.example.bot', true)
const first = manager.createNotification('com.example.digest', {
title: '今日晨报已生成',
body: '覆盖 3 个群聊',
level: 'success',
dedupeKey: 'morning-2026-12-01'
})
expect(first.deduped).toBe(false)
const duplicate = manager.createNotification('com.example.digest', {
title: '今日晨报已更新',
body: '覆盖 4 个群聊',
level: 'info',
dedupeKey: 'morning-2026-12-01'
})
expect(duplicate.deduped).toBe(true)
expect(duplicate.id).toBe(first.id)
expect(manager.listNotifications('com.example.digest')).toHaveLength(1)
expect(manager.listNotifications('com.example.digest')[0].title).toBe('今日晨报已更新')
// 另一个扩展使用相同 dedupeKey 不会跨扩展碰撞。
const other = manager.createNotification('com.example.bot', {
title: '机器人提醒',
level: 'warning',
dedupeKey: 'morning-2026-12-01'
})
expect(other.deduped).toBe(false)
// 固定 digest 到一级菜单后,digest 的未读在 unreadByExtension,而 bot 的未读聚合到 unpinnedUnread。
manager.pinNavigation('com.example.digest')
const summary = manager.getNotificationSummary()
expect(summary.totalUnread).toBe(2)
expect(summary.unpinnedUnread).toBe(1)
expect(summary.unreadByExtension['com.example.digest']).toBe(1)
expect(summary.unreadByExtension['com.example.bot']).toBe(1)
// 标记单条已读。
expect(manager.markNotificationsRead({ id: first.id })).toBe(1)
expect(manager.getNotificationSummary().totalUnread).toBe(1)
// 停用扩展后拒绝新通知。
await manager.setEnabled('com.example.bot', false)
expect(() =>
manager.createNotification('com.example.bot', { title: '停用后新通知' })
).toThrowError(/停用/)
await manager.dispose()
// 模拟重启恢复后通知与未读计数保持一致。
const manager2 = makeManager(userData)
await manager2.initialize()
expect(manager2.listNotifications()).toHaveLength(2)
expect(manager2.getNotificationSummary().unpinnedUnread).toBe(1)
// 卸载扩展后清理该扩展所有宿主通知状态。
await manager2.uninstall('com.example.bot', true)
expect(manager2.listNotifications('com.example.bot')).toEqual([])
expect(manager2.getNotificationSummary().totalUnread).toBe(0)
await manager2.dispose()
})
it('单扩展高频写入触发防刷屏限频,且标记已读严格按扩展隔离', async () => {
const root = makeTempDir()
const userData = path.join(root, 'userData')
const extA = path.join(root, 'ext-flood')
const extB = path.join(root, 'ext-peer')
writeExtension(extA, 'com.example.flood', '刷屏测试', ['notifications.create'])
writeExtension(extB, 'com.example.peer', '相邻扩展', ['notifications.create'])
const manager = makeManager(userData)
await manager.initialize()
await manager.installFromDirectory(extA)
await manager.installFromDirectory(extB)
await manager.setEnabled('com.example.flood', true)
await manager.setEnabled('com.example.peer', true)
const peerNotice = manager.createNotification('com.example.peer', { title: 'B 扩展通知' })
// 使用 flood 的 extensionId 尝试标记 peer 的通知已读不得生效。
expect(
manager.markNotificationsRead({ extensionId: 'com.example.flood', id: peerNotice.id })
).toBe(0)
expect(manager.listNotifications('com.example.peer')[0].read).toBe(false)
// 连续创建 20 条新通知成功,第 21 条触发 CONCURRENCY_LIMITED。
for (let i = 0; i < 20; i += 1) {
manager.createNotification('com.example.flood', { title: `通知 ${i}` })
}
expect(() =>
manager.createNotification('com.example.flood', { title: '第 21 条刷屏通知' })
).toThrowError(/过于频繁/)
await manager.dispose()
})
})
+99
View File
@@ -0,0 +1,99 @@
import fs from 'fs-extra'
import os from 'node:os'
import path from 'node:path'
import { afterEach, describe, expect, it } from 'vitest'
import { createExtensionPaths } from '../../src/main/extensions/extension-paths'
import {
buildExtensionPrivateMediaPreviewUrl,
resolveExtensionProtocolFile
} from '../../src/main/extensions/extension-protocol'
const tempDirs: string[] = []
function makeTempDir(): string {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'tm-ext-protocol-'))
tempDirs.push(dir)
return dir
}
afterEach(() => {
while (tempDirs.length > 0) {
const dir = tempDirs.pop()
if (dir) fs.removeSync(dir)
}
})
describe('extension-protocol 受控私有媒体预览', () => {
it('仅放行本扩展 rendered/ 与 media-cache/ 下的白名单媒体文件,拒绝越界与敏感文件', async () => {
const root = makeTempDir()
const paths = createExtensionPaths(root)
const extId = 'com.example.preview'
const otherId = 'com.example.other'
const extInstallDir = paths.installDir(extId)
const extDataDir = paths.extensionDataDir(extId)
const otherDataDir = paths.extensionDataDir(otherId)
fs.ensureDirSync(path.join(extInstallDir, 'ui'))
fs.writeFileSync(path.join(extInstallDir, 'ui', 'index.html'), '<html></html>')
fs.ensureDirSync(path.join(extDataDir, 'rendered'))
fs.ensureDirSync(path.join(extDataDir, 'media-cache', 'acct1234', 'images'))
fs.ensureDirSync(path.join(otherDataDir, 'rendered'))
const pngPath = path.join(extDataDir, 'rendered', 'digest.png')
const cachedJpgPath = path.join(extDataDir, 'media-cache', 'acct1234', 'images', 'a.jpg')
const storagePath = path.join(extDataDir, 'storage.json')
const htmlInRendered = path.join(extDataDir, 'rendered', 'evil.html')
const outsideSecret = path.join(root, 'secret.png')
const symlinkInRendered = path.join(extDataDir, 'rendered', 'link.png')
const otherPngPath = path.join(otherDataDir, 'rendered', 'other.png')
fs.writeFileSync(pngPath, Buffer.from([0x89, 0x50, 0x4e, 0x47, 1, 2, 3, 4]))
fs.writeFileSync(cachedJpgPath, Buffer.from([0xff, 0xd8, 0xff, 0xe0]))
fs.writeFileSync(storagePath, '{"token":"secret"}')
fs.writeFileSync(htmlInRendered, '<script>alert(1)</script>')
fs.writeFileSync(outsideSecret, Buffer.from([0x89, 0x50, 0x4e, 0x47, 9, 9]))
fs.writeFileSync(otherPngPath, Buffer.from([0x89, 0x50, 0x4e, 0x47, 7, 7]))
fs.symlinkSync(outsideSecret, symlinkInRendered)
const deps = {
paths,
resolveRoot: (id: string) => (id === extId ? extInstallDir : null)
}
const previewUrl = buildExtensionPrivateMediaPreviewUrl(extId, extDataDir, pngPath)
expect(previewUrl).toBe(`tm-extension://${extId}/_data/rendered/digest.png`)
const resolvedPng = await resolveExtensionProtocolFile(previewUrl!, deps)
expect(resolvedPng).not.toBeNull()
expect(resolvedPng?.contentType).toBe('image/png')
expect(resolvedPng?.isPrivateMedia).toBe(true)
expect(resolvedPng?.csp).toContain("default-src 'none'")
const cachedPreviewUrl = buildExtensionPrivateMediaPreviewUrl(extId, extDataDir, cachedJpgPath)
expect(cachedPreviewUrl).toBe(`tm-extension://${extId}/_data/media-cache/acct1234/images/a.jpg`)
const resolvedJpg = await resolveExtensionProtocolFile(cachedPreviewUrl!, deps)
expect(resolvedJpg?.contentType).toBe('image/jpeg')
// 拒绝 storage.json 与非白名单后缀(如 html)。
expect(buildExtensionPrivateMediaPreviewUrl(extId, extDataDir, storagePath)).toBeUndefined()
expect(
await resolveExtensionProtocolFile(`tm-extension://${extId}/_data/storage.json`, deps)
).toBeNull()
expect(
await resolveExtensionProtocolFile(`tm-extension://${extId}/_data/rendered/evil.html`, deps)
).toBeNull()
// 拒绝路径穿越、符号链接逃逸和未安装扩展访问。
expect(
await resolveExtensionProtocolFile(
`tm-extension://${extId}/_data/rendered/../../secret.png`,
deps
)
).toBeNull()
expect(
await resolveExtensionProtocolFile(`tm-extension://${extId}/_data/rendered/link.png`, deps)
).toBeNull()
expect(
await resolveExtensionProtocolFile(`tm-extension://${otherId}/_data/rendered/other.png`, deps)
).toBeNull()
})
})
@@ -75,13 +75,14 @@ function record(overrides: Partial<ExtensionRegistryRecord>): ExtensionRegistryR
}
describe('官方模板目录', () => {
it('列出三个模板,未安装时状态为 not-installed', async () => {
it('列出四个模板,未安装时状态为 not-installed', async () => {
const { catalog } = setup()
const list = await catalog.list()
expect(list.map((item) => item.template.templateId).sort()).toEqual([
'douyin-sender',
'group-chat-bot',
'keyword-bot'
'keyword-bot',
'morning-digest'
])
expect(list.every((item) => item.state === 'not-installed')).toBe(true)
// 版本来自 manifest,不是硬编码。
+4 -3
View File
@@ -39,7 +39,7 @@ function stageExamples(): { sourceRoot: string; lockFile: string } {
}
describe('官方模板构建', () => {
it('产出三个模板与索引,索引指向真实文件', () => {
it('产出四个模板与索引,索引指向真实文件', () => {
const { sourceRoot, lockFile } = stageExamples()
const outputDir = path.join(tempRoot(), 'out')
const result = buildTemplates({ sourceRoot, outputDir, lockFile })
@@ -47,11 +47,12 @@ describe('官方模板构建', () => {
expect(result.templates.map((item) => item.templateId).sort()).toEqual([
'douyin-sender',
'group-chat-bot',
'keyword-bot'
'keyword-bot',
'morning-digest'
])
const index = fs.readJsonSync(path.join(outputDir, 'index.json'))
expect(index.version).toBe(1)
expect(index.templates).toHaveLength(3)
expect(index.templates).toHaveLength(4)
for (const template of index.templates) {
expect(fs.existsSync(path.join(outputDir, template.file))).toBe(true)
expect(template.sha256).toMatch(/^[a-f0-9]{64}$/)
+302
View File
@@ -0,0 +1,302 @@
import fs from 'fs-extra'
import os from 'node:os'
import path from 'node:path'
import { pathToFileURL } from 'node:url'
import { afterEach, describe, expect, it, vi } from 'vitest'
import {
HtmlRenderService,
STATIC_RENDER_CSP,
assertSafeStaticHtml,
buildIsolatedHtmlDocument,
createDocumentIsolationHandler,
type RenderWindowAdapter
} from '../../src/main/services/html-render-service'
const tempDirs: string[] = []
function makeTempDir(): string {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'tm-html-render-'))
tempDirs.push(dir)
return dir
}
afterEach(() => {
for (const dir of tempDirs.splice(0)) fs.removeSync(dir)
})
function createMockWindow(options: {
width?: number
height?: number
pngBuffer?: Buffer
delayMs?: number
throwOnCapture?: Error
} = {}) {
let destroyed = false
let contentSize: [number, number] = [options.width ?? 430, 800]
let readyCallback: (() => void) | null = null
let resizeCallback: (() => void) | null = null
const loadedFiles: string[] = []
let filterCleared = false
let filterInstalled = false
const adapter: RenderWindowAdapter = {
loadFile: vi.fn(async (filePath: string) => {
loadedFiles.push(filePath)
if (options.delayMs) {
await new Promise((resolve) => setTimeout(resolve, options.delayMs))
}
readyCallback?.()
}),
onceReadyToShow: (cb) => {
readyCallback = cb
},
onceResize: (cb) => {
resizeCallback = cb
},
getContentSize: () => contentSize,
setContentSize: (w, h) => {
contentSize = [w, h]
resizeCallback?.()
},
executeJavaScript: vi.fn(async (code: string) => {
if (code.includes('scrollWidth')) {
return { width: options.width ?? 430, height: options.height ?? 1280 }
}
return undefined
}),
capturePage: vi.fn(async () => {
if (options.throwOnCapture) throw options.throwOnCapture
return options.pngBuffer ?? Buffer.alloc(1500, 0x89)
}),
installRequestFilter: vi.fn(() => {
filterInstalled = true
}),
clearRequestFilter: vi.fn(() => {
filterCleared = true
}),
isDestroyed: () => destroyed,
destroy: vi.fn(() => {
destroyed = true
})
}
return {
adapter,
getState: () => ({ destroyed, loadedFiles, filterInstalled, filterCleared, contentSize })
}
}
describe('HtmlRenderService 通用渲染与安全隔离', () => {
it('成功渲染静态 HTML/CSS 到扩展私有目录,注入严格 CSP 并清理临时 HTML', async () => {
const root = makeTempDir()
const tempDir = path.join(root, 'tmp-html')
const extDataDir = path.join(root, 'extensions-data', 'com.example.digest')
const mockWin = createMockWindow({ width: 520, height: 1400 })
const partitions: string[] = []
const service = new HtmlRenderService({
tempDir,
createWindow: (opts) => {
partitions.push(opts.partition)
expect(opts.enforceStaticCsp).toBe(true)
return mockWin.adapter
}
})
const result = await service.renderExtensionHtmlToPng({
html: '<main><h1>晨报</h1><p>今日重点</p></main>',
css: 'main { padding: 20px; }',
extensionDataRoot: extDataDir,
fileName: 'morning-2026-12-01.png',
width: 520
})
expect(result.mimeType).toBe('image/png')
expect(result.width).toBe(520)
expect(result.height).toBe(1400)
expect(result.path).toBe(path.join(extDataDir, 'rendered', 'morning-2026-12-01.png'))
expect(fs.existsSync(result.path)).toBe(true)
expect(partitions[0]).toMatch(/^html-render-/)
const state = mockWin.getState()
expect(state.destroyed).toBe(true)
expect(state.filterInstalled).toBe(true)
expect(state.filterCleared).toBe(true)
// 临时 HTML 已被完整清理。
expect(state.loadedFiles).toHaveLength(1)
expect(fs.existsSync(state.loadedFiles[0])).toBe(false)
const doc = buildIsolatedHtmlDocument('<div>hi</div>', 'div{color:#111}')
expect(doc).toContain(STATIC_RENDER_CSP)
})
it('拒绝脚本、内联事件、iframe、meta refresh 与外部网络资源等恶意 HTML', () => {
const maliciousCases = [
'<script>alert(1)</script>',
'<img src="data:image/png;base64,AA" onerror="fetch(1)">',
'<iframe src="about:blank"></iframe>',
'<a href="javascript:alert(1)">click</a>',
'<meta http-equiv="refresh" content="0;url=https://example.com">',
'<img src="https://example.com/pixel.png">',
'<img src="file:///etc/passwd">'
]
for (const html of maliciousCases) {
expect(() => assertSafeStaticHtml(html)).toThrowError()
}
expect(() =>
assertSafeStaticHtml('<div>ok</div>', '@import url("https://example.com/a.css");')
).toThrowError()
expect(() =>
assertSafeStaticHtml('<div>ok</div>', 'body { background: url(https://example.com/bg.png); }')
).toThrowError()
})
it('拒绝路径越界与符号链接逃逸,输出路径必须落在扩展私有目录内', async () => {
const root = makeTempDir()
const extDataDir = path.join(root, 'extensions-data', 'com.example.digest')
const outsideDir = path.join(root, 'outside')
fs.ensureDirSync(extDataDir)
fs.ensureDirSync(outsideDir)
const service = new HtmlRenderService({
tempDir: path.join(root, 'tmp'),
createWindow: () => createMockWindow().adapter
})
await expect(
service.renderExtensionHtmlToPng({
html: '<div>safe</div>',
extensionDataRoot: extDataDir,
fileName: '../escape.png'
})
).rejects.toMatchObject({ code: 'EXTENSION_INVALID_PATH' })
await expect(
service.renderExtensionHtmlToPng({
html: '<div>safe</div>',
extensionDataRoot: extDataDir,
fileName: '/tmp/escape.png'
})
).rejects.toMatchObject({ code: 'EXTENSION_INVALID_PATH' })
// 在扩展目录内放一个指向外部目录的符号链接,必须被 realpath 拦截。
fs.symlinkSync(outsideDir, path.join(extDataDir, 'rendered'))
await expect(
service.renderExtensionHtmlToPng({
html: '<div>safe</div>',
extensionDataRoot: extDataDir,
fileName: 'symlink-escape.png'
})
).rejects.toMatchObject({ code: 'EXTENSION_INVALID_PATH' })
})
it('网络隔离拦截器只放行当前单个 HTML 文件,拦截所有外链与其他本地文件', () => {
const root = makeTempDir()
const allowed = path.join(root, 'allowed.html')
const other = path.join(root, 'other.html')
const blocked: Array<{ url: string; reason: string }> = []
const handler = createDocumentIsolationHandler(allowed, (details, reason) => {
blocked.push({ url: details.url, reason })
})
const runCheck = (url: string): boolean => {
let canceled = false
handler({ url, method: 'GET', resourceType: 'other' }, (res) => {
canceled = res.cancel
})
return canceled
}
expect(runCheck(pathToFileURL(allowed).href)).toBe(false)
expect(runCheck(pathToFileURL(other).href)).toBe(true)
expect(runCheck('https://example.com/a.png')).toBe(true)
expect(runCheck('http://127.0.0.1:8080/api')).toBe(true)
expect(runCheck('ws://127.0.0.1:9000')).toBe(true)
expect(blocked).toHaveLength(4)
})
it('并发限制、超时与失败后完整销毁窗口并清理临时文件', async () => {
const root = makeTempDir()
const tempDir = path.join(root, 'tmp-cleanup')
const extDataDir = path.join(root, 'extensions-data', 'com.example.digest')
const slowWin = createMockWindow({ delayMs: 800 })
const service = new HtmlRenderService({
tempDir,
maxConcurrent: 1,
createWindow: () => slowWin.adapter
})
const first = service.renderExtensionHtmlToPng({
html: '<div>slow</div>',
extensionDataRoot: extDataDir,
timeoutMs: 500
})
// 等待第一个任务进入 renderFileToPng 占用并发槽。
await new Promise((resolve) => setTimeout(resolve, 40))
// 第二个并发渲染必须立即被拒绝。
await expect(
service.renderExtensionHtmlToPng({
html: '<div>second</div>',
extensionDataRoot: extDataDir
})
).rejects.toMatchObject({ code: 'CONCURRENCY_LIMITED' })
// 第一个超时后必须销毁窗口并清理临时 HTML,且释放并发槽。
await expect(first).rejects.toMatchObject({ code: 'ACTION_TIMEOUT' })
expect(slowWin.getState().destroyed).toBe(true)
expect(service.activeRenders).toBe(0)
expect(fs.readdirSync(tempDir)).toEqual([])
// 超过 PNG 体积上限时拒绝且不残留输出文件。
const hugeService = new HtmlRenderService({
tempDir,
maxPngBytes: 1024,
createWindow: () => createMockWindow({ pngBuffer: Buffer.alloc(2048, 0x89) }).adapter
})
await expect(
hugeService.renderExtensionHtmlToPng({
html: '<div>huge</div>',
extensionDataRoot: extDataDir,
fileName: 'huge.png'
})
).rejects.toMatchObject({ code: 'STORAGE_LIMIT_EXCEEDED' })
expect(fs.existsSync(path.join(extDataDir, 'rendered', 'huge.png'))).toBe(false)
})
it('阻断 srcset/xlink:href/style 逃逸并解析真实 PNG IHDR 像素尺寸', async () => {
expect(() => assertSafeStaticHtml('<img srcset="https://evil.example/a.png 2x">')).toThrowError(
/外部网络/
)
expect(() =>
assertSafeStaticHtml('<svg><image xlink:href="https://evil.example/b.png"/></svg>')
).toThrowError(/外部网络/)
expect(() => assertSafeStaticHtml('<div>ok</div>', 'body{}</style><div>x</div>')).toThrowError(
/style/
)
// 构造带合法 IHDR(860x1600)的 2x Retina PNG 头,校验 pixelWidth/pixelHeight/deviceScaleFactor。
const pngHeader = Buffer.alloc(160, 0)
Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]).copy(pngHeader, 0)
pngHeader.writeUInt32BE(860, 16)
pngHeader.writeUInt32BE(1600, 20)
const root = makeTempDir()
const service = new HtmlRenderService({
tempDir: path.join(root, 'tmp'),
createWindow: () => createMockWindow({ width: 430, height: 800, pngBuffer: pngHeader }).adapter
})
const res = await service.renderExtensionHtmlToPng({
html: '<div>retina</div>',
width: 430,
extensionDataRoot: path.join(root, 'extensions-data', 'com.example.retina')
})
expect(res.width).toBe(430)
expect(res.height).toBe(800)
expect(res.pixelWidth).toBe(860)
expect(res.pixelHeight).toBe(1600)
expect(res.deviceScaleFactor).toBe(2)
})
})