Compare commits

...
25 Commits
Author SHA1 Message Date
qingmao 6f0209514e Merge pull request #83 from Michael-py001/chore/update-qr-group7 2026-11-27 23:15:30 +08:00
wushili 7461e12599 chore: 更新交流群二维码为 TM 的 7 群 2026-11-27 23:13:07 +08:00
Wxw-Gu 337f0e6173 chore: 更新交流群二维码, 替换过期旧图 2026-11-25 17:37:55 +08:00
Wxw-Gu 8f47dcabe5 Merge branch 'main' of https://github.com/Wxw-Gu/TraceMemo 2026-11-19 10:10:08 +08:00
Wxw-Gu 2fb519a373 fix: 修复机器人测试文本错误, 提升版本号 2026-11-19 10:07:55 +08:00
Wxw-Gu f64ac4e326 Merge branch 'develop' of https://github.com/Wxw-Gu/TraceMemo into develop 2026-11-18 17:47:01 +08:00
Wxw-Gu 0ec8029f17 feat: 拓展中心机器人模板 2026-11-18 17:42:18 +08:00
Wxw-Gu 4d86aa8d31 feat: windows同步mac增加发文件 2026-11-18 17:42:18 +08:00
Wxw-Gu 5ca465f203 fix: 补充mac发送的类型
修复图片key
2026-11-18 17:42:17 +08:00
Wxw-Gu f16067d6d0 feat: 拓展中心加入机器人 2026-11-18 17:42:17 +08:00
Wxw-Gu 116989a091 feat: 拓展中心 2026-11-18 17:42:17 +08:00
Wxw-Gu b171818df5 feat: Windows增加发送视频 dy下载脚本 2026-11-18 17:42:17 +08:00
Wxw-Gu ebea992b10 feat: 新增拓展中心功能, 提供 关键词回复 去水印模板 2026-11-18 17:42:13 +08:00
Wxw-Gu fb1a1c9bb0 feat: 拓展中心机器人模板 2026-11-18 17:00:52 +08:00
Wxw-Gu 49e2dab2a6 feat: windows同步mac增加发文件 2026-11-18 11:49:41 +08:00
Wxw-Gu e0e749510a fix: 补充mac发送的类型
修复图片key
2026-11-18 11:31:50 +08:00
Wxw-Gu a81b3733fa feat: 拓展中心加入机器人 2026-11-18 11:22:39 +08:00
Wxw-Gu 4eaddc2d75 feat: 拓展中心 2026-11-16 15:55:00 +08:00
Wxw-Gu 9ffa1efc26 feat: Windows增加发送视频 dy下载脚本 2026-11-16 10:02:20 +08:00
Wxw-Gu b9ad4e1d71 feat: 新增拓展中心功能, 提供 关键词回复 去水印模板 2026-11-13 17:54:37 +08:00
Wxw-Gu aca103cb96 fix: 增加@所有人 完善mac发送清理与端口回退 2026-11-12 16:00:45 +08:00
Wxw-Gu c50f8861a4 Merge branch 'develop' of github.com:Wxw-Gu/TraceMemo into develop 2026-11-12 11:18:37 +08:00
Wxw-Gu 5d4ba73771 feat: 发送支持群聊@成员
生命周期整理
清理残留整理
完善skill
2026-11-12 11:18:32 +08:00
qingmao 340eacf527 Merge pull request #70 from hateyouing-ai/fix/reader-bounded-empty-window
fix: 避免 Reader 有界空窗读取阻塞主线程
2026-11-10 16:03:20 +08:00
hateyouing-ai 00b55c9cca fix: 避免 Reader 有界空窗读取阻塞主线程 2026-11-10 15:27:06 +08:00
165 changed files with 33539 additions and 633 deletions

No files matched your search

+8
View File
@@ -31,3 +31,11 @@ task_plan.md
*libtmlicense*
debug-originals
/build/mac-staging/
# 去水印脚本与群聊机器人核心引擎
/examples/extensions/douyin-sender/scripts/douyin.py
/examples/extensions/group-chat-bot/lib/
/examples/extensions/group-chat-bot/tests/
# 官方扩展模板构建产物(由 scripts/build-extension-templates.cjs 生成)
/build/extension-templates/
+1 -4
View File
@@ -137,7 +137,7 @@ TraceMemo 最早叫 **WechatExplorer**。
## 💬 交流与反馈
<p align="center">
<img src="./public/二维码.jpg" alt="TraceMemo 交流与售后群二维码" width="280" />
<img src="./public/二维码.png" alt="TraceMemo 交流与售后群二维码" width="280" />
</p>
## 从你的任务开始
@@ -212,9 +212,6 @@ TraceMemo 在早期适配微信 4.x 时,曾参考 **[WeFlow](https://github.co
- **[chatlog](https://github.com/sjzar/chatlog)**
- 提供了数据处理方面的参考。
- **[wechat_chatter](https://github.com/yincongcyincong/wechat_chatter)**
- 提供了发送方面的参考。
感谢所有开源作者,也感谢所有帮助 TraceMemo 发现问题、提出建议和持续使用它的人。
---
+2
View File
@@ -50,6 +50,8 @@ Agent Hub 让微信机器人调用本机 TraceMemo;Reader Skill / Local HTTP A
## 开发文档
- [开发、测试与构建](./development/overview.md)
- [克隆 TraceMemo 后开发自己的扩展](./extensions/clone-and-customize.md)
- [扩展 API 参考](./extensions/api-reference.md)
- [界面开发规范:按钮与主题色](./development/ui-guidelines.md)
- [微信系统消息解析与格式兼容](./development/wechat-system-message-parsing.md)
- [Query Agent POC(开发测试入口)](./development/query-agent-poc.md)
+191
View File
@@ -0,0 +1,191 @@
# 扩展 API 参考(v1)
## manifest.json
| 字段 | 必填 | 说明 |
| --- | --- | --- |
| `manifestVersion` | 是 | 固定 `1` |
| `id` | 是 | 反向域名,小写;禁止 `com.tracememo.` / `tracememo.` / `tm.` 前缀 |
| `name` | 是 | 展示名,≤ 64 字 |
| `version` | 是 | `x.y.z`(可带 prerelease) |
| `apiVersion` | 是 | 必须为 `1` |
| `minAppVersion` | 否 | 低于该版本拒绝安装 |
| `description` / `author` / `homepage` | 否 | 展示用;homepage 仅接受 http(s) |
| `permissions` | 是 | 见权限表;未知权限直接判 manifest 非法 |
| `entrypoints.page` | 二选一 | 页面 HTML 相对路径 |
| `entrypoints.background` | 二选一 | 后台入口相对路径 |
| `subscriptions` | 条件 | 申请 `messages.subscribe` 时必填 |
| `contributions.pages` | 否 | `[{ id, title, entry? }]`,`id` 形如 `settings` |
| `contributions.automationActions` | 否 | `[{ id, title, description? }]`,有此项必须提供 background |
路径规则:相对路径、不允许 `..`、反斜杠、盘符、控制字符、Windows 保留名;
安装时还会用 realpath 复核入口仍在扩展目录内。
## 权限
| 权限 | 风险 | 能力 |
| --- | --- | --- |
| `messages.subscribe` | 高 | 接收 `message.received` |
| `messages.query` | 高 | `tm.messages.query` |
| `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` |
| `storage` | 低 | `tm.storage.*` 与页面存储 |
| `automation.action` | 中 | `tm.automation.registerAction` |
安装时只自动授予**低风险**权限;其余在「启用」确认后授予。停用后回落到低风险集合。
## 后台 API
### tm.extension
- `id: string`
- `dataDir: string`(扩展私有数据目录,媒体文件写这里才能通过发送校验)
- `permissions: string[]`(当前已授予)
### tm.events
- `on('message.received', handler): () => void`
- `off('message.received', handler): void`
事件字段见 `TraceMemoMessageEvent`:`eventId / accountId / conversationId / messageId /
senderId? / senderName? / isGroup / isSelf / type / text? / mentionsMe / timestamp(ms)`。
### tm.messages.query
```ts
await tm.messages.query({ conversationId, startTime?, endTime?, limit? })
// → { messages: [{ messageId, conversationId, senderId?, senderName?, isSelf, type, text?, timestamp }] }
```
- 时间参数是 **epoch 毫秒**;默认最近 24 小时。
- 单次窗口最多 7 天,`limit` 上限 200。
- 数据库未连接时抛 `DATABASE_NOT_READY`。
### 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。
任何一步不通过都抛带错误码的异常,不会「静默丢弃」。
媒体路径额外约束:
- 必须是**绝对路径**的普通文件,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。
## 错误码
| 码 | 含义 |
| --- | --- |
| `EXTENSION_NOT_FOUND` | 扩展不存在 / 已卸载 |
| `EXTENSION_DISABLED` | 扩展未启用 |
| `EXTENSION_INCOMPATIBLE` | apiVersion 或 minAppVersion 不满足 |
| `EXTENSION_INVALID_MANIFEST` | manifest 不合法 |
| `EXTENSION_INVALID_PATH` | 入口 / 资源路径越界 |
| `EXTENSION_HOST_UNAVAILABLE` | 后台进程未运行 |
| `PERMISSION_DENIED` | 未授予权限,或超出声明范围 |
| `CAPABILITY_UNAVAILABLE` | 本机能力不具备(未绑定 / 未就绪) |
| `LICENSE_REQUIRED` | 无有效授权 |
| `DATABASE_NOT_READY` | 微信数据库未连接 |
| `SEND_NOT_SUPPORTED` | 当前平台或内容类型不支持 |
| `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 }
}
```
+99
View File
@@ -0,0 +1,99 @@
# 扩展中心架构(v1)
## 目标
把用户二次开发从官方源码里剥离:扩展装在自己的目录、走稳定的 SDK、由宿主做权限与能力检查。
官方升级只替换应用本体,不触碰扩展目录与数据目录。
## 分层
```text
TraceMemo Core(Electron 主进程 / 渲染层)
│
ExtensionManager ─── ExtensionRegistry(启用状态 / 授权集合)
│ ExtensionInstaller(目录 / ZIP 安装,原子替换)
│ ExtensionLogStore(日志)
│ ExtensionActionRegistry(自动化动作)
│ ExtensionEventBus(消息事件分发)
│
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 → 只读快照
```
关键边界:
- **主进程从不 `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/ 安装临时目录(成功后原子改名)
```
三者分离的原因:
| 场景 | 结果 |
| --- | --- |
| 官方应用升级 | `userData` 不变,扩展与配置原样保留 |
| 扩展升级(同 id 新版本) | 只替换 `extensions/<id>`,`extensions-data` 不动 |
| 卸载并选择保留数据 | 删除代码目录,保留 `extensions-data` |
| 卸载并清除数据 | 同时删除数据目录与日志 |
## 生命周期
```text
install → 校验 manifest / 入口 → 临时目录 → 原子替换 → 登记(默认未启用)
enable → 授予 manifest 声明的权限 → 启动子进程 → activate 握手 → active
message → ExtensionEventBus 去重 → 按 subscriptions 过滤 → 投递给子进程
action → 自动化 runner → ExtensionHost.invokeAction → 返回 reply / output
disable → 停止子进程 → 撤销高风险权限(仅保留 storage)→ inactive
upgrade → 停进程 → 替换目录 → 保留 enabled 与授权 → 重启
```
崩溃处理:子进程异常退出时按 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`,不会静默删除用户配置。
+170
View File
@@ -0,0 +1,170 @@
# 克隆 TraceMemo 后开发自己的扩展
本指南说明如何从 TraceMemo 示例开始,编写、安装和调试自己的扩展。扩展代码与 TraceMemo 主程序分开维护;通常只需要写一个扩展目录,不必改 TraceMemo 的业务源码。
本文适用于包含 Extension Center v1 的 TraceMemo 版本,扩展 API 版本为 `1`。较早的源码或安装包如果还没有左侧「扩展」入口,需要先使用包含 Extension Center 的分支或版本。
## 1. 克隆并启动 TraceMemo
先按项目开发文档准备 Node.js 与 pnpm,然后克隆源码、安装依赖并启动开发版:
```bash
git clone https://github.com/Wxw-Gu/TraceMemo.git
cd TraceMemo
pnpm install
pnpm dev
```
`pnpm dev` 启动的是 TraceMemo 开发版。扩展安装后会复制到应用的用户数据目录;修改源码目录里的文件不会自动同步到已安装副本,每次改完都要重新安装同一扩展目录。
## 2. 从示例创建扩展
建议先复制示例,再按功能删改文件:
```bash
cp -R examples/extensions/keyword-bot ../my-tracememo-extension
```
`keyword-bot` 带有规则、匹配与发送逻辑;如果只是做最小扩展,保留 `manifest.json`、`ui/` 与 `storage` 用法,删除 `lib/`、规则 UI 以及 `background` 里的匹配/发送代码即可。
目录通常如下:
```text
my-tracememo-extension/
manifest.json 扩展身份、入口和权限声明
background/index.js 可选;后台逻辑,运行于独立 Node 子进程
ui/ 可选;扩展页面,运行于 sandbox iframe
index.html
app.js
style.css
```
最小扩展只要求有一个页面或后台入口。可先从 `keyword-bot` 保留 `manifest.json`、页面桥与 `storage` 用法,再把 `manifest.json` 中的 `id`、`name`、`description`、`author` 改成自己的信息;`id` 是反向域名格式,例如 `com.example.my-helper`,必须唯一,不能使用 `com.tracememo.`、`tracememo.` 或 `tm.` 前缀。版本采用 `x.y.z` 格式。
示例中的页面脚本也有一个 `EXTENSION_ID` 常量,使用页面桥时要将它改成 manifest 中完全相同的 id。稳定 id 很重要:相同 id 的升级会保留该扩展的配置;换 id 则会被视为另一个扩展。
典型 manifest:
```json
{
"manifestVersion": 1,
"id": "com.example.my-helper",
"name": "我的扩展",
"version": "1.0.0",
"apiVersion": "1",
"minAppVersion": "2.6.0",
"description": "我的 TraceMemo 扩展",
"permissions": ["storage"],
"entrypoints": {
"page": "ui/index.html",
"background": "background/index.js"
},
"contributions": {
"pages": [{ "id": "settings", "title": "设置" }]
}
}
```
`minAppVersion` 是最低应用版本,可按扩展实际依赖调整。入口路径必须是扩展目录内的安全相对路径;安装器会检查 manifest 和入口文件。
## 3. 编写后台逻辑
后台入口导出 `activate(tm)`。TraceMemo 会在扩展启用时启动独立 Node 子进程,并注入 `tm` API:
```js
module.exports = function activate(tm) {
tm.log.info(`扩展已启动:${tm.extension.id}`)
tm.events.on('message.received', async (event) => {
if (event.isSelf || !event.mentionsMe || !event.text) return
await tm.wechat.send({
to: event.conversationId,
text: '收到,我来处理。',
dedupeKey: event.eventId
})
})
}
```
上面这个例子需要在 manifest 中声明 `messages.subscribe`、`wechat.send.text`,并声明消息订阅范围:
```json
{
"permissions": ["messages.subscribe", "wechat.send.text", "storage"],
"subscriptions": {
"messageTypes": ["text"],
"conversationIds": [],
"requireMentionMe": true,
"includeSelf": false
}
}
```
按需申请权限,不要为了省事把所有权限都加上。高、中风险权限会在启用时要求用户确认;没有获得相应授权的 API 会返回权限错误。微信发送仍经过 TraceMemo 的权限、范围、频率、发送能力和授权校验。
可用 API 包括 `tm.events`、有界的 `tm.messages.query`、`tm.wechat.send`、`tm.ai.chat`、`tm.storage`、`tm.automation.registerAction`、`tm.capabilities.get` 和 `tm.log`。字段、限制与错误码见[扩展 API 参考](./api-reference.md)。仓库的 `packages/extension-sdk/index.d.ts` 只提供类型定义,不是运行时依赖;运行时的 `tm` 由 TraceMemo 注入。
## 4. 编写扩展页面
页面在 sandbox iframe 中运行,不能访问 `window.api`、Node 或 Electron。需要调用宿主白名单功能时,通过 `postMessage` 页面桥通信。可参考 `examples/extensions/keyword-bot/ui/app.js` 里的 `callHost()` 与消息处理,并更新其中的扩展 id。页面桥目前允许存储读写、能力查询、群列表查询(需 `contacts.list`)和扩展信息查询;页面不能直接读取聊天消息、调用 AI 或发送微信。
后台逻辑使用 `tm.storage`;页面则通过页面桥的 `storage.get` / `storage.set` 等方法访问同一扩展的私有存储。
## 5. 在 TraceMemo 中安装和调试
1. 在开发版或已支持扩展的 TraceMemo 中打开左侧「扩展」。
2. 选择「安装目录」,指向 `my-tracememo-extension`。也可以将扩展文件打成 ZIP;`manifest.json` 必须位于 ZIP 根目录,然后选择「安装 ZIP」。
3. 安装完成后,选中扩展并点「启用」。检查权限清单,只确认扩展功能确实需要的权限。
4. 有页面入口时点「打开页面」;检查配置是否读写正常。后台运行日志可在扩展详情页查看。
5. 修改源码后重新安装同一个目录,以更新已安装副本;如后台进程仍未刷新,再停用后重新启用。页面资源更新后重新打开或刷新扩展页面。
同一 `id` 重新安装会更新扩展代码并保留已授予权限、启用状态和扩展存储。卸载默认保留数据;需要清理时再明确选择删除数据。
## 6. 编写和运行测试
纯 JavaScript 扩展可用 Node 内置检查器与测试运行器,不需要把扩展依赖装进 TraceMemo:
```bash
node --check ../my-tracememo-extension/background/index.js
node --test ../my-tracememo-extension/tests/*.test.mjs
```
若扩展放在 TraceMemo 仓库的 `examples/extensions/` 下,也可以参照示例的测试命令,例如:
```bash
node --test examples/extensions/keyword-bot/tests/matcher.test.mjs
```
改动 TraceMemo 扩展宿主、SDK 契约或示例校验时,再运行对应的 TraceMemo 测试:
```bash
pnpm exec vitest run --config vitest.unit.config.ts tests/unit/extension-manifest.test.ts tests/unit/extension-installer.test.ts tests/unit/extension-host.test.ts
pnpm typecheck
```
## 7. 自动化动作
扩展可以在 manifest 中用 `contributions.automationActions` 声明动作,并申请 `automation.action`;后台通过 `tm.automation.registerAction()` 注册实现。动作返回的 `reply` 由 TraceMemo 宿主经统一 Gateway 发送,扩展不应自行绕过 Gateway。
当前版本可以在扩展详情页查看动作是否已注册;自动化规则编辑器尚未提供选择扩展动作的入口,因此目前不能通过界面把这些扩展动作配置到规则中。相关执行接口已在宿主侧实现,界面入口开放后再按产品文档配置。
## 8. 安全与发布前检查
扩展后台虽然运行在独立进程,但这**不是操作系统级沙箱**。它是任意 Node.js 代码,拥有运行 TraceMemo 用户的文件与网络权限。只安装自己编写或信任来源的扩展,不要把不可信扩展当成受隔离代码。
发布前至少确认:
- manifest id 唯一、版本递增、权限最小化,所有入口文件都在扩展目录内;
- 页面只使用受支持的 postMessage 白名单,不假设能访问 Electron API;
- 消息回调处理异常并使用稳定的 `dedupeKey`;
- 单元测试覆盖纯逻辑,人工验证安装、启用、停用、重装和配置保留;
- README 说明扩展行为、权限用途、外部依赖与可能发送的内容。
## 相关资料
- [扩展开发入门与 API 用法](./getting-started.md)
- [扩展 API 参考](./api-reference.md)
- [扩展中心架构](./architecture.md)
- [扩展安全模型](./security.md)
- [可安装示例](../../examples/extensions/README.md)
+141
View File
@@ -0,0 +1,141 @@
# 扩展开发入门
从克隆源码到创建独立扩展的完整流程见[克隆 TraceMemo 后开发自己的扩展](./clone-and-customize.md)。本页保留 API 用法速查。
## 1. 安装示例
1. 打开 TraceMemo,左侧一级导航点「扩展」。
2. 点「安装目录」,选择 `examples/extensions/keyword-bot`。
3. 列表里出现 **关键词回复机器人**,状态为「已停用」。
4. 点「启用」→「打开页面」;页面顶部的「启用机器人」默认关闭,打开后修改规则并保存。
5. 完全退出并重启 TraceMemo,配置仍在。
`examples/extensions/douyin-sender` 用同样的方式安装;它依赖本机 `python3`、Chrome 和抖音解析脚本,先看它自己的 README。
## 2. 最小扩展
```text
my-extension/
manifest.json
ui/index.html
background/index.js
```
`manifest.json`:
```json
{
"manifestVersion": 1,
"id": "com.example.my-extension",
"name": "我的扩展",
"version": "1.0.0",
"apiVersion": "1",
"minAppVersion": "2.6.0",
"permissions": ["storage"],
"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
}
}
```
```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
})
})
}
```
`dedupeKey` 建议直接用 `event.eventId`:同一条消息重复投递时,Gateway 会按审计记录短路。
## 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 中实现,界面暂未暴露)。
+86
View File
@@ -0,0 +1,86 @@
# 扩展安全模型(v1)
## 信任分级
| 类型 | 说明 | 本版支持 |
| --- | --- | --- |
| 声明式 UI 扩展 | 只有页面,使用白名单存储 / 能力查询 | 是 |
| 受信任本地代码扩展 | 后台是任意 Node 代码,可读写本机文件 | 是(安装即视为信任) |
**独立进程不等于强沙箱。** 后台子进程(`ELECTRON_RUN_AS_NODE`)拥有运行用户的全部
Node 能力,因此扩展作者可以读写本机文件、发起网络请求。本版不声称限制了这些——
它限制的是**TraceMemo 内部能力**:
- 拿不到数据库句柄、数据库密钥、授权凭据、Native Runtime 句柄;
- 不能直接调用原生发送接口(dylib / 底层端口);
- 不能 `require` 官方主进程模块;
- 不能伪造宿主可信元数据(`origin` / `purpose` / `triggerType` / 幂等键)。
## 进程与权限
```text
主进程 ── fork ──▶ 扩展子进程(每扩展一个)
│ 只注入 tm
▼
白名单 RPC(method + params)
│
宿主再次校验权限
```
两侧都检查权限:子进程提前失败给出明确错误码,宿主侧才是权威判定。
子进程崩溃 / 挂死不影响主进程:宿主有启动超时、调用超时、退避重启与熔断。
## 发送安全
```text
扩展声明「发什么」
↓
宿主填 origin=extension / purpose=extension_send / recipient 类型 / 幂等键
↓
ExtensionSendGateway:权限 → 会话范围 → 频率 → 本机能力 → 授权校验
↓
WechatActionGateway:用途白名单 + `extension_*` 必须来自 origin=extension
↓
WechatSendGateway:真实发送 + Send Log
```
- 扩展不能在请求里指定 `purpose`,因此无法借用 `manual_*` / `api_*` 等用途绕过白名单。
- 自动化草稿里的 `extensionAction` 只保存扩展 id、动作 id 与静态输入;
发送内容由扩展返回,发送动作由 runner 发起,幂等键由 `executionId` 派生。
- 授权只在主进程判定:macOS 读 Native license(要求 `authorized === true`),
Windows 探测 `/license/status` 只接受 `LICENSE_OK`。UI 上的 `ready` 不作为授权依据。
## 页面安全
- 自定义协议 `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`。
## 安装安全
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` 自行幂等。
+3 -1
View File
@@ -1,11 +1,13 @@
---
name: tracememo-reader
version: 1.4.0
description: 通过 TraceMemo 本地 HTTP API 按需读取用户有权访问的微信聊天数据和图片媒体、管理定时日报任务,并用用户本机登录的微信账号发送消息。当用户要求查看微信消息、查找联系人或群聊、总结聊天、查看或理解图片、生成群聊总结、查询或修改定时日报、给好友或群发送微信消息、代发消息、查看发送记录时使用。此 Skill 由本机 TraceMemo 提供数据,不是 MCP Server。
description: 本机微信聊天记录的读取入口(TraceMemo 本地 HTTP API,默认 http://127.0.0.1:6131/api/v1)。凡是「看微信内容」的请求都必须先走本 Skill:某个群或某人今天聊了什么、刚刚聊了啥、最近消息、谁说了什么、总结聊天、翻历史记录、撤回的消息、图片内容、语音转文字、查找联系人或群聊、群成员、生成群聊总结、定时日报、给好友或群发微信消息、查看发送记录、查看未读。本 Skill 已处理鉴权、撤回归档、图片媒体、语音转写与压缩编码解码,当用户要求查看微信消息、查找联系人或群聊、总结聊天、查看或理解图片、生成群聊总结、查询或修改定时日报、给好友或群发送微信消息、代发消息、查看发送记录时使用。此 Skill 由本机 TraceMemo 提供数据,不是 MCP Server。
---
# TraceMemo Reader
> **加载到本文件,说明通道选对了。** 只要问题涉及「读本机微信聊天内容」——某个群或某人今天聊了什么、刚刚聊了啥、最近消息、撤回、图片、语音、联系人、日报——本 Skill 就是第一顺位。
你是一个通过本机 TraceMemo 读取微信历史的 Agent。先确认用户已经在 TraceMemo 中完成数据库连接,再按需调用 API;不要假设数据库已就绪,也不要声称读取了没有调用过的消息。
## 连接信息
+5
View File
@@ -39,6 +39,11 @@ extraResources:
- runtime/win32/**
- wcdb/win32/x64/**
- '!wcdb/**/tm-wcdb-config-helper*'
# 官方扩展模板(构建期由 scripts/build-extension-templates.cjs 生成)
- from: build/extension-templates
to: extension-templates
filter:
- '**/*'
# 默认不打包helper
# - from: resources/wcdb/win32/x64
# to: resources/wcdb/win32/x64
+6
View File
@@ -40,6 +40,12 @@ extraResources:
to: skill/tracememo-reader
filter:
- '**/*'
# 官方扩展模板:构建期由 scripts/build-extension-templates.cjs 生成,
# 安装包必须自带,运行时不依赖源码树或网络。
- from: build/extension-templates
to: extension-templates
filter:
- '**/*'
nsis:
oneClick: false
allowToChangeInstallationDirectory: true
+2
View File
@@ -11,6 +11,8 @@ export default defineConfig({
rollupOptions: {
input: {
index: resolve('src/main/index.ts'),
/* 扩展后台宿主:由 `ExtensionHost` 以子进程方式 fork,不在主进程加载。 */
extensionHost: resolve('src/main/extensions/host-runtime.ts'),
reportTemplateTest: resolve('src/main/report-template-test-entry.ts'),
queryAgentPoc: resolve('src/main/query-agent-poc-entry.ts'),
voiceRecognitionWorker: resolve('src/main/voice-pipeline/voice-recognition-worker.ts'),
+9
View File
@@ -34,5 +34,14 @@ export default defineConfig(
...eslintPluginReactRefresh.configs.vite.rules
}
},
{
// 扩展示例是给第三方作者抄的 CommonJS,不是 TS 源码:
// 返回类型/require 规则在这里没有意义,强制它们只会让示例变成反例。
files: ['examples/**/*.{js,mjs}'],
rules: {
'@typescript-eslint/explicit-function-return-type': 'off',
'@typescript-eslint/no-require-imports': 'off'
}
},
eslintConfigPrettier
)
+39
View File
@@ -0,0 +1,39 @@
# 扩展示例
三个可直接安装的官方模板示例,用来验证扩展中心从安装到发送的完整链路。
| 目录 | 用途 | 申请权限 |
| --- | --- | --- |
| `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` |
| `douyin-sender/` | @我 发抖音链接 → 解析 → 下载 → 发回视频;配置页可测试发送 | `messages.subscribe`、`contacts.list`、`wechat.send.video`、`wechat.send.text`、`storage` |
## 安装
TraceMemo → 左侧「扩展」→「官方模板」一键安装,或点「安装目录」选择对应目录。
安装后扩展默认**未启用**:
- `keyword-bot` 的 `enabled` 为 `false`,需要在配置页手动打开才会回复;
- `group-chat-bot` 需要本机已配置 AI Provider(需要语音回复时在「设置 → 文字转语音」配置音色),并在配置页勾选生效群聊;
- `douyin-sender` 依赖本机的 `python3`、Chrome 和抖音解析脚本,安装前先看它自己的 README。
## 测试建议
- 关键词机器人默认监听全部群聊 + 私聊;想只对某个群生效,在「监听范围」里搜索并多选群聊。
- 冷却时间按「会话 + 规则」计算,避免同一句话连续刷屏。
- 扩展的发送走 `tm.wechat.send`,最终仍由 TraceMemo Gateway 做权限、授权校验、限流与审计。
## 开发
扩展目录里只需要 `manifest.json` 与入口文件:
```text
my-extension/
manifest.json
ui/index.html
background/index.js
```
`background/index.js` 导出 `activate(tm)`(或 `module.exports = { activate }`)。页面通过
`postMessage` 与宿主通信,协议见 `docs/extensions/api-reference.md`。
+143
View File
@@ -0,0 +1,143 @@
# 抖音视频搬运
被 @ 且消息里带抖音分享链接时,解析作品、下载视频,并发回原会话。
判定范围由扩展自己控制:只有**真正 @ 到当前登录账号**的文本消息才会进入流程
(`subscriptions.requireMentionMe: true`),普通消息直接忽略。
## 前置条件
- 本机有 `python3`(3.10 及以上)。
- 本机装了 Chrome:解析脚本用真实浏览器打开作品页、拦截页面自己发出的 `aweme/detail` 响应,
不自造签名。
- 解析脚本已存在于本机(默认 `scripts/douyin.py`,相对于扩展目录,也可在配置页指定自定义路径)。
- 首次运行时脚本会在 `~/Library/Caches/douyin-video/venv`(Windows 落在 `%LOCALAPPDATA%`)
自建 venv 并安装 `playwright` / `requests`,约 30 秒;之后复用,不再安装。
## 安装
TraceMemo → 左侧「扩展」→「安装目录」,选择本目录 `douyin-sender/`。
安装完成后:
1. 打开「抖音解析设置」页面,确认 Python 路径与脚本路径;
2. 打开总开关,保存;
3. 在「测试发送」里选目标群、粘贴抖音分享文案,点「测试发送」验证;
或在微信里 @ 自己发一条带抖音分享链接的文本消息。
扩展默认 `enabled: false`,安装后不会自动对外发送。
配置页的群列表来自本机通讯录,对应权限 `contacts.list`(只读群名与会话 id,不含聊天内容)。
升级同 id 的扩展会替换代码并保留配置;如果新版本**新增了权限**(例如从 image 换成 video),
升级后请「停用 → 启用」一次,让宿主按新 manifest 重新授权。
## 测试发送(配置页)
配置页底部有独立的「测试发送」:
1. 下拉选择目标群(列表来自 `contacts.listGroups`,需要 `contacts.list` 权限);
2. 粘贴抖音链接或整段分享文案(命令行脚本不需要手动截取 URL);
3. 点「测试发送」,页面会轮询进度,解析完成后把去水印视频发到该群;
4. 测试路径**不发回执**,避免测试时多一条消息;
5. 测试任务同样计入统计,进度显示在「当前任务」。
设置页可选使用「抖音 Cookie」面板粘贴并保存 Cookie header。宿主通过系统安全存储加密后保存在本机,页面只展示是否已配置,不会回显内容;测试发送与自动解析时在后台使用该 Cookie,未配置时也可回退读取本机 `douyin-cookie` 文件。
## 配置字段
| 字段 | 默认值 | 说明 |
| ----------------- | ------------------------ | ---------------------------------------------------------------------- |
| `enabled` | `false` | 总开关;关闭时任何消息都不处理 |
| `pythonPath` | `python3` | Python 可执行文件,支持 `~` |
| `scriptPath` | `scripts/douyin.py` | 解析脚本路径(默认相对于扩展目录,支持 `~` 与绝对路径) |
| `quality` | `720` | `''` 最高 / `1080` / `720` / `540`;其他值收敛到 `720` |
| `showUi` | `false` | 排障开关:显示浏览器窗口以观察最终页面;不保证改变平台响应 |
| 抖音 Cookie | 未配置 | 配置页输入后由 Electron `safeStorage` 加密保存 |
| `ackText` | `收到,正在解析,请稍候…`| 命中后先回复的文本;留空表示不回执 |
| `errorReply` | `true` | 失败时是否在原会话回一条简短说明 |
| `includeDirect` | `false` | 是否同时处理私聊 |
| `groups` | `[]` | 群白名单;空数组表示全部群 |
| `cooldownSeconds` | `60` | 按会话计的冷却,0–3600 |
| `maxFileMB` | `100` | 单文件上限,1–100,不能超过宿主 100 MB 硬限制 |
保存时写入 `configVersion: 1`;后台最多 1 秒内读到新配置(配置缓存 TTL 1000 ms)。
## 处理流程
1. `message.received` → 判定顺序:总开关 → 自己发的 → 非 text → 未 @我 → 提取链接 → 会话范围 → 冷却。
2. 命中后先回执(`ackText`,默认「收到,正在解析,请稍候…」;留空关闭),再进入解析。
3. `python3 <script> "<链接>" -o <dataDir>/downloads --wait 40 --download-timeout 90 --json --video-only --download`,单次打开作品页并完成解析、下载;图集只返回类型、不下载;进程总超时 420 秒,输出上限 8 MB,`cwd` 为扩展数据目录。
4. 从 JSON 结果中读取作品元数据与 `saved` 绝对路径;校验文件存在、是普通文件、未超过上限。
5. 若结果为图集,记为 `IMAGE_SET` 并按配置处理失败提示;若解析/下载失败,保留脚本返回的错误原因。
6. 发送视频,`dedupeKey = eventId + ':video'`(不再额外发送作品标题文本)。
7. 每个阶段都写 `progress` 快照并记一条日志;配置页每 2 秒刷新一次进度。
8. 无论成败写一条统计(成功/失败分别计数);失败只记阶段、错误码与去掉 URL / 路径的短原因。
9. 冷却只在**视频发送成功后**写入。
同一会话同时只跑一个任务;同一条消息重复投递时按 `会话 + 链接` 去重。启动时会清理
`<dataDir>/downloads`:只保留最近 20 个文件,并删除 7 天前的文件。
失败文案固定为三种,原因截断到 60 字且不含路径:
- `解析失败:<短原因>`
- `视频过大(<N>MB),已跳过`
- `暂不支持图集`
## 发送通道
视频走宿主的 **video 通道**:`tm.wechat.send({ type: 'video', to, path })`。
原生 Host 以 `{toWxid, type:'video', msg:<路径>}` 提交,所以 `permissions` 里申请的是 `wechat.send.video`。
媒体文件必须落在扩展数据目录或系统临时目录内(宿主会用 `realpath` 复核),扩展名必须是
`mp4/mov/m4v`,大小 1 B–100 MB。所有发送仍要过 Gateway 的权限、
授权与限流:同一扩展 60 秒最多 10 条,两条之间至少 2 秒。
## 限制
- 只处理视频;图集(`type: 'image'`)不下载,按配置回「暂不支持图集」。
- 单个文件 ≤ 100 MB,超过不发送。
- 冷却按会话计,冷却期内同一会话的新链接会被忽略。
- 事件投递是「至多一次」:TraceMemo 未运行期间的消息不会补发。
- 脚本路径必须在本机真实存在;路径错误时错误文案会提示检查 Python 路径。
- 解析依赖抖音页面结构,脚本自身失效时扩展只能报「解析失败」。
## 排障:`页面已加载(NNNKB)但未发出 detail 请求`
这是浏览器打开了页面,但没有捕获到 `aweme/detail` 的作品数据。仅凭这一条错误不能判断作品已删除;页面也可能是作品壳、推荐页或平台验证状态。先看 `--debug` 现场中的页面标题、地址和截图。扩展不会并发启动第二次解析;测试发送失败时会在页面显示阶段、错误码和去掉 URL / 本地路径后的短原因。
仍需手动复试时:
1. 先等一会儿再尝试,避免同一作品短时间内重复请求;
2. 配置页勾选「显示浏览器窗口」后重新测试,观察最终停留页面;
3. 命令行单独验证时使用同一份脚本,避免与扩展并发运行:
```bash
python3 scripts/douyin.py \
"https://v.douyin.com/xxxxxx/" --json --wait 40 --show-ui
```
## 进度与统计
- 回执:命中后先发一条 `ackText`,默认「收到,正在解析,请稍候…」;留空则不回。
- 进度:存储键 `progress`,结构 `{stage,status,startedAt,updatedAt,awemeId,errorType,errorMessage}`。
配置页每 2 秒读取一次,显示「已接收 / 解析 / 下载 / 发送 / 补发文案 / 完成」,
失败时显示失败所在阶段与错误码。
- 统计:存储键 `stats`,结构 `{dateKey,todayTotal,todaySuccess,todayFailure,lastJobs[]}`;
失败也计数,`lastJobs` 保留最近 20 条(含阶段与错误码)。
- 页面顶部「统计」显示今日总计 / 成功 / 失败;表格展示最近 8 条。
## 隐私
- 分享链接会交给本机脚本,由脚本访问抖音页面;扩展本身不向任何第三方发请求。
- 下载的视频存放在扩展数据目录 `downloads/` 下,发送后不自动删除(按上面的规则轮转清理)。
- 统计只保存时间、作品 id、阶段、成败、错误码,**不含** URL、标题、作者、会话 id。
- 日志只写阶段与错误类型。
## 测试
```bash
node --test examples/extensions/douyin-sender/tests/douyin.test.mjs
```
用例全部离线:不联网、不启动 python、不读写真实文件。
@@ -0,0 +1,842 @@
'use strict'
/**
* 抖音视频搬运 —— 后台入口。
*
* 链路:`message.received` → 纯函数判定 → 解析并下载脚本 →
* 经宿主 `wechat.send` 的 video 通道发回原会话。
*
* 这个文件跑在宿主的扩展子进程里,**只**用 `tm` 暴露的能力:
* 没有 socket、没有 dylib、没有直接读写微信数据目录。
*/
const os = require('node:os')
const path = require('node:path')
const fsSync = require('node:fs')
const fs = require('node:fs/promises')
const { execFile } = require('node:child_process')
const { promisify } = require('node:util')
const {
normalizeConfig,
extractDouyinUrl,
parseDownloadedResult,
shouldHandle,
isFileTooLarge
} = require('../lib/douyin')
const execFileAsync = promisify(execFile)
const CONFIG_KEY = 'config'
const STATS_KEY = 'stats'
/** 安全存储里的 Cookie 键名。 */
const SECRET_COOKIE_KEY = 'douyinCookie'
const PROGRESS_KEY = 'progress'
const TEST_RESULT_KEY = 'testResult'
const CONFIG_TTL_MS = 1000
/** 配置页「测试发送」的轮询间隔;页面只负责写请求、读结果。 */
/** 阶段名只用于展示与日志,不参与判断。 */
const STAGE_LABELS = {
accepted: '已接收',
resolve: '解析',
resolveDownload: '解析并下载',
download: '下载',
send: '发送',
caption: '补发文案',
done: '完成',
failed: '失败'
}
/** 脚本内部等待抖音接口的秒数,解析与下载共用。 */
const SCRIPT_WAIT_SECONDS = '40'
const DOWNLOAD_AND_RESOLVE_TIMEOUT_MS = 420_000
const MAX_OUTPUT_BYTES = 8 * 1024 * 1024
/** 宿主限制:同一扩展两次发送之间至少 2 秒,这里留 200ms 余量。 */
const SEND_GAP_MS = 2200
const KEEP_RECENT_FILES = 20
const MAX_FILE_AGE_MS = 7 * 24 * 60 * 60 * 1000
const MAX_JOB_HISTORY = 20
const COOLDOWN_MAP_LIMIT = 500
let tm = null
let cachedConfig = null
let cachedAt = 0
let cachedStats = null
let cachedProgress = null
/** 会话 → 冷却截止时间(epoch 毫秒)。 */
const cooldownUntil = new Map()
/** 正在处理的会话:同一会话同时只跑一个任务。 */
const activeConversations = new Set()
/** 正在处理的 `会话|链接`:避免同一条消息被重复投递时跑两遍。 */
const activeJobs = new Set()
function safeLog(level, message) {
try {
const writer = tm && tm.log && tm.log[level]
if (typeof writer === 'function') writer.call(tm.log, String(message))
} catch {
// 日志通道本身不可用时不能影响发送流程。
}
}
/** 错误类型化:日志只保留阶段与错误码,不写 URL、路径、标题。 */
function errorType(error) {
if (!error) return 'UNKNOWN'
if (error.killed || error.signal) return 'TIMEOUT'
// 数字退出码单独标成 EXIT_n,避免统计里只看到一个「2」。
if (typeof error.code === 'number') return `EXIT_${error.code}`
if (typeof error.code === 'string' && /^[A-Z0-9_]+$/.test(error.code)) return error.code
if (error.name === 'Error') return 'ERROR'
return String(error.name || 'ERROR')
}
/** 去掉换行、链接与路径,只留 ≤60 字的短原因。 */
function shortReason(input) {
let text = String(input === null || input === undefined ? '' : input)
.replace(/https?:\/\/\S+/gi, ' ')
.replace(/[\r\n\t]+/g, ' ')
.replace(/(?:[A-Za-z]:)?(?:[\\/][^\s"'))]+)+/g, ' ')
.replace(/\s+/g, ' ')
.trim()
text = text.replace(/^[::,,。;;-]+/, '').trim()
text = text.replace(/title=[^,,))]+/gi, 'title=已隐藏')
if (!text) return '未知原因'
return text.slice(0, 60)
}
function parseFailure(cause, type) {
return { ok: false, message: `解析失败:${shortReason(cause)}`, errorType: type || 'PARSE' }
}
function tooLargeMessage(sizeBytes) {
const megabytes = Math.max(1, Math.ceil(Number(sizeBytes) / (1024 * 1024)))
return `视频过大(${megabytes}MB),已跳过`
}
function expandHome(value) {
const raw = String(value || '').trim()
if (!raw) return ''
if (raw === '~') return os.homedir()
if (raw.startsWith('~/') || raw.startsWith('~' + path.sep)) {
return path.join(os.homedir(), raw.slice(2))
}
return raw
}
function downloadsDir() {
return path.join(tm.extension.dataDir, 'downloads')
}
async function loadConfig() {
if (cachedConfig && Date.now() - cachedAt < CONFIG_TTL_MS) return cachedConfig
let stored = null
try {
stored = await tm.storage.get(CONFIG_KEY)
} catch (error) {
safeLog('warn', `读取配置失败:${errorType(error)}`)
}
cachedConfig = normalizeConfig(stored)
cachedAt = Date.now()
return cachedConfig
}
function dateKey(timestamp) {
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}`
}
function normalizeStats(raw) {
const input = raw && typeof raw === 'object' && !Array.isArray(raw) ? raw : {}
const lastJobs = Array.isArray(input.lastJobs)
? input.lastJobs
.filter((job) => job && typeof job === 'object')
.slice(0, MAX_JOB_HISTORY)
.map((job) => ({
at: Number(job.at) || 0,
awemeId: String(job.awemeId || '').slice(0, 32),
ok: job.ok === true,
stage: String(job.stage || '').slice(0, 20),
errorType: String(job.errorType || '').slice(0, 24)
}))
: []
const total = Math.max(0, Math.trunc(Number(input.todayTotal ?? input.todayCount) || 0))
return {
dateKey: typeof input.dateKey === 'string' ? input.dateKey.slice(0, 10) : '',
todayTotal: total,
todaySuccess: Math.max(0, Math.trunc(Number(input.todaySuccess) || 0)),
todayFailure: Math.max(0, Math.trunc(Number(input.todayFailure) || 0)),
lastJobs
}
}
async function loadStats() {
if (cachedStats) return cachedStats
let stored = null
try {
stored = await tm.storage.get(STATS_KEY)
} catch (error) {
safeLog('warn', `读取统计失败:${errorType(error)}`)
}
cachedStats = normalizeStats(stored)
return cachedStats
}
/**
* 追加一条任务记录。
*
* 统计里只允许出现 awemeId / 时间 / 阶段 / 成败 / 错误类型;URL、标题、作者、
* 会话 id 都不写,避免把聊天内容沉淀成扩展数据。
*/
async function recordJob(job) {
const now = Date.now()
const current = await loadStats()
const key = dateKey(now)
const sameDay = current.dateKey === key
const next = {
dateKey: key,
todayTotal: (sameDay ? current.todayTotal : 0) + 1,
todaySuccess: (sameDay ? current.todaySuccess : 0) + (job.ok === true ? 1 : 0),
todayFailure: (sameDay ? current.todayFailure : 0) + (job.ok === true ? 0 : 1),
lastJobs: [
{
at: now,
awemeId: String(job.awemeId || '').slice(0, 32),
ok: job.ok === true,
stage: String(job.stage || '').slice(0, 20),
errorType: String(job.errorType || '').slice(0, 24)
},
...current.lastJobs
].slice(0, MAX_JOB_HISTORY)
}
cachedStats = next
try {
await tm.storage.set(STATS_KEY, next)
} catch (error) {
safeLog('warn', `写入统计失败:${errorType(error)}`)
}
}
/**
* 写「当前任务」快照,供配置页展示进度。
*
* 只保留一条最近任务:jobId 用事件 id(不可逆哈希),不含会话与正文。
* 写失败只 warn,不能因为展示层异常影响发送。
*/
async function setProgress(patch) {
const now = Date.now()
const next = {
...(cachedProgress || {}),
...patch,
updatedAt: now
}
if (!next.startedAt) next.startedAt = now
cachedProgress = next
const label = STAGE_LABELS[next.stage] || next.stage || ''
safeLog('info', `任务进度:${label}${next.awemeId ? `(${next.awemeId})` : ''}`)
try {
await tm.storage.set(PROGRESS_KEY, next)
} catch (error) {
safeLog('warn', `写入进度失败:${errorType(error)}`)
}
}
function markCooldown(conversationId, seconds) {
if (!conversationId || !(seconds > 0)) return
cooldownUntil.set(conversationId, Date.now() + seconds * 1000)
if (cooldownUntil.size > COOLDOWN_MAP_LIMIT) {
const now = Date.now()
for (const [key, until] of cooldownUntil) {
if (until <= now) cooldownUntil.delete(key)
}
}
}
function sleep(milliseconds) {
return new Promise((resolve) => setTimeout(resolve, milliseconds))
}
/** WindowsApps 下的是 Microsoft Store 别名,执行不成脚本,探测时要跳过。 */
function isStoreAliasPath(value) {
return /[\\/]WindowsApps[\\/]/i.test(String(value || ''))
}
/** 在 PATH 中按顺序找第一个真实存在的可执行文件。 */
function findOnPath(names) {
const dirs = String(process.env.PATH || '')
.split(path.delimiter)
.filter((dir) => dir && !isStoreAliasPath(dir))
for (const name of names) {
for (const dir of dirs) {
for (const ext of ['.exe', '.EXE', '']) {
const candidate = path.join(dir, name + ext)
try {
if (fsSync.existsSync(candidate) && fsSync.statSync(candidate).isFile()) return candidate
} catch {
// 目录不可读就跳过,继续下一个候选。
}
}
}
}
return ''
}
/** 配置为空或是默认名时,按 py -3 → python 的顺序探测。 */
function resolveWindowsPython(pythonPath) {
const configured = expandHome(pythonPath)
const looksDefault = !configured || configured === 'python' || configured === 'python3'
if (!looksDefault && !isStoreAliasPath(configured)) {
return { file: configured, prefixArgs: [] }
}
const py = findOnPath(['py'])
if (py) return { file: py, prefixArgs: ['-3'] }
const python = findOnPath(['python'])
if (python) return { file: python, prefixArgs: [] }
return { file: 'python', prefixArgs: [] }
}
// Apple Silicon 上 x86_64 的 python3 会把 P_TRANSLATED 传给 Chrome,页面卡加载;
// 优先用 venv 原生解释器并经 /usr/bin/arch -arm64 强制原生运行。
function resolvePythonInvocation(pythonPath, scriptPath, args) {
if (process.platform === 'win32') {
const resolved = resolveWindowsPython(pythonPath)
return {
file: resolved.file,
args: [...resolved.prefixArgs, scriptPath, ...args]
}
}
if (process.platform !== 'darwin') {
return { file: pythonPath, args: [scriptPath, ...args] }
}
const resolvedPython = pythonPath
try {
if (fsSync.existsSync('/usr/bin/arch')) {
return {
file: '/usr/bin/arch',
args: ['-arm64', resolvedPython, scriptPath, ...args]
}
}
} catch {
// 非标准系统环境缺少 /usr/bin/arch 时直接调用解释器。
}
return { file: resolvedPython, args: [scriptPath, ...args] }
}
/**
* 解析可用的抖音 Cookie。
*
* 只认两个来源:调用方显式传入的 header,以及扩展私有目录里由用户配置生成的文件。
* **不扫描桌面**——扩展不该去读用户没有明确交给它的文件。
*/
async function resolveCookieHeader(explicitHeader) {
const direct = String(explicitHeader || '').trim()
if (direct) return direct
if (tm && tm.douyin && typeof tm.douyin.getCookie === 'function') {
try {
const fromHost = String((await tm.douyin.getCookie()) || '').trim()
if (fromHost) return fromHost
} catch {
// 宿主未提供或读取失败时按「未配置」处理。
}
}
// 优先用安全存储;未授权或不可用时再退回旧的扩展数据文件(迁移期兼容)。
if (tm.secrets) {
try {
const stored = await tm.secrets.get(SECRET_COOKIE_KEY)
if (stored) return String(stored).trim()
} catch {
// 未授予 secrets 权限或系统安全存储不可用:继续走兼容分支。
}
}
try {
const content = String(await fs.readFile(path.join(tm.extension.dataDir, 'douyin-cookie.txt'), 'utf8')).trim()
if (content) return content
} catch {
// 未配置 Cookie 时走游客模式。
}
return ''
}
/**
* 把旧的明文 Cookie 迁进安全存储,成功后删除明文文件。
*
* 只在「安全存储可用 + 用户已授权 secrets」时执行;否则保持原样,
* 绝不把加密数据降级成明文,也不谎报迁移成功。
*/
async function migrateLegacyCookie() {
if (!tm.secrets) return
try {
const existing = await tm.secrets.get(SECRET_COOKIE_KEY)
if (existing) return
const legacyPath = path.join(tm.extension.dataDir, 'douyin-cookie.txt')
const legacy = String(await fs.readFile(legacyPath, 'utf8')).trim()
if (!legacy) return
await tm.secrets.set(SECRET_COOKIE_KEY, legacy)
await fs.unlink(legacyPath).catch(() => undefined)
tm.log.info('已把旧版明文 Cookie 迁入系统安全存储,并删除明文文件')
} catch {
// 未授权或不可用时静默保留旧文件,由页面提示用户重新填写。
}
}
function resolveScriptPath(value) {
const expanded = expandHome(value)
if (!expanded) return path.resolve(__dirname, '..', 'scripts', 'douyin.py')
if (path.isAbsolute(expanded)) return expanded
return path.resolve(__dirname, '..', expanded)
}
/**
* 解析脚本不随应用分发(来源与分发许可未确认),缺失时整条视频链路必须停住。
* 缺失提示只打一次,避免每条消息刷日志。
*/
let scriptMissingLogged = false
function ensureScriptReady(config) {
let ready = false
try {
ready = fsSync.existsSync(resolveScriptPath(config.scriptPath))
} catch {
ready = false
}
if (!ready && !scriptMissingLogged) {
scriptMissingLogged = true
safeLog('warn', '缺少解析脚本 scripts/douyin.py,视频处理已暂停;请按扩展说明自行提供后重启')
}
if (ready) scriptMissingLogged = false
return ready
}
/** 统一封装脚本调用:固定 cwd、超时、输出上限、UTF-8 与 macOS 原生 arm64 执行。 */
async function runPython(args, timeoutMs, config) {
// 首次启用时 dataDir 可能还没被创建;execFile 的 cwd 不存在会直接 ENOENT。
await fs.mkdir(tm.extension.dataDir, { recursive: true })
const pythonPath = expandHome(config.pythonPath)
const scriptPath = resolveScriptPath(config.scriptPath)
const invocation = resolvePythonInvocation(pythonPath, scriptPath, args)
return execFileAsync(invocation.file, invocation.args, {
cwd: tm.extension.dataDir,
timeout: timeoutMs,
maxBuffer: MAX_OUTPUT_BYTES,
env: {
...process.env,
PYTHONIOENCODING: 'utf-8',
PYTHONUNBUFFERED: '1',
DOUYIN_ARM64_READY: '1'
},
windowsHide: true
})
}
function describeExecError(error) {
if (!error) return '失败'
if (error.code === 'ENOENT') return '找不到 Python 可执行文件,请检查 Python 路径'
if (error.killed || error.signal) return '超时'
if (typeof error.code === 'number') return `脚本退出码 ${error.code}`
if (typeof error.code === 'string' && /^E[A-Z]+$/.test(error.code)) {
return `失败(${error.code})`
}
return '失败'
}
async function resolveAndDownloadVideo(url, config, options = {}) {
const dir = downloadsDir()
try {
await fs.mkdir(dir, { recursive: true })
} catch (error) {
return parseFailure('下载目录不可用(' + errorType(error) + ')', errorType(error))
}
const args = [
url,
'-o',
dir,
'--wait',
SCRIPT_WAIT_SECONDS,
'--download-timeout',
'90',
'--json',
'--debug',
'--video-only',
'--download'
]
if (config.quality) args.push('-q', config.quality)
if (config.showUi) args.push('--show-ui')
const cookieHeader = await resolveCookieHeader(options.cookieHeader)
let temporaryCookieFile = ''
let stdout = ''
try {
if (cookieHeader) {
await fs.mkdir(tm.extension.dataDir, { recursive: true })
temporaryCookieFile = path.join(
tm.extension.dataDir,
`.douyin-cookie-${Date.now()}-${Math.random().toString(36).slice(2)}.txt`
)
await fs.writeFile(temporaryCookieFile, cookieHeader, { mode: 0o600, flag: 'wx' })
await fs.chmod(temporaryCookieFile, 0o600)
args.push('--cookie-file', temporaryCookieFile)
}
const result = await runPython(args, DOWNLOAD_AND_RESOLVE_TIMEOUT_MS, config)
stdout = String(result.stdout || '')
} catch (error) {
stdout = String((error && error.stdout) || '')
if (!stdout.trim()) {
// 别把失败统一报成「Cookie 不可用」,否则 ENOENT 和脚本退出码都被盖掉。
const reason = describeExecError(error)
const withMode = temporaryCookieFile ? `${reason}(Cookie 模式)` : reason
return parseFailure(withMode, temporaryCookieFile ? 'COOKIE_OR_TIMEOUT' : errorType(error))
}
} finally {
if (temporaryCookieFile) {
try {
await fs.unlink(temporaryCookieFile)
} catch {
// 解析结束后清除临时凭证文件。
}
}
}
const parsed = parseDownloadedResult(stdout)
if (!parsed) {
const failure = /✗\s*(?:失败[::])?\s*(.+)/.exec(stdout)
return parseFailure(failure ? failure[1] : '脚本输出无法识别', 'INVALID_OUTPUT')
}
if (!parsed.ok) return parseFailure(parsed.message, parsed.errorType)
let stat = null
try {
stat = await fs.stat(parsed.path)
} catch {
return parseFailure('下载文件不存在', 'MISSING_FILE')
}
if (!stat.isFile()) return parseFailure('下载结果不是文件', 'NOT_A_FILE')
if (isFileTooLarge(stat.size, config.maxFileMB)) {
return { ok: false, message: tooLargeMessage(stat.size), errorType: 'TOO_LARGE' }
}
return { ok: true, path: parsed.path, size: stat.size, meta: parsed.meta }
}
let lastSendAt = 0
async function waitSendSlot() {
const elapsed = Date.now() - lastSendAt
if (lastSendAt > 0 && elapsed < SEND_GAP_MS) {
await sleep(SEND_GAP_MS - elapsed)
}
lastSendAt = Date.now()
}
async function sendText(to, text, dedupeKey, stage) {
try {
await waitSendSlot()
await tm.wechat.send({ to, text, dedupeKey })
lastSendAt = Date.now()
return true
} catch (error) {
safeLog('warn', `未完成:阶段=${stage || 'text'} 错误=${errorType(error)}`)
return false
}
}
/** 发视频:走宿主 video 通道,`dedupeKey` 保证同一条消息只发一次。 */
async function sendVideo(event, filePath) {
try {
await waitSendSlot()
await tm.wechat.send({
type: 'video',
to: event.conversationId,
path: filePath,
dedupeKey: `${event.eventId}:video`
})
lastSendAt = Date.now()
return true
} catch (error) {
safeLog('warn', `未完成:阶段=send 错误=${errorType(error)}`)
return false
}
}
async function reportFailure(event, config, message) {
if (!config.errorReply) return
await sendText(event.conversationId, message, `${event.eventId}:error`, 'reply')
}
/**
* 一次完整任务。
*
* `stage` 记录失败发生的位置:`resolveDownload` / `send` / `done`。
* 进度快照与统计都会落盘;失败原因只保留错误类型,不写 URL / 路径 / 标题。
*/
async function processLink(event, config, url, options = {}) {
if (!ensureScriptReady(config)) return
const jobId = event.eventId
let awemeId = ''
let stage = 'accepted'
let ok = false
let failureCode = ''
let failureMessage = ''
try {
stage = 'resolveDownload'
await setProgress({ jobId, awemeId, stage, status: 'running' })
const downloaded = await resolveAndDownloadVideo(url, config, options)
if (!downloaded.ok) {
failureCode = downloaded.errorType || 'DOWNLOAD_FAILED'
failureMessage = downloaded.message
return
}
const meta = downloaded.meta
awemeId = String(meta.aweme_id || '')
stage = 'send'
await setProgress({ jobId, awemeId, stage, status: 'running' })
const sent = await sendVideo(event, downloaded.path)
if (!sent) {
failureCode = 'SEND_FAILED'
failureMessage = '视频发送失败'
return
}
ok = true
stage = 'done'
// 冷却只在视频真正发出去之后才写入,失败不占用下一次机会。
markCooldown(event.conversationId, config.cooldownSeconds)
} catch (error) {
failureCode = errorType(error)
failureMessage = '处理异常'
safeLog('warn', `处理异常:阶段=${stage} 错误=${failureCode}`)
} finally {
if (ok) {
await setProgress({ jobId, awemeId, stage: 'done', status: 'done', errorType: '' })
} else {
if (failureMessage && options.replyOnFailure !== false) {
await reportFailure(event, config, failureMessage)
}
await setProgress({
jobId,
awemeId,
stage: stage === 'accepted' ? 'resolve' : stage,
status: 'failed',
errorType: failureCode || 'FAILED',
errorMessage: failureMessage ? shortReason(failureMessage) : ''
})
safeLog('warn', `未完成:阶段=${stage} 错误=${failureCode || 'FAILED'}`)
}
await recordJob({
awemeId,
ok,
stage: ok ? 'done' : stage,
errorType: ok ? '' : failureCode || 'FAILED'
})
}
}
async function handleEvent(event) {
try {
const config = await loadConfig()
if (!ensureScriptReady(config)) return
const decision = shouldHandle(event, config, cooldownUntil, Date.now())
if (!decision.handle) return
const conversationId = event.conversationId
const jobKey = `${conversationId}|${decision.url}`
if (activeConversations.has(conversationId) || activeJobs.has(jobKey)) return
activeConversations.add(conversationId)
activeJobs.add(jobKey)
try {
await setProgress({
jobId: event.eventId,
stage: 'accepted',
status: 'running',
startedAt: Date.now(),
awemeId: '',
errorType: '',
errorMessage: ''
})
// 先回执再干活:解析/下载要十几秒,用户不该靠猜。
if (config.ackText) {
await sendText(conversationId, config.ackText, `${event.eventId}:ack`, 'ack')
}
await processLink(event, config, decision.url)
} finally {
activeConversations.delete(conversationId)
activeJobs.delete(jobKey)
}
} catch (error) {
safeLog('warn', `事件处理失败:${errorType(error)}`)
}
}
let lastTestRequestId = ''
let testInFlight = false
let pendingTestRequest = null
async function writeTestResult(result) {
try {
await tm.storage.set(TEST_RESULT_KEY, result)
} catch (error) {
safeLog('warn', `写入测试结果失败:${errorType(error)}`)
}
}
/**
* 配置页「测试发送」。
*
* 测试请求通过宿主一次性送达,不落入扩展持久化存储。
*/
async function pollTestRequest() {
if (testInFlight) return
const request = pendingTestRequest
pendingTestRequest = null
if (!request || typeof request !== 'object') return
const id = String(request.id || '').trim()
if (!id || id === lastTestRequestId) return
lastTestRequestId = id
const to = String(request.to || '').trim()
const text = String(request.text || '').trim()
if (!to || !text) {
await writeTestResult({
id,
status: 'failed',
message: '测试请求缺少群聊或链接',
at: Date.now()
})
return
}
if (activeConversations.has(to)) {
await writeTestResult({
id,
status: 'failed',
message: '该群正在执行其他任务,请稍后重试',
at: Date.now()
})
return
}
const url = extractDouyinUrl(text)
if (!url) {
await writeTestResult({ id, status: 'failed', message: '没有识别到抖音链接', at: Date.now() })
return
}
const config = await loadConfig()
const cookieHeader = request.cookieHeader ? String(request.cookieHeader) : ''
testInFlight = true
activeConversations.add(to)
try {
await writeTestResult({ id, status: 'running', message: '已开始解析…', at: Date.now() })
await setProgress({
jobId: `test:${id}`,
stage: 'accepted',
status: 'running',
startedAt: Date.now(),
awemeId: '',
errorType: '',
errorMessage: ''
})
// 测试路径不发回执:结果直接显示在配置页,视频发到目标群。
await processLink(
{
eventId: `test:${id}`,
conversationId: to,
isGroup: to.endsWith('@chatroom'),
isSelf: false,
type: 'text',
text,
mentionsMe: true
},
config,
url,
{ replyOnFailure: false, cookieHeader }
)
const progress = cachedProgress || {}
if (progress.status === 'done') {
await writeTestResult({
id,
status: 'done',
message: '测试发送完成:视频已发到该群',
at: Date.now()
})
} else {
const label = STAGE_LABELS[progress.stage] || progress.stage || '未知阶段'
await writeTestResult({
id,
status: 'failed',
message: `测试发送失败:${label}${progress.errorType ? `(${progress.errorType})` : ''}${progress.errorMessage ? `:${progress.errorMessage}` : ''}`,
at: Date.now()
})
}
} catch (error) {
await writeTestResult({
id,
status: 'failed',
message: `测试发送异常:${errorType(error)}`,
at: Date.now()
})
} finally {
activeConversations.delete(to)
testInFlight = false
}
}
/**
* 清理下载目录:只保留最近 20 个文件,并删除 7 天前的文件。
*
* 清理失败不影响发送能力,逐条 try/catch,最坏情况是目录继续变大。
*/
async function cleanupDownloads() {
const dir = downloadsDir()
let entries = []
try {
entries = await fs.readdir(dir, { withFileTypes: true })
} catch {
return
}
const files = []
for (const entry of entries) {
if (!entry.isFile()) continue
const full = path.join(dir, entry.name)
try {
const stat = await fs.stat(full)
files.push({ full, mtime: stat.mtimeMs })
} catch {
// 枚举期间被删除或无法访问,跳过即可。
}
}
files.sort((left, right) => right.mtime - left.mtime)
const now = Date.now()
for (let index = 0; index < files.length; index += 1) {
const fresh = now - files[index].mtime <= MAX_FILE_AGE_MS
if (index < KEEP_RECENT_FILES && fresh) continue
try {
await fs.unlink(files[index].full)
} catch {
// 单个文件删不掉就留着,下一次启动再试。
}
}
}
module.exports = function activate(api) {
tm = api
// 宿主对 handler 有 10 秒超时;脚本可能要跑几分钟,所以这里只排队不等待。
tm.events.on('message.received', (event) => {
void handleEvent(event)
})
void cleanupDownloads()
globalThis.__tmTestSend = async (request) => {
pendingTestRequest = request
await pollTestRequest()
return { accepted: true }
}
tm.log.info('抖音搬运已加载')
}
@@ -0,0 +1,370 @@
'use strict'
/**
* 抖音分享链接解析的纯函数层。
*
* 这一层不碰文件系统、不启子进程、不读时钟:所有输入都从参数进来,
* 所有输出都可序列化,便于在 `node:test` 里离线断言。
*
* 单位约定:
* - 时间一律 epoch 毫秒;
* - 文件大小一律字节,配置里的上限单位是 MB(1 MB = 1024 * 1024 B)。
*/
/** 宿主发送通道的硬上限:单个媒体文件 100 MB,配置不允许突破。 */
const HOST_MAX_FILE_MB = 100
/** 解析脚本的默认位置(相对于扩展目录,支持自定义绝对路径或 `~/`)。 */
const DEFAULT_SCRIPT_PATH = 'scripts/douyin.py'
/** 画质白名单;空串表示「最高」,不传 `-q` 给脚本。 */
const QUALITY_VALUES = ['', '1080', '720', '540']
// Windows 的 python3.exe 通常是 Microsoft Store 别名,执行不成脚本。
const DEFAULT_PYTHON_PATH =
typeof process !== 'undefined' && process.platform === 'win32' ? 'python' : 'python3'
const DEFAULT_CONFIG = {
configVersion: 1,
enabled: false,
pythonPath: DEFAULT_PYTHON_PATH,
scriptPath: DEFAULT_SCRIPT_PATH,
quality: '720',
/** 排障开关:显示浏览器窗口以观察实际页面状态。 */
showUi: false,
/** 命中后先回一句,避免用户不知道是否收到;空串表示不回复。 */
ackText: '收到,正在解析,请稍候…',
sendCaption: false,
captionTemplate: '{author}:{title}',
errorReply: true,
includeDirect: false,
groups: [],
cooldownSeconds: 60,
maxFileMB: HOST_MAX_FILE_MB
}
/** 分享链接只认这三种形态;短链的 id 是字母数字,长链只认数字作品 id。 */
const DOUYIN_URL_PATTERN =
/https?:\/\/(?:v\.douyin\.com\/[A-Za-z0-9_-]{1,64}|(?:www\.)?douyin\.com\/(?:video|note)\/\d{1,32})/i
/** 中文文案里链接后面常跟这些符号,属于分隔符不属于链接。 */
const TRAILING_PUNCTUATION = /[)\]}>,.;:!?'"`。,、;:!?…)】》〉」』”’]+$/
const CAPTION_MAX_LENGTH = 200
const GROUP_MAX_COUNT = 200
function clampInt(value, min, max, fallback) {
const numeric = Number(value)
if (!Number.isFinite(numeric)) return fallback
const rounded = Math.trunc(numeric)
if (rounded < min) return min
if (rounded > max) return max
return rounded
}
function normalizeQuality(value) {
if (value === null || value === undefined) return DEFAULT_CONFIG.quality
const text = String(value).trim()
// 数值型画质(720)与字符串画质('720')同义;`''` 表示最高。
if (text === '') return ''
return QUALITY_VALUES.includes(text) ? text : DEFAULT_CONFIG.quality
}
function normalizeGroups(value) {
const list = Array.isArray(value) ? value : typeof value === 'string' ? value.split(/[\s,]+/) : []
const result = []
for (const item of list) {
const id = String(item === null || item === undefined ? '' : item).trim()
if (!id) continue
if (result.includes(id)) continue
result.push(id.slice(0, 128))
if (result.length >= GROUP_MAX_COUNT) break
}
return result
}
function normalizeText(value, fallback, maxLength) {
const text = typeof value === 'string' ? value.trim() : ''
return (text || fallback).slice(0, maxLength)
}
/**
* 把任意来源(存储、表单、旧版本)的配置收敛成可执行形态。
*
* 契约:**永不抛错**,字段缺失或非法时回落到默认值;返回对象永远是全新的,
* 调用方可以直接持有并修改,不会污染 `DEFAULT_CONFIG`。
*/
function normalizeConfig(raw) {
const input = raw && typeof raw === 'object' && !Array.isArray(raw) ? raw : {}
return {
configVersion: 1,
enabled: input.enabled === true,
pythonPath: normalizeText(input.pythonPath, DEFAULT_CONFIG.pythonPath, 512),
scriptPath: normalizeText(input.scriptPath, DEFAULT_SCRIPT_PATH, 512),
quality: normalizeQuality(input.quality),
showUi: input.showUi === true,
ackText:
input.ackText === undefined
? DEFAULT_CONFIG.ackText
: String(input.ackText).trim().slice(0, 200),
sendCaption: input.sendCaption === true,
captionTemplate: normalizeText(input.captionTemplate, DEFAULT_CONFIG.captionTemplate, 200),
errorReply: input.errorReply !== false,
includeDirect: input.includeDirect === true,
groups: normalizeGroups(input.groups),
cooldownSeconds: clampInt(input.cooldownSeconds, 0, 3600, DEFAULT_CONFIG.cooldownSeconds),
maxFileMB: clampInt(input.maxFileMB, 1, HOST_MAX_FILE_MB, DEFAULT_CONFIG.maxFileMB)
}
}
/**
* 从一段文本里取第一个抖音分享链接。
*
* 输入可能是裸链接,也可能是「复制打开抖音…」整段文案;返回值已去掉尾随标点,
* 查询串与 fragment 一并丢弃(短链换长链由脚本完成,扩展不参与)。
*
* 返回 `null` 表示没有可识别的抖音作品链接;`javascript:` / `ftp:` / 非抖音域名
* 一律不匹配。
*/
function extractDouyinUrl(text) {
const source = typeof text === 'string' ? text : ''
if (!source) return null
const matched = DOUYIN_URL_PATTERN.exec(source)
if (!matched) return null
const cleaned = matched[0].replace(TRAILING_PUNCTUATION, '')
return cleaned || null
}
/** 从 `start` 处的 `[` 找到配对的 `]`,跳过字符串字面量与转义;失败返回 -1。 */
function findArrayEnd(text, start) {
let depth = 0
let inString = false
let escaped = false
for (let index = start; index < text.length; index += 1) {
const char = text[index]
if (inString) {
if (escaped) escaped = false
else if (char === '\\') escaped = true
else if (char === '"') inString = false
continue
}
if (char === '"') {
inString = true
continue
}
if (char === '[') {
depth += 1
continue
}
if (char === ']') {
depth -= 1
if (depth === 0) return index
if (depth < 0) return -1
}
}
return -1
}
function isResolveResultList(value) {
if (!Array.isArray(value) || value.length === 0) return false
return value.every(
(item) =>
item &&
typeof item === 'object' &&
typeof item.url === 'string' &&
typeof item.ok === 'boolean'
)
}
/**
* 从 stdout 中取第一个结构合法的结果数组。
*
* 按结构判定(非空数组、每项含 `url:string` 与 `ok:boolean`),跳过进度行里的
* `[1]` 与嵌套的 `quality_options`;空数组与非法 JSON 返回 `null`。
*/
function parseResolveJson(stdout) {
const text = typeof stdout === 'string' ? stdout : ''
if (!text) return null
for (let start = 0; start < text.length; start += 1) {
if (text[start] !== '[') continue
const end = findArrayEnd(text, start)
if (end < 0) continue
try {
const value = JSON.parse(text.slice(start, end + 1))
if (isResolveResultList(value)) return value
} catch {
// 这个 `[` 不是数组起点(可能在字符串里),继续向后找。
}
}
return null
}
/**
* 从下载输出里取最后一个 `✅` 后面的绝对路径。
*
* 脚本对视频打印 ` ✅ /abs/xxx.mp4`,对图集打印目录后面再跟一段「(N 个文件)」。
* 路径里可能含空格(作者名与标题),所以只按行首标记切分,不按空白切分。
*
* 返回 `null` 表示没有可用的绝对路径。
*/
function parseSavedPath(stdout) {
const text = typeof stdout === 'string' ? stdout : ''
if (!text) return null
const lines = text.split(/\r?\n/)
for (let index = lines.length - 1; index >= 0; index -= 1) {
const marker = lines[index].indexOf('✅')
if (marker < 0) continue
let rest = lines[index].slice(marker + 1).trim()
// 去掉尾部的「(N 个文件)」之类附注,它不属于路径。
rest = rest.replace(/\s*[((][^(())]*[))]\s*$/, '').trim()
if (!rest) continue
if (!isAbsoluteMediaPath(rest)) continue
return rest
}
return null
}
// 绝对路径判定:POSIX `/x`、Windows `C:\x` / `C:/x`、UNC `\\server\share`。
function isAbsoluteMediaPath(value) {
if (typeof value !== 'string') return false
const text = value.trim()
if (!text) return false
if (text.startsWith('/')) return true // POSIX
if (/^[A-Za-z]:[\\/]/.test(text)) return true // C:\ 或 C:/
if (text.startsWith('\\\\')) return true // UNC \\server\share
return false
}
function parseDownloadedResult(stdout) {
const results = parseResolveJson(stdout)
const video = pickVideoResult(results)
if (video) {
const saved = Array.isArray(video.saved)
? video.saved.find((value) => isAbsoluteMediaPath(value))
: null
if (saved) return { ok: true, meta: video, path: saved }
if (video.error) return { ok: false, message: video.error, errorType: 'DOWNLOAD_FAILED' }
return null
}
const image = results && results.find((item) => item && item.ok === true && item.type === 'image')
if (image) return { ok: false, message: '暂不支持图集', errorType: 'IMAGE_SET' }
const failure = results && results.find((item) => item && item.ok === false)
if (failure && failure.error) {
return {
ok: false,
message: failure.error,
errorType: failure.aweme_id ? 'DOWNLOAD_FAILED' : 'RESOLVE_FAILED'
}
}
return null
}
/**
* 按模板渲染文案。
*
* 已知变量 `{author}` / `{title}` / `{awemeId}` 会被替换;未知变量原样保留,
* 让用户能看见自己写错了什么。结果 trim 后截断到 200 字。
*/
function renderCaption(template, meta) {
const source = typeof template === 'string' ? template : ''
const data = meta && typeof meta === 'object' ? meta : {}
const values = {
author: data.author === null || data.author === undefined ? '' : String(data.author),
title: data.title === null || data.title === undefined ? '' : String(data.title),
awemeId: data.awemeId === null || data.awemeId === undefined ? '' : String(data.awemeId)
}
// 已知变量即使取不到值也替换成空串:正文里留下 `{author}` 会被当成程序缺陷。
const rendered = source.replace(/\{(author|title|awemeId)\}/g, (whole, name) => values[name])
return rendered.trim().slice(0, CAPTION_MAX_LENGTH)
}
function inScope(event, config) {
if (event.isGroup) {
return config.groups.length === 0 || config.groups.includes(event.conversationId)
}
return config.includeDirect === true
}
function readCooldown(cooldownUntil, conversationId) {
if (!cooldownUntil || !conversationId) return 0
const value =
typeof cooldownUntil.get === 'function'
? cooldownUntil.get(conversationId)
: cooldownUntil[conversationId]
const numeric = Number(value)
return Number.isFinite(numeric) && numeric > 0 ? numeric : 0
}
/**
* 判断一条事件是否该进入处理流程。
*
* 判定顺序固定:总开关 → 自己发的 → 非 text → 未 @我 → 提取链接 → 会话范围 → 冷却。
* `reason` 的取值集合固定为
* `disabled | self | type | mention | no_link | scope | cooldown | ok`。
*
* `url` 只要提取成功就会返回,即使后续被范围或冷却拦下,便于调用方写日志。
*/
function shouldHandle(event, config, cooldownUntil, now) {
const settings = normalizeConfig(config)
if (!settings.enabled) return { handle: false, url: null, reason: 'disabled' }
if (!event || typeof event !== 'object') return { handle: false, url: null, reason: 'no_link' }
if (event.isSelf) return { handle: false, url: null, reason: 'self' }
if (event.type !== 'text') return { handle: false, url: null, reason: 'type' }
if (!event.mentionsMe) return { handle: false, url: null, reason: 'mention' }
const url = extractDouyinUrl(event.text)
if (!url) return { handle: false, url: null, reason: 'no_link' }
if (!inScope(event, settings)) return { handle: false, url, reason: 'scope' }
const until = readCooldown(cooldownUntil, event.conversationId)
const timestamp = Number.isFinite(Number(now)) ? Number(now) : Date.now()
if (timestamp < until) return { handle: false, url, reason: 'cooldown' }
return { handle: true, url, reason: 'ok' }
}
/**
* 文件是否不该发送。
*
* 返回 true 的三种情况:超过配置上限、字节数非法、文件为空。
* 上限本身被收敛到 1–100 MB,宿主 100 MB 的硬限制不会被配置绕过。
*/
function isFileTooLarge(sizeBytes, maxFileMB) {
const limitMB = clampInt(maxFileMB, 1, HOST_MAX_FILE_MB, DEFAULT_CONFIG.maxFileMB)
const size = Number(sizeBytes)
if (!Number.isFinite(size) || size <= 0) return true
return size > limitMB * 1024 * 1024
}
/**
* 从解析结果里挑第一条可下载的视频。
*
* 图集(`type === 'image'`)与失败项都不算;没有视频时返回 `null`,
* 由调用方决定回复「暂不支持图集」还是通用失败文案。
*/
function pickVideoResult(results) {
if (!Array.isArray(results)) return null
for (const item of results) {
if (!item || typeof item !== 'object') continue
if (item.ok !== true) continue
if (item.type !== 'video') continue
return item
}
return null
}
module.exports = {
DEFAULT_CONFIG,
normalizeConfig,
extractDouyinUrl,
parseResolveJson,
parseSavedPath,
isAbsoluteMediaPath,
parseDownloadedResult,
renderCaption,
shouldHandle,
isFileTooLarge,
pickVideoResult
}
@@ -0,0 +1,38 @@
{
"manifestVersion": 1,
"id": "com.example.douyin-sender",
"name": "抖音视频搬运",
"version": "1.0.5",
"apiVersion": "1",
"minAppVersion": "2.6.0",
"description": "被 @ 且消息里带抖音分享链接时,解析视频并发送回原会话。需要本机 Python、Chrome 与解析脚本。",
"author": "TraceMemo Examples",
"permissions": [
"secrets",
"messages.subscribe",
"contacts.list",
"wechat.send.video",
"wechat.send.text",
"storage"
],
"entrypoints": {
"page": "ui/index.html",
"background": "background/index.js"
},
"subscriptions": {
"messageTypes": [
"text"
],
"conversationIds": [],
"requireMentionMe": true,
"includeSelf": false
},
"contributions": {
"pages": [
{
"id": "settings",
"title": "抖音解析设置"
}
]
}
}
@@ -0,0 +1,130 @@
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
用 urllib 从镜像拉 wheel,再交给 pip 本地安装 —— 绕开 pip 自己那层网络栈。
python fetch_wheels.py <目标目录> [包名 ...]
"""
import os
import re
import ssl
import sys
import urllib.parse
import urllib.request
from pathlib import Path
MIRRORS = [
"https://pypi.tuna.tsinghua.edu.cn/simple",
"https://mirrors.aliyun.com/pypi/simple",
]
DEFAULT_PACKAGES = ["requests", "playwright"]
WHEEL_RE = re.compile(r'href="([^"#]+\.whl)[^"]*"')
VER_RE = re.compile(r'-(\d+(?:\.\d+)*)')
# 部分镜像对浏览器 UA 返回 403,用 pip 自己的才放行。
USER_AGENT = "pip/26.1.2"
def page_links(mirror: str, package: str) -> list[str]:
"""索引页 href 是相对路径,用 urljoin 归一。"""
url = f"{mirror}/{package}/"
ctx = ssl.create_default_context()
req = urllib.request.Request(url, headers={"User-Agent": USER_AGENT})
with urllib.request.urlopen(req, timeout=30, context=ctx) as resp:
html = resp.read().decode("utf-8", "replace")
return [urllib.parse.urljoin(url, href) for href in WHEEL_RE.findall(html)]
def wheel_key(name: str) -> tuple:
"""排序键:越靠后越优先。"""
base = name.rsplit("/", 1)[-1].lower()
pure = 1 if ("none-any" in base) else 0
win_amd64 = 1 if "win_amd64" in base else 0
cp313 = 1 if "cp313" in base else 0
abi3 = 1 if "abi3" in base else 0
return (pure, win_amd64, abi3, cp313)
def version_key(url: str) -> tuple:
"""从文件名取版本号数字段。"""
m = VER_RE.search(url.rsplit("/", 1)[-1])
if not m:
return ()
return tuple(int(part) for part in m.group(1).split("."))
def pick(links: list[str]) -> str | None:
"""挑一个 Windows x64 / cp313 可用的 wheel。"""
candidates = []
for link in links:
low = link.lower()
if "macosx" in low or "manylinux" in low or "musllinux" in low:
continue
if "win32" in low or "win_arm64" in low:
continue
if "none-any.whl" in low or "win_amd64.whl" in low:
candidates.append(link)
if not candidates:
return None
candidates.sort(key=lambda url: (wheel_key(url), version_key(url)))
return candidates[-1]
def download(url: str, dest_dir: Path) -> Path:
name = url.rsplit("/", 1)[-1].split("#")[0]
target = dest_dir / name
if target.exists() and target.stat().st_size > 0:
print(f" cached {name}")
return target
req = urllib.request.Request(url, headers={"User-Agent": USER_AGENT})
with urllib.request.urlopen(req, timeout=60) as resp:
data = resp.read()
target.write_bytes(data)
print(f" saved {name} ({len(data)//1024} KB)")
return target
def main() -> int:
if len(sys.argv) < 2:
print(__doc__)
return 2
dest = Path(sys.argv[1]).expanduser()
packages = sys.argv[2:] or DEFAULT_PACKAGES
dest.mkdir(parents=True, exist_ok=True)
failed = []
for package in packages:
print(f"[{package}]")
chosen = None
for mirror in MIRRORS:
try:
links = page_links(mirror, package)
except Exception as exc:
print(f" mirror {mirror} failed: {type(exc).__name__}")
continue
chosen = pick(links)
if chosen:
print(f" mirror {mirror}")
break
if not chosen:
print(" no compatible wheel found")
failed.append(package)
continue
try:
download(chosen, dest)
except Exception as exc:
print(f" download failed: {type(exc).__name__} {exc}")
failed.append(package)
if failed:
print("FAILED: " + ", ".join(failed))
return 1
print(f"OK -> {dest}")
return 0
if __name__ == "__main__":
raise SystemExit(main())
@@ -0,0 +1,439 @@
'use strict'
/**
* 纯函数层测试:不联网、不启动 python、不读真实文件。
* 运行:node --test examples/extensions/douyin-sender/tests/douyin.test.mjs
*/
import test from 'node:test'
import assert from 'node:assert/strict'
import douyin from '../lib/douyin.js'
const {
DEFAULT_CONFIG,
normalizeConfig,
extractDouyinUrl,
parseResolveJson,
parseSavedPath,
isAbsoluteMediaPath,
parseDownloadedResult,
renderCaption,
shouldHandle,
isFileTooLarge,
pickVideoResult
} = douyin
const SHORT_URL = 'https://v.douyin.com/fixture123'
const SHORT_TEXT_URL = 'https://v.douyin.com/fixture123/'
const VIDEO_URL = 'https://www.douyin.com/video/7300000000000000001'
const NOTE_URL = 'https://douyin.com/note/7300000000000000002'
function makeEvent(overrides = {}) {
return {
eventId: 'message:fixture-1',
accountId: 'wxid_fixture',
conversationId: 'fixture-room@chatroom',
messageId: 'local-1',
senderId: 'wxid_fixture',
senderName: '张三',
isGroup: true,
isSelf: false,
type: 'text',
text: `@李四 ${SHORT_TEXT_URL}`,
mentionsMe: true,
timestamp: 0,
...overrides
}
}
function makeConfig(overrides = {}) {
return normalizeConfig({ enabled: true, ...overrides })
}
test('从裸短链里提取链接', () => {
assert.equal(extractDouyinUrl(SHORT_TEXT_URL), SHORT_URL)
})
test('从长链 video 里提取链接', () => {
assert.equal(extractDouyinUrl(VIDEO_URL), VIDEO_URL)
})
test('从 note 链接里提取链接', () => {
assert.equal(extractDouyinUrl(NOTE_URL), NOTE_URL)
})
test('从整段分享文案里提取链接', () => {
const text =
'7.89 复制打开抖音,看看【张三的作品】很有意思 https://v.douyin.com/fixture123/ 01/02 abc:/'
assert.equal(extractDouyinUrl(text), SHORT_URL)
})
test('去掉链接尾随的中文标点', () => {
assert.equal(extractDouyinUrl('看这个 https://v.douyin.com/fixture123/。'), SHORT_URL)
})
test('拒绝非抖音域名', () => {
assert.equal(extractDouyinUrl('https://example.com/video/7300000000000000001'), null)
assert.equal(extractDouyinUrl('https://douyin.com.evil.test/video/1'), null)
assert.equal(extractDouyinUrl('https://foo.douyin.com/video/1'), null)
})
test('拒绝 javascript: 与 ftp:', () => {
assert.equal(extractDouyinUrl('javascript://v.douyin.com/fixture123/'), null)
assert.equal(extractDouyinUrl('ftp://v.douyin.com/fixture123/'), null)
})
test('没有链接时返回 null', () => {
assert.equal(extractDouyinUrl('今天天气不错'), null)
assert.equal(extractDouyinUrl(''), null)
assert.equal(extractDouyinUrl(undefined), null)
})
test('JSON 前后有噪声也能解析出数组', () => {
const stdout = [
'共 1 个链接',
'▶ https://v.douyin.com/fixture123/',
' ✓ 解析成功:video | 张三 | 标题',
'',
'[{"url":"https://v.douyin.com/fixture123/","ok":true,"type":"video","aweme_id":"730"}]',
'',
'完成:1/1 成功'
].join('\n')
const parsed = parseResolveJson(stdout)
assert.ok(Array.isArray(parsed))
assert.equal(parsed.length, 1)
assert.equal(parsed[0].aweme_id, '730')
})
test('缩进的多行 JSON 数组按真实输出解析', () => {
const stdout = [
' ✓ 解析成功:video | 张三 | 标题',
'==================================================',
'完成:1/1 成功',
'[',
' {',
' "url": "https://v.douyin.com/fixture123/",',
' "ok": true,',
' "type": "video",',
' "quality_options": [',
' {"gear": "720p", "rank": 720}',
' ]',
' }',
']'
].join('\n')
const parsed = parseResolveJson(stdout)
assert.ok(Array.isArray(parsed))
assert.equal(parsed[0].quality_options[0].rank, 720)
})
test('非法 JSON 返回 null', () => {
assert.equal(parseResolveJson('不是 JSON'), null)
assert.equal(parseResolveJson('[{"ok":true,'), null)
assert.equal(parseResolveJson(''), null)
})
test('进度行里的方括号不会被误认为结果数组', () => {
const stdout = [
' [1] 跳过(无地址)',
' ✅ /tmp/fixture-folder (2 个文件)',
'[{"url":"https://v.douyin.com/fixture123","ok":true,"type":"image","aweme_id":"730"}]'
].join('\n')
const parsed = parseResolveJson(stdout)
assert.ok(Array.isArray(parsed))
assert.equal(parsed.length, 1)
assert.equal(parsed[0].type, 'image')
})
test('空数组视为无效结果', () => {
assert.equal(parseResolveJson('[]'), null)
})
test('合法 JSON 但不是数组时返回 null', () => {
assert.equal(parseResolveJson('{"ok":true}'), null)
})
test('下载输出里能取到绝对路径', () => {
const stdout = [
' ✓ 解析成功:video | 张三 | 标题',
' 下载中 → 张三 - 标题 - 730.mp4',
' ✅ /tmp/fixture/downloads/张三 - 标题 - 730.mp4',
' 5.2MB | MP4'
].join('\n')
assert.equal(parseSavedPath(stdout), '/tmp/fixture/downloads/张三 - 标题 - 730.mp4')
})
test('多条 ✅ 时取最后一个', () => {
const stdout = [' ✅ /tmp/one.mp4', ' ✅ /tmp/two.mp4', ' 1.0MB | MP4'].join('\n')
assert.equal(parseSavedPath(stdout), '/tmp/two.mp4')
})
test('从 JSON 下载结果同时提取作品元数据和保存路径', () => {
const parsed = parseDownloadedResult(
'[{"url":"https://v.douyin.com/fixture123","ok":true,"type":"video","aweme_id":"730","saved":["/tmp/fixture-video.mp4"]}]'
)
assert.deepEqual(parsed, {
ok: true,
meta: {
url: 'https://v.douyin.com/fixture123',
ok: true,
type: 'video',
aweme_id: '730',
saved: ['/tmp/fixture-video.mp4']
},
path: '/tmp/fixture-video.mp4'
})
assert.equal(
parseDownloadedResult(
'[{"url":"https://v.douyin.com/fixture123","ok":true,"type":"video","saved":["relative.mp4"]}]'
),
null
)
})
test('Windows 盘符路径同样算绝对路径', () => {
const winPath = 'C:\\fixture\\Downloads\\张三 - 标题 - 730.mp4'
assert.equal(isAbsoluteMediaPath(winPath), true)
assert.equal(isAbsoluteMediaPath('C:/fixture/a.mp4'), true)
assert.equal(isAbsoluteMediaPath('\\\\server\\share\\a.mp4'), true)
assert.equal(isAbsoluteMediaPath('Downloads/a.mp4'), false)
assert.equal(isAbsoluteMediaPath(''), false)
assert.equal(isAbsoluteMediaPath(null), false)
// 只认 '/' 开头会把 Windows 的 ✅ 行整条丢掉
const stdout = [
' ✓ 解析成功:video | 张三 | 标题',
' ✅ ' + winPath,
' 5.2MB | MP4'
].join('\n')
assert.equal(parseSavedPath(stdout), winPath)
const json = JSON.stringify([
{ url: 'https://v.douyin.com/fixture123', ok: true, type: 'video', saved: [winPath] }
])
const parsed = parseDownloadedResult(json)
assert.equal(parsed.ok, true)
assert.equal(parsed.path, winPath)
})
test('JSON 下载失败保留脚本错误,图集保持不支持状态', () => {
assert.deepEqual(
parseDownloadedResult(
'[{"url":"https://v.douyin.com/fixture123","ok":false,"error":"fixture platform error"}]'
),
{ ok: false, message: 'fixture platform error', errorType: 'RESOLVE_FAILED' }
)
assert.deepEqual(
parseDownloadedResult(
'[{"url":"https://v.douyin.com/fixture123","ok":true,"type":"image","images":[]}]'
),
{ ok: false, message: '暂不支持图集', errorType: 'IMAGE_SET' }
)
})
test('下载阶段失败时标记为下载错误', () => {
assert.deepEqual(
parseDownloadedResult(
'[{"url":"https://v.douyin.com/fixture123","ok":false,"aweme_id":"730","error":"fixture CDN timeout"}]'
),
{ ok: false, message: 'fixture CDN timeout', errorType: 'DOWNLOAD_FAILED' }
)
})
test('图集目录后面的附注被剥离', () => {
const stdout = [' ✅ /tmp/fixture-folder (5 个文件)'].join('\n')
assert.equal(parseSavedPath(stdout), '/tmp/fixture-folder')
})
test('没有 ✅ 行时返回 null', () => {
assert.equal(parseSavedPath(' ✗ 失败:超时\n完成:0/1 成功'), null)
assert.equal(parseSavedPath(''), null)
})
test('模板替换三个已知变量', () => {
const caption = renderCaption('{author}:{title}({awemeId})', {
author: '张三',
title: '测试标题',
awemeId: '730'
})
assert.equal(caption, '张三:测试标题(730)')
})
test('未知变量原样保留', () => {
const caption = renderCaption('{author} {unknownVar}', { author: '张三' })
assert.equal(caption, '张三 {unknownVar}')
})
test('超长文案截断到 200 字', () => {
const caption = renderCaption('{title}', { title: '字'.repeat(400) })
assert.equal(caption.length, 200)
})
test('默认配置符合约定', () => {
const config = normalizeConfig(undefined)
assert.equal(config.configVersion, 1)
assert.equal(config.enabled, false)
// Windows 的 python3.exe 通常是 Microsoft Store 的应用执行别名,默认改用 python。
assert.equal(config.pythonPath, process.platform === 'win32' ? 'python' : 'python3')
assert.equal(config.scriptPath, 'scripts/douyin.py')
assert.equal(config.quality, '720')
assert.equal(config.showUi, false)
assert.equal(config.sendCaption, false)
assert.equal(config.captionTemplate, '{author}:{title}')
assert.equal(config.errorReply, true)
assert.equal(config.includeDirect, false)
assert.deepEqual(config.groups, [])
assert.equal(config.cooldownSeconds, 60)
assert.equal(config.maxFileMB, 100)
})
test('常规配置不接纳 Cookie 凭证字段', () => {
const config = normalizeConfig({ cookie: 'must-not-persist', cookieFile: '/tmp/fixture-cookie' })
assert.equal(Object.hasOwn(config, 'cookie'), false)
assert.equal(Object.hasOwn(config, 'cookieFile'), false)
})
test('非法画质收敛到 720,空串表示最高', () => {
assert.equal(normalizeConfig({ quality: '4k' }).quality, '720')
assert.equal(normalizeConfig({ quality: '' }).quality, '')
assert.equal(normalizeConfig({ quality: '1080' }).quality, '1080')
})
test('数值型画质按字符串处理', () => {
assert.equal(normalizeConfig({ quality: 540 }).quality, '540')
})
test('showUi 只接受布尔 true', () => {
assert.equal(normalizeConfig({ showUi: true }).showUi, true)
assert.equal(normalizeConfig({ showUi: 'true' }).showUi, false)
assert.equal(normalizeConfig({ showUi: 1 }).showUi, false)
})
test('ackText 默认有回执,空串表示关闭', () => {
assert.match(normalizeConfig({}).ackText, /收到/)
assert.equal(normalizeConfig({ ackText: '' }).ackText, '')
assert.equal(normalizeConfig({ ackText: ' 好的 ' }).ackText, '好的')
assert.equal(normalizeConfig({ ackText: 'x'.repeat(300) }).ackText.length, 200)
})
test('冷却与文件上限被夹到合法区间', () => {
assert.equal(normalizeConfig({ cooldownSeconds: -10 }).cooldownSeconds, 0)
assert.equal(normalizeConfig({ cooldownSeconds: 999999 }).cooldownSeconds, 3600)
assert.equal(normalizeConfig({ maxFileMB: 0 }).maxFileMB, 1)
assert.equal(normalizeConfig({ maxFileMB: 500 }).maxFileMB, 100)
})
test('群 id 去空、去重并截断上限', () => {
const config = normalizeConfig({
groups: [' fixture-room@chatroom ', '', 'fixture-room@chatroom']
})
assert.deepEqual(config.groups, ['fixture-room@chatroom'])
})
test('总开关关闭时拒绝处理', () => {
const decision = shouldHandle(makeEvent(), makeConfig({ enabled: false }), new Map(), Date.now())
assert.deepEqual(decision, { handle: false, url: null, reason: 'disabled' })
})
test('自己发的消息拒绝处理', () => {
const decision = shouldHandle(makeEvent({ isSelf: true }), makeConfig(), new Map(), Date.now())
assert.equal(decision.handle, false)
assert.equal(decision.reason, 'self')
})
test('非 text 消息拒绝处理', () => {
const decision = shouldHandle(makeEvent({ type: 'image' }), makeConfig(), new Map(), Date.now())
assert.equal(decision.handle, false)
assert.equal(decision.reason, 'type')
})
test('没有真正 @ 我时拒绝处理', () => {
const decision = shouldHandle(
makeEvent({ mentionsMe: false }),
makeConfig(),
new Map(),
Date.now()
)
assert.equal(decision.handle, false)
assert.equal(decision.reason, 'mention')
})
test('消息里没有链接时拒绝处理', () => {
const decision = shouldHandle(
makeEvent({ text: '@李四 今天天气不错' }),
makeConfig(),
new Map(),
Date.now()
)
assert.equal(decision.handle, false)
assert.equal(decision.reason, 'no_link')
})
test('群不在白名单里时拒绝处理,但仍返回提取到的链接', () => {
const decision = shouldHandle(
makeEvent(),
makeConfig({ groups: ['other-room@chatroom'] }),
new Map(),
Date.now()
)
assert.equal(decision.handle, false)
assert.equal(decision.reason, 'scope')
assert.equal(decision.url, SHORT_URL)
})
test('群在白名单里时允许处理', () => {
const decision = shouldHandle(
makeEvent(),
makeConfig({ groups: ['fixture-room@chatroom'] }),
new Map(),
Date.now()
)
assert.deepEqual(decision, { handle: true, url: SHORT_URL, reason: 'ok' })
})
test('私聊默认不处理,开启后处理', () => {
const direct = makeEvent({ isGroup: false, conversationId: 'wxid_fixture' })
assert.equal(shouldHandle(direct, makeConfig(), new Map(), Date.now()).reason, 'scope')
assert.equal(
shouldHandle(direct, makeConfig({ includeDirect: true }), new Map(), Date.now()).reason,
'ok'
)
})
test('冷却未过期时拒绝,过期后放行', () => {
const now = 1_767_225_600_000
const cooldown = new Map([['fixture-room@chatroom', now + 30_000]])
assert.equal(shouldHandle(makeEvent(), makeConfig(), cooldown, now).reason, 'cooldown')
assert.equal(shouldHandle(makeEvent(), makeConfig(), cooldown, now + 30_001).reason, 'ok')
})
test('图集不算视频', () => {
const results = [
{ url: SHORT_URL, ok: true, type: 'image', aweme_id: '730' },
{ url: VIDEO_URL, ok: true, type: 'video', aweme_id: '731' }
]
assert.equal(pickVideoResult(results).aweme_id, '731')
assert.equal(pickVideoResult([results[0]]), null)
})
test('跳过失败项并容忍非数组输入', () => {
assert.equal(pickVideoResult([{ ok: false, error: '超时' }]), null)
assert.equal(pickVideoResult(null), null)
assert.equal(pickVideoResult([]), null)
})
test('文件大小判定覆盖上限与非法值', () => {
assert.equal(isFileTooLarge(100 * 1024 * 1024, 100), false)
assert.equal(isFileTooLarge(100 * 1024 * 1024 + 1, 100), true)
assert.equal(isFileTooLarge(2 * 1024 * 1024, 1), true)
assert.equal(isFileTooLarge(0, 100), true)
assert.equal(isFileTooLarge(Number.NaN, 100), true)
assert.equal(isFileTooLarge(1, 100), false)
})
test('DEFAULT_CONFIG 不被 normalizeConfig 修改', () => {
const before = JSON.stringify(DEFAULT_CONFIG)
const config = normalizeConfig({ enabled: true, groups: ['fixture-room@chatroom'] })
config.groups.push('wxid_fixture')
assert.equal(JSON.stringify(DEFAULT_CONFIG), before)
})
+618
View File
@@ -0,0 +1,618 @@
'use strict'
/**
* 扩展页面桥。
*
* 页面只能通过宿主白名单能力与宿主通信,
* 没有发送能力,也没有 `require`。
*/
const EXTENSION_ID = 'com.example.douyin-sender'
const PAGE_SOURCE = 'tracememo-extension-page'
const HOST_SOURCE = 'tracememo-extension-host'
const CONFIG_KEY = 'config'
const STATS_KEY = 'stats'
const PROGRESS_KEY = 'progress'
const TEST_RESULT_KEY = 'testResult'
const ALLOWED_METHODS = new Set([
'storage.get',
'storage.set',
'storage.remove',
'storage.list',
'capabilities.get',
'contacts.listGroups',
'extension.request',
'extension.info'
])
const DEFAULT_CONFIG = {
configVersion: 1,
enabled: false,
pythonPath: 'python3',
scriptPath: 'scripts/douyin.py',
quality: '720',
showUi: false,
ackText: '收到,正在解析,请稍候…',
sendCaption: false,
captionTemplate: '{author}:{title}',
errorReply: true,
includeDirect: false,
groups: [],
cooldownSeconds: 60,
maxFileMB: 100
}
const STAGE_LABELS = {
accepted: '已接收',
resolve: '解析',
resolveDownload: '解析并下载',
download: '下载',
send: '发送',
caption: '补发文案',
done: '完成',
failed: '失败'
}
const pending = new Map()
let sequence = 0
let config = clone(DEFAULT_CONFIG)
function clone(value) {
return JSON.parse(JSON.stringify(value))
}
function callHost(method, params) {
return new Promise((resolve, reject) => {
if (!ALLOWED_METHODS.has(method)) {
reject(new Error(`不支持的调用:${method}`))
return
}
const requestId = `req-${++sequence}`
pending.set(requestId, { resolve, reject })
window.parent.postMessage(
{ source: PAGE_SOURCE, extensionId: EXTENSION_ID, requestId, method, params },
'*'
)
})
}
window.addEventListener('message', (event) => {
const data = event.data
if (!data || data.source !== HOST_SOURCE) return
const entry = pending.get(data.requestId)
if (!entry) return
pending.delete(data.requestId)
if (data.ok) entry.resolve(data.result)
else entry.reject(new Error((data.error && data.error.message) || '调用失败'))
})
const status = document.getElementById('status')
const rows = document.getElementById('job-rows')
const todayTotal = document.getElementById('today-total')
const todaySuccess = document.getElementById('today-success')
const todayFailure = document.getElementById('today-failure')
const progressBadge = document.getElementById('progress-badge')
const progressStage = document.getElementById('progress-stage')
const progressTime = document.getElementById('progress-time')
const progressDetail = document.getElementById('progress-detail')
const testGroup = document.getElementById('test-group')
const testUrl = document.getElementById('test-url')
const cookieHeader = document.getElementById('cookie-header')
const cookieState = document.getElementById('cookie-state')
const testResult = document.getElementById('test-result')
const groupPicker = document.getElementById('group-picker')
const groupChips = document.getElementById('group-chips')
const groupSearch = document.getElementById('group-search')
const groupOptions = document.getElementById('group-options')
let allGroups = []
let selectedGroupIds = new Set()
let groupLoadError = ''
function setStatus(text, kind) {
status.textContent = text
status.dataset.kind = kind || ''
}
function clampInt(value, fallback, min, max) {
const numeric = Number(value)
if (!Number.isFinite(numeric)) return fallback
return Math.max(min, Math.min(Math.trunc(numeric), max))
}
function normalizeConfig(raw) {
const input = raw && typeof raw === 'object' ? raw : {}
const quality = ['', '1080', '720', '540'].includes(String(input.quality))
? String(input.quality)
: DEFAULT_CONFIG.quality
return {
configVersion: 1,
enabled: input.enabled === true,
pythonPath: String(input.pythonPath || DEFAULT_CONFIG.pythonPath).trim(),
scriptPath: String(input.scriptPath || DEFAULT_CONFIG.scriptPath).trim(),
quality,
showUi: input.showUi === true,
ackText:
input.ackText === undefined
? DEFAULT_CONFIG.ackText
: String(input.ackText).trim().slice(0, 200),
sendCaption: false,
captionTemplate: String(input.captionTemplate || DEFAULT_CONFIG.captionTemplate).slice(0, 200),
errorReply: input.errorReply !== false,
includeDirect: input.includeDirect === true,
groups: Array.isArray(input.groups)
? input.groups
.map((id) => String(id).trim())
.filter(Boolean)
.slice(0, 200)
: [],
cooldownSeconds: clampInt(input.cooldownSeconds, DEFAULT_CONFIG.cooldownSeconds, 0, 3600),
maxFileMB: clampInt(input.maxFileMB, DEFAULT_CONFIG.maxFileMB, 1, 100)
}
}
function syncForm() {
document.getElementById('enabled').checked = config.enabled === true
document.getElementById('python-path').value = config.pythonPath
document.getElementById('script-path').value = config.scriptPath
document.getElementById('quality').value = config.quality
document.getElementById('show-ui').checked = config.showUi === true
document.getElementById('ack-text').value = config.ackText
document.getElementById('error-reply').checked = config.errorReply === true
selectedGroupIds = new Set(config.groups)
renderGroupChips()
renderGroupOptions()
document.getElementById('include-direct').checked = config.includeDirect === true
document.getElementById('cooldown').value = String(config.cooldownSeconds)
document.getElementById('max-file-mb').value = String(config.maxFileMB)
}
function readForm() {
config.enabled = document.getElementById('enabled').checked
config.pythonPath = document.getElementById('python-path').value.trim()
config.scriptPath = document.getElementById('script-path').value.trim()
config.quality = document.getElementById('quality').value
config.showUi = document.getElementById('show-ui').checked
config.ackText = document.getElementById('ack-text').value.trim().slice(0, 200)
config.sendCaption = false
config.errorReply = document.getElementById('error-reply').checked
config.groups = [...selectedGroupIds].slice(0, 200)
config.includeDirect = document.getElementById('include-direct').checked
config.cooldownSeconds = clampInt(
document.getElementById('cooldown').value,
DEFAULT_CONFIG.cooldownSeconds,
0,
3600
)
config.maxFileMB = clampInt(
document.getElementById('max-file-mb').value,
DEFAULT_CONFIG.maxFileMB,
1,
100
)
config.configVersion = 1
}
function formatTime(value) {
const numeric = Number(value)
if (!Number.isFinite(numeric) || numeric <= 0) return '—'
const date = new Date(numeric)
const pad = (part) => String(part).padStart(2, '0')
return `${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(date.getSeconds())}`
}
function renderStats(raw) {
const stats = raw && typeof raw === 'object' ? raw : {}
const jobs = Array.isArray(stats.lastJobs) ? stats.lastJobs.slice(0, 8) : []
const total = Math.max(0, Math.trunc(Number(stats.todayTotal ?? stats.todayCount) || 0))
todayTotal.textContent = String(total)
todaySuccess.textContent = String(Math.max(0, Math.trunc(Number(stats.todaySuccess) || 0)))
todayFailure.textContent = String(Math.max(0, Math.trunc(Number(stats.todayFailure) || 0)))
rows.textContent = ''
if (!jobs.length) {
const row = document.createElement('tr')
const cell = document.createElement('td')
cell.colSpan = 5
cell.className = 'empty'
cell.textContent = '暂无记录'
row.append(cell)
rows.append(row)
return
}
for (const job of jobs) {
const row = document.createElement('tr')
const time = document.createElement('td')
time.textContent = formatTime(job && job.at)
const id = document.createElement('td')
id.className = 'mono'
id.textContent = (job && job.awemeId) || '—'
const stage = document.createElement('td')
stage.textContent = STAGE_LABELS[job && job.stage] || (job && job.stage) || '—'
const result = document.createElement('td')
const ok = job && job.ok === true
result.textContent = ok ? '成功' : '失败'
result.className = ok ? 'ok' : 'fail'
const error = document.createElement('td')
error.className = 'mono'
error.textContent = (job && job.errorType) || '—'
row.append(time, id, stage, result, error)
rows.append(row)
}
}
/** 进度:运行中显示阶段与已用时间;失败显示失败阶段与错误码。 */
function renderProgress(raw) {
const progress = raw && typeof raw === 'object' ? raw : null
if (!progress || !progress.stage) {
progressBadge.textContent = '空闲'
progressBadge.dataset.status = 'idle'
progressStage.textContent = '暂无任务'
progressTime.textContent = ''
progressDetail.textContent = '触发后这里会显示解析、下载、发送进行到哪一步。'
return
}
const status =
progress.status === 'failed' ? 'failed' : progress.status === 'done' ? 'done' : 'running'
progressBadge.textContent = status === 'failed' ? '失败' : status === 'done' ? '完成' : '进行中'
progressBadge.dataset.status = status
progressStage.textContent =
status === 'failed'
? `失败于:${STAGE_LABELS[progress.stage] || progress.stage}`
: status === 'done'
? '已完成'
: `正在${STAGE_LABELS[progress.stage] || progress.stage}`
const startedAt = Number(progress.startedAt)
// 运行中用当前时间计算,脚本卡住时秒数也会继续走,不会看起来停在 0s。
const updatedAt = status === 'running' ? Date.now() : Number(progress.updatedAt) || Date.now()
const elapsed =
Number.isFinite(startedAt) && startedAt > 0
? Math.max(0, Math.round((updatedAt - startedAt) / 1000))
: null
progressTime.textContent = elapsed === null ? '' : `· ${elapsed}s`
const parts = []
if (progress.awemeId) parts.push(`作品 ${progress.awemeId}`)
if (status === 'failed' && progress.errorType) parts.push(`错误 ${progress.errorType}`)
if (status === 'failed' && progress.errorMessage) parts.push(progress.errorMessage)
if (status === 'done') parts.push('视频已发送')
progressDetail.textContent = parts.join(' · ') || ''
}
async function loadStats() {
try {
const stored = await callHost('storage.get', { key: STATS_KEY })
renderStats(stored)
} catch (error) {
renderStats(null)
setStatus(`统计读取失败:${error.message}`, 'error')
}
}
async function loadProgress() {
try {
const stored = await callHost('storage.get', { key: PROGRESS_KEY })
renderProgress(stored)
} catch {
renderProgress(null)
}
}
let testPollTimer = null
let activeTestId = ''
function setTestResult(text, kind) {
testResult.textContent = text
testResult.dataset.kind = kind || ''
}
function groupDisplayName(group) {
if (!group) return ''
return group.name && group.name !== group.id ? `${group.name}(${group.id})` : group.id
}
function emptyGroupOption(text) {
const empty = document.createElement('div')
empty.className = 'group-option-empty'
empty.textContent = text
return empty
}
function renderGroupChips() {
groupChips.textContent = ''
groupChips.hidden = selectedGroupIds.size === 0
for (const id of selectedGroupIds) {
const group = allGroups.find((item) => item.id === id)
const chip = document.createElement('span')
chip.className = 'group-chip'
const name = document.createElement('span')
name.textContent = group ? group.name || id : id
name.title = id
const remove = document.createElement('button')
remove.type = 'button'
remove.className = 'group-chip-remove'
remove.textContent = '×'
remove.setAttribute('aria-label', `移除 ${group ? group.name || id : id}`)
remove.addEventListener('click', (event) => {
event.stopPropagation()
selectedGroupIds.delete(id)
renderGroupChips()
renderGroupOptions()
})
chip.append(name, remove)
groupChips.append(chip)
}
}
function renderGroupOptions() {
if (groupOptions.hidden) return
const query = groupSearch.value.trim().toLowerCase()
groupOptions.textContent = ''
if (groupLoadError) {
groupOptions.append(emptyGroupOption(groupLoadError))
return
}
if (!allGroups.length) {
groupOptions.append(emptyGroupOption('未读取到群列表(请先连接微信数据库)'))
return
}
const matches = allGroups.filter((group) => {
if (!query) return true
return group.id.toLowerCase().includes(query) || group.name.toLowerCase().includes(query)
})
if (!matches.length) {
groupOptions.append(emptyGroupOption('没有匹配的群聊'))
return
}
for (const group of matches.slice(0, 200)) {
const option = document.createElement('label')
option.className = 'group-option'
const checkbox = document.createElement('input')
checkbox.type = 'checkbox'
checkbox.checked = selectedGroupIds.has(group.id)
checkbox.addEventListener('change', () => {
if (checkbox.checked) selectedGroupIds.add(group.id)
else selectedGroupIds.delete(group.id)
renderGroupChips()
})
const text = document.createElement('span')
text.textContent = groupDisplayName(group)
option.append(checkbox, text)
groupOptions.append(option)
}
}
function openGroupOptions() {
groupOptions.hidden = false
renderGroupOptions()
}
function closeGroupOptions() {
groupOptions.hidden = true
groupSearch.value = ''
}
groupSearch.addEventListener('focus', openGroupOptions)
groupSearch.addEventListener('input', openGroupOptions)
groupSearch.addEventListener('keydown', (event) => {
if (event.key === 'Escape') {
closeGroupOptions()
groupSearch.blur()
}
})
document.addEventListener('click', (event) => {
if (!groupPicker.contains(event.target)) closeGroupOptions()
})
/** 群列表来自宿主通讯录;数据库未连接时给出明确空态,而不是假装有选项。 */
async function loadGroups() {
const current = testGroup.value
try {
const result = await callHost('contacts.listGroups', {})
allGroups = result && Array.isArray(result.groups) ? result.groups : []
groupLoadError = ''
testGroup.textContent = ''
if (!allGroups.length) {
const option = document.createElement('option')
option.value = ''
option.textContent = '未读取到群列表(请先连接微信数据库)'
testGroup.append(option)
renderGroupChips()
renderGroupOptions()
return
}
const placeholder = document.createElement('option')
placeholder.value = ''
placeholder.textContent = '请选择群聊'
testGroup.append(placeholder)
for (const group of allGroups) {
const option = document.createElement('option')
option.value = group.id
option.textContent = groupDisplayName(group)
testGroup.append(option)
}
const saved = await callHost('storage.get', { key: 'testGroup' }).catch(() => null)
const target = current || (typeof saved === 'string' ? saved : '')
if (target && allGroups.some((group) => group.id === target)) testGroup.value = target
} catch (error) {
allGroups = []
groupLoadError = `群列表读取失败:${error.message}`
testGroup.textContent = ''
const option = document.createElement('option')
option.value = ''
option.textContent = groupLoadError
testGroup.append(option)
}
renderGroupChips()
renderGroupOptions()
}
/** 轮询后台写入的测试结果;只认本次请求的 id,避免串台。 */
async function pollTestResult() {
if (!activeTestId) return
window.clearTimeout(testPollTimer)
try {
const result = await callHost('storage.get', { key: TEST_RESULT_KEY })
if (result && result.id === activeTestId) {
if (result.status === 'running') {
setTestResult(result.message || '处理中…', 'running')
} else if (result.status === 'done') {
setTestResult(result.message || '测试发送完成', 'ok')
activeTestId = ''
return
} else if (result.status === 'failed') {
setTestResult(result.message || '测试发送失败', 'error')
activeTestId = ''
return
}
}
} catch {
// 单次读取失败继续重试。
}
testPollTimer = window.setTimeout(() => {
void pollTestResult()
}, 1500)
}
async function loadConfig() {
const stored = await callHost('storage.get', { key: CONFIG_KEY })
config = normalizeConfig(stored)
syncForm()
}
async function loadCookieState() {
try {
const result = await callHost('extension.request', { method: 'douyinCookie.status', params: {} })
cookieState.textContent =
result && result.configured ? '已保存 Cookie(内容不可回显)' : '未配置'
} catch {
cookieState.textContent = '安全存储不可用,无法读取状态'
}
}
void loadCookieState()
async function checkCapabilities() {
try {
const snapshot = await callHost('capabilities.get', {})
const send = snapshot && snapshot.send ? snapshot.send : null
if (!send || !send.canSendVideo) {
setStatus('当前环境未就绪:视频发送通道不可用,配置仍可保存。', 'error')
return true
}
} catch {
// 能力查询失败不阻塞配置编辑。
}
return false
}
testGroup.addEventListener('change', () => {
void callHost('storage.set', { key: 'testGroup', value: testGroup.value }).catch(() => undefined)
})
document.getElementById('test-refresh').addEventListener('click', () => {
void loadGroups()
})
document.getElementById('test-send').addEventListener('click', async () => {
const to = testGroup.value
const text = testUrl.value.trim()
if (!to) {
setTestResult('请先选择目标群聊。', 'error')
return
}
if (!text) {
setTestResult('请粘贴抖音分享链接或整段分享文案。', 'error')
return
}
activeTestId = `test-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`
setTestResult('已提交,等待后台开始解析…', 'running')
try {
const submitted = callHost('extension.request', {
method: 'testSend',
params: { id: activeTestId, to, text, at: Date.now() }
})
void pollTestResult()
await submitted
} catch (error) {
activeTestId = ''
setTestResult(`提交失败:${error.message}`, 'error')
}
})
document.getElementById('cookie-save').addEventListener('click', async () => {
const value = cookieHeader.value.trim()
if (!value) {
setStatus('请先粘贴抖音 Cookie。', 'error')
return
}
try {
await callHost('extension.request', {
method: 'douyinCookie.set',
params: { cookieHeader: value }
})
cookieHeader.value = ''
await loadCookieState()
setStatus('Cookie 已安全保存。', 'ok')
} catch (error) {
setStatus(`Cookie 保存失败:${error.message}`, 'error')
}
})
document.getElementById('cookie-clear').addEventListener('click', async () => {
try {
await callHost('extension.request', { method: 'douyinCookie.clear', params: {} })
cookieHeader.value = ''
await loadCookieState()
setStatus('Cookie 已清除。', 'ok')
} catch (error) {
setStatus(`Cookie 清除失败:${error.message}`, 'error')
}
})
document.getElementById('save').addEventListener('click', async () => {
readForm()
if (!config.pythonPath) {
setStatus('Python 可执行文件不能为空。', 'error')
return
}
if (!config.scriptPath) {
setStatus('解析脚本路径不能为空。', 'error')
return
}
if (!config.captionTemplate.trim() && config.sendCaption) {
setStatus('已开启标题文案,模板不能为空。', 'error')
return
}
try {
await callHost('storage.set', { key: CONFIG_KEY, value: config })
setStatus('配置已保存,后台 1 秒内生效', 'ok')
} catch (error) {
setStatus(`保存失败:${error.message}`, 'error')
}
})
document.getElementById('reload').addEventListener('click', async () => {
try {
await loadConfig()
await loadStats()
await loadProgress()
setStatus('已重新读取配置。', 'ok')
} catch (error) {
setStatus(`读取失败:${error.message}`, 'error')
}
})
async function boot() {
await loadConfig()
await Promise.all([loadStats(), loadProgress(), loadGroups()])
const blocked = await checkCapabilities()
if (!blocked) setStatus('配置已读取。默认不启用,避免安装后立即对外发送。')
// 页面打开期间轮询进度,任务跑到哪一步不用猜;统计低频刷新即可。
window.setInterval(() => {
void loadProgress()
}, 2000)
window.setInterval(() => {
void loadStats()
}, 6000)
}
boot().catch((error) => setStatus(`加载失败:${error.message}`, 'error'))
@@ -0,0 +1,192 @@
<!doctype html>
<html lang="zh-CN">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>抖音视频搬运</title>
<link rel="stylesheet" href="./style.css" />
</head>
<body>
<main class="page">
<header class="page-header">
<div>
<h1>抖音视频搬运</h1>
<p>
被 @ 且消息里带抖音分享链接时,解析视频并发回原会话。本页只写配置,发送全部由后台经
TraceMemo Gateway 完成。
</p>
</div>
<label class="switch">
<input id="enabled" type="checkbox" />
<span>启用</span>
</label>
</header>
<section class="panel">
<h2>运行环境</h2>
<label class="field">
<span>Python 可执行文件</span>
<input id="python-path" type="text" placeholder="python3" />
</label>
<label class="field">
<span>解析脚本路径(默认相对于扩展目录,支持 <code>~</code>,首次运行会在缓存目录创建 venv)</span>
<input
id="script-path"
type="text"
placeholder="scripts/douyin.py"
/>
</label>
<label class="field">
<span>画质</span>
<select id="quality">
<option value="">最高</option>
<option value="1080">1080</option>
<option value="720">720</option>
<option value="540">540</option>
</select>
</label>
<label class="check">
<input id="show-ui" type="checkbox" />
<span>显示浏览器窗口(排障用;可观察作品页实际停留状态,不保证改变平台响应)</span>
</label>
</section>
<section class="panel">
<h2>抖音 Cookie</h2>
<label class="field">
<span>Cookie(安全加密保存;仅本机使用)</span>
<input
id="cookie-header"
type="password"
autocomplete="new-password"
spellcheck="false"
placeholder="粘贴抖音 Cookie header"
/>
</label>
<p id="cookie-state" class="muted">未配置</p>
<div class="row">
<button id="cookie-save" type="button" class="primary">保存 Cookie</button>
<button id="cookie-clear" type="button" class="ghost">清除 Cookie</button>
</div>
</section>
<section class="panel">
<h2>回复与文案</h2>
<label class="field">
<span>触发后先回复一句(留空表示不回复)</span>
<input id="ack-text" type="text" maxlength="200" placeholder="收到,正在解析,请稍候…" />
</label>
<label class="check"
><input id="error-reply" type="checkbox" /><span
>失败时在原会话回一条简短说明</span
></label
>
</section>
<section class="panel">
<h2>监听范围</h2>
<div class="field">
<span>只处理这些群(可多选、可搜索;留空表示全部群)</span>
<div id="group-picker" class="group-picker">
<div id="group-chips" class="group-chips" hidden></div>
<input
id="group-search"
type="text"
placeholder="搜索群聊名称或 id…"
autocomplete="off"
/>
<div id="group-options" class="group-options" hidden></div>
</div>
</div>
<div class="row">
<label class="check"
><input id="include-direct" type="checkbox" /><span>同时处理私聊</span></label
>
</div>
<div class="grid-2">
<label class="field">
<span>冷却秒数(0–3600,按会话计)</span>
<input id="cooldown" type="number" min="0" max="3600" step="1" />
</label>
<label class="field">
<span>文件大小上限(MB,1–100)</span>
<input id="max-file-mb" type="number" min="1" max="100" step="1" />
</label>
</div>
</section>
<section class="panel">
<h2>测试发送</h2>
<label class="field">
<span>目标群聊</span>
<select id="test-group">
<option value="">加载中…</option>
</select>
</label>
<label class="field">
<span>抖音分享链接或整段分享文案</span>
<textarea
id="test-url"
rows="3"
placeholder="https://v.douyin.com/xxxxxx/ 复制打开抖音…"
></textarea>
</label>
<div class="row">
<button id="test-send" type="button" class="primary">测试发送</button>
<button id="test-refresh" type="button" class="ghost">刷新群列表</button>
</div>
<p id="test-result" class="status">
选择群聊、粘贴链接后点「测试发送」,解析完成后视频会直接发到该群。已保存的 Cookie
自动用于测试。
</p>
</section>
<section class="panel">
<div class="panel-header">
<h2>当前任务</h2>
<span id="progress-badge" class="badge">空闲</span>
</div>
<p class="progress-line">
<strong id="progress-stage">暂无任务</strong>
<span id="progress-time" class="muted"></span>
</p>
<p id="progress-detail" class="muted">触发后这里会显示解析、下载、发送进行到哪一步。</p>
</section>
<section class="panel">
<div class="panel-header">
<h2>统计</h2>
<span class="muted"
>今日 总计 <strong id="today-total">0</strong> · 成功
<strong id="today-success">0</strong> · 失败 <strong id="today-failure">0</strong></span
>
</div>
<table class="stats">
<thead>
<tr>
<th>时间</th>
<th>作品 ID</th>
<th>阶段</th>
<th>结果</th>
<th>错误</th>
</tr>
</thead>
<tbody id="job-rows">
<tr>
<td colspan="5" class="empty">暂无记录</td>
</tr>
</tbody>
</table>
</section>
<footer class="page-footer">
<div class="row">
<button id="save" type="button" class="primary">保存配置</button>
<button id="reload" type="button" class="ghost">重新读取</button>
</div>
<p id="status" class="status" role="status"></p>
</footer>
</main>
<script src="./app.js"></script>
</body>
</html>
@@ -0,0 +1,387 @@
:root {
color-scheme: light dark;
--bg: #f6f8f7;
--card: #ffffff;
--text: #1c2622;
--muted: #6b7a73;
--border: #dfe6e2;
--brand: #247a63;
--danger: #b4472f;
}
@media (prefers-color-scheme: dark) {
:root {
--bg: #161c19;
--card: #1e2622;
--text: #eef4f1;
--muted: #9aaba3;
--border: #33403a;
--brand: #4bb894;
--danger: #e0735a;
}
}
* {
box-sizing: border-box;
}
body {
margin: 0;
min-height: 100vh;
background: var(--bg);
color: var(--text);
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'PingFang SC', 'Microsoft YaHei',
sans-serif;
}
.page {
max-width: 720px;
margin: 0 auto;
padding: 26px 22px 40px;
display: flex;
flex-direction: column;
gap: 16px;
}
.page-header {
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 16px;
flex-wrap: wrap;
}
h1 {
margin: 0;
font-size: 19px;
}
h2 {
margin: 0;
font-size: 13px;
font-weight: 700;
}
header p {
margin: 8px 0 0;
max-width: 52ch;
color: var(--muted);
font-size: 12px;
line-height: 19px;
}
.panel {
display: flex;
flex-direction: column;
gap: 12px;
padding: 16px 18px;
border: 1px solid var(--border);
border-radius: 12px;
background: var(--card);
}
.panel-header {
display: flex;
align-items: baseline;
justify-content: space-between;
gap: 12px;
}
.field {
display: flex;
flex-direction: column;
gap: 5px;
}
.field > span {
color: var(--muted);
font-size: 11px;
}
input[type='text'],
input[type='number'],
select,
textarea {
width: 100%;
padding: 7px 9px;
border: 1px solid var(--border);
border-radius: 8px;
background: transparent;
color: var(--text);
font-family: inherit;
font-size: 12px;
}
textarea {
resize: vertical;
}
.grid-2 {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
gap: 12px;
}
.row {
display: flex;
align-items: center;
gap: 12px;
flex-wrap: wrap;
}
.check,
.switch {
display: inline-flex;
align-items: center;
gap: 6px;
font-size: 12px;
color: var(--muted);
}
.switch {
padding: 6px 10px;
border: 1px solid var(--border);
border-radius: 999px;
color: var(--text);
}
button {
padding: 6px 11px;
border: 1px solid var(--border);
border-radius: 8px;
background: transparent;
color: var(--text);
font-family: inherit;
font-size: 12px;
cursor: pointer;
}
button.primary {
border-color: transparent;
background: var(--brand);
color: #fff;
}
button.ghost:hover {
border-color: var(--brand);
}
.page-footer {
display: flex;
align-items: center;
gap: 16px;
flex-wrap: wrap;
}
.status {
min-height: 18px;
margin: 0;
color: var(--muted);
font-size: 12px;
}
.status[data-kind='ok'] {
color: var(--brand);
}
.status[data-kind='error'] {
color: var(--danger);
}
.muted {
color: var(--muted);
font-size: 12px;
}
.muted strong {
color: var(--text);
font-size: 13px;
}
.stats {
width: 100%;
border-collapse: collapse;
font-size: 12px;
}
.stats th {
padding: 6px 8px;
border-bottom: 1px solid var(--border);
color: var(--muted);
font-size: 11px;
font-weight: 600;
text-align: left;
}
.stats td {
padding: 6px 8px;
border-bottom: 1px solid var(--border);
}
.stats tr:last-child td {
border-bottom: 0;
}
.stats td.empty {
color: var(--muted);
text-align: center;
}
.stats .mono {
font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
font-size: 11px;
}
.stats .ok {
color: var(--brand);
}
.stats .fail {
color: var(--danger);
}
code {
padding: 1px 4px;
border-radius: 4px;
background: var(--bg);
font-size: 11px;
}
/* 当前任务:状态徽标 + 一行阶段 + 一行细节。 */
.badge {
padding: 2px 8px;
border-radius: 999px;
background: var(--bg);
color: var(--muted);
font-size: 11px;
font-weight: 600;
}
.badge[data-status='running'] {
background: color-mix(in srgb, var(--brand) 14%, transparent);
color: var(--brand);
}
.badge[data-status='done'] {
background: color-mix(in srgb, var(--brand) 14%, transparent);
color: var(--brand);
}
.badge[data-status='failed'] {
background: color-mix(in srgb, var(--danger) 14%, transparent);
color: var(--danger);
}
.progress-line {
display: flex;
align-items: baseline;
gap: 8px;
margin: 0;
font-size: 13px;
}
.progress-line .muted {
font-size: 11px;
}
/* 群聊多选:chips + 搜索框 + 复选下拉。 */
.group-picker {
position: relative;
border: 1px solid var(--border);
border-radius: 8px;
background: var(--card);
padding: 6px;
}
.group-picker:focus-within {
border-color: var(--brand);
}
.group-chips {
display: flex;
flex-wrap: wrap;
gap: 4px;
margin-bottom: 4px;
}
.group-chip {
display: inline-flex;
align-items: center;
gap: 2px;
max-width: 100%;
padding: 2px 4px 2px 8px;
border-radius: 6px;
background: var(--bg);
font-size: 11px;
}
.group-chip > span {
max-width: 220px;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.group-chip-remove {
border: 0;
background: transparent;
color: var(--muted);
cursor: pointer;
font-size: 14px;
line-height: 1;
padding: 0 4px;
}
.group-chip-remove:hover {
color: var(--danger);
}
.group-picker > input[type='text'] {
width: 100%;
border: 0;
outline: 0;
background: transparent;
color: var(--text);
padding: 4px 2px;
font: inherit;
font-size: 12px;
}
.group-options {
position: absolute;
z-index: 30;
left: 0;
right: 0;
top: calc(100% + 4px);
max-height: 220px;
overflow: auto;
padding: 4px;
border: 1px solid var(--border);
border-radius: 8px;
background: var(--card);
box-shadow: 0 8px 24px rgba(0, 0, 0, 0.12);
}
.group-option {
display: flex;
align-items: center;
gap: 6px;
padding: 5px 6px;
border-radius: 6px;
cursor: pointer;
font-size: 12px;
}
.group-option:hover {
background: var(--bg);
}
.group-option input {
margin: 0;
}
.group-option-empty {
padding: 8px 6px;
color: var(--muted);
font-size: 11px;
}
@@ -0,0 +1,32 @@
# 群聊机器人 (`com.example.group-chat-bot`)
TraceMemo 官方扩展模板。结合 TraceMemo 已配置的 AI 模型与文字转语音(TTS)音色,在指定微信群聊中按角色设定自然接话,支持单群长期记忆与随机回复文字 / 随机发送语音。
## 核心特性
1. **多套群聊人格(Persona)**:内置「日常群友」「技术搭子」「温柔捧场王」「幽默气氛组」四套预设人格,支持新建、修改或删除自定义人格(独立配置人设背景、说话风格、字数上限与追问约束),并可为不同微信群绑定不同人格。
2. **短期上下文 + 单群长期记忆(Memory)**:
- **短期记忆**:接话时自动读取本群最近 N 条文本消息作为多轮对话上下文。
- **长期记忆**:按群独立维护「固定背景记忆(手动置顶的群规、群友称呼偏好)」与「AI 自动提炼的互动摘要(常聊话题、近期约定)」。可按对话轮数自动更新,也可在配置页随时手动触发 AI 提炼或修订。
3. **自然群聊节奏控制**:支持「仅 @我」「命中唤醒词」「@我 或唤醒词」「自然活跃接话(@我必回 + 普通群消息按概率随机搭话)」四种触发模式,区分直接唤醒冷却与环境闲聊冷却,并支持重复表达抑制。
4. **随机回复文字 / 随机发送语音 + TraceMemo 音色同步展示**:
- 配置页直接展示 TraceMemo「设置 → 文字转语音」中当前选定的音色(名称、ID、标签、合成模型与样本试听)。
- 支持「随机混合(按概率随机回复文字或发送语音)」「仅回复文字」「仅发送语音」三种模式,单群可独立覆盖;当语音未就绪或发送失败时支持自动降级为发送文字。
## 申请权限
| 权限 | 用途 |
| --- | --- |
| `messages.subscribe` | 接收微信群聊新文本消息事件 |
| `messages.query` | 读取触发群聊最近的上下文消息 |
| `contacts.list` | 在配置页读取群聊列表供勾选生效范围 |
| `wechat.send.text` | 经 TraceMemo Gateway 发送群聊文字回复 |
| `wechat.send.voice` | 经 TraceMemo 文字转语音服务与 Gateway 发送群聊语音气泡 |
| `ai.chat` | 调用 TraceMemo 已配置的 AI Provider 进行思考回复与记忆提炼 |
| `storage` | 保存机器人配置、单群长期记忆与今日统计 |
## 测试
```bash
node --test examples/extensions/group-chat-bot/tests/bot-engine.test.mjs
```
@@ -0,0 +1,31 @@
'use strict'
/** 群聊机器人后台入口壳:核心逻辑由 lib/bot-engine 承载,缺失时保持静默空操作且不报错。 */
let engine = null
try {
engine = require('../lib/bot-engine')
} catch {
engine = null
}
function registerFallbackHandlers(tm) {
if (!tm || !tm.page || typeof tm.page.onRequest !== 'function') return
const unavailable = async () => {
throw new Error('当前功能暂不可用')
}
tm.page.onRequest('previewReply', unavailable)
tm.page.onRequest('refreshGroupMemory', unavailable)
tm.page.onRequest('testSend', unavailable)
}
module.exports = function activate(api) {
if (engine && typeof engine.activateBotRuntime === 'function') {
engine.activateBotRuntime(api)
} else {
registerFallbackHandlers(api)
}
if (api && api.log && typeof api.log.info === 'function') {
api.log.info('群聊机器人已启动')
}
}
@@ -0,0 +1,39 @@
{
"manifestVersion": 1,
"id": "com.example.group-chat-bot",
"name": "群聊机器人 - 模板(如需使用请找授权你的人",
"version": "1.0.0",
"apiVersion": "1",
"minAppVersion": "2.6.0",
"description": "支持多套群聊人格设定、群聊长期与短期记忆、自然接话节奏,并可结合 TraceMemo 音色随机回复文字或发送语音。",
"author": "TraceMemo Examples",
"permissions": [
"messages.subscribe",
"messages.query",
"contacts.list",
"wechat.send.text",
"wechat.send.voice",
"ai.chat",
"storage"
],
"entrypoints": {
"page": "ui/index.html",
"background": "background/index.js"
},
"subscriptions": {
"messageTypes": [
"text"
],
"conversationIds": [],
"requireMentionMe": false,
"includeSelf": false
},
"contributions": {
"pages": [
{
"id": "settings",
"title": "群聊机器人设置"
}
]
}
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,475 @@
<!doctype html>
<html lang="zh-CN">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>群聊机器人 - 模板(如需使用请找授权你的人</title>
<link rel="stylesheet" href="./style.css" />
</head>
<body>
<main class="page">
<header class="hero">
<div>
<p class="eyebrow">TraceMemo 官方扩展模板 · com.example.group-chat-bot</p>
<div class="hero-title-row">
<h1>群聊机器人 - 模板(如需使用请找授权你的人</h1>
<span id="hero-send-warn" class="send-warn-badge" hidden>
<span class="send-warn-bang" aria-hidden="true">!</span>
当前暂无发送能力
</span>
</div>
<p class="subtitle">
支持多套群聊人格设定、基于本机聊天记录的群记忆提炼、敏感探测安全拦截,并可结合
TraceMemo 已选音色随机回复文字或发送微信语音。
</p>
</div>
<div class="hero-stats">
<div class="stat-pill">
<span>今日回复</span>
<strong id="stat-total">0</strong>
</div>
<div class="stat-pill">
<span>文字 / 语音</span>
<strong id="stat-split">0 / 0</strong>
</div>
</div>
</header>
<div id="send-unavailable-mask" class="send-unavailable-mask" hidden>
<div class="send-unavailable-dialog">
<button
id="close-send-mask-btn"
type="button"
class="send-unavailable-close"
aria-label="关闭提示并预览界面"
title="关闭提示(可浏览界面,无法保存启用)"
>
×
</button>
<div class="send-unavailable-icon" aria-hidden="true">!</div>
<h2>当前暂无发送能力</h2>
<p id="send-unavailable-reason">
当前尚未绑定个人微信或发送组件未就绪。你可以点击右上角 × 关闭遮罩预览界面,但无法保存启用。
</p>
<div class="send-unavailable-actions">
<button id="recheck-send-cap-btn" type="button" class="primary">重新检测发送能力</button>
<button id="preview-only-btn" type="button" class="ghost">关闭并预览界面</button>
</div>
</div>
</div>
<section class="capability-bar" aria-label="宿主能力状态">
<div class="cap-item">
<span class="cap-dot" id="cap-ai-dot"></span>
<span>AI 模型:<strong id="cap-ai-text">检测中…</strong></span>
</div>
<div class="cap-item">
<span class="cap-dot" id="cap-send-dot"></span>
<span>微信发送:<strong id="cap-send-text">检测中…</strong></span>
</div>
<div class="cap-item">
<span class="cap-dot" id="cap-tts-dot"></span>
<span>语音合成:<strong id="cap-tts-text">检测中…</strong></span>
</div>
</section>
<section class="card">
<div class="card-header">
<div>
<h2>语音回复与 TraceMemo 音色</h2>
<p class="hint">
自动同步展示 TraceMemo「设置 → 文字转语音」中选定的音色,可配置随机回复文字或随机发送语音。
</p>
</div>
<button id="refresh-voice-btn" type="button" class="ghost">刷新音色状态</button>
</div>
<div class="voice-showcase" id="voice-showcase">
<div class="voice-avatar" id="voice-avatar">音</div>
<div class="voice-info">
<div class="voice-title-row">
<strong id="voice-name">正在读取 TraceMemo 选定音色…</strong>
<span class="badge" id="voice-badge">未检测</span>
<span class="badge muted" id="voice-model-badge">s2.1-pro-free</span>
</div>
<p class="voice-desc" id="voice-desc">
在 TraceMemo「设置 → 文字转语音」中选择音色后,这里会自动展示当前音色详情。
</p>
<div class="voice-meta-row" id="voice-tags"></div>
</div>
<div class="voice-actions">
<button id="voice-preview-btn" type="button" class="ghost" hidden>试听音色样本</button>
</div>
</div>
<div class="grid two">
<label class="field">
<span>默认回复形式</span>
<select id="delivery-mode">
<option value="random_mix">随机混合(随机回复文字 / 随机发送语音)</option>
<option value="text_only">仅回复文字</option>
<option value="voice_only">仅发送语音</option>
</select>
</label>
<label class="field" id="voice-chance-field">
<span>随机发送语音概率(0–100%)</span>
<input id="voice-chance" type="number" min="0" max="100" value="35" />
</label>
</div>
<div class="grid two">
<label class="field">
<span>单条语音最大字数(超出自动改发文字)</span>
<input id="voice-max-chars" type="number" min="20" max="400" value="120" />
</label>
<label class="field">
<span>指定覆盖音色 ID(可选,留空跟随上方 TraceMemo 音色)</span>
<input
id="custom-voice-id"
type="text"
maxlength="80"
placeholder="留空则默认使用 TraceMemo 当前选定的音色"
/>
</label>
</div>
<label class="check">
<input id="voice-fallback" type="checkbox" checked />
<span>当语音合成未就绪或发送失败时,自动降级为发送文字回复(推荐开启,避免漏回)</span>
</label>
</section>
<section class="card">
<div class="card-header">
<div>
<h2>群聊人格设定</h2>
<p class="hint">
可准备多套群聊人格(人设背景 + 说话风格),支持全局默认人格或为不同微信群分配专属人格。
</p>
</div>
<div class="inline-actions">
<select id="preset-import-select" aria-label="选择预设人格导入">
<option value="">+ 导入预设人格…</option>
<option value="casual-friend">日常群友</option>
<option value="tech-partner">技术搭子</option>
<option value="warm-listener">温柔捧场王</option>
<option value="witty-vibe">幽默气氛组</option>
</select>
<button id="persona-add-btn" type="button" class="ghost">新建人格</button>
<button id="persona-delete-btn" type="button" class="ghost danger">删除当前</button>
</div>
</div>
<div class="grid two">
<label class="field">
<span>当前编辑的人格</span>
<select id="persona-select"></select>
</label>
<label class="field">
<span>人格显示名称</span>
<input id="persona-name" type="text" maxlength="36" placeholder="例如:日常群友" />
</label>
</div>
<label class="field">
<span>人设背景与角色定位</span>
<textarea
id="persona-identity"
rows="3"
maxlength="3000"
placeholder="描述机器人在群里的身份、性格特点与处事原则"
></textarea>
</label>
<label class="field">
<span>说话风格与语气约束</span>
<textarea
id="persona-style"
rows="2"
maxlength="1500"
placeholder="例如:口语化短句,1-2句话说清,不端架子,不用列表和客服腔"
></textarea>
</label>
<div class="grid two">
<label class="field">
<span>该人格回复字数上限(40–500)</span>
<input id="persona-max-chars" type="number" min="40" max="500" value="180" />
</label>
<label class="field">
<span>单次回复允许反问上限(0–2,0 代表不主动追问)</span>
<input id="persona-follow-up" type="number" min="0" max="2" value="0" />
</label>
</div>
</section>
<section class="card">
<h2>触发策略、节奏与安全防护</h2>
<p class="hint">扩展在扩展中心启用后即开始接话,接话范围由下方勾选的群聊决定。</p>
<div class="grid two">
<label class="field">
<span>触发方式</span>
<select id="trigger-mode">
<option value="mention">仅被 @我 时接话</option>
<option value="mention_or_wake">被 @我 或命中唤醒词时接话</option>
<option value="wake_word">仅命中唤醒词时接话</option>
<option value="ambient">自然活跃接话(@我必回 + 普通群消息按概率随机搭话)</option>
</select>
</label>
<label class="field">
<span>全局默认人格</span>
<select id="default-persona-select"></select>
</label>
</div>
<label class="field" id="wake-words-field">
<span>唤醒词列表(逗号分隔,最多 16 个)</span>
<input id="wake-words" type="text" placeholder="例如:小助手, 搭子, 机器人" />
</label>
<div class="grid three">
<label class="field">
<span>直接唤醒冷却(秒)</span>
<input id="cooldown-seconds" type="number" min="3" max="600" value="20" />
</label>
<label class="field" id="ambient-chance-field">
<span>普通群消息随机接话概率(%)</span>
<input id="ambient-chance" type="number" min="0" max="100" value="25" />
</label>
<label class="field" id="ambient-cooldown-field">
<span>环境闲聊冷却(秒)</span>
<input id="ambient-cooldown" type="number" min="5" max="1800" value="45" />
</label>
</div>
<div class="grid two">
<label class="field">
<span>短期记忆:每次读取本群最近消息条数(4–40)</span>
<input id="context-limit" type="number" min="4" max="40" value="18" />
</label>
<label class="field">
<span>长期记忆:每回复多少轮自动更新一次群摘要(3–50)</span>
<input id="memory-interval" type="number" min="3" max="50" value="8" />
</label>
</div>
<div class="check-row">
<label class="check">
<input id="suppress-duplicate" type="checkbox" checked />
<span>开启重复表达抑制(防止环境闲聊连续发送相同回复)</span>
</label>
<label class="check">
<input id="memory-enabled" type="checkbox" checked />
<span>启用群聊长期记忆(按群独立保存固定记忆与历史摘要)</span>
</label>
</div>
<hr style="border: 0; border-top: 1px solid var(--border); margin: 14px 0" />
<label class="check" style="margin-top: 4px">
<input id="security-guard-enabled" type="checkbox" checked />
<span
><strong>开启敏感探测与 AI 二次安全拦截</strong>(第一层:正则确定性阻断提示词套取、敏感词过滤规则试探、端口/root/IP
探测及编码外带;第二层:调用 AI 时注入二次安全审查指令,识别伪装话术并拦截)</span
>
</label>
<div class="grid two">
<label class="field">
<span>命中安全拦截时的处理方式</span>
<select id="security-reply-mode">
<option value="refuse">返回安全拒答话术</option>
<option value="silent">静默忽略不回复</option>
</select>
</label>
<label class="field">
<span>安全拒答话术</span>
<input
id="security-refuse-text"
type="text"
maxlength="120"
value="这个话题我没法回答哈,咱们聊点别的吧~"
/>
</label>
</div>
<label class="field">
<span>AI 二次安全审查拦截提示词(调用模型时注入,识别“通用示例/假设场景”等伪装套话并触发 SECURITY_BLOCK)</span>
<textarea
id="ai-security-prompt"
rows="2"
maxlength="600"
placeholder="定义需要 AI 在推理时二次识别并拦截的诱导场景…"
></textarea>
</label>
<label class="field">
<span>自定义敏感屏蔽词(可选,逗号分隔,最多 32 个)</span>
<input
id="blocked-keywords"
type="text"
placeholder="例如:内部接口, 测试密码, 后台地址"
/>
</label>
</section>
<section class="card">
<div class="card-header">
<div>
<h2>生效群聊与单群策略</h2>
<p class="hint">
先在上方下拉里挑选群聊,选中的会列在下方;每行的「生效」控制该群是否接话。人格、回复形式与群记忆可按群单独设置。
</p>
</div>
<button id="reload-groups-btn" type="button" class="ghost">刷新群列表</button>
</div>
<div class="field">
<span>选择群聊</span>
<div id="roster-picker" class="roster-picker">
<button
id="roster-toggle"
type="button"
class="roster-toggle"
aria-haspopup="true"
aria-expanded="false"
>
选择群聊…
</button>
<div id="roster-menu" class="roster-menu" hidden>
<input
id="roster-search"
type="text"
autocomplete="off"
placeholder="搜索群名称或 chatroom ID…"
/>
<div id="roster-options"></div>
</div>
</div>
</div>
<div class="group-table-header">
<span>群聊名称</span>
<span>生效</span>
<span>绑定人格</span>
<span>回复形式</span>
<span>群记忆</span>
<span>操作</span>
</div>
<div id="group-list" class="group-list"></div>
<p id="group-empty" class="empty-hint">
还未选择群聊。请在上方下拉中选择需要接话的群聊。
</p>
</section>
<section class="card">
<div class="card-header">
<div>
<h2>群聊记忆管理(基于本机聊天记录均衡采样提炼)</h2>
<p class="hint">
从 TraceMemo 本机微信记录提炼群记忆:自动按「每人基础条数上限(7 天 12 条/人、30 天 15 条/人)」均衡采样,若总条数未满上限(100/160 条)则自动轮询扩充余量,防止单人刷屏占满上下文。
</p>
</div>
<div class="inline-actions">
<select id="memory-group-select" aria-label="选择要管理记忆的群聊">
<option value="">选择群聊查看记忆…</option>
</select>
<button id="memory-extract-7d-btn" type="button" class="ghost">
提炼最近 7 天记录
</button>
<button id="memory-extract-30d-btn" type="button" class="ghost">
提炼最近 30 天记录
</button>
<button id="memory-clear-btn" type="button" class="ghost danger">清空该群记忆</button>
</div>
</div>
<p class="meta-line" id="memory-meta">
请先在上方下拉框选择一个群聊,即可查看或从本机最近 7 天 / 30 天聊天记录提炼群记忆。
</p>
<label class="field">
<span>本群固定记忆与背景备注(手动维护,每次对话最高优先级注入)</span>
<textarea
id="memory-pinned"
rows="2"
maxlength="800"
placeholder="例如:群主是老王;每周五晚 9 点固定组队;大家喜欢聊独立开发与数码产品。"
></textarea>
</label>
<label class="field">
<span>本群长期互动记忆摘要(可根据最近 7 天 / 30 天本机聊天记录提炼,也可手动修订)</span>
<textarea
id="memory-summary"
rows="4"
maxlength="800"
placeholder="点击右上角「提炼最近 7 天记录」或「提炼最近 30 天记录」,即可从 TraceMemo 本机微信数据库中读取该群历史发言并生成长期记忆摘要。"
></textarea>
</label>
<div class="inline-actions">
<button id="memory-save-btn" type="button" class="ghost">保存该群记忆修改</button>
</div>
</section>
<section class="card">
<h2>AI 回复预览与发送测试</h2>
<p class="hint">
使用 TraceMemo 当前配置的 AI 模型测试人格思考与安全拦截效果,或向指定群测试文字/语音发送(需先在扩展中心启用本扩展)。
</p>
<div class="grid two">
<label class="field">
<span>测试目标群聊(可选,用于读取群记忆或测试真实发送)</span>
<select id="test-group-select">
<option value="">不指定群聊(仅用当前人格预览)</option>
</select>
</label>
<label class="field">
<span>模拟群友昵称</span>
<input id="test-sender-name" type="text" maxlength="32" value="测试群友" />
</label>
</div>
<label class="field">
<span>模拟群友消息 / 测试发送内容</span>
<input
id="test-message-input"
type="text"
maxlength="400"
value="今晚大家有什么安排?出来聊五毛钱的~"
/>
</label>
<div class="inline-actions">
<button id="preview-reply-btn" type="button" class="ghost">
预览 AI 思考回复(不发微信)
</button>
<button id="test-send-auto-btn" type="button" class="ghost">
按配置随机测试发送
</button>
<button id="test-send-text-btn" type="button" class="ghost">
测试发送文字
</button>
<button id="test-send-voice-btn" type="button" class="ghost">
测试发送语音
</button>
</div>
<pre id="test-output" class="preview-box" hidden></pre>
</section>
<footer class="footer-bar">
<div class="footer-buttons">
<button id="save-config-btn" type="button" class="primary">保存全部配置</button>
<button id="reload-config-btn" type="button" class="ghost">重新读取</button>
</div>
<span id="status-banner" class="status-banner" role="status" aria-live="polite"></span>
</footer>
</main>
<script src="./app.js"></script>
</body>
</html>
@@ -0,0 +1,651 @@
:root {
color-scheme: light dark;
--bg: #f6f7f9;
--surface: #ffffff;
--surface-subtle: #f1f5f9;
--border: #e2e8f0;
--text: #0f172a;
--muted: #64748b;
--accent: #059669;
--accent-hover: #047857;
--accent-soft: rgba(5, 150, 105, 0.12);
--warn: #d97706;
--danger: #dc2626;
}
@media (prefers-color-scheme: dark) {
:root {
--bg: #0b0f17;
--surface: #131b26;
--surface-subtle: #1c2636;
--border: #263244;
--text: #f1f5f9;
--muted: #94a3b8;
--accent: #10b981;
--accent-hover: #059669;
--accent-soft: rgba(16, 185, 129, 0.16);
--warn: #f59e0b;
--danger: #f87171;
}
}
* {
box-sizing: border-box;
}
[hidden] {
display: none !important;
}
body {
margin: 0;
background: var(--bg);
color: var(--text);
font: 14px/1.55 -apple-system, BlinkMacSystemFont, "PingFang SC", "Microsoft YaHei", sans-serif;
}
.page {
max-width: 900px;
margin: 0 auto;
padding: 20px 24px 48px;
}
.hero {
display: flex;
justify-content: space-between;
align-items: flex-start;
gap: 16px;
margin-bottom: 14px;
}
.eyebrow {
margin: 0 0 4px;
color: var(--muted);
font-size: 12px;
}
h1 {
margin: 0 0 6px;
font-size: 22px;
font-weight: 700;
}
h2 {
margin: 0;
font-size: 16px;
font-weight: 600;
}
.subtitle,
.hint,
.meta-line {
margin: 4px 0 0;
color: var(--muted);
font-size: 13px;
}
.hero-stats {
display: flex;
gap: 10px;
flex-shrink: 0;
}
.stat-pill {
background: var(--surface);
border: 1px solid var(--border);
border-radius: 10px;
padding: 8px 14px;
min-width: 100px;
text-align: right;
}
.stat-pill span {
display: block;
font-size: 11px;
color: var(--muted);
}
.stat-pill strong {
font-size: 16px;
font-weight: 700;
}
.capability-bar {
display: flex;
flex-wrap: wrap;
gap: 16px;
background: var(--surface);
border: 1px solid var(--border);
border-radius: 10px;
padding: 10px 14px;
margin-bottom: 14px;
font-size: 13px;
}
.cap-item {
display: inline-flex;
align-items: center;
gap: 7px;
}
.cap-dot {
width: 8px;
height: 8px;
border-radius: 999px;
background: var(--muted);
}
.cap-dot.ok {
background: var(--accent);
}
.cap-dot.warn {
background: var(--warn);
}
.card {
background: var(--surface);
border: 1px solid var(--border);
border-radius: 12px;
padding: 16px 18px;
margin-bottom: 14px;
}
.card-header {
display: flex;
justify-content: space-between;
align-items: flex-start;
gap: 12px;
white-space: normal;
margin-bottom: 12px;
}
.voice-showcase {
display: flex;
align-items: center;
gap: 14px;
background: var(--surface-subtle);
border: 1px solid var(--border);
border-radius: 10px;
padding: 12px 14px;
margin-bottom: 14px;
}
.voice-avatar {
width: 46px;
height: 46px;
border-radius: 10px;
background: var(--accent-soft);
color: var(--accent);
display: flex;
align-items: center;
justify-content: center;
font-size: 18px;
font-weight: 700;
flex-shrink: 0;
overflow: hidden;
}
.voice-avatar img {
width: 100%;
height: 100%;
object-fit: cover;
}
.voice-info {
flex: 1;
min-width: 0;
}
.voice-title-row {
display: flex;
align-items: center;
flex-wrap: wrap;
gap: 8px;
}
.voice-desc {
margin: 4px 0 6px;
color: var(--muted);
font-size: 12px;
}
.voice-meta-row {
display: flex;
flex-wrap: wrap;
gap: 6px;
}
.badge {
display: inline-flex;
align-items: center;
padding: 2px 8px;
border-radius: 999px;
font-size: 11px;
font-weight: 600;
background: var(--accent-soft);
color: var(--accent);
}
.badge.muted {
background: var(--surface);
border: 1px solid var(--border);
color: var(--muted);
font-weight: 500;
}
.badge.warn {
background: rgba(217, 119, 6, 0.14);
color: var(--warn);
}
.grid.two {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 12px;
}
.grid.three {
display: grid;
grid-template-columns: 1fr 1fr 1fr;
gap: 12px;
}
@media (max-width: 680px) {
.grid.two,
.grid.three {
grid-template-columns: 1fr;
}
.hero,
.card-header {
flex-direction: column;
}
}
.field {
display: flex;
flex-direction: column;
gap: 5px;
margin-top: 10px;
}
.field > span {
font-size: 12px;
font-weight: 500;
color: var(--muted);
}
input[type="text"],
input[type="number"],
select,
textarea {
width: 100%;
border: 1px solid var(--border);
border-radius: 8px;
padding: 8px 10px;
background: var(--bg);
color: var(--text);
font: inherit;
}
textarea {
resize: vertical;
}
.check {
display: inline-flex;
align-items: center;
gap: 8px;
margin-top: 12px;
cursor: pointer;
font-size: 13px;
}
.check-row {
display: flex;
flex-wrap: wrap;
gap: 18px;
}
.inline-actions {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 8px;
margin-top: 10px;
}
.card-header .inline-actions {
margin-top: 0;
}
button {
border-radius: 8px;
padding: 7px 13px;
font: inherit;
font-weight: 600;
cursor: pointer;
border: 1px solid transparent;
transition: opacity 0.15s ease;
}
button:disabled {
opacity: 0.55;
cursor: not-allowed;
}
button.primary {
background: var(--accent);
color: #ffffff;
}
button.primary:hover:not(:disabled) {
background: var(--accent-hover);
}
.card-header > button {
flex: 0 0 auto;
white-space: nowrap;
}
.ghost {
background: transparent;
border-color: var(--border);
color: var(--text);
}
button.ghost.danger {
color: var(--danger);
}
.roster-picker {
position: relative;
}
/* 下拉开关:外观对齐同排 select,右侧给个箭头。 */
.roster-toggle {
width: 100%;
padding: 9px 12px;
border: 1px solid var(--border);
border-radius: 8px;
background: var(--surface);
color: var(--text);
font-size: 13px;
text-align: left;
cursor: pointer;
}
.roster-toggle::after {
content: '▾';
float: right;
color: var(--muted);
}
.roster-options {
margin-top: 4px;
max-height: 240px;
overflow-y: auto;
}
.roster-menu {
position: absolute;
z-index: 20;
left: 0;
right: 0;
top: calc(100% + 4px);
max-height: 230px;
overflow-y: auto;
background: var(--surface);
border: 1px solid var(--border);
border-radius: 8px;
padding: 6px;
box-shadow: 0 10px 28px rgba(0, 0, 0, 0.18);
}
.roster-option {
display: flex;
align-items: center;
gap: 8px;
padding: 6px 8px;
border-radius: 6px;
cursor: pointer;
font-size: 13px;
}
.roster-option:hover {
background: var(--surface-subtle);
}
.roster-empty {
padding: 10px;
color: var(--muted);
font-size: 13px;
}
.group-table-header {
display: grid;
grid-template-columns: minmax(140px, 1.4fr) 64px minmax(120px, 1fr) minmax(130px, 1fr) 80px 88px;
gap: 8px;
margin-top: 14px;
padding: 0 8px 6px;
border-bottom: 1px solid var(--border);
color: var(--muted);
font-size: 12px;
}
.group-list {
display: flex;
flex-direction: column;
gap: 8px;
margin-top: 8px;
}
.group-row {
display: grid;
grid-template-columns: minmax(140px, 1.4fr) 64px minmax(120px, 1fr) minmax(130px, 1fr) 80px 88px;
gap: 8px;
align-items: center;
padding: 8px;
border: 1px solid var(--border);
border-radius: 8px;
background: var(--surface-subtle);
}
/* 未勾选生效的群:整行降透明,但仍可编辑人格/回复形式。 */
.group-row.is-off {
opacity: 0.62;
}
.group-row.is-off:hover {
opacity: 0.85;
}
.group-title {
font-weight: 500;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.group-title small {
display: block;
color: var(--muted);
font-size: 11px;
font-weight: 400;
}
@media (max-width: 720px) {
.group-table-header {
display: none;
}
.group-row {
grid-template-columns: 1fr;
}
}
.empty-hint {
margin: 12px 0 0;
color: var(--muted);
font-size: 13px;
}
.preview-box {
margin: 12px 0 0;
padding: 12px;
border-radius: 8px;
border: 1px solid var(--border);
background: var(--surface-subtle);
white-space: pre-wrap;
word-break: break-word;
font-size: 13px;
}
.footer-bar {
position: sticky;
bottom: 0;
display: flex;
justify-content: space-between;
align-items: center;
gap: 12px;
padding: 12px 16px;
background: var(--surface);
border: 1px solid var(--border);
border-radius: 12px;
box-shadow: 0 6px 20px rgba(0, 0, 0, 0.08);
}
.footer-buttons {
display: flex;
gap: 8px;
}
.status-banner {
font-size: 13px;
color: var(--muted);
}
.status-banner[data-tone="ok"] {
color: var(--accent);
}
.status-banner[data-tone="error"] {
color: var(--danger);
}
.hero-title-row {
display: flex;
align-items: center;
gap: 10px;
flex-wrap: wrap;
}
.send-warn-badge {
display: inline-flex;
align-items: center;
gap: 5px;
padding: 3px 10px;
border-radius: 999px;
background: rgba(220, 38, 38, 0.12);
border: 1px solid rgba(220, 38, 38, 0.3);
color: #dc2626;
font-size: 12px;
font-weight: 700;
}
.send-warn-bang {
display: inline-flex;
align-items: center;
justify-content: center;
width: 16px;
height: 16px;
border-radius: 50%;
background: #dc2626;
color: #ffffff;
font-size: 11px;
font-weight: 800;
}
.send-unavailable-mask {
position: fixed;
inset: 0;
z-index: 100;
display: flex;
align-items: center;
justify-content: center;
padding: 24px;
background: rgba(15, 23, 42, 0.38);
backdrop-filter: blur(4px);
}
.send-unavailable-mask[hidden] {
display: none !important;
}
.send-unavailable-dialog {
position: relative;
max-width: 440px;
width: 100%;
padding: 26px 28px;
border-radius: 14px;
border: 1px solid rgba(220, 38, 38, 0.28);
background: var(--surface);
box-shadow: 0 20px 44px rgba(0, 0, 0, 0.2);
text-align: center;
}
.send-unavailable-close {
position: absolute;
top: 10px;
right: 10px;
display: inline-flex;
align-items: center;
justify-content: center;
width: 28px;
height: 28px;
padding: 0;
border: 1px solid transparent;
border-radius: 8px;
background: transparent;
color: var(--muted);
font-size: 18px;
line-height: 1;
cursor: pointer;
}
.send-unavailable-close:hover {
background: var(--surface-subtle);
color: var(--text);
}
.send-unavailable-icon {
display: inline-flex;
align-items: center;
justify-content: center;
width: 44px;
height: 44px;
border-radius: 50%;
background: #dc2626;
color: #ffffff;
font-size: 24px;
font-weight: 800;
box-shadow: 0 6px 16px rgba(220, 38, 38, 0.3);
}
.send-unavailable-dialog h2 {
margin: 12px 0 8px;
color: #dc2626;
font-size: 18px;
}
.send-unavailable-dialog p {
margin: 0 0 18px;
color: var(--muted);
font-size: 13px;
line-height: 1.65;
}
.send-unavailable-actions {
display: flex;
justify-content: center;
gap: 10px;
}
+116
View File
@@ -0,0 +1,116 @@
# 关键词回复机器人
监听微信文本消息,按规则表匹配关键词,命中后经 TraceMemo Gateway 回复。
两条入口共用同一份配置与同一套判定(`lib/matcher.js`):
- `message.received` 事件:扩展自己判断范围与冷却,再调用 `tm.wechat.send`;
- 自动化动作 `keyword.reply`:只返回回复文本,不发送,发送由宿主的自动化流程完成。
扩展本身不碰 socket、dylib 或 HTTP,所有发送都经过宿主 Gateway 的权限、授权校验、限流与审计。
## 目录
```text
keyword-bot/
manifest.json 权限、订阅、页面与自动化动作声明
background/index.js 事件编排、冷却表、命中统计
lib/matcher.js 纯函数:规范化 / 匹配 / 范围 / 模板 / 决策
ui/ 配置页(沙箱 iframe,只调用 storage.* / capabilities.get / extension.info)
tests/matcher.test.mjs
```
## 功能
- 规则支持三种匹配方式:`contains`(包含)、`exact`(完全匹配)、`prefix`(以…开头),均不区分大小写;
- 每条规则可单独启用/停用,并设置优先级与冷却;
- 监听范围可按群限定,可开关私聊,可要求真正 @ 我;
- 回复内容支持模板变量;
- 配置页展示今日命中数与最近 5 条命中结果。
## 配置字段
顶层:
| 字段 | 类型 | 默认 | 说明 |
| ------------------------ | -------- | ------- | ----------------------------------------- |
| `configVersion` | number | `2` | 保存时写入;v1(无此字段)读取时自动迁移 |
| `enabled` | boolean | `false` | 总开关。缺省关闭,避免安装后立即对外发送 |
| `rules` | array | `[]` | 规则表,见下 |
| `scope.groups` | string[] | `[]` | 群 id(`xxx@chatroom`);空数组表示全部群 |
| `scope.includeDirect` | boolean | `true` | 是否处理私聊 |
| `scope.requireMentionMe` | boolean | `false` | 是否只处理真正 @ 登录账号的消息 |
规则:
| 字段 | 类型 | 默认 | 约束 |
| ----------------- | ------- | ------------- | ------------------------------------------- |
| `id` | string | `rule-<序号>` | ≤ 64 字符;冷却键的一部分,尽量稳定 |
| `keyword` | string | `''` | ≤ 120 字符;启用中为空的规则会被丢弃 |
| `mode` | string | `contains` | `contains` / `exact` / `prefix` |
| `reply` | string | `''` | ≤ 2000 字符;启用中为空的规则会被丢弃 |
| `cooldownSeconds` | number | `0` | 0–3600,取整到秒 |
| `enabled` | boolean | `true` | v1 规则迁移后为 `true`;显式 `false` 才停用 |
| `priority` | number | `0` | 0–100 整数,越大越先匹配 |
配置页保存时只校验**启用中**的规则必须有 `keyword` 与 `reply`;停用的规则允许留空,方便先存草稿。
## 模板变量
| 变量 | 含义 |
| ----------- | -------------------------------------------------------------------------- |
| `{sender}` | 发送者昵称;为空时渲染为「你」。自动化动作路径没有发送者上下文,恒为「你」 |
| `{keyword}` | 命中的关键词(规则里的原文) |
| `{time}` | 当前本地时间 `HH:mm` |
未知变量(例如 `{group}`)原样保留,不会被静默删除。渲染结果 trim 后截断到 2000 字符。
## 优先级与冷却语义
- 只考虑 `enabled !== false` 的规则;按 `priority` 降序排列,同优先级保持规则在数组中的顺序;
- 取**第一个**命中的规则,一条消息最多回复一次(stopOnMatch),不会叠加多条回复;
- 冷却键是 `conversationId:ruleId`,即「同一会话 + 同一条规则」各自独立计时;
- 冷却只在**发送成功后**写入:发送失败不占用冷却,下一条命中会立刻重试;
- 冷却表只存在内存里,扩展进程重启后清空——宁可多回一条,也不跨重启误拦。
## 统计口径与隐私边界
存储键 `stats`,结构:
```json
{
"dateKey": "2026-11-12",
"todayCount": 3,
"lastHits": [{ "at": 0, "ruleId": "rule-1", "ok": true }]
}
```
- 每条命中记一条,**成功和失败都记**;`todayCount` 统计的是命中的次数(含发送失败);
- `lastHits` 最多保留 20 条,配置页只展示最近 5 条;`at` 是 epoch 毫秒;
- 跨日后读取会把 `todayCount` 归零,`lastHits` 作为滚动历史保留;
- 只记录规则 id、时间与发送结果,**不记录会话 id、消息正文、发送者昵称或群名**;
- 统计写入失败只打 warn 日志,不影响回复;
- 统计只覆盖事件自动回复,不包含自动化动作 `keyword.reply` 的调用。
## 测试
零依赖,Node 内置测试运行器,不安装任何包:
```bash
node --test examples/extensions/keyword-bot/tests/matcher.test.mjs
node --check examples/extensions/keyword-bot/lib/matcher.js
node --check examples/extensions/keyword-bot/background/index.js
node --check examples/extensions/keyword-bot/ui/app.js
```
用例覆盖:三种匹配方式、大小写、空关键词、禁用规则、优先级与稳定性、群范围与私聊开关、@ 要求、自己发的消息、冷却中/过期、模板替换与未知变量、超长截断、v1 迁移、非法规则丢弃、数值越界收敛、决策顺序。
`tests/matcher.test.mjs` 中的 fixture 全部为占位数据(`张三`、`李四`、`测试群`、`fixture-room@chatroom`、`wxid_fixture`)。
## 已知限制
- 不回复自己发送的消息(`isSelf` 直接跳过);
- 消息事件是「至多一次」投递:扩展进程重启的瞬间可能丢事件,没有补投队列;
- 不读取群名,因此没有 `{group}` 变量;需要按群定制时请拆成多条规则并配合「监听范围」;
- 配置缓存窗口为 1 秒,保存后最多 1 秒生效;
- 冷却表与配置缓存都在扩展后台进程内存中,进程重启即丢失。
@@ -0,0 +1,227 @@
/**
* 关键词回复机器人。
*
* 两条入口共用同一份配置与 `lib/matcher.js` 的同一套判定:
* 1. `message.received` 事件 → 自己判断范围 / 冷却 → `tm.wechat.send`;
* 2. 自动化动作 `keyword.reply` → 只返回回复内容,由宿主 Gateway 发送。
*
* 发送**永远**经过宿主:本文件里没有任何 socket、dylib 或 HTTP 调用。
* 匹配/规范化逻辑全部在 `lib/matcher.js`,本文件只负责编排与统计。
*/
const { normalizeConfig, pickRule, renderReply, shouldReply } = require('../lib/matcher.js')
const CONFIG_KEY = 'config'
const STATS_KEY = 'stats'
/** 配置缓存窗口:配置页保存后最多 1 秒生效,避免每条消息都读一次 storage。 */
const CONFIG_TTL_MS = 1000
/** 最近命中记录上限;只保留规则 id、时间与结果,不保留任何会话内容。 */
const STATS_HISTORY_LIMIT = 20
/** 冷却表清理阈值:超过后剔除已过期项,避免长期运行无限增长。 */
const COOLDOWN_PRUNE_SIZE = 500
let tm = null
let cachedConfig = null
let cachedAt = 0
let cachedStats = null
const cooldownUntil = new Map()
/** 统计写入串行化:并发消息不互相覆盖 `stats` 快照。 */
let statsChain = Promise.resolve()
function loadConfig() {
if (cachedConfig && Date.now() - cachedAt < CONFIG_TTL_MS) return Promise.resolve(cachedConfig)
return Promise.resolve(tm.storage.get(CONFIG_KEY))
.then((stored) => {
cachedConfig = normalizeConfig(stored)
cachedAt = Date.now()
return cachedConfig
})
.catch((error) => {
tm.log.warn(`读取配置失败,本次按未启用处理:${describeError(error)}`)
// 读失败也要缓存一小段时间,避免每条消息都打一次失败日志。
cachedConfig = normalizeConfig(null)
cachedAt = Date.now()
return cachedConfig
})
}
/** 本地时区的 `YYYY-MM-DD`,用于判定「今日」。 */
function statsDateKey(timestamp) {
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}`
}
/** 本地时区的 `HH:mm`,模板变量 `{time}` 与统计展示共用。 */
function formatClock(timestamp) {
const date = new Date(timestamp)
const hour = String(date.getHours()).padStart(2, '0')
const minute = String(date.getMinutes()).padStart(2, '0')
return `${hour}:${minute}`
}
function emptyStats(timestamp) {
return { dateKey: statsDateKey(timestamp), todayCount: 0, lastHits: [] }
}
/**
* 规范化统计快照。
*
* 跨日后 `todayCount` 归零;`lastHits` 作为滚动历史保留(它记的是「最近命中」,
* 不是「今日命中」)。任何字段缺失或类型不对都退化为空值,统计损坏不能影响回复。
*/
function normalizeStats(raw, timestamp) {
const base = emptyStats(timestamp)
if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return base
const lastHits = Array.isArray(raw.lastHits)
? raw.lastHits
.filter((hit) => hit && typeof hit === 'object')
.map((hit) => ({
at: Number(hit.at),
ruleId: String(hit.ruleId == null ? '' : hit.ruleId).slice(0, 64),
ok: hit.ok === true
}))
.filter((hit) => Number.isFinite(hit.at) && hit.at > 0 && hit.ruleId)
.slice(-STATS_HISTORY_LIMIT)
: []
const sameDay = raw.dateKey === base.dateKey
const count = sameDay ? Math.max(0, Math.floor(Number(raw.todayCount) || 0)) : 0
return { dateKey: base.dateKey, todayCount: count, lastHits }
}
function loadStats() {
if (cachedStats) return Promise.resolve(cachedStats)
return Promise.resolve(tm.storage.get(STATS_KEY))
.then((stored) => {
cachedStats = normalizeStats(stored, Date.now())
return cachedStats
})
.catch(() => {
cachedStats = emptyStats(Date.now())
return cachedStats
})
}
/**
* 追加一条命中记录并落库。
*
* 成功与失败都记;只写 `ruleId` / `at` / `ok`,绝不写会话 id、正文或昵称。
* 写失败只 warn:统计是旁路,不能因为 storage 异常把回复一起吞掉。
*/
function recordHit(ruleId, ok) {
statsChain = statsChain
.then(async () => {
const stats = await loadStats()
const now = Date.now()
const dateKey = statsDateKey(now)
if (stats.dateKey !== dateKey) {
stats.dateKey = dateKey
stats.todayCount = 0
}
stats.todayCount += 1
stats.lastHits = stats.lastHits
.concat({ at: now, ruleId: String(ruleId || '').slice(0, 64), ok: ok === true })
.slice(-STATS_HISTORY_LIMIT)
await tm.storage.set(STATS_KEY, stats)
})
.catch((error) => {
tm.log.warn(`命中统计写入失败:${describeError(error)}`)
})
return statsChain
}
/** 冷却只在真正发送成功后写入;发送失败不占冷却,下一条可以立刻重试。 */
function markCooldown(conversationId, rule, timestamp) {
const seconds = Number(rule.cooldownSeconds) || 0
cooldownUntil.set(`${conversationId}:${rule.id}`, timestamp + seconds * 1000)
if (cooldownUntil.size > COOLDOWN_PRUNE_SIZE) {
for (const [key, until] of cooldownUntil) {
if (until <= timestamp) cooldownUntil.delete(key)
}
}
}
function describeError(error) {
return error && error.message ? error.message : String(error)
}
async function onMessage(event) {
try {
const config = await loadConfig()
// 交给自动化规则处理时,订阅路径必须彻底闭嘴,否则同一条消息回复两次。
if (config.executionMode === 'automation') return
const now = Date.now()
const verdict = shouldReply(event, config, cooldownUntil, now)
if (!verdict.reply || !verdict.rule) return
const rule = verdict.rule
const text = renderReply(rule.reply, {
senderName: event.senderName,
keyword: rule.keyword,
time: formatClock(now)
})
try {
await tm.wechat.send({
to: event.conversationId,
text,
// 同一条微信消息在补投/重启后 eventId 不变,交给 Gateway 幂等短路。
dedupeKey: event.eventId
})
} catch (error) {
await recordHit(rule.id, false)
throw error
}
markCooldown(event.conversationId, rule, Date.now())
await recordHit(rule.id, true)
tm.log.info(`关键词命中,已发送回复(规则 ${rule.id})`)
} catch (error) {
tm.log.error(`自动回复失败:${describeError(error)}`)
}
}
module.exports = function activate(api) {
tm = api
tm.events.on('message.received', onMessage)
tm.automation.registerAction({
id: 'keyword.reply',
title: '关键词回复',
description: '按机器人配置匹配关键词并返回回复内容',
inputSchema: {
type: 'object',
properties: { text: { type: 'string' } },
required: ['text']
},
async handler(input) {
const config = await loadConfig()
if (!config.enabled) {
return { success: false, error: '机器人未启用' }
}
// 订阅模式下这条路径同样会发送:直接跳过,避免与事件路径重复回复。
if (config.executionMode === 'subscribe') {
return { success: true, output: { matched: false, skipped: 'subscribe-mode' } }
}
const rule = pickRule(input.text, config)
if (!rule) {
return { success: true, output: { matched: false } }
}
return {
success: true,
output: { matched: true, ruleId: rule.id },
// 动作路径没有发送者上下文,`{sender}` 会渲染成「你」。
reply: {
type: 'text',
text: renderReply(rule.reply, {
keyword: rule.keyword,
time: formatClock(Date.now())
})
}
}
}
})
tm.log.info('关键词回复机器人已加载')
}
@@ -0,0 +1,224 @@
'use strict'
/**
* 关键词回复的纯函数层:配置规范化、匹配、范围判定、模板渲染、决策。
*
* 契约:
* - 全部函数无副作用、不读写 storage、不打印日志,便于单测与后台进程复用;
* - 输入一律容忍 `undefined` / 错误类型,坏配置退化为「不回复」而不是抛错;
* - `enabled` 在任何一层都是硬开关:配置损坏时不能自动对外发送。
*/
/** 当前配置结构版本。v1 没有该字段,读取时按 v1 迁移。 */
const CONFIG_VERSION = 2
/** 与 UI、宿主动作输出保持一致的长度上限(字符)。 */
const MAX_RULE_ID_LENGTH = 64
const MAX_KEYWORD_LENGTH = 120
const MAX_REPLY_LENGTH = 2000
const MAX_GROUPS = 200
const MODES = new Set(['contains', 'exact', 'prefix'])
/**
* 两条回复入口的执行模式。
*
* 同一条消息若同时被「事件订阅」和「自动化动作」处理,会回复两次。
* 这里用互斥模式从根上避免:默认保留订阅(兼容旧用户),
* 切到 `automation` 后订阅路径完全不再发送。
*/
const EXECUTION_MODES = new Set(['subscribe', 'automation'])
/**
* 把任意来源的配置规范化为 `configVersion: 2`。
*
* 启用中的空规则丢弃,停用的空规则保留为草稿;顶层 `enabled` 缺省 `false`,
* 配置缺失或损坏时宁可静默,也不能自动群发。
*
* @param {unknown} raw storage 里读出的原始值
*/
function normalizeConfig(raw) {
const input = raw && typeof raw === 'object' && !Array.isArray(raw) ? raw : {}
const sourceRules = Array.isArray(input.rules) ? input.rules : []
const rules = sourceRules
.filter((rule) => rule && typeof rule === 'object' && !Array.isArray(rule))
.map((rule, index) => ({
id: String(rule.id || `rule-${index + 1}`).slice(0, MAX_RULE_ID_LENGTH),
keyword: String(rule.keyword == null ? '' : rule.keyword).slice(0, MAX_KEYWORD_LENGTH),
mode: MODES.has(rule.mode) ? rule.mode : 'contains',
reply: String(rule.reply == null ? '' : rule.reply).slice(0, MAX_REPLY_LENGTH),
cooldownSeconds: clampNumber(rule.cooldownSeconds, 0, 3600),
// v1 规则没有该字段;只有显式 false 才算禁用。
enabled: rule.enabled !== false,
priority: clampNumber(rule.priority, 0, 100)
}))
.filter((rule) => rule.enabled === false || (rule.keyword.trim() && rule.reply.trim()))
const scope = input.scope && typeof input.scope === 'object' ? input.scope : {}
return {
configVersion: CONFIG_VERSION,
enabled: input.enabled === true,
executionMode: EXECUTION_MODES.has(input.executionMode) ? input.executionMode : 'subscribe',
rules,
scope: {
groups: Array.isArray(scope.groups)
? scope.groups
.map((id) => String(id == null ? '' : id).trim())
.filter(Boolean)
.slice(0, MAX_GROUPS)
: [],
includeDirect: scope.includeDirect !== false,
requireMentionMe: scope.requireMentionMe === true
}
}
}
/**
* 单条规则是否命中文本:大小写不敏感;`exact` / `prefix` 先 trim,
* `contains` 只 trim 关键词;空关键词恒为 false。
*
* @param {unknown} text 消息正文
* @param {{ keyword?: unknown, mode?: unknown }} rule
* @returns {boolean}
*/
function matchRule(text, rule) {
const keyword = String((rule && rule.keyword) == null ? '' : rule.keyword)
.trim()
.toLowerCase()
if (!keyword) return false
const haystack = String(text == null ? '' : text).toLowerCase()
const mode = rule && MODES.has(rule.mode) ? rule.mode : 'contains'
if (mode === 'exact') return haystack.trim() === keyword
if (mode === 'prefix') return haystack.trim().startsWith(keyword)
return haystack.includes(keyword)
}
/**
* 选出唯一命中的规则:`priority` 降序、同优先级保持数组顺序,取第一个命中。
*
* 这就是 stopOnMatch 语义:一条消息最多回复一次,命中即停。
* 禁用规则(`enabled === false`)不参与匹配。
*
* @param {unknown} text
* @param {object} config normalizeConfig 的产物
*/
function pickRule(text, config) {
const rules = config && Array.isArray(config.rules) ? config.rules : []
const candidates = rules
.map((rule, index) => ({ rule, index }))
.filter((item) => item.rule && item.rule.enabled !== false)
// 显式带下标排序,避免依赖引擎排序稳定性。
.sort((a, b) => (b.rule.priority || 0) - (a.rule.priority || 0) || a.index - b.index)
for (const item of candidates) {
if (matchRule(text, item.rule)) return item.rule
}
return null
}
/**
* 会话是否在生效范围内。
*
* - 群聊:`groups` 为空表示全部群;非空时必须包含 `event.conversationId`;
* - 私聊:只看 `includeDirect`。
*
* 范围在规则匹配之前判定:范围外的会话连匹配都不做,避免误触统计。
*/
function inScope(event, config) {
const scope = (config && config.scope) || {}
if (event && event.isGroup) {
const groups = Array.isArray(scope.groups) ? scope.groups : []
return groups.length === 0 || groups.includes(event.conversationId)
}
return scope.includeDirect !== false
}
/**
* 渲染回复模板。
*
* 支持 `{sender}`(发送者昵称,空则「你」)、`{keyword}`(命中关键词)、
* `{time}`(调用方给的本地时间字符串,缺省空串)。未知 `{xxx}` 原样保留,
* 方便用户在模板里写其它占位而不是被静默吃掉。结果 trim 后截断到 2000 字符。
*/
function renderReply(template, ctx) {
const source = String(template == null ? '' : template)
const context = ctx && typeof ctx === 'object' ? ctx : {}
const sender = String(context.senderName == null ? '' : context.senderName).trim() || '你'
const keyword = String(context.keyword == null ? '' : context.keyword)
const time = String(context.time == null ? '' : context.time)
const rendered = source.replace(/\{(sender|keyword|time)\}/g, (match, token) => {
if (token === 'sender') return sender
if (token === 'keyword') return keyword
if (token === 'time') return time
return match
})
return rendered.trim().slice(0, MAX_REPLY_LENGTH)
}
/**
* 综合决策:是否回复、用哪条规则、为什么。
*
* `reason` 取值固定,可直接用于日志/统计口径:
* `disabled` | `self` | `type` | `scope` | `mention` | `no_match` | `cooldown` | `ok`。
*
* 判断顺序固定为:总开关 → 自己发的 → 消息类型 → 会话范围 → @ 要求 → 规则匹配 → 冷却。
* 冷却键为 `conversationId:ruleId`,值为到期时间戳(epoch 毫秒),`now < until` 即冷却中。
* 冷却表允许是 `Map` 或普通对象,后台进程重启后自然清空(宁可多回一条,也不跨重启误拦)。
*
* @param {object} event 宿主的 message.received 事件
* @param {object} config normalizeConfig 的产物
* @param {Map<string, number>|Record<string, number>} [cooldownUntil]
* @param {number} [now] epoch 毫秒,缺省取当前时间
*/
function shouldReply(event, config, cooldownUntil, now) {
if (!config || config.enabled !== true) {
return { reply: false, rule: null, reason: 'disabled' }
}
if (!event || event.isSelf === true) {
return { reply: false, rule: null, reason: 'self' }
}
if (event.type !== 'text') {
return { reply: false, rule: null, reason: 'type' }
}
if (!inScope(event, config)) {
return { reply: false, rule: null, reason: 'scope' }
}
if (config.scope && config.scope.requireMentionMe === true && event.mentionsMe !== true) {
return { reply: false, rule: null, reason: 'mention' }
}
const rule = pickRule(event.text, config)
if (!rule) {
return { reply: false, rule: null, reason: 'no_match' }
}
const currentTime = Number.isFinite(now) ? now : Date.now()
const key = `${event.conversationId}:${rule.id}`
if (currentTime < readCooldown(cooldownUntil, key)) {
return { reply: false, rule: null, reason: 'cooldown' }
}
return { reply: true, rule, reason: 'ok' }
}
/** 冷却表读取:兼容 Map 与普通对象,缺失值按 0(永不冷却)。 */
function readCooldown(table, key) {
if (!table) return 0
const value = table instanceof Map ? table.get(key) : table[key]
const until = Number(value)
return Number.isFinite(until) ? until : 0
}
/** 收敛到 [min, max] 的整数;非数字 / NaN 一律当 0。 */
function clampNumber(value, min, max) {
const numeric = Number(value)
if (!Number.isFinite(numeric)) return 0
return Math.min(Math.max(Math.round(numeric), min), max)
}
module.exports = {
CONFIG_VERSION,
EXECUTION_MODES,
normalizeConfig,
matchRule,
pickRule,
inScope,
renderReply,
shouldReply
}
@@ -0,0 +1,44 @@
{
"manifestVersion": 1,
"id": "com.example.keyword-bot",
"name": "关键词回复机器人",
"version": "1.0.1",
"apiVersion": "1",
"minAppVersion": "2.6.0",
"description": "监听微信文本消息,命中关键词后经 TraceMemo Gateway 回复。",
"author": "TraceMemo Examples",
"permissions": [
"messages.subscribe",
"contacts.list",
"wechat.send.text",
"storage",
"automation.action"
],
"entrypoints": {
"page": "ui/index.html",
"background": "background/index.js"
},
"subscriptions": {
"messageTypes": [
"text"
],
"conversationIds": [],
"requireMentionMe": false,
"includeSelf": false
},
"contributions": {
"pages": [
{
"id": "settings",
"title": "机器人配置"
}
],
"automationActions": [
{
"id": "keyword.reply",
"title": "关键词回复",
"description": "按机器人配置匹配关键词并返回回复内容"
}
]
}
}
@@ -0,0 +1,279 @@
import test from 'node:test'
import assert from 'node:assert/strict'
import matcher from '../lib/matcher.js'
const { normalizeConfig, matchRule, pickRule, inScope, renderReply, shouldReply } = matcher
const GROUP_ID = 'fixture-room@chatroom'
const NOW = 1_700_000_000_000
/** 构造一份启用状态下的最小配置,参数按需覆盖。 */
function buildConfig(overrides = {}) {
return normalizeConfig({
enabled: true,
rules: [{ id: 'rule-1', keyword: '关键词', mode: 'contains', reply: '默认回复' }],
scope: { groups: [], includeDirect: true, requireMentionMe: false },
...overrides
})
}
/** 构造一条群聊文本消息事件。 */
function buildEvent(overrides = {}) {
return {
eventId: 'event-fixture-1',
accountId: 'account-fixture',
conversationId: GROUP_ID,
messageId: 'message-fixture-1',
senderId: 'wxid_fixture',
senderName: '张三',
isGroup: true,
isSelf: false,
type: 'text',
text: '你好,关键词',
mentionsMe: false,
timestamp: NOW,
...overrides
}
}
test('exact 模式比较 trim 后的完整文本', () => {
const rule = { keyword: '关键词', mode: 'exact' }
assert.equal(matchRule(' 关键词 ', rule), true)
assert.equal(matchRule('你好,关键词', rule), false)
})
test('exact 模式不匹配大小写不同的关键词之外的差异', () => {
const rule = { keyword: 'Hello', mode: 'exact' }
assert.equal(matchRule('hello', rule), true)
assert.equal(matchRule('hello world', rule), false)
})
test('contains 模式匹配任意位置的子串', () => {
const rule = { keyword: '关键词', mode: 'contains' }
assert.equal(matchRule('前面的关键词后面', rule), true)
assert.equal(matchRule('完全无关', rule), false)
})
test('prefix 模式只匹配开头', () => {
const rule = { keyword: '你好', mode: 'prefix' }
assert.equal(matchRule(' 你好世界', rule), true)
assert.equal(matchRule('世界你好', rule), false)
})
test('匹配对大小写不敏感', () => {
assert.equal(matchRule('Say HELLO now', { keyword: 'hello', mode: 'contains' }), true)
assert.equal(matchRule('HELLO WORLD', { keyword: 'hello', mode: 'prefix' }), true)
})
test('空关键词在任何模式下都不命中', () => {
for (const mode of ['contains', 'exact', 'prefix']) {
assert.equal(matchRule('任意文本', { keyword: ' ', mode }), false)
assert.equal(matchRule('', { keyword: '', mode }), false)
}
})
test('pickRule 跳过禁用规则', () => {
const config = buildConfig({
rules: [
{ id: 'disabled', keyword: '关键词', reply: '不会发送', enabled: false },
{ id: 'active', keyword: '关键词', reply: '会发送' }
]
})
const rule = pickRule('关键词', config)
assert.equal(rule.id, 'active')
})
test('pickRule 按 priority 降序选择', () => {
const config = buildConfig({
rules: [
{ id: 'low', keyword: '关键词', reply: '低', priority: 10 },
{ id: 'high', keyword: '关键词', reply: '高', priority: 90 }
]
})
assert.equal(pickRule('关键词', config).id, 'high')
})
test('同优先级保持数组顺序(先定义先命中)', () => {
const config = buildConfig({
rules: [
{ id: 'first', keyword: '关键词', reply: '一', priority: 50 },
{ id: 'second', keyword: '关键词', reply: '二', priority: 50 }
]
})
assert.equal(pickRule('关键词', config).id, 'first')
})
test('同一条消息只返回一个规则(stopOnMatch)', () => {
const config = buildConfig({
rules: [
{ id: 'a', keyword: '关键词', reply: '一', priority: 1 },
{ id: 'b', keyword: '关键词', reply: '二', priority: 2 }
]
})
const rule = pickRule('关键词 关键词', config)
assert.equal(rule.id, 'b')
})
test('群范围命中指定群', () => {
const config = buildConfig({ scope: { groups: [GROUP_ID] } })
assert.equal(inScope(buildEvent(), config), true)
})
test('群范围排除未列出的群', () => {
const config = buildConfig({ scope: { groups: ['other-room@chatroom'] } })
assert.equal(inScope(buildEvent(), config), false)
})
test('groups 为空表示全部群聊', () => {
const config = buildConfig({ scope: { groups: [] } })
assert.equal(inScope(buildEvent(), config), true)
})
test('includeDirect 为 false 时不处理私聊', () => {
const closed = buildConfig({ scope: { groups: [], includeDirect: false } })
const open = buildConfig({ scope: { groups: [], includeDirect: true } })
const direct = buildEvent({ isGroup: false, conversationId: 'wxid_fixture' })
assert.equal(inScope(direct, closed), false)
assert.equal(inScope(direct, open), true)
})
test('requireMentionMe 只放行真正 @ 我的消息', () => {
const config = buildConfig({ scope: { groups: [], requireMentionMe: true } })
assert.equal(shouldReply(buildEvent(), config, new Map(), NOW).reason, 'mention')
assert.equal(shouldReply(buildEvent({ mentionsMe: true }), config, new Map(), NOW).reason, 'ok')
})
test('自己发的消息不回复', () => {
const verdict = shouldReply(buildEvent({ isSelf: true }), buildConfig(), new Map(), NOW)
assert.deepEqual(verdict, { reply: false, rule: null, reason: 'self' })
})
test('非文本消息不回复', () => {
const verdict = shouldReply(buildEvent({ type: 'image' }), buildConfig(), new Map(), NOW)
assert.equal(verdict.reason, 'type')
})
test('总开关关闭时不回复', () => {
const config = buildConfig({ enabled: false })
assert.equal(shouldReply(buildEvent(), config, new Map(), NOW).reason, 'disabled')
assert.equal(shouldReply(buildEvent(), null, new Map(), NOW).reason, 'disabled')
})
test('没有命中规则时 reason 为 no_match', () => {
const verdict = shouldReply(buildEvent({ text: '无关内容' }), buildConfig(), new Map(), NOW)
assert.deepEqual(verdict, { reply: false, rule: null, reason: 'no_match' })
})
test('冷却中不回复', () => {
const cooldown = new Map([[`${GROUP_ID}:rule-1`, NOW + 30_000]])
const verdict = shouldReply(buildEvent(), buildConfig(), cooldown, NOW)
assert.deepEqual(verdict, { reply: false, rule: null, reason: 'cooldown' })
})
test('冷却过期后恢复回复', () => {
const cooldown = new Map([[`${GROUP_ID}:rule-1`, NOW]])
const verdict = shouldReply(buildEvent(), buildConfig(), cooldown, NOW)
assert.equal(verdict.reply, true)
assert.equal(verdict.reason, 'ok')
assert.equal(verdict.rule.id, 'rule-1')
})
test('冷却表也支持普通对象', () => {
const cooldown = { [`${GROUP_ID}:rule-1`]: NOW + 1 }
assert.equal(shouldReply(buildEvent(), buildConfig(), cooldown, NOW).reason, 'cooldown')
assert.equal(shouldReply(buildEvent(), buildConfig(), {}, NOW).reason, 'ok')
})
test('模板变量按上下文替换', () => {
const text = renderReply('{sender} 说了 {keyword},现在是 {time}', {
senderName: '张三',
keyword: '关键词',
time: '09:05'
})
assert.equal(text, '张三 说了 关键词,现在是 09:05')
})
test('发送者昵称为空时渲染为「你」', () => {
assert.equal(renderReply('{sender}', { senderName: ' ' }), '你')
assert.equal(renderReply('{sender}', {}), '你')
})
test('未知变量原样保留', () => {
const text = renderReply('{sender} 和 {group}', { senderName: '李四' })
assert.equal(text, '李四 和 {group}')
})
test('模板缺失的时间变量渲染为空串', () => {
assert.equal(renderReply('[{time}]', {}), '[]')
})
test('渲染结果 trim 后截断到 2000 字符', () => {
const input = ` ${'长'.repeat(2100)} `
const text = renderReply(input, {})
assert.equal(text.length, 2000)
assert.equal(text, '长'.repeat(2000))
})
test('v1 配置迁移补齐 enabled / priority 与 configVersion', () => {
const config = normalizeConfig({
enabled: true,
rules: [{ id: 'old', keyword: '关键词', mode: 'contains', reply: '旧规则' }],
scope: { groups: ['fixture-room@chatroom'] }
})
assert.equal(config.configVersion, 2)
assert.equal(config.rules.length, 1)
assert.equal(config.rules[0].enabled, true)
assert.equal(config.rules[0].priority, 0)
assert.equal(config.scope.includeDirect, true)
assert.equal(config.scope.requireMentionMe, false)
})
test('keyword 或 reply 为空的启用规则被丢弃,停用草稿保留', () => {
const config = normalizeConfig({
enabled: true,
rules: [
{ id: 'no-keyword', keyword: ' ', reply: '有回复' },
{ id: 'no-reply', keyword: '有词', reply: ' ' },
{ id: 'draft', keyword: '', reply: '', enabled: false },
{ id: 'ok', keyword: '有词', reply: '有回复' }
]
})
assert.deepEqual(
config.rules.map((rule) => rule.id),
['draft', 'ok']
)
})
test('非对象与缺失字段的配置退化为未启用空配置', () => {
for (const raw of [null, undefined, 'broken', 42, []]) {
const config = normalizeConfig(raw)
assert.equal(config.configVersion, 2)
assert.equal(config.enabled, false)
assert.deepEqual(config.rules, [])
assert.deepEqual(config.scope, { groups: [], includeDirect: true, requireMentionMe: false })
}
})
test('越界数值收敛到边界,非法值按 0', () => {
const config = normalizeConfig({
rules: [
{ id: 'clamp-high', keyword: '一', reply: '一', cooldownSeconds: 99_999, priority: 999 },
{ id: 'clamp-low', keyword: '二', reply: '二', cooldownSeconds: -5, priority: -5 },
{ id: 'nan', keyword: '三', reply: '三', cooldownSeconds: 'oops', priority: 'oops' }
]
})
assert.equal(config.rules[0].cooldownSeconds, 3600)
assert.equal(config.rules[0].priority, 100)
assert.equal(config.rules[1].cooldownSeconds, 0)
assert.equal(config.rules[1].priority, 0)
assert.equal(config.rules[2].cooldownSeconds, 0)
assert.equal(config.rules[2].priority, 0)
})
test('群范围过滤先于规则匹配,范围外不产生命中', () => {
const config = buildConfig({ scope: { groups: ['other-room@chatroom'] } })
const verdict = shouldReply(buildEvent(), config, new Map(), NOW)
assert.equal(verdict.reason, 'scope')
assert.equal(verdict.rule, null)
})
+495
View File
@@ -0,0 +1,495 @@
const EXTENSION_ID = 'com.example.keyword-bot'
const PAGE_SOURCE = 'tracememo-extension-page'
const HOST_SOURCE = 'tracememo-extension-host'
const CONFIG_KEY = 'config'
const STATS_KEY = 'stats'
const CONFIG_VERSION = 2
const MAX_KEYWORD_LENGTH = 120
const MAX_REPLY_LENGTH = 2000
const STATS_PREVIEW = 5
const DEFAULT_CONFIG = {
configVersion: CONFIG_VERSION,
enabled: false,
rules: [
{
id: 'rule-1',
keyword: '你好',
mode: 'contains',
reply: '你好呀,{sender}!',
cooldownSeconds: 30,
enabled: true,
priority: 0
}
],
scope: { groups: [], includeDirect: true, requireMentionMe: false }
}
const pending = new Map()
let sequence = 0
let config = clone(DEFAULT_CONFIG)
function clone(value) {
return JSON.parse(JSON.stringify(value))
}
function callHost(method, params) {
return new Promise((resolve, reject) => {
const requestId = `req-${++sequence}`
pending.set(requestId, { resolve, reject })
window.parent.postMessage(
{ source: PAGE_SOURCE, extensionId: EXTENSION_ID, requestId, method, params },
'*'
)
})
}
window.addEventListener('message', (event) => {
const data = event.data
if (!data || data.source !== HOST_SOURCE) return
const entry = pending.get(data.requestId)
if (!entry) return
pending.delete(data.requestId)
if (data.ok) entry.resolve(data.result)
else entry.reject(new Error((data.error && data.error.message) || '调用失败'))
})
const rulesContainer = document.getElementById('rules')
const status = document.getElementById('status')
const statsSummary = document.getElementById('stats-summary')
const statsList = document.getElementById('stats-list')
const groupPicker = document.getElementById('group-picker')
const groupChips = document.getElementById('group-chips')
const groupSearch = document.getElementById('group-search')
const groupOptions = document.getElementById('group-options')
let allGroups = []
let selectedGroupIds = new Set()
let groupLoadError = ''
function groupDisplayName(group) {
if (!group) return ''
return group.name && group.name !== group.id ? `${group.name}(${group.id})` : group.id
}
function renderGroupChips() {
groupChips.textContent = ''
groupChips.hidden = selectedGroupIds.size === 0
for (const id of selectedGroupIds) {
const group = allGroups.find((item) => item.id === id)
const chip = document.createElement('span')
chip.className = 'group-chip'
const name = document.createElement('span')
name.textContent = group ? group.name || id : id
name.title = id
const remove = document.createElement('button')
remove.type = 'button'
remove.className = 'group-chip-remove'
remove.textContent = '×'
remove.setAttribute('aria-label', `移除 ${group ? group.name || id : id}`)
remove.addEventListener('click', (event) => {
event.stopPropagation()
selectedGroupIds.delete(id)
renderGroupChips()
renderGroupOptions()
})
chip.append(name, remove)
groupChips.append(chip)
}
}
function renderGroupOptions() {
if (groupOptions.hidden) return
const query = groupSearch.value.trim().toLowerCase()
groupOptions.textContent = ''
if (groupLoadError) {
groupOptions.append(emptyGroupOption(groupLoadError))
return
}
if (!allGroups.length) {
groupOptions.append(emptyGroupOption('未读取到群列表(请先连接微信数据库)'))
return
}
const matches = allGroups.filter((group) => {
if (!query) return true
return group.id.toLowerCase().includes(query) || group.name.toLowerCase().includes(query)
})
if (!matches.length) {
groupOptions.append(emptyGroupOption('没有匹配的群聊'))
return
}
for (const group of matches.slice(0, 200)) {
const option = document.createElement('label')
option.className = 'group-option'
const checkbox = document.createElement('input')
checkbox.type = 'checkbox'
checkbox.checked = selectedGroupIds.has(group.id)
checkbox.addEventListener('change', () => {
if (checkbox.checked) selectedGroupIds.add(group.id)
else selectedGroupIds.delete(group.id)
renderGroupChips()
})
const text = document.createElement('span')
text.textContent = groupDisplayName(group)
option.append(checkbox, text)
groupOptions.append(option)
}
}
function emptyGroupOption(text) {
const empty = document.createElement('div')
empty.className = 'group-option-empty'
empty.textContent = text
return empty
}
function openGroupOptions() {
groupOptions.hidden = false
renderGroupOptions()
}
function closeGroupOptions() {
groupOptions.hidden = true
groupSearch.value = ''
}
groupSearch.addEventListener('focus', openGroupOptions)
groupSearch.addEventListener('input', openGroupOptions)
groupSearch.addEventListener('keydown', (event) => {
if (event.key === 'Escape') {
closeGroupOptions()
groupSearch.blur()
}
})
document.addEventListener('click', (event) => {
if (!groupPicker.contains(event.target)) closeGroupOptions()
})
async function loadGroups() {
try {
const result = await callHost('contacts.listGroups', {})
allGroups = result && Array.isArray(result.groups) ? result.groups : []
groupLoadError = ''
} catch (error) {
allGroups = []
groupLoadError = `群列表读取失败:${error.message}`
}
renderGroupChips()
renderGroupOptions()
}
function setStatus(text, kind) {
status.textContent = text
status.dataset.kind = kind || ''
}
function clampInteger(value, min, max, fallback) {
const numeric = Number(value)
if (!Number.isFinite(numeric)) return fallback
return Math.min(Math.max(Math.round(numeric), min), max)
}
function newRuleId() {
return `rule-${Date.now().toString(36)}`
}
/**
* 页面侧的轻量规范化:只用于展示与回写,真正的判定在后台 lib/matcher.js。
* 缺字段一律补默认值,保证 v1 配置打开后能直接编辑。
*/
function normalizeRule(rule, index) {
const source = rule && typeof rule === 'object' ? rule : {}
return {
id: String(source.id || `rule-${index + 1}`).slice(0, 64),
keyword: String(source.keyword == null ? '' : source.keyword).slice(0, MAX_KEYWORD_LENGTH),
mode: ['contains', 'exact', 'prefix'].includes(source.mode) ? source.mode : 'contains',
reply: String(source.reply == null ? '' : source.reply).slice(0, MAX_REPLY_LENGTH),
cooldownSeconds: clampInteger(source.cooldownSeconds, 0, 3600, 0),
enabled: source.enabled !== false,
priority: clampInteger(source.priority, 0, 100, 0)
}
}
function normalizeStoredConfig(stored) {
if (!stored || typeof stored !== 'object') return clone(DEFAULT_CONFIG)
const scope = stored.scope && typeof stored.scope === 'object' ? stored.scope : {}
return {
configVersion: CONFIG_VERSION,
enabled: stored.enabled === true,
rules: Array.isArray(stored.rules)
? stored.rules.map(normalizeRule)
: clone(DEFAULT_CONFIG.rules),
scope: {
groups: Array.isArray(scope.groups)
? scope.groups.map((id) => String(id).trim()).filter(Boolean)
: [],
includeDirect: scope.includeDirect !== false,
requireMentionMe: scope.requireMentionMe === true
}
}
}
function field(label, control) {
const wrapper = document.createElement('label')
wrapper.className = 'field'
const caption = document.createElement('span')
caption.textContent = label
wrapper.append(caption, control)
return wrapper
}
function renderRules() {
rulesContainer.textContent = ''
config.rules.forEach((rule, index) => {
const card = document.createElement('article')
card.className = 'rule-card'
if (!rule.enabled) card.classList.add('is-disabled')
const head = document.createElement('div')
head.className = 'rule-head'
const title = document.createElement('strong')
title.textContent = `规则 ${index + 1}`
const toggle = document.createElement('label')
toggle.className = 'check'
const enabledInput = document.createElement('input')
enabledInput.type = 'checkbox'
enabledInput.checked = rule.enabled
enabledInput.addEventListener('change', () => {
rule.enabled = enabledInput.checked
card.classList.toggle('is-disabled', !rule.enabled)
})
const toggleText = document.createElement('span')
toggleText.textContent = '启用'
toggle.append(enabledInput, toggleText)
const remove = document.createElement('button')
remove.type = 'button'
remove.className = 'ghost danger'
remove.textContent = '删除'
remove.addEventListener('click', () => {
config.rules.splice(index, 1)
renderRules()
})
const headActions = document.createElement('div')
headActions.className = 'rule-head-actions'
headActions.append(toggle, remove)
head.append(title, headActions)
const keywordInput = document.createElement('input')
keywordInput.type = 'text'
keywordInput.maxLength = MAX_KEYWORD_LENGTH
keywordInput.value = rule.keyword
keywordInput.addEventListener('input', () => {
rule.keyword = keywordInput.value
})
const modeSelect = document.createElement('select')
;[
['contains', '包含'],
['exact', '完全匹配'],
['prefix', '以…开头']
].forEach(([value, label]) => {
const option = document.createElement('option')
option.value = value
option.textContent = label
option.selected = rule.mode === value
modeSelect.append(option)
})
modeSelect.addEventListener('change', () => {
rule.mode = modeSelect.value
})
const replyInput = document.createElement('textarea')
replyInput.rows = 2
replyInput.maxLength = MAX_REPLY_LENGTH
replyInput.value = rule.reply
replyInput.addEventListener('input', () => {
rule.reply = replyInput.value
})
const replyBlock = field('回复内容', replyInput)
const replyHint = document.createElement('p')
replyHint.className = 'hint'
replyHint.textContent =
'可用变量:{sender}(发送者)、{keyword}(命中词)、{time}(当前时间 HH:mm)'
replyBlock.append(replyHint)
const cooldownInput = document.createElement('input')
cooldownInput.type = 'number'
cooldownInput.min = '0'
cooldownInput.max = '3600'
cooldownInput.value = String(rule.cooldownSeconds)
cooldownInput.addEventListener('change', () => {
rule.cooldownSeconds = clampInteger(cooldownInput.value, 0, 3600, 0)
cooldownInput.value = String(rule.cooldownSeconds)
})
const priorityInput = document.createElement('input')
priorityInput.type = 'number'
priorityInput.min = '0'
priorityInput.max = '100'
priorityInput.step = '1'
priorityInput.value = String(rule.priority)
priorityInput.addEventListener('change', () => {
rule.priority = clampInteger(priorityInput.value, 0, 100, 0)
priorityInput.value = String(rule.priority)
})
const numberRow = document.createElement('div')
numberRow.className = 'field-row'
const cooldownField = field('冷却时间(秒)', cooldownInput)
const priorityField = field('优先级(0–100,越大越先匹配)', priorityInput)
numberRow.append(cooldownField, priorityField)
card.append(
head,
field('关键词', keywordInput),
field('匹配方式', modeSelect),
replyBlock,
numberRow
)
rulesContainer.append(card)
})
}
function syncForm() {
document.getElementById('enabled').checked = config.enabled === true
selectedGroupIds = new Set(config.scope.groups)
renderGroupChips()
renderGroupOptions()
document.getElementById('include-direct').checked = config.scope.includeDirect !== false
document.getElementById('require-mention').checked = config.scope.requireMentionMe === true
renderRules()
}
function readForm() {
config.enabled = document.getElementById('enabled').checked
config.scope.groups = [...selectedGroupIds].slice(0, 200)
config.scope.includeDirect = document.getElementById('include-direct').checked
config.scope.requireMentionMe = document.getElementById('require-mention').checked
}
function localDateKey(timestamp) {
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}`
}
function formatClock(timestamp) {
const date = new Date(timestamp)
const hour = String(date.getHours()).padStart(2, '0')
const minute = String(date.getMinutes()).padStart(2, '0')
return `${hour}:${minute}`
}
/** 统计展示:只读 storage,不参与任何写入。 */
function renderStats(raw) {
statsList.textContent = ''
const now = Date.now()
const sameDay = raw && raw.dateKey === localDateKey(now)
const todayCount = sameDay ? Math.max(0, Math.floor(Number(raw.todayCount) || 0)) : 0
const hits = raw && Array.isArray(raw.lastHits) ? raw.lastHits.filter((hit) => hit && hit.at) : []
if (!hits.length && todayCount === 0) {
statsSummary.textContent = '暂无命中记录'
return
}
statsSummary.textContent = `今日命中 ${todayCount} 次`
hits
.slice(-STATS_PREVIEW)
.reverse()
.forEach((hit) => {
const item = document.createElement('li')
item.className = 'stats-item'
const time = document.createElement('span')
time.textContent = formatClock(Number(hit.at))
const ruleId = document.createElement('code')
ruleId.textContent = String(hit.ruleId || '未知规则')
const result = document.createElement('span')
result.className = hit.ok === true ? 'stats-ok' : 'stats-fail'
result.textContent = hit.ok === true ? '成功' : '失败'
item.append(time, ruleId, result)
statsList.append(item)
})
}
async function loadStats() {
try {
const stored = await callHost('storage.get', { key: STATS_KEY })
renderStats(stored)
} catch (error) {
renderStats(null)
setStatus(`统计读取失败:${error.message}`, 'error')
}
}
document.getElementById('add-rule').addEventListener('click', () => {
config.rules.push({
id: newRuleId(),
keyword: '',
mode: 'contains',
reply: '',
cooldownSeconds: 30,
enabled: true,
priority: 0
})
renderRules()
})
document.getElementById('save').addEventListener('click', async () => {
readForm()
// 只有启用中的规则必须有内容:停用的草稿允许留空,方便先存后写。
const invalid = config.rules.find(
(rule) => rule.enabled && (!rule.keyword.trim() || !rule.reply.trim())
)
if (invalid) {
setStatus('启用中的规则都需要关键词和回复内容;也可以先取消启用再保存。', 'error')
return
}
const payload = {
configVersion: CONFIG_VERSION,
enabled: config.enabled === true,
rules: config.rules.map(normalizeRule),
scope: {
groups: config.scope.groups.slice(0, 200),
includeDirect: config.scope.includeDirect !== false,
requireMentionMe: config.scope.requireMentionMe === true
}
}
try {
await callHost('storage.set', { key: CONFIG_KEY, value: payload })
// 回写规范化结果但保留原对象引用:卡片上的输入事件仍在改这些对象。
payload.rules.forEach((rule, index) => Object.assign(config.rules[index], rule))
config.configVersion = CONFIG_VERSION
setStatus('配置已保存。后台进程会在下一次收到消息时生效。', 'ok')
loadStats()
} catch (error) {
setStatus(`保存失败:${error.message}`, 'error')
}
})
document.getElementById('reset').addEventListener('click', async () => {
config = clone(DEFAULT_CONFIG)
syncForm()
try {
await callHost('storage.set', { key: CONFIG_KEY, value: config })
setStatus('已恢复默认配置。', 'ok')
} catch (error) {
setStatus(`重置失败:${error.message}`, 'error')
}
})
document.getElementById('refresh-stats').addEventListener('click', () => {
loadStats()
})
async function boot() {
const stored = await callHost('storage.get', { key: CONFIG_KEY })
config = normalizeStoredConfig(stored)
syncForm()
await loadGroups()
setStatus('配置已读取。默认不启用,避免安装后立即对外发送。')
loadStats()
}
boot().catch((error) => setStatus(`加载失败:${error.message}`, 'error'))
@@ -0,0 +1,71 @@
<!doctype html>
<html lang="zh-CN">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>关键词回复机器人</title>
<link rel="stylesheet" href="./style.css" />
</head>
<body>
<main class="page">
<header class="page-header">
<div>
<h1>关键词回复机器人</h1>
<p>收到文本消息后按规则匹配,命中即经 TraceMemo Gateway 回复。本页只写配置,不直接发送。</p>
</div>
<label class="switch">
<input id="enabled" type="checkbox" />
<span>启用机器人</span>
</label>
</header>
<section class="panel">
<div class="panel-header">
<h2>关键词规则</h2>
<button id="add-rule" type="button" class="ghost">添加规则</button>
</div>
<div id="rules" class="rules"></div>
</section>
<section class="panel">
<h2>监听范围</h2>
<div class="field">
<span>只监听这些群聊(可多选、可搜索;留空表示全部群聊)</span>
<div id="group-picker" class="group-picker">
<div id="group-chips" class="group-chips" hidden></div>
<input
id="group-search"
type="text"
placeholder="搜索群聊名称或 id…"
autocomplete="off"
/>
<div id="group-options" class="group-options" hidden></div>
</div>
</div>
<div class="row">
<label class="check"><input id="include-direct" type="checkbox" /><span>同时处理私聊</span></label>
<label class="check"><input id="require-mention" type="checkbox" /><span>只处理真正 @ 我的消息</span></label>
</div>
</section>
<section class="panel">
<div class="panel-header">
<h2>运行统计</h2>
<button id="refresh-stats" type="button" class="ghost">刷新</button>
</div>
<p id="stats-summary" class="stats-summary">暂无命中记录</p>
<ul id="stats-list" class="stats-list"></ul>
<p class="hint">统计只记录规则编号、命中时间与发送结果,不含会话、昵称与消息正文。</p>
</section>
<footer class="page-footer">
<div class="row">
<button id="save" type="button" class="primary">保存配置</button>
<button id="reset" type="button" class="ghost">恢复默认</button>
</div>
<p id="status" class="status" role="status"></p>
</footer>
</main>
<script src="./app.js"></script>
</body>
</html>
@@ -0,0 +1,384 @@
:root {
color-scheme: light dark;
--bg: #f6f8f7;
--card: #ffffff;
--text: #1c2622;
--muted: #6b7a73;
--border: #dfe6e2;
--brand: #247a63;
--danger: #b4472f;
}
@media (prefers-color-scheme: dark) {
:root {
--bg: #161c19;
--card: #1e2622;
--text: #eef4f1;
--muted: #9aaba3;
--border: #33403a;
--brand: #4bb894;
--danger: #e0735a;
}
}
* {
box-sizing: border-box;
}
body {
margin: 0;
min-height: 100vh;
background: var(--bg);
color: var(--text);
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'PingFang SC', 'Microsoft YaHei',
sans-serif;
}
.page {
max-width: 720px;
margin: 0 auto;
padding: 26px 22px 40px;
display: flex;
flex-direction: column;
gap: 16px;
}
.page-header {
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 16px;
flex-wrap: wrap;
}
h1 {
margin: 0;
font-size: 19px;
}
h2 {
margin: 0;
font-size: 13px;
font-weight: 700;
}
header p {
margin: 8px 0 0;
max-width: 52ch;
color: var(--muted);
font-size: 12px;
line-height: 19px;
}
.panel {
display: flex;
flex-direction: column;
gap: 12px;
padding: 16px 18px;
border: 1px solid var(--border);
border-radius: 12px;
background: var(--card);
}
.panel-header {
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
}
.rules {
display: flex;
flex-direction: column;
gap: 12px;
}
.rule-card {
display: flex;
flex-direction: column;
gap: 10px;
padding: 12px 14px;
border: 1px solid var(--border);
border-radius: 10px;
}
.rule-head {
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
font-size: 12px;
}
.rule-head-actions {
display: flex;
align-items: center;
gap: 10px;
}
.rule-card.is-disabled {
border-style: dashed;
}
.rule-card.is-disabled .field,
.rule-card.is-disabled .field-row {
opacity: 0.55;
}
.field-row {
display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr));
gap: 12px;
}
.field {
display: flex;
flex-direction: column;
gap: 5px;
}
.hint {
margin: 0;
color: var(--muted);
font-size: 11px;
line-height: 16px;
}
.stats-summary {
margin: 0;
color: var(--text);
font-size: 12px;
}
.stats-list {
display: flex;
flex-direction: column;
gap: 6px;
margin: 0;
padding: 0;
list-style: none;
}
.stats-item {
display: flex;
align-items: center;
gap: 8px;
color: var(--muted);
font-size: 12px;
}
.stats-ok {
color: var(--brand);
}
.stats-fail {
color: var(--danger);
}
@media (max-width: 480px) {
.field-row {
grid-template-columns: minmax(0, 1fr);
}
}
.field > span {
color: var(--muted);
font-size: 11px;
}
input[type='text'],
input[type='number'],
select,
textarea {
width: 100%;
padding: 7px 9px;
border: 1px solid var(--border);
border-radius: 8px;
background: transparent;
color: var(--text);
font-family: inherit;
font-size: 12px;
}
textarea {
resize: vertical;
}
.row {
display: flex;
align-items: center;
gap: 12px;
flex-wrap: wrap;
}
.check,
.switch {
display: inline-flex;
align-items: center;
gap: 6px;
font-size: 12px;
color: var(--muted);
}
.switch {
padding: 6px 10px;
border: 1px solid var(--border);
border-radius: 999px;
color: var(--text);
}
button {
padding: 6px 11px;
border: 1px solid var(--border);
border-radius: 8px;
background: transparent;
color: var(--text);
font-family: inherit;
font-size: 12px;
cursor: pointer;
}
button.primary {
border-color: transparent;
background: var(--brand);
color: #fff;
}
button.ghost:hover {
border-color: var(--brand);
}
button.danger {
color: var(--danger);
}
.page-footer {
display: flex;
align-items: center;
gap: 16px;
flex-wrap: wrap;
}
.status {
min-height: 18px;
margin: 0;
color: var(--muted);
font-size: 12px;
}
.status[data-kind='ok'] {
color: var(--brand);
}
.status[data-kind='error'] {
color: var(--danger);
}
code {
padding: 1px 4px;
border-radius: 4px;
background: var(--bg);
font-size: 11px;
}
/* 群聊多选:chips + 搜索框 + 复选下拉。 */
.group-picker {
position: relative;
border: 1px solid var(--border);
border-radius: 8px;
background: var(--card);
padding: 6px;
}
.group-picker:focus-within {
border-color: var(--brand);
}
.group-chips {
display: flex;
flex-wrap: wrap;
gap: 4px;
margin-bottom: 4px;
}
.group-chip {
display: inline-flex;
align-items: center;
gap: 2px;
max-width: 100%;
padding: 2px 4px 2px 8px;
border-radius: 6px;
background: var(--bg);
font-size: 11px;
}
.group-chip > span {
max-width: 220px;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.group-chip-remove {
border: 0;
background: transparent;
color: var(--muted);
cursor: pointer;
font-size: 14px;
line-height: 1;
padding: 0 4px;
}
.group-chip-remove:hover {
color: var(--danger);
}
.group-picker > input[type='text'] {
width: 100%;
border: 0;
outline: 0;
background: transparent;
color: var(--text);
padding: 4px 2px;
font: inherit;
font-size: 12px;
}
.group-options {
position: absolute;
z-index: 30;
left: 0;
right: 0;
top: calc(100% + 4px);
max-height: 220px;
overflow: auto;
padding: 4px;
border: 1px solid var(--border);
border-radius: 8px;
background: var(--card);
box-shadow: 0 8px 24px rgba(0, 0, 0, 0.12);
}
.group-option {
display: flex;
align-items: center;
gap: 6px;
padding: 5px 6px;
border-radius: 6px;
cursor: pointer;
font-size: 12px;
}
.group-option:hover {
background: var(--bg);
}
.group-option input {
margin: 0;
}
.group-option-empty {
padding: 8px 6px;
color: var(--muted);
font-size: 11px;
}
+29
View File
@@ -0,0 +1,29 @@
{
"version": 1,
"templates": {
"douyin-sender@1.0.3": {
"sha256": "01cd4b1a7af2b9e0208145b64e487af2a17f354ab7344f32cf9ff7565deb11a6",
"bytes": 32839
},
"douyin-sender@1.0.4": {
"sha256": "4fd4a478232d6b52a68187d2e0c3f42733acda1e65ce9f9594f99440e6edd3e5",
"bytes": 32981
},
"douyin-sender@1.0.5": {
"sha256": "d33559d6620ca173c97a19aafc8570521bf6426f6420e6fb8f90923333b554c8",
"bytes": 33471
},
"group-chat-bot@1.0.0": {
"sha256": "122a4da7710cf882975f09440819e9dc1b619e4bd6f94153085a7d6fe8a33885",
"bytes": 24981
},
"keyword-bot@1.0.0": {
"sha256": "3d8e5453e7ae6de7e29c16eb3c9e718a98bae27e9ed2edfd10399fb158e1c87d",
"bytes": 19121
},
"keyword-bot@1.0.1": {
"sha256": "ae379a10dac553b60cc8c823186734d917b604b6dff27e2e7d2d62f5cf5e4d41",
"bytes": 19517
}
}
}
+19
View File
@@ -0,0 +1,19 @@
<!doctype html>
<html>
<head>
<meta charset="UTF-8" />
<title>TraceMemo(迹忆)</title>
<link rel="icon" type="image/svg+xml" href="./assets/brand-icon-DQrJvdgV.svg" />
<!-- https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP -->
<meta
http-equiv="Content-Security-Policy"
content="default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data: https: wxe-media:; media-src 'self' https: blob: data: wxe-media:; frame-src tm-extension:;"
/>
<script type="module" crossorigin src="./assets/index-CRoZdOvo.js"></script>
<link rel="stylesheet" crossorigin href="./assets/index-DJPGPmFx.css">
</head>
<body>
<div id="root"></div>
</body>
</html>
+11 -9
View File
@@ -1,6 +1,6 @@
{
"name": "tracememo",
"version": "2.6.0",
"version": "2.7.0",
"packageManager": "pnpm@7.33.7",
"description": "TraceMemo(迹忆)是一款本地优先、可追溯的 AI 微信知识与分析工作台。 原名 WechatExplorer,支持聊天记录搜索、知识库、微信群聊总结和 Agent 助手。",
"keywords": [
@@ -60,20 +60,22 @@
"build": "npm run typecheck && electron-vite build",
"postinstall": "electron-builder install-app-deps && node scripts/prepare-electron-runtime.cjs && node scripts/ensure-electron-binary.cjs",
"build:unpack": "npm run build && electron-builder --config electron-builder.yml --dir",
"build:win": "npm run typecheck && npm run prepare:win-runtime && electron-vite build && electron-builder --config electron-builder.win.yml --win --x64",
"build:mac:arm64": "npm run typecheck && npm run prepare:ffmpeg:mac:arm64 && electron-vite build && electron-builder --config electron-builder.yml --mac --arm64",
"build:mac:arm64:send-runtime": "npm run typecheck && npm run prepare:ffmpeg:mac:arm64 && electron-vite build && cross-env TM_SEND_RUNTIME_BUILD=1 electron-builder --config electron-builder.send-runtime.yml --mac --arm64",
"build:win": "npm run build:templates && npm run typecheck && npm run prepare:win-runtime && electron-vite build && electron-builder --config electron-builder.win.yml --win --x64",
"build:mac:arm64": "npm run build:templates && npm run typecheck && npm run prepare:ffmpeg:mac:arm64 && electron-vite build && electron-builder --config electron-builder.yml --mac --arm64",
"build:mac:arm64:send-runtime": "npm run build:templates && npm run typecheck && npm run prepare:ffmpeg:mac:arm64 && electron-vite build && cross-env TM_SEND_RUNTIME_BUILD=1 electron-builder --config electron-builder.send-runtime.yml --mac --arm64",
"build:mac:public": "node scripts/build-macos-edition.cjs public",
"build:mac:native": "node scripts/build-macos-edition.cjs native",
"build:mac:x64": "npm run typecheck && npm run prepare:ffmpeg:mac:x64 && electron-vite build && electron-builder --config electron-builder.yml --mac --x64",
"build:mac:x64": "npm run build:templates && npm run typecheck && npm run prepare:ffmpeg:mac:x64 && electron-vite build && electron-builder --config electron-builder.yml --mac --x64",
"release": "npm run release:mac && npm run release:win",
"release:mac": "npm run typecheck && electron-vite build && npm run release:mac:arm64 && npm run release:mac:x64",
"release:mac:arm64": "npm run prepare:ffmpeg:mac:arm64 && electron-builder --config electron-builder.yml --mac --arm64 --publish always --config.directories.output=dist/release/mac-arm64",
"release:mac:x64": "npm run prepare:ffmpeg:mac:x64 && electron-builder --config electron-builder.yml --mac --x64 --publish always --config.directories.output=dist/release/mac-x64",
"release:win": "npm run typecheck && npm run prepare:win-runtime && electron-vite build && electron-builder --config electron-builder.win.yml --win --x64 --publish always",
"release:mac:arm64": "npm run build:templates && npm run prepare:ffmpeg:mac:arm64 && electron-builder --config electron-builder.yml --mac --arm64 --publish always --config.directories.output=dist/release/mac-arm64",
"release:mac:x64": "npm run build:templates && npm run prepare:ffmpeg:mac:x64 && electron-builder --config electron-builder.yml --mac --x64 --publish always --config.directories.output=dist/release/mac-x64",
"release:win": "npm run build:templates && npm run typecheck && npm run prepare:win-runtime && electron-vite build && electron-builder --config electron-builder.win.yml --win --x64 --publish always",
"release:beta": "cross-env EP_PRE_RELEASE=true npm run release",
"release:stable": "npm run release",
"build:linux": "electron-vite build && electron-builder --config electron-builder.yml --linux"
"build:linux": "electron-vite build && electron-builder --config electron-builder.yml --linux",
"build:templates": "node scripts/build-extension-templates.cjs",
"prebuild": "node scripts/build-extension-templates.cjs"
},
"dependencies": {
"@electron-toolkit/preload": "^3.0.2",
+27
View File
@@ -0,0 +1,27 @@
# @tracememo/extension-sdk
TraceMemo 扩展 SDK v1 的**类型定义**。运行期不需要安装或打包这个包:宿主在扩展后台进程里注入全局 `tm`。
## 用法
把 `index.d.ts` 复制进扩展仓库(或作为 devDependency),然后:
```ts
import type { TraceMemoApi } from './extension-sdk'
module.exports = function activate(tm: TraceMemoApi): void {
tm.events.on('message.received', async (event) => {
if (event.isSelf || event.type !== 'text') return
if (!event.text?.includes('你好')) return
await tm.wechat.send({ to: event.conversationId, text: '你好呀!', dedupeKey: event.eventId })
})
}
```
## 约定
- 所有能力都要在 `manifest.json` 里声明权限;未声明的调用返回 `PERMISSION_DENIED`。
- 后台是**独立 Node 子进程**,不是强沙箱:安装即表示信任该扩展代码。
- 页面运行在 `sandbox="allow-scripts"` 的 iframe 里,只能通过 postMessage 调用
`storage.*` / `capabilities.get` / `extension.info`,不能发送微信消息。
- 发送永远经过宿主 Gateway:权限、授权校验、限流、审计与幂等都在宿主侧执行。
+200
View File
@@ -0,0 +1,200 @@
/** TraceMemo 扩展 SDK v1:仅类型定义,运行期由宿主注入全局 tm。 */
export type ExtensionMessageType =
| 'text'
| 'image'
| 'voice'
| 'video'
| 'sticker'
| 'file'
| 'link'
| 'system'
| 'other'
export interface TraceMemoMessageEvent {
/** 同一条微信消息稳定不变:`message:<sha1(sessionId:localId)>`。 */
eventId: string
accountId: string
conversationId: string
messageId: string
senderId?: string
senderName?: string
isGroup: boolean
isSelf: boolean
type: ExtensionMessageType
text?: string
/** 真正 @ 到当前登录账号,不是正文里的 `@昵称`。 */
mentionsMe: boolean
/** epoch 毫秒。 */
timestamp: number
}
export interface TraceMemoQueriedMessage {
messageId: string
conversationId: string
senderId?: string
senderName?: string
isSelf: boolean
type: string
text?: string
/** epoch 毫秒。 */
timestamp: number
}
export interface TraceMemoSendTextRequest {
/** 缺省为 text。 */
type?: 'text'
/** 群为 `xxx@chatroom`,私聊为 wxid。 */
to: string
text: string
at?: Record<string, string>
/** 相同键的重复请求会被 Gateway 审计短路。 */
dedupeKey?: string
}
/** 图片发送。 */
export interface TraceMemoSendImageRequest {
type: 'image'
to: string
path: string
dedupeKey?: string
}
/** 视频发送。原生 Host 以 `{toWxid, type:'video', msg:<路径>}` 提交;路径必须位于扩展数据目录或系统临时目录。 */
export interface TraceMemoSendVideoRequest {
type: 'video'
to: string
path: string
dedupeKey?: string
}
export interface TraceMemoSendVoiceRequest {
type: 'voice'
to: string
/** 传 `text` 时由宿主使用已配置的文字转语音服务合成并发送。 */
text?: string
/** 传 `path` 时发送扩展数据目录或系统临时目录中的音频文件。 */
path?: string
/** 可选音色 ID;省略时使用 TraceMemo 设置页选定的默认音色。 */
voiceId?: string
dedupeKey?: string
}
export type TraceMemoSendRequest =
| TraceMemoSendTextRequest
| TraceMemoSendImageRequest
| TraceMemoSendVideoRequest
| TraceMemoSendVoiceRequest
export interface TraceMemoAutomationActionDefinition {
id: string
title: string
description?: string
inputSchema?: {
type: 'object'
properties?: Record<string, { type?: 'string' | 'number' | 'boolean'; description?: string }>
required?: string[]
}
handler: (input: Record<string, unknown>) => unknown | Promise<unknown>
}
export interface TraceMemoAutomationActionOutput {
success: boolean
output?: Record<string, unknown>
/** 宿主经 Gateway 发回原会话;扩展自己不发消息。 */
reply?: { type: 'text'; text: string; at?: Record<string, string> }
error?: string
}
export interface TraceMemoCapabilities {
extensionId: string
enabled: boolean
permissions: string[]
platform: string
databaseReady: boolean
send: {
supported: boolean
ready: boolean
canSendText: boolean
canSendImage: boolean
canSendVideo: boolean
canSendVoice?: boolean
licensed: boolean
message: string
}
ai: { configured: boolean; modelName: string }
tts?: {
configured: boolean
model: string
selectedVoiceId: string
selectedVoice: {
id: string
name: string
description: string
tags: string[]
languages: string[]
authorName?: string
previewUrl?: string
coverImage?: string
} | null
}
}
export interface TraceMemoApi {
extension: {
readonly id: string
/** 扩展私有数据目录;下载与生成的文件应放在这里。 */
readonly dataDir: string
readonly permissions: string[]
}
events: {
on(
name: 'message.received',
handler: (event: TraceMemoMessageEvent) => void | Promise<void>
): () => void
off(
name: 'message.received',
handler: (event: TraceMemoMessageEvent) => void | Promise<void>
): void
}
messages: {
query(request: {
conversationId: string
/** epoch 毫秒;默认最近 24 小时。 */
startTime?: number
/** epoch 毫秒;默认现在。 */
endTime?: number
limit?: number
}): Promise<{ messages: TraceMemoQueriedMessage[] }>
}
wechat: {
send(request: TraceMemoSendRequest): Promise<{ actionId: string; status: 'sent' }>
}
ai: {
chat(messages: Array<{ role: string; content: string }>): Promise<{ text: string }>
}
storage: {
get(key: string): Promise<unknown>
set(key: string, value: unknown): Promise<void>
remove(key: string): Promise<boolean>
list(): Promise<Array<{ key: string; value: unknown }>>
}
automation: {
registerAction(definition: TraceMemoAutomationActionDefinition): void
}
capabilities: {
get(): Promise<TraceMemoCapabilities>
}
log: {
info(message: unknown): void
warn(message: unknown): void
error(message: unknown): void
}
}
/** 后台入口签名。 */
export type TraceMemoActivate = (tm: TraceMemoApi) => void | Promise<void>
declare global {
var tm: TraceMemoApi
}
+9
View File
@@ -0,0 +1,9 @@
{
"name": "@tracememo/extension-sdk",
"version": "1.0.0",
"private": true,
"description": "TraceMemo 扩展 SDK 的类型定义(v1)。运行期由宿主注入 tm 对象,无需打包进扩展。",
"types": "index.d.ts",
"files": ["index.d.ts", "README.md"],
"license": "MIT"
}
Binary file not shown.

Before

Width:  |  Height:  |  Size: 153 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 478 KiB

+58 -1
View File
@@ -417,6 +417,7 @@ function isMacosCodeValid(targetPath, run = runCodesign) {
function findMacosHelperPaths(runtimeResources) {
const paths = MACOS_HELPER_NAMES.map((name) => path.join(runtimeResources, 'resources', name))
paths.push(path.join(runtimeResources, 'runtime', 'darwin-arm64', 'tm-wechat-host'))
if (process.env.TRACEMEMO_EDITION) {
paths.push(...MACOS_EDITION_CODE_PATHS.map((segments) => path.join(runtimeResources, 'resources', ...segments)))
}
@@ -427,7 +428,8 @@ function signMacosHelpers(runtimeResources, run = runCodesign) {
const helperPaths = findMacosHelperPaths(runtimeResources)
for (const helperPath of helperPaths) {
if (!helperPath.endsWith('.dylib')) chmodSync(helperPath, 0o755)
if (!isMacosCodeValid(helperPath, run)) {
const runtimeHost = path.basename(helperPath) === 'tm-wechat-host'
if (runtimeHost || !isMacosCodeValid(helperPath, run)) {
run(['--force', '--sign', '-', helperPath])
}
const architectures = readBinaryArchitectures(helperPath)
@@ -766,6 +768,60 @@ function enforceSendRuntimeBoundary(
return null
}
/**
* 官方模板资源必须随包发布,且索引与 ZIP 的哈希一致。
*
* 这一层挡的是「打包时忘了跑构建脚本」:没有它,安装包会静默少两个模板,
* 而用户看到的只是空列表。
*/
function validateExtensionTemplates(runtimeResources) {
const root = path.join(runtimeResources, 'extension-templates')
const indexPath = path.join(root, 'index.json')
if (!existsSync(indexPath)) {
throw new Error(
'Missing extension templates: ' +
indexPath +
'. Run `node scripts/build-extension-templates.cjs` before packaging.'
)
}
let index
try {
index = JSON.parse(readFileSync(indexPath, 'utf8'))
} catch (error) {
throw new Error('Invalid extension template index: ' + error.message)
}
if (!index || index.version !== 1 || !Array.isArray(index.templates)) {
throw new Error('Invalid extension template index structure')
}
if (index.templates.length === 0) {
throw new Error('Extension template index is empty')
}
for (const template of index.templates) {
const fileName = String(template.file || '')
if (!fileName || fileName.includes('/') || fileName.includes('\\')) {
throw new Error('Invalid extension template file name: ' + fileName)
}
const zipPath = path.join(root, fileName)
if (!existsSync(zipPath)) {
throw new Error('Missing extension template archive: ' + fileName)
}
const digest = createHash('sha256').update(readFileSync(zipPath)).digest('hex')
if (digest !== template.sha256) {
throw new Error(
'Extension template checksum mismatch: ' +
fileName +
' (index=' +
template.sha256 +
', actual=' +
digest +
')'
)
}
}
console.log('[afterPack] extension templates verified: ' + index.templates.length)
}
exports.default = async function afterPack(context) {
const runtimeResources = getRuntimeResources(context)
const arch = normalizeBuilderArch(context.arch)
@@ -780,6 +836,7 @@ exports.default = async function afterPack(context) {
}
validateAsarRuntimeDependencies(runtimeResources)
validateReaderSkillRuntime(runtimeResources)
validateExtensionTemplates(runtimeResources)
validateSilkWasmRuntime(runtimeResources)
const ffmpegPath = validateFfmpegRuntime(runtimeResources, context.electronPlatformName)
validateElectronMainBinary(
+410
View File
@@ -0,0 +1,410 @@
#!/usr/bin/env node
/* eslint-disable @typescript-eslint/no-require-imports, @typescript-eslint/explicit-function-return-type */
/** 把官方模板打成确定性 ZIP 并生成索引;手写 ZIP 才能固定时间戳、权限与条目顺序。 */
const fs = require('node:fs')
const path = require('node:path')
const zlib = require('node:zlib')
const crypto = require('node:crypto')
const ROOT = path.resolve(__dirname, '..')
const SOURCE_ROOT = path.join(ROOT, 'examples', 'extensions')
const OUTPUT_DIR = path.join(ROOT, 'build', 'extension-templates')
const LOCK_FILE = path.join(SOURCE_ROOT, 'template-lock.json')
/** 模板白名单:只有显式登记的目录才进包,避免新增目录被静默发布。 */
const TEMPLATE_SPECS = [
{
id: 'keyword-bot',
dir: 'keyword-bot',
requires: {
python: false,
chrome: false,
externalScript: false
},
platforms: ['darwin', 'win32']
},
{
id: 'group-chat-bot',
dir: 'group-chat-bot',
requires: {
python: false,
chrome: false,
externalScript: false
},
platforms: ['darwin', 'win32']
},
{
id: 'douyin-sender',
dir: 'douyin-sender',
requires: {
python: { required: true, minVersion: '3.10', reason: '解析与下载依赖本机 Python 脚本' },
chrome: { required: true, reason: '解析脚本通过本机 Chrome 读取页面' },
externalScript: {
required: true,
path: 'scripts/douyin.py',
reason: '解析脚本不随应用分发,需用户自行提供后才能处理视频'
}
},
platforms: ['darwin', 'win32']
}
]
/** 与安装器保持同一套路径规则:任何一段越界或不合法都会让安装失败。 */
const SAFE_SEGMENT = /^[A-Za-z0-9._@+\- ]+$/
const RESERVED_SEGMENT = /^(con|prn|aux|nul|com\d|lpt\d)(\.|$)/i
const EXCLUDED_DIRECTORIES = new Set([
'.git',
'.hg',
'.svn',
'node_modules',
'__pycache__',
'.venv',
'venv',
'tests',
'coverage'
])
const EXCLUDED_FILES = new Set(['.DS_Store', 'Thumbs.db'])
/** 即使本机存在也不进包:来源与分发许可未确认,或属于本机私有脚本。 */
const EXCLUDED_RELATIVE_PATHS = new Set(['scripts/douyin.py', 'lib/bot-engine.js'])
const EXCLUDED_EXTENSIONS = new Set(['.pyc', '.log', '.env', '.local'])
const CRC_TABLE = (() => {
const table = new Uint32Array(256)
for (let index = 0; index < 256; index += 1) {
let value = index
for (let bit = 0; bit < 8; bit += 1) {
value = value & 1 ? 0xedb88320 ^ (value >>> 1) : value >>> 1
}
table[index] = value >>> 0
}
return table
})()
function crc32(buffer) {
let crc = 0xffffffff
for (const byte of buffer) crc = CRC_TABLE[(crc ^ byte) & 0xff] ^ (crc >>> 8)
return (crc ^ 0xffffffff) >>> 0
}
/** 归一化 CRLF:Windows 检出与 macOS 基线必须产出同一份字节,否则 sha256 必然不匹配。 */
function normalizeLineEndings(buffer) {
if (buffer.includes(0)) return buffer
if (!buffer.includes(0x0d)) return buffer
return Buffer.from(buffer.toString('latin1').replace(/\r\n/g, '\n'), 'latin1')
}
function isSafeRelativePath(value) {
if (typeof value !== 'string' || !value || value.length > 240) return false
if (value.includes('\0')) return false
const segments = value.split('/')
if (segments.length > 10) return false
for (const segment of segments) {
if (!segment || segment === '.' || segment === '..') return false
if (segment.length > 64) return false
if (!SAFE_SEGMENT.test(segment)) return false
if (/[. ]$/.test(segment)) return false
if (RESERVED_SEGMENT.test(segment)) return false
}
return true
}
/** 收集模板文件。 */
function collectTemplateFiles(spec, sourceRoot = SOURCE_ROOT) {
const root = path.join(sourceRoot, spec.dir)
if (!fs.existsSync(root)) {
throw new Error(`模板目录不存在:${spec.dir}`)
}
const files = []
const walk = (directory, prefix) => {
for (const entry of fs
.readdirSync(directory, { withFileTypes: true })
.sort((a, b) => a.name.localeCompare(b.name))) {
if (entry.isSymbolicLink()) {
throw new Error(`模板目录不能包含符号链接:${prefix}${entry.name}`)
}
if (entry.isDirectory()) {
if (EXCLUDED_DIRECTORIES.has(entry.name)) continue
walk(path.join(directory, entry.name), `${prefix}${entry.name}/`)
continue
}
if (!entry.isFile()) continue
if (EXCLUDED_FILES.has(entry.name)) continue
if (EXCLUDED_EXTENSIONS.has(path.extname(entry.name).toLowerCase())) continue
const relative = `${prefix}${entry.name}`
if (EXCLUDED_RELATIVE_PATHS.has(relative)) continue
if (!isSafeRelativePath(relative)) {
throw new Error(`模板内文件路径不合法:${spec.dir}/${relative}`)
}
files.push({
path: relative,
data: normalizeLineEndings(fs.readFileSync(path.join(directory, entry.name)))
})
}
}
walk(root, '')
return files.sort((left, right) => left.path.localeCompare(right.path))
}
function validateManifest(spec, files) {
const manifestFile = files.find((file) => file.path === 'manifest.json')
if (!manifestFile) throw new Error(`模板 ${spec.id} 缺少 manifest.json`)
let manifest
try {
manifest = JSON.parse(manifestFile.data.toString('utf8'))
} catch {
throw new Error(`模板 ${spec.id} 的 manifest.json 不是合法 JSON`)
}
const idPattern =
/^[a-z0-9](?:[a-z0-9-]{0,38}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,38}[a-z0-9])?)+$/
if (manifest.manifestVersion !== 1) throw new Error(`模板 ${spec.id} 的 manifestVersion 必须是 1`)
if (!idPattern.test(String(manifest.id || ''))) {
throw new Error(`模板 ${spec.id} 的 id 不是反向域名格式`)
}
if (
!/^\d{1,4}\.\d{1,4}\.\d{1,4}(?:-[0-9A-Za-z.-]{1,40})?$/.test(String(manifest.version || ''))
) {
throw new Error(`模板 ${spec.id} 的 version 不是 x.y.z 格式`)
}
const names = new Set(files.map((file) => file.path))
const entrypoints = manifest.entrypoints || {}
for (const [key, value] of Object.entries(entrypoints)) {
if (!value) continue
if (!names.has(value)) {
throw new Error(`模板 ${spec.id} 的入口 ${key} 指向不存在的文件:${value}`)
}
}
if (!entrypoints.page && !entrypoints.background) {
throw new Error(`模板 ${spec.id} 至少需要一个页面或后台入口`)
}
return manifest
}
/** 固定时间戳(1980-01-01 00:00)与权限,保证相同内容得到相同字节。 */
const DOS_TIME = 0
const DOS_DATE = 0x21
function buildZip(entries) {
const locals = []
const centrals = []
let offset = 0
for (const entry of entries) {
const name = Buffer.from(entry.path, 'utf8')
const data = entry.data
const compressed = zlib.deflateRawSync(data, { level: 9 })
const checksum = crc32(data)
const local = Buffer.alloc(30)
local.writeUInt32LE(0x04034b50, 0)
local.writeUInt16LE(20, 4)
local.writeUInt16LE(0x0800, 6) // UTF-8 文件名
local.writeUInt16LE(8, 8) // deflate
local.writeUInt16LE(DOS_TIME, 10)
local.writeUInt16LE(DOS_DATE, 12)
local.writeUInt32LE(checksum, 14)
local.writeUInt32LE(compressed.length, 18)
local.writeUInt32LE(data.length, 22)
local.writeUInt16LE(name.length, 26)
local.writeUInt16LE(0, 28)
locals.push(local, name, compressed)
const central = Buffer.alloc(46)
central.writeUInt32LE(0x02014b50, 0)
central.writeUInt16LE(20, 4)
central.writeUInt16LE(20, 6)
central.writeUInt16LE(0x0800, 8)
central.writeUInt16LE(8, 10)
central.writeUInt16LE(DOS_TIME, 12)
central.writeUInt16LE(DOS_DATE, 14)
central.writeUInt32LE(checksum, 16)
central.writeUInt32LE(compressed.length, 20)
central.writeUInt32LE(data.length, 24)
central.writeUInt16LE(name.length, 28)
central.writeUInt16LE(0, 30)
central.writeUInt16LE(0, 32)
central.writeUInt16LE(0, 34)
central.writeUInt16LE(0, 36)
central.writeUInt32LE((0o100644 << 16) >>> 0, 38)
central.writeUInt32LE(offset, 42)
centrals.push(central, name)
offset += local.length + name.length + compressed.length
}
const centralBuffer = Buffer.concat(centrals)
const end = Buffer.alloc(22)
end.writeUInt32LE(0x06054b50, 0)
end.writeUInt16LE(entries.length, 8)
end.writeUInt16LE(entries.length, 10)
end.writeUInt32LE(centralBuffer.length, 12)
end.writeUInt32LE(offset, 16)
return Buffer.concat([...locals, centralBuffer, end])
}
function sha256(buffer) {
return crypto.createHash('sha256').update(buffer).digest('hex')
}
function readLock(lockFile = LOCK_FILE) {
try {
const parsed = JSON.parse(fs.readFileSync(lockFile, 'utf8'))
if (!parsed || typeof parsed !== 'object') return { version: 1, templates: {} }
return { version: 1, templates: parsed.templates || {} }
} catch {
return { version: 1, templates: {} }
}
}
function writeLock(lock, lockFile = LOCK_FILE) {
const sorted = { version: 1, templates: {} }
for (const key of Object.keys(lock.templates).sort()) {
sorted.templates[key] = lock.templates[key]
}
fs.writeFileSync(lockFile, `${JSON.stringify(sorted, null, 2)}\n`, 'utf8')
}
/** 构建入口。 */
function buildTemplates(options = {}) {
const updateLock = options.updateLock === true
const checkOnly = options.check === true
const sourceRoot = options.sourceRoot || SOURCE_ROOT
const outputDir = options.outputDir || OUTPUT_DIR
const lockFile = options.lockFile || LOCK_FILE
const specs = options.specs || TEMPLATE_SPECS
const lock = readLock(lockFile)
const templates = []
const warnings = []
const seenIds = new Set()
const seenTemplateIds = new Set()
for (const spec of specs) {
if (seenTemplateIds.has(spec.id)) {
throw new Error(`模板 id 重复:${spec.id}`)
}
seenTemplateIds.add(spec.id)
const files = collectTemplateFiles(spec, sourceRoot)
if (!files.length) throw new Error(`模板 ${spec.id} 没有任何文件`)
const manifest = validateManifest(spec, files)
if (seenIds.has(manifest.id)) {
throw new Error(`模板扩展 id 重复:${manifest.id}`)
}
seenIds.add(manifest.id)
const zip = buildZip(files)
const digest = sha256(zip)
const fileName = `${spec.id}-${manifest.version}.zip`
const lockKey = `${spec.id}@${manifest.version}`
const previous = lock.templates[lockKey]
if (previous && previous.sha256 !== digest && !updateLock) {
throw new Error(
`模板 ${spec.id} 的版本仍为 ${manifest.version},但内容已变化。` +
`请升级 manifest.version,或确认后用 --update-lock 更新基线。`
)
}
if (!previous) {
// 新版本(或首次构建):允许,并把基线更新到当前内容。
lock.templates[lockKey] = { sha256: digest, bytes: zip.length }
} else if (updateLock) {
lock.templates[lockKey] = { sha256: digest, bytes: zip.length }
}
// 缺少外部脚本的模板必须显式标记,不能对外宣称开箱即用。
const externalScript = spec.requires.externalScript
if (externalScript && externalScript.required) {
const present = files.some((file) => file.path === externalScript.path)
if (present) {
warnings.push(
`模板 ${spec.id} 的依赖脚本 ${externalScript.path} 意外进入了发布包,请检查排除规则`
)
}
}
templates.push({
templateId: spec.id,
extensionId: manifest.id,
name: String(manifest.name || spec.id),
version: String(manifest.version),
...(manifest.description ? { description: String(manifest.description) } : {}),
permissions: Array.isArray(manifest.permissions) ? manifest.permissions : [],
file: fileName,
sha256: digest,
bytes: zip.length,
fileCount: files.length,
platforms: spec.platforms,
requires: spec.requires,
zip
})
}
if (!checkOnly) {
fs.mkdirSync(outputDir, { recursive: true })
// 删掉不属于本次产物的旧 ZIP,避免「旧版本文件还在、索引却指向新版本」。
const keep = new Set(templates.map((template) => template.file))
for (const name of fs.readdirSync(outputDir)) {
if (!name.endsWith('.zip')) continue
if (keep.has(name)) continue
fs.unlinkSync(path.join(outputDir, name))
}
for (const template of templates) {
fs.writeFileSync(path.join(outputDir, template.file), template.zip)
}
const index = {
version: 1,
templates: templates.map((template) => {
const copy = { ...template }
delete copy.zip
return copy
})
}
fs.writeFileSync(
path.join(outputDir, 'index.json'),
`${JSON.stringify(index, null, 2)}\n`,
'utf8'
)
writeLock(lock, lockFile)
}
return {
templates: templates.map((template) => {
const copy = { ...template }
delete copy.zip
return copy
}),
warnings
}
}
function main() {
const argv = process.argv.slice(2)
const updateLock = argv.includes('--update-lock')
const checkOnly = argv.includes('--check')
try {
const result = buildTemplates({ updateLock, checkOnly })
for (const template of result.templates) {
console.log(
`[templates] ${template.templateId} ${template.version} ` +
`${template.fileCount} files ${(template.bytes / 1024).toFixed(1)}KB ${template.sha256.slice(0, 12)}`
)
}
for (const warning of result.warnings) {
console.error(`[templates] WARN ${warning}`)
}
console.log(`[templates] 输出目录 ${path.relative(ROOT, OUTPUT_DIR)}`)
} catch (error) {
console.error(`[templates] ${error instanceof Error ? error.message : String(error)}`)
process.exit(1)
}
}
if (require.main === module) main()
module.exports = {
buildTemplates,
buildZip,
collectTemplateFiles,
TEMPLATE_SPECS,
OUTPUT_DIR,
LOCK_FILE
}
+1
View File
@@ -60,6 +60,7 @@ function createBuilderConfig({ edition, stageRoot, buildOutput, outputRoot, appV
],
extraResources: [
{ from: path.join(stageRoot, 'resources'), to: 'resources', filter: ['**/*'] },
{ from: path.join(ROOT, 'build/extension-templates'), to: 'extension-templates', filter: ['**/*'] },
{ from: path.join(ROOT, 'build/app-update.yml'), to: 'app-update.yml' },
{
from: path.join(ROOT, 'docs/skill/tracememo-reader'),
+51 -1
View File
@@ -83,7 +83,57 @@ function prepareFfmpegRuntime(targetPlatform = process.platform, targetArch = pr
fs.chmodSync(ffmpegPath, 0o755)
if (process.platform === 'darwin') {
execFileSync('/usr/bin/codesign', ['--force', '--sign', '-', ffmpegPath], { stdio: 'ignore' })
assertMachOIntact(ffmpegPath)
try {
execFileSync('/usr/bin/codesign', ['--force', '--sign', '-', ffmpegPath], {
stdio: ['ignore', 'pipe', 'pipe']
})
} catch (error) {
const detail = error?.stderr?.toString?.().trim() || error.message
throw new Error(
'codesign 失败:' +
detail +
'\n最常见原因:ffmpeg-static 下载被截断,文件不完整。' +
'\n处理:删除 ' +
ffmpegPath +
' 后重跑本命令;网络不稳时先用 curl -C - 把 .gz 补齐再解压。'
)
}
}
}
/**
* 截断的 Mach-O 能被 file 认出来,却签不了名,也跑不起来。
* otool 解析 load command,截断会直接失败——比事后读 codesign 的天书便宜。
*/
function assertMachOIntact(ffmpegPath) {
let listing = ''
try {
listing = execFileSync('/usr/bin/otool', ['-l', ffmpegPath], {
encoding: 'utf8',
maxBuffer: 16 * 1024 * 1024
})
} catch {
throw new Error(
'ffmpeg 二进制无法解析(下载不完整):' + ffmpegPath + '\n处理:删除该文件后重跑本命令。'
)
}
// otool 对超出文件末尾的段会标 "(past end of file)":下载被截断的确凿信号。
if (listing.includes('past end of file')) {
throw new Error(
'ffmpeg 二进制被截断(下载不完整):' +
ffmpegPath +
'\n处理:删除该文件后重跑本命令;网络不稳时先用 curl -C - 把 .gz 补齐再解压。'
)
}
let kind = ''
try {
kind = execFileSync('/usr/bin/file', ['-b', ffmpegPath], { encoding: 'utf8' })
} catch {
kind = ''
}
if (!kind.includes('Mach-O')) {
throw new Error('ffmpeg 不是 Mach-O 可执行文件:' + ffmpegPath)
}
}
@@ -0,0 +1,156 @@
import type { ExtensionAutomationActionContribution } from '../../shared/extensions/manifest'
import type { ExtensionAutomationActionSummary } from '../../shared/extensions/types'
import type { ExtensionActionInputSchema } from '../../shared/extensions/action-schema'
export interface RegisteredExtensionAction {
extensionId: string
extensionName: string
actionId: string
title: string
description?: string
/** 后台进程是否真的注册了这个动作。 */
registered: boolean
/** manifest 是否声明了它(声明了但没注册 = 扩展代码有问题)。 */
declared: boolean
inputSchema?: ExtensionActionInputSchema
/** Schema 校验失败的原因;有值时动作不可配置。 */
schemaError?: string
}
/**
* 扩展贡献的自动化动作注册表。
*
* 两个来源刻意分开记:
* - `declared`:manifest 里写了什么 —— 用于在规则编辑器里展示「这个扩展提供了哪些动作」;
* - `registered`:后台进程运行期真正注册了什么 —— 只有它能被执行。
*
* 二者不一致时**不猜**:动作在界面上显示为不可用,规则执行时明确报错。
*/
export class ExtensionActionRegistry {
private readonly registered = new Map<
string,
Map<
string,
{
title: string
description?: string
inputSchema?: ExtensionActionInputSchema
schemaError?: string
}
>
>()
private readonly declared = new Map<
string,
{ name: string; actions: ExtensionAutomationActionContribution[] }
>()
private readonly names = new Map<string, string>()
setDeclared(
extensionId: string,
extensionName: string,
actions: ExtensionAutomationActionContribution[]
): void {
this.names.set(extensionId, extensionName)
this.declared.set(extensionId, { name: extensionName, actions: [...actions] })
}
setRegistered(
extensionId: string,
extensionName: string,
actions: Array<{
id: string
title: string
description?: string
inputSchema?: ExtensionActionInputSchema
schemaError?: string
}>
): void {
this.names.set(extensionId, extensionName)
this.registered.set(
extensionId,
new Map(
actions.map((action) => [
action.id,
{
title: action.title,
...(action.description ? { description: action.description } : {}),
...(action.inputSchema ? { inputSchema: action.inputSchema } : {}),
...(action.schemaError ? { schemaError: action.schemaError } : {})
}
])
)
)
}
remove(extensionId: string): void {
this.registered.delete(extensionId)
this.declared.delete(extensionId)
this.names.delete(extensionId)
}
removeRuntime(extensionId: string): void {
this.registered.delete(extensionId)
}
isRegistered(extensionId: string, actionId: string): boolean {
return this.registered.get(extensionId)?.has(actionId) === true
}
get(extensionId: string, actionId: string): RegisteredExtensionAction | undefined {
const declaredAction = this.declared
.get(extensionId)
?.actions.find((action) => action.id === actionId)
const runtime = this.registered.get(extensionId)?.get(actionId)
if (!declaredAction && !runtime) return undefined
return {
extensionId,
extensionName: this.names.get(extensionId) || extensionId,
actionId,
title: runtime?.title || declaredAction?.title || actionId,
...(runtime?.description || declaredAction?.description
? { description: runtime?.description || declaredAction?.description }
: {}),
registered: Boolean(runtime),
declared: Boolean(declaredAction),
...(runtime?.inputSchema ? { inputSchema: runtime.inputSchema } : {}),
...(runtime?.schemaError ? { schemaError: runtime.schemaError } : {})
}
}
list(): RegisteredExtensionAction[] {
const result: RegisteredExtensionAction[] = []
const extensionIds = new Set([...this.declared.keys(), ...this.registered.keys()])
for (const extensionId of extensionIds) {
const declaredActions = this.declared.get(extensionId)?.actions ?? []
const runtimeActions = this.registered.get(extensionId) ?? new Map()
const ids = new Set([...declaredActions.map((action) => action.id), ...runtimeActions.keys()])
for (const actionId of ids) {
const action = this.get(extensionId, actionId)
if (action) result.push(action)
}
}
return result.sort((left, right) => {
if (left.extensionName !== right.extensionName)
return left.extensionName.localeCompare(right.extensionName)
return left.title.localeCompare(right.title)
})
}
summariesFor(extensionId: string): ExtensionAutomationActionSummary[] {
const declaredActions = this.declared.get(extensionId)?.actions ?? []
const runtimeActions = this.registered.get(extensionId) ?? new Map()
const ids = new Set([...declaredActions.map((action) => action.id), ...runtimeActions.keys()])
return Array.from(ids).map((actionId) => {
const declaredAction = declaredActions.find((action) => action.id === actionId)
const runtime = runtimeActions.get(actionId)
return {
id: actionId,
title: runtime?.title || declaredAction?.title || actionId,
...(runtime?.description || declaredAction?.description
? { description: runtime?.description || declaredAction?.description }
: {}),
registered: Boolean(runtime)
}
})
}
}
@@ -0,0 +1,45 @@
import { ExtensionError } from '../../shared/extensions/errors'
import { hasExtensionPermission } from '../../shared/extensions/permissions'
import type { ExtensionAutomationActionOutput } from '../../shared/extensions/rpc'
import type { ExtensionMessageEvent } from '../../shared/extensions/events'
import { getExtensionManager, hasExtensionManager } from './extension-service'
export interface ExtensionActionContext {
conversationId: string
isGroup: boolean
accountId: string
message?: ExtensionMessageEvent
}
/**
* 自动化 → 扩展动作的桥。
*
* 输入里的 `conversationId` / `accountId` / `message` 是**宿主注入的运行时上下文**,
* 与用户在规则里配置的静态 `input` 合并;同名键以宿主值为准,扩展不能靠配置
* 伪造一个假的会话或账号。
*/
export async function invokeExtensionAction(
extensionId: string,
actionId: string,
input: Record<string, unknown>,
context: ExtensionActionContext
): Promise<ExtensionAutomationActionOutput> {
if (!hasExtensionManager()) {
throw new ExtensionError('EXTENSION_HOST_UNAVAILABLE', '扩展系统尚未初始化')
}
const runtimeInput: Record<string, unknown> = {
...input,
conversationId: context.conversationId,
isGroup: context.isGroup,
accountId: context.accountId,
...(context.message ? { message: context.message } : {})
}
return getExtensionManager().invokeAutomationAction(extensionId, actionId, runtimeInput)
}
export function canExtensionSendText(extensionId: string): boolean {
if (!hasExtensionManager()) return false
const extension = getExtensionManager().get(extensionId)
if (!extension?.enabled) return false
return hasExtensionPermission(extension.grantedPermissions, 'wechat.send.text')
}
@@ -0,0 +1,124 @@
import { createHash } from 'node:crypto'
import fs from 'node:fs'
import path from 'node:path'
/** 与安装器的排除规则保持一致:这些目录不属于扩展产物。 */
const DEFAULT_IGNORED_DIRECTORIES = new Set([
'.git',
'.hg',
'.svn',
'node_modules',
'__pycache__',
'.venv',
'venv'
])
const DEFAULT_IGNORED_FILES = new Set(['.DS_Store', 'Thumbs.db'])
const IGNORED_EXTENSIONS = new Set(['.pyc', '.log'])
export interface CodeDigestOptions {
ignoreDirectories?: Iterable<string>
ignoreFiles?: Iterable<string>
}
interface DigestEntry {
path: string
sha256: string
}
/**
* 计算一个目录的代码指纹。
*
* 只覆盖**代码与静态资源**:不包含 `extensions-data`、日志或缓存,
* 所以用户改配置不会让指纹变化,改一行 JS 就会。
*
* 细则:
* - 相对路径参与哈希,因此改名与改内容都能被发现;
* - 文件按路径排序后再累加,结果与遍历顺序无关;
* - 符号链接按链接目标字符串参与哈希,不跟随(避免读到宿主私有文件)。
*/
export function computeDirectoryDigest(root: string, options: CodeDigestOptions = {}): string {
const ignoreDirectories = new Set([
...DEFAULT_IGNORED_DIRECTORIES,
...(options.ignoreDirectories ?? [])
])
const ignoreFiles = new Set([...DEFAULT_IGNORED_FILES, ...(options.ignoreFiles ?? [])])
const entries: DigestEntry[] = []
const walk = (directory: string, prefix: string): void => {
let items: fs.Dirent[]
try {
items = fs.readdirSync(directory, { withFileTypes: true })
} catch {
return
}
for (const item of items) {
if (item.isDirectory()) {
if (ignoreDirectories.has(item.name)) continue
walk(path.join(directory, item.name), prefix ? `${prefix}/${item.name}` : item.name)
continue
}
if (ignoreFiles.has(item.name)) continue
if (IGNORED_EXTENSIONS.has(path.extname(item.name).toLowerCase())) continue
const relative = prefix ? `${prefix}/${item.name}` : item.name
const absolute = path.join(directory, item.name)
if (item.isSymbolicLink()) {
try {
const target = fs.readlinkSync(absolute)
entries.push({
path: relative,
sha256: createHash('sha256').update(`link:${target}`).digest('hex')
})
} catch {
entries.push({ path: relative, sha256: 'link:unreadable' })
}
continue
}
if (!item.isFile()) continue
try {
const content = fs.readFileSync(absolute)
entries.push({
path: relative,
sha256: createHash('sha256').update(content).digest('hex')
})
} catch {
// 读不到的文件不应让整个指纹失效,但必须留下痕迹。
entries.push({ path: relative, sha256: 'unreadable' })
}
}
}
walk(root, '')
entries.sort((left, right) => left.path.localeCompare(right.path))
const hash = createHash('sha256')
for (const entry of entries) {
hash.update(`${entry.path}\0${entry.sha256}\n`)
}
return hash.digest('hex')
}
/** 列出参与指纹的文件数量;用于诊断「是不是把缓存算进去了」。 */
export function countDigestFiles(root: string): number {
let count = 0
const walk = (directory: string): void => {
let items: fs.Dirent[]
try {
items = fs.readdirSync(directory, { withFileTypes: true })
} catch {
return
}
for (const item of items) {
if (item.isDirectory()) {
if (DEFAULT_IGNORED_DIRECTORIES.has(item.name)) continue
walk(path.join(directory, item.name))
continue
}
if (DEFAULT_IGNORED_FILES.has(item.name)) continue
if (IGNORED_EXTENSIONS.has(path.extname(item.name).toLowerCase())) continue
count += 1
}
}
walk(root)
return count
}
@@ -0,0 +1,74 @@
import { mapLicenseStatus, probeLicenseStatus } from '../services/msg-insert-capability-service'
import { macWechatRuntimeManager } from '../services/mac-wechat-runtime-manager'
export interface ExtensionEntitlementResult {
ok: boolean
message: string
source: 'mac_license' | 'hook_license' | 'unsupported'
}
export interface ExtensionEntitlementDependencies {
platform?: NodeJS.Platform
getMacLicense?: () => Promise<{ authorized: boolean; message?: string }>
probeLicense?: () => Promise<{ ok: boolean; status?: string }>
}
/**
* 扩展发送的 授权校验。
*
* 只在主进程可信边界调用,且**不接受渲染层 / 扩展传入的任何布尔值**:
* - macOS:读 Native Runtime 的 license 状态,要求 `authorized === true`;
* - Windows:探测本机 Hook 的 `/license/status`,只接受 `LICENSE_OK`。
*
* 与「发送能力 ready」是两件事:能力 ready 只说明本机装好了 Runtime,
* 不代表授权有效。
*/
export async function checkExtensionSendEntitlement(
dependencies: ExtensionEntitlementDependencies = {}
): Promise<ExtensionEntitlementResult> {
const platform = dependencies.platform ?? process.platform
if (platform === 'darwin') {
try {
const status = dependencies.getMacLicense
? await dependencies.getMacLicense()
: await macWechatRuntimeManager.getMacLicenseStatus()
if (status.authorized) {
return { ok: true, message: '授权有效', source: 'mac_license' }
}
return {
ok: false,
message: status.message || '需要有效授权才能由扩展发送消息',
source: 'mac_license'
}
} catch (error) {
return {
ok: false,
message: error instanceof Error ? error.message : '无法确认授权状态',
source: 'mac_license'
}
}
}
if (platform === 'win32') {
try {
const probe = dependencies.probeLicense
? await dependencies.probeLicense()
: await probeLicenseStatus()
if (!probe.ok) {
return { ok: false, message: '无法确认授权状态', source: 'hook_license' }
}
const mapped = mapLicenseStatus(probe.status)
return {
ok: mapped.entitlement === 'valid',
message: mapped.message,
source: 'hook_license'
}
} catch (error) {
return {
ok: false,
message: error instanceof Error ? error.message : '无法确认授权状态',
source: 'hook_license'
}
}
}
return { ok: false, message: '当前平台不支持微信发送', source: 'unsupported' }
}
+135
View File
@@ -0,0 +1,135 @@
import { createHash } from 'node:crypto'
import type { ExtensionEventEnvelope } from '../../shared/extensions/events'
import {
buildExtensionMessageEvent,
EXTENSION_EVENT_PROTOCOL_VERSION,
shouldDeliverExtensionEvent,
type ExtensionMessageEvent
} from '../../shared/extensions/events'
import type { ExtensionSubscriptions } from '../../shared/extensions/manifest'
import type { NormalizedIncomingMessage } from '../services/message-listener-service'
const DEDUPE_TTL_MS = 10 * 60 * 1000
const DEDUPE_MAX_ENTRIES = 5_000
export interface ExtensionEventSubscriber {
extensionId: string
subscriptions: ExtensionSubscriptions | undefined
deliver: (envelope: ExtensionEventEnvelope) => boolean
}
export interface ExtensionEventBusDependencies {
listSubscribers: () => ExtensionEventSubscriber[]
getAccountId: () => string
getSelfUsernames: () => string[]
now?: () => number
onDelivered?: (extensionId: string, event: ExtensionMessageEvent) => void
}
export interface ExtensionEventBusStats {
received: number
deduped: number
delivered: number
dropped: number
}
/**
* 把 MessageListener 的规范化消息分发给扩展。
*
* 去重键 `sessionId:localId`,扩展侧独立保留一层,避免进程重启后补投重复;
* 旧 Runtime 只能回读最近活跃会话,能力诊断会如实标记降级。
*/
export class ExtensionEventBus {
private readonly seen = new Map<string, number>()
private readonly now: () => number
private accountId = ''
private counters: ExtensionEventBusStats = { received: 0, deduped: 0, delivered: 0, dropped: 0 }
constructor(private readonly dependencies: ExtensionEventBusDependencies) {
this.now = dependencies.now ?? (() => Date.now())
}
/** 切换账号时清空去重表:旧账号的 localId 不能在新账号下命中。 */
setAccountId(accountId: string): void {
const next = String(accountId || '').trim()
if (next === this.accountId) return
this.accountId = next
this.seen.clear()
}
stats(): ExtensionEventBusStats {
return { ...this.counters }
}
/** 入口**绝不抛**:它挂在 MessageListener 的投递循环上。 */
handleMessage(message: NormalizedIncomingMessage): void {
try {
this.counters.received += 1
const eventId = buildEventId(message.sessionId, message.localId)
if (!this.markSeen(eventId)) {
this.counters.deduped += 1
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 envelope: ExtensionEventEnvelope = {
version: EXTENSION_EVENT_PROTOCOL_VERSION,
kind: 'message.received',
event
}
for (const subscriber of this.dependencies.listSubscribers()) {
if (!shouldDeliverExtensionEvent(subscriber.subscriptions, event)) continue
if (subscriber.deliver(envelope)) {
this.counters.delivered += 1
this.dependencies.onDelivered?.(subscriber.extensionId, event)
} else {
this.counters.dropped += 1
}
}
} catch (error) {
console.warn(
`[ExtensionEventBus] dispatch failed: ${error instanceof Error ? error.message : String(error)}`
)
}
}
private markSeen(eventId: string): boolean {
const now = this.now()
if (this.seen.has(eventId)) return false
this.seen.set(eventId, now)
if (this.seen.size > DEDUPE_MAX_ENTRIES) {
for (const [key, at] of this.seen) {
if (now - at > DEDUPE_TTL_MS) this.seen.delete(key)
}
if (this.seen.size > DEDUPE_MAX_ENTRIES) {
const overflow = this.seen.size - DEDUPE_MAX_ENTRIES
let removed = 0
for (const key of this.seen.keys()) {
this.seen.delete(key)
removed += 1
if (removed >= overflow) break
}
}
}
return true
}
}
export function buildEventId(sessionId: string, localId: string): string {
const digest = createHash('sha1').update(`${sessionId}\u0001${localId}`).digest('hex')
return `message:${digest}`
}
+988
View File
@@ -0,0 +1,988 @@
import { fork, spawn, type ChildProcess } from 'node:child_process'
import { randomUUID } from 'node:crypto'
import { ExtensionError, toExtensionErrorPayload } from '../../shared/extensions/errors'
import type { ExtensionRuntimeSnapshot } from '../../shared/extensions/types'
import {
sortPermissionsByRisk,
type ExtensionPermission
} from '../../shared/extensions/permissions'
import { EXTENSION_API_VERSION } from '../../shared/extensions/manifest'
import {
EXTENSION_HOST_PROTOCOL_VERSION,
type ExtensionAutomationActionOutput,
type ExtensionHostCall,
type ExtensionHostCallMethod,
type ExtensionHostInboundMessage,
type ExtensionHostOutboundMessage,
type ExtensionMessagesQueryRequest,
type ExtensionQueriedMessage,
type ExtensionSendImageRequest,
type ExtensionSendTextRequest,
type ExtensionSendTextResult,
type ExtensionSendVideoRequest,
type ExtensionSendVoiceRequest
} from '../../shared/extensions/rpc'
import type { ExtensionEventEnvelope } from '../../shared/extensions/events'
import type { ExtensionCapabilitySnapshot } from '../../shared/extensions/types'
import {
parseActionInputSchema,
type ExtensionActionInputSchema
} from '../../shared/extensions/action-schema'
import type { ExtensionStorage } from './extension-storage'
import type { ExtensionSecretStore } from './extension-secret-store'
const DEFAULT_ACTIVATE_TIMEOUT_MS = 8_000
const DEFAULT_ACTION_TIMEOUT_MS = 15_000
const MAX_RESTARTS = 3
const RESTART_WINDOW_MS = 5 * 60 * 1000
const RESTART_BASE_DELAY_MS = 1_000
const EVENT_BUCKET_CAPACITY = 100
const EVENT_REFILL_PER_SECOND = 60
/** 发出 shutdown 后等待扩展自行退出的时间。 */
const GRACEFUL_EXIT_MS = 2_500
/** 结束进程树之后等待 exit 事件的时间。 */
const FORCE_EXIT_MS = 3_000
/** taskkill 的等待上限:卡住时按降级处理,不能拖死停用流程。 */
const TASKKILL_TIMEOUT_MS = 5_000
/** stderr 采样窗口:只把有代表性的片段写进日志,避免日志洪水拖住主进程。 */
const STDERR_WINDOW_MS = 10_000
const STDERR_WINDOW_BYTES = 64 * 1024
const STDERR_WINDOW_ENTRIES = 20
const STDERR_MAX_CHUNK_CHARS = 400
/** stderr 里的凭据形态;落日志前只保留键名。 */
const SECRET_ASSIGNMENT =
/\b(cookie|token|authorization|password|passwd|secret|api[_-]?key)\b(\s*[:=]\s*)(?!Bearer\b)([^\s,;"']{4,})/gi
const BEARER_TOKEN = /\bBearer\s+[A-Za-z0-9._~+/-]{8,}=*/gi
export function redactSecrets(value: string): string {
// 顺序不能反:先抹 `Bearer <token>` 整体,再按「键=值」处理,
// 否则 `Authorization: Bearer xxx` 会只抹掉 `Bearer`,token 本体留在日志里。
return String(value ?? '')
.replace(BEARER_TOKEN, 'Bearer ***')
.replace(
SECRET_ASSIGNMENT,
(_match, name: string, separator: string) => `${name}${separator}***`
)
}
export interface ExtensionHostChild {
send(message: unknown): void
/** 终止本扩展的整棵进程树;实现方负责平台差异。 */
kill(): void
on(event: 'message', listener: (message: unknown) => void): void
on(event: 'exit', listener: (code: number | null, signal: string | null) => void): void
on(event: 'error', listener: (error: Error) => void): void
once?(event: 'exit', listener: () => void): void
readonly pid?: number
/** stderr 必须持续消费,否则管道写满会让子进程阻塞在 write。 */
readonly stderr?: NodeJS.ReadableStream | null
}
export interface ExtensionHostSpawnOptions {
extensionId: string
extensionDir: string
}
export interface ExtensionHostDependencies {
extensionId: string
extensionDir: string
/** 扩展私有数据目录;媒体文件只允许从这里或临时目录发送。 */
dataDir: string
permissions: ExtensionPermission[]
storage: ExtensionStorage
secrets?: ExtensionSecretStore
spawn: (options: ExtensionHostSpawnOptions) => ExtensionHostChild
onLog?: (level: 'info' | 'warn' | 'error', message: string) => void
onStateChange?: (snapshot: ExtensionRuntimeSnapshot) => void
onActionsChanged?: () => void
queryMessages?: (
extensionId: string,
request: ExtensionMessagesQueryRequest
) => Promise<ExtensionQueriedMessage[]>
sendText?: (
extensionId: string,
request: ExtensionSendTextRequest
) => Promise<ExtensionSendTextResult>
sendImage?: (
extensionId: string,
request: ExtensionSendImageRequest
) => Promise<ExtensionSendTextResult>
sendVideo?: (
extensionId: string,
request: ExtensionSendVideoRequest
) => Promise<ExtensionSendTextResult>
sendVoice?: (
extensionId: string,
request: ExtensionSendVoiceRequest
) => Promise<ExtensionSendTextResult>
aiChat?: (
extensionId: string,
messages: Array<{ role: string; content: string }>
) => Promise<{ text: string }>
capabilities?: (extensionId: string) => Promise<ExtensionCapabilitySnapshot>
now?: () => number
activateTimeoutMs?: number
actionTimeoutMs?: number
/** 覆盖「等扩展自行退出」的时间;生产默认 2.5s。 */
gracefulExitMs?: number
/** 覆盖「结束进程树后等 exit」的时间;生产默认 3s。 */
forceExitMs?: number
}
interface PendingAction {
resolve: (value: ExtensionAutomationActionOutput) => void
reject: (error: Error) => void
timer: ReturnType<typeof setTimeout>
}
interface RegisteredAction {
id: string
title: string
description?: string
/** 已校验的参数 Schema;非法时为 undefined 且 `schemaError` 有值。 */
inputSchema?: ExtensionActionInputSchema
schemaError?: string
}
interface ActivationWaiter {
resolve: () => void
reject: (error: Error) => void
timer: ReturnType<typeof setTimeout>
child: ExtensionHostChild
}
/** 单个扩展的后台进程:独立 Node 子进程,主进程从不 require 扩展代码。 */
export class ExtensionHost {
private readonly dependencies: ExtensionHostDependencies
private readonly storage: ExtensionStorage
private readonly now: () => number
private child: ExtensionHostChild | null = null
private state: ExtensionRuntimeSnapshot
private stopping = false
private activation: Promise<void> | null = null
private activationWaiter: ActivationWaiter | null = null
private restartTimer: ReturnType<typeof setTimeout> | null = null
private readonly pendingActions = new Map<string, PendingAction>()
private readonly testHandlers = new Map<
string,
{
resolve: (value: unknown) => void
reject: (error: Error) => void
timer: ReturnType<typeof setTimeout>
}
>()
private readonly actions = new Map<string, RegisteredAction>()
private readonly pendingPageRequests = new Map<
string,
{
resolve: (value: unknown) => void
reject: (error: Error) => void
timer: ReturnType<typeof setTimeout>
}
>()
private eventTokens = EVENT_BUCKET_CAPACITY
private eventTokensAt: number
private droppedEvents = 0
private mutedDropLog = false
private restartTimestamps: number[] = []
private stderrWindow = { bytes: 0, entries: 0, dropped: 0, at: 0 }
constructor(dependencies: ExtensionHostDependencies) {
this.dependencies = dependencies
this.storage = dependencies.storage
this.now = dependencies.now ?? (() => Date.now())
this.eventTokensAt = this.now()
this.stderrWindow.at = this.now()
this.state = { state: 'inactive', since: this.now(), restarts: 0 }
}
snapshot(): ExtensionRuntimeSnapshot {
return { ...this.state }
}
registeredActions(): RegisteredAction[] {
return Array.from(this.actions.values()).map((action) => ({ ...action }))
}
/** 把页面请求转给同扩展的后台处理器;这是唯一入口:页面拿不到 Node,后台必须显式注册 `tm.page.onRequest`。 */
async requestPage(
method: string,
params: Record<string, unknown>,
timeoutMs = 90_000
): Promise<unknown> {
const child = this.child
if (!child) throw new ExtensionError('EXTENSION_HOST_UNAVAILABLE')
const requestId = randomUUID()
return new Promise<unknown>((resolve, reject) => {
const timer = setTimeout(
() => {
this.pendingPageRequests.delete(requestId)
reject(new ExtensionError('ACTION_TIMEOUT', '页面请求超时'))
},
Math.max(1_000, timeoutMs)
)
this.pendingPageRequests.set(requestId, { resolve, reject, timer })
try {
child.send({
type: 'page-request',
version: EXTENSION_HOST_PROTOCOL_VERSION,
requestId,
method,
params,
timeoutMs
})
} catch (error) {
clearTimeout(timer)
this.pendingPageRequests.delete(requestId)
reject(
new ExtensionError(
'EXTENSION_HOST_UNAVAILABLE',
error instanceof Error ? error.message : '扩展进程不可用'
)
)
}
})
}
async testSend(params: Record<string, unknown>): Promise<unknown> {
return this.runTestMessage('test-send', params)
}
private async runTestMessage(
type: 'test-send',
params: Record<string, unknown>
): Promise<unknown> {
if (this.state.state !== 'active' || !this.child) {
throw new ExtensionError('EXTENSION_HOST_UNAVAILABLE')
}
const requestId = randomUUID()
return new Promise((resolve, reject) => {
const timer = setTimeout(() => {
this.testHandlers.delete(requestId)
reject(new ExtensionError('ACTION_TIMEOUT'))
}, 450_000)
this.testHandlers.set(requestId, { resolve, reject, timer })
try {
this.child?.send({
type,
version: EXTENSION_HOST_PROTOCOL_VERSION,
requestId,
params
})
} catch (error) {
clearTimeout(timer)
this.testHandlers.delete(requestId)
reject(
new ExtensionError(
'EXTENSION_HOST_UNAVAILABLE',
error instanceof Error ? error.message : '扩展进程不可用'
)
)
}
})
}
/** 启动并等待 `activate` 握手完成。重复调用复用同一次启动。 */
async start(): Promise<void> {
if (this.state.state === 'active') return
if (this.activation) return this.activation
this.stopping = false
this.activation = this.doStart().finally(() => {
this.activation = null
})
return this.activation
}
/** 停止后台:等真实 exit 才算完成,只发信号会在进程占用文件时替换失败。 */
async stop(): Promise<void> {
this.stopping = true
if (this.restartTimer) {
clearTimeout(this.restartTimer)
this.restartTimer = null
}
const child = this.child
this.child = null
this.settleActivation(new ExtensionError('EXTENSION_HOST_UNAVAILABLE', '扩展已停止'))
this.failPendingActions(new ExtensionError('EXTENSION_HOST_UNAVAILABLE', '扩展已停止'))
this.failPendingTests(new ExtensionError('EXTENSION_HOST_UNAVAILABLE', '扩展已停止'))
this.actions.clear()
if (!child) {
this.setState('inactive')
return
}
try {
child.send({ type: 'shutdown', version: EXTENSION_HOST_PROTOCOL_VERSION })
} catch {
// 进程可能已经断开;后续按「未退出」处理。
}
if (await this.waitForExit(child, this.dependencies.gracefulExitMs ?? GRACEFUL_EXIT_MS)) {
this.setState('inactive')
return
}
this.dependencies.onLog?.('warn', '扩展未在预期时间内退出,正在结束进程树')
await this.killTree(child)
if (!(await this.waitForExit(child, this.dependencies.forceExitMs ?? FORCE_EXIT_MS))) {
this.dependencies.onLog?.('error', '扩展进程树未能退出,可能有子进程仍在运行')
}
this.setState('inactive')
}
/** 结束进程树;Windows 的 taskkill /T 必须在父进程存活时执行,否则找不到孙进程。 */
private async killTree(child: ExtensionHostChild): Promise<void> {
const pid = child.pid
if (!pid) {
try {
child.kill()
} catch {
// ignore
}
return
}
const result = await killProcessTree(pid, {
timeoutMs: this.dependencies.forceExitMs ?? TASKKILL_TIMEOUT_MS
})
if (result === 'group') return
if (process.platform === 'win32') {
this.dependencies.onLog?.('warn', '结束扩展进程树失败,可能有子进程仍在运行')
return
}
this.dependencies.onLog?.('warn', '未能结束扩展进程组,已退化为只结束主进程')
}
private waitForExit(child: ExtensionHostChild, timeoutMs: number): Promise<boolean> {
return new Promise<boolean>((resolve) => {
let settled = false
const finish = (exited: boolean): void => {
if (settled) return
settled = true
clearTimeout(timer)
resolve(exited)
}
const timer = setTimeout(() => finish(false), timeoutMs)
child.once?.('exit', () => finish(true))
})
}
/** 投递消息事件;令牌桶是**背压边界**:扩展处理慢或消息突发时宁可丢事件并如实记日志, 也不能让主进程的监听回调被拖垮。 */
deliverEvent(envelope: ExtensionEventEnvelope): boolean {
if (this.state.state !== 'active' || !this.child) return false
this.refillTokens()
if (this.eventTokens < 1) {
this.droppedEvents += 1
if (!this.mutedDropLog && this.droppedEvents % 100 === 1) {
this.dependencies.onLog?.('warn', '消息事件超过扩展处理上限,部分事件已丢弃')
this.mutedDropLog = true
setTimeout(() => {
this.mutedDropLog = false
}, 10_000)
}
return false
}
this.eventTokens -= 1
try {
this.child.send({ type: 'event', version: EXTENSION_HOST_PROTOCOL_VERSION, envelope })
return true
} catch {
return false
}
}
/** 调用扩展注册的自动化动作。超时由宿主强制结束,扩展无法自行取消。 */
async invokeAction(
actionId: string,
input: Record<string, unknown>,
timeoutMs = this.dependencies.actionTimeoutMs ?? DEFAULT_ACTION_TIMEOUT_MS
): Promise<ExtensionAutomationActionOutput> {
if (this.state.state !== 'active' || !this.child) {
throw new ExtensionError('EXTENSION_HOST_UNAVAILABLE')
}
if (!this.actions.has(actionId)) {
throw new ExtensionError('ACTION_FAILED', `扩展没有注册动作 ${actionId}`)
}
const requestId = randomUUID()
return new Promise<ExtensionAutomationActionOutput>((resolve, reject) => {
const timer = setTimeout(
() => {
this.pendingActions.delete(requestId)
reject(new ExtensionError('ACTION_TIMEOUT'))
},
Math.max(1_000, Math.min(timeoutMs, 60_000))
)
this.pendingActions.set(requestId, { resolve, reject, timer })
try {
this.child?.send({
type: 'invoke-action',
version: EXTENSION_HOST_PROTOCOL_VERSION,
requestId,
actionId,
input,
timeoutMs
})
} catch (error) {
clearTimeout(timer)
this.pendingActions.delete(requestId)
reject(
new ExtensionError(
'EXTENSION_HOST_UNAVAILABLE',
error instanceof Error ? error.message : '扩展进程不可用'
)
)
}
})
}
private async doStart(): Promise<void> {
this.setState('starting')
this.actions.clear()
let child: ExtensionHostChild
try {
child = this.dependencies.spawn({
extensionId: this.dependencies.extensionId,
extensionDir: this.dependencies.extensionDir
})
} catch (error) {
this.setState('error', error instanceof Error ? error.message : '扩展进程启动失败')
throw new ExtensionError('EXTENSION_HOST_UNAVAILABLE', '扩展进程启动失败')
}
this.child = child
this.wire(child)
try {
await this.activateChild(child)
this.setState('active')
this.dependencies.onLog?.('info', '扩展后台已启动')
} catch (error) {
this.dependencies.onLog?.(
'error',
`扩展启动失败:${error instanceof Error ? error.message : String(error)}`
)
// 先摘掉引用再 kill:否则 exit 回调会被当成「运行期崩溃」并触发重启。
if (this.child === child) this.child = null
try {
child.kill()
} catch {
// ignore
}
this.setState('error', error instanceof Error ? error.message : '扩展启动失败')
throw error instanceof Error
? error
: new ExtensionError('EXTENSION_HOST_UNAVAILABLE', '扩展启动失败')
}
}
/** 发 `activate` 并等待 `activated`。握手结果由 `handleMessage` 统一结算。 */
private activateChild(child: ExtensionHostChild): Promise<void> {
const timeoutMs = this.dependencies.activateTimeoutMs ?? DEFAULT_ACTIVATE_TIMEOUT_MS
return new Promise<void>((resolve, reject) => {
const timer = setTimeout(
() => {
this.settleActivation(new ExtensionError('ACTION_TIMEOUT', '扩展启动超时'))
},
Math.max(2_000, timeoutMs)
)
this.activationWaiter = { resolve, reject, timer, child }
try {
child.send({
type: 'activate',
version: EXTENSION_HOST_PROTOCOL_VERSION,
extensionId: this.dependencies.extensionId,
extensionDir: this.dependencies.extensionDir,
dataDir: this.dependencies.dataDir,
apiVersion: EXTENSION_API_VERSION,
permissions: sortPermissionsByRisk(this.dependencies.permissions)
})
} catch (error) {
this.settleActivation(
new ExtensionError(
'EXTENSION_HOST_UNAVAILABLE',
error instanceof Error ? error.message : '无法向扩展进程发送激活指令'
)
)
}
})
}
private settleActivation(error?: Error): void {
const waiter = this.activationWaiter
if (!waiter) return
this.activationWaiter = null
clearTimeout(waiter.timer)
if (error) waiter.reject(error)
else waiter.resolve()
}
private wire(child: ExtensionHostChild): void {
child.on('message', (message) => this.handleMessage(message))
child.on('error', (error) => {
this.dependencies.onLog?.('error', `扩展进程错误:${error.message}`)
})
child.on('exit', (code) => this.handleExit(child, code))
this.consumeStderr(child)
}
/** 消费子进程 stderr;两点必须同时成立:管道始终有人读(否则子进程写满缓冲会阻塞), 且进入日志的内容有速率与长度上限(否则一次日志风暴能把主进程拖垮)。 */
private consumeStderr(child: ExtensionHostChild): void {
const stream = child.stderr
if (!stream || typeof stream.on !== 'function') return
const onData = (chunk: Buffer | string): void => {
try {
const now = this.now()
if (now - this.stderrWindow.at >= STDERR_WINDOW_MS) {
const dropped = this.stderrWindow.dropped
this.stderrWindow = { bytes: 0, entries: 0, dropped: 0, at: now }
if (dropped > 0) {
this.dependencies.onLog?.('warn', `扩展 stderr 有 ${dropped} 字节省略未记录`)
}
}
const text = redactSecrets(String(chunk)).replace(/\s+/g, ' ').trim()
if (!text) return
const bytes = Buffer.byteLength(text, 'utf8')
if (
this.stderrWindow.entries >= STDERR_WINDOW_ENTRIES ||
this.stderrWindow.bytes + bytes > STDERR_WINDOW_BYTES
) {
this.stderrWindow.dropped += bytes
return
}
this.stderrWindow.bytes += bytes
this.stderrWindow.entries += 1
this.dependencies.onLog?.('warn', `[stderr] ${text.slice(0, STDERR_MAX_CHUNK_CHARS)}`)
} catch {
// stderr 处理失败不能影响扩展运行。
}
}
const onEnd = (): void => {
if (this.stderrWindow.dropped > 0) {
this.dependencies.onLog?.(
'warn',
`扩展 stderr 有 ${this.stderrWindow.dropped} 字节省略未记录`
)
this.stderrWindow.dropped = 0
}
stream.removeListener?.('data', onData)
stream.removeListener?.('end', onEnd)
}
stream.on('data', onData)
stream.on('end', onEnd)
}
private handleExit(child: ExtensionHostChild, code: number | null): void {
if (this.child !== child) return
this.child = null
this.actions.clear()
this.settleActivation(new ExtensionError('EXTENSION_HOST_UNAVAILABLE', '扩展进程已退出'))
this.failPendingActions(
new ExtensionError('EXTENSION_HOST_UNAVAILABLE', `扩展进程已退出(${code ?? 'unknown'})`)
)
this.failPendingTests(new ExtensionError('EXTENSION_HOST_UNAVAILABLE', '扩展进程已退出'))
if (this.stopping) {
this.setState('inactive')
return
}
const timestamp = this.now()
this.restartTimestamps = this.restartTimestamps.filter(
(item) => timestamp - item < RESTART_WINDOW_MS
)
if (this.restartTimestamps.length >= MAX_RESTARTS) {
this.dependencies.onLog?.('error', '扩展连续异常退出,已停止自动重启')
this.setState('crashed', '扩展连续异常退出,已停止自动重启')
return
}
this.restartTimestamps.push(timestamp)
this.setState('starting', '扩展进程异常退出,正在重启')
const delay = RESTART_BASE_DELAY_MS * 2 ** (this.restartTimestamps.length - 1)
this.restartTimer = setTimeout(() => {
this.restartTimer = null
this.state = { ...this.state, restarts: this.state.restarts + 1, since: this.now() }
void this.start().catch(() => undefined)
}, delay)
}
private handleMessage(raw: unknown): void {
if (!raw || typeof raw !== 'object') return
const message = raw as ExtensionHostOutboundMessage & { version?: number }
if (message.version !== EXTENSION_HOST_PROTOCOL_VERSION) return
switch (message.type) {
case 'activated':
this.settleActivation(
message.ok
? undefined
: new ExtensionError('ACTION_FAILED', message.error?.message || '扩展激活失败')
)
return
case 'call':
void this.handleCall(message)
return
case 'register-action': {
const action = message.action
if (!action || typeof action.id !== 'string') return
// Schema 不合法的动作仍然登记:界面上要能看到它,并显示具体原因,
// 而不是让它凭空消失。
let inputSchema: ExtensionActionInputSchema | undefined
let schemaError: string | undefined
if (action.inputSchema !== undefined) {
const parsed = parseActionInputSchema(action.inputSchema)
if (parsed.ok) inputSchema = parsed.schema
else schemaError = parsed.reason
}
this.actions.set(action.id, {
id: action.id,
title: String(action.title || action.id).slice(0, 60),
...(action.description ? { description: String(action.description).slice(0, 200) } : {}),
...(inputSchema ? { inputSchema } : {}),
...(schemaError ? { schemaError } : {})
})
if (schemaError) {
this.dependencies.onLog?.(
'warn',
`动作 ${action.id} 的参数 Schema 不可用:${schemaError}`
)
}
this.dependencies.onActionsChanged?.()
return
}
case 'page-result': {
const pending = this.pendingPageRequests.get(message.requestId)
if (!pending) return
clearTimeout(pending.timer)
this.pendingPageRequests.delete(message.requestId)
if (message.ok) {
pending.resolve(message.result)
} else {
pending.reject(
new ExtensionError('ACTION_FAILED', message.error?.message || '扩展页面请求失败')
)
}
return
}
case 'log':
this.dependencies.onLog?.(message.level, message.message)
return
case 'action-result': {
const pending = this.pendingActions.get(message.requestId)
if (!pending) return
clearTimeout(pending.timer)
this.pendingActions.delete(message.requestId)
if (message.ok && message.output) {
pending.resolve(message.output)
} else {
pending.reject(
new ExtensionError(
'ACTION_FAILED',
message.error?.message || message.output?.error || '扩展动作执行失败'
)
)
}
return
}
case 'test-result': {
const pending = this.testHandlers.get(message.requestId)
if (!pending) return
clearTimeout(pending.timer)
this.testHandlers.delete(message.requestId)
if (message.ok) pending.resolve(message.result)
else
pending.reject(
new ExtensionError(message.error?.code || 'ACTION_FAILED', message.error?.message)
)
return
}
}
}
private async handleCall(message: ExtensionHostCall): Promise<void> {
try {
const result = await this.executeCall(message.method, message.params)
this.send({
type: 'call-result',
version: EXTENSION_HOST_PROTOCOL_VERSION,
callId: message.callId,
ok: true,
result
})
} catch (error) {
this.send({
type: 'call-result',
version: EXTENSION_HOST_PROTOCOL_VERSION,
callId: message.callId,
ok: false,
error: toExtensionErrorPayload(error)
})
}
}
private async executeCall(
method: ExtensionHostCallMethod,
params: Record<string, unknown>
): Promise<unknown> {
const extensionId = this.dependencies.extensionId
switch (method) {
case 'storage.get':
this.requirePermission('storage')
return this.storage.get(extensionId, params.key)
case 'storage.set':
this.requirePermission('storage')
this.storage.set(extensionId, params.key, params.value)
return { ok: true }
case 'storage.remove':
this.requirePermission('storage')
return { removed: this.storage.remove(extensionId, params.key) }
case 'storage.list':
this.requirePermission('storage')
return { entries: this.storage.list(extensionId) }
case 'secrets.get': {
this.requirePermission('secrets')
if (!this.dependencies.secrets) throw new ExtensionError('CAPABILITY_UNAVAILABLE')
return this.dependencies.secrets.get(extensionId, String(params.key ?? ''))
}
case 'secrets.set': {
this.requirePermission('secrets')
if (!this.dependencies.secrets) throw new ExtensionError('CAPABILITY_UNAVAILABLE')
this.dependencies.secrets.set(
extensionId,
String(params.key ?? ''),
String(params.value ?? '')
)
return { ok: true }
}
case 'secrets.delete': {
this.requirePermission('secrets')
if (!this.dependencies.secrets) throw new ExtensionError('CAPABILITY_UNAVAILABLE')
return { removed: this.dependencies.secrets.delete(extensionId, String(params.key ?? '')) }
}
case 'secrets.has': {
this.requirePermission('secrets')
if (!this.dependencies.secrets) throw new ExtensionError('CAPABILITY_UNAVAILABLE')
return this.dependencies.secrets.has(extensionId, String(params.key ?? ''))
}
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
)
}
}
case 'wechat.send.text': {
this.requirePermission('wechat.send.text')
if (!this.dependencies.sendText) throw new ExtensionError('SEND_NOT_SUPPORTED')
return this.dependencies.sendText(
extensionId,
params as unknown as ExtensionSendTextRequest
)
}
case 'wechat.send.image': {
this.requirePermission('wechat.send.image')
if (!this.dependencies.sendImage) throw new ExtensionError('SEND_NOT_SUPPORTED')
return this.dependencies.sendImage(
extensionId,
params as unknown as ExtensionSendImageRequest
)
}
case 'wechat.send.video': {
this.requirePermission('wechat.send.video')
if (!this.dependencies.sendVideo) throw new ExtensionError('SEND_NOT_SUPPORTED')
return this.dependencies.sendVideo(
extensionId,
params as unknown as ExtensionSendVideoRequest
)
}
case 'wechat.send.voice': {
this.requirePermission('wechat.send.voice')
if (!this.dependencies.sendVoice) throw new ExtensionError('SEND_NOT_SUPPORTED')
return this.dependencies.sendVoice(
extensionId,
params as unknown as ExtensionSendVoiceRequest
)
}
case 'ai.chat': {
this.requirePermission('ai.chat')
if (!this.dependencies.aiChat) throw new ExtensionError('CAPABILITY_UNAVAILABLE')
const messages = Array.isArray(params.messages) ? params.messages : []
const normalized = messages
.filter((item): item is { role: string; content: string } =>
Boolean(item && typeof item === 'object')
)
.slice(0, 40)
.map((item) => ({
role: String((item as { role?: unknown }).role || 'user'),
content: String((item as { content?: unknown }).content || '').slice(0, 20_000)
}))
return this.dependencies.aiChat(extensionId, normalized)
}
case 'capabilities.get':
if (!this.dependencies.capabilities) throw new ExtensionError('CAPABILITY_UNAVAILABLE')
return this.dependencies.capabilities(extensionId)
default:
throw new ExtensionError('INVALID_REQUEST', `未知方法:${String(method)}`)
}
}
private requirePermission(permission: ExtensionPermission): void {
if (!this.dependencies.permissions.includes(permission)) {
throw new ExtensionError('PERMISSION_DENIED', `扩展没有 ${permission} 权限`)
}
}
private send(message: ExtensionHostInboundMessage): void {
try {
this.child?.send(message)
} catch {
// 进程已退出:pending 会由 handleExit 统一失败。
}
}
private failPendingActions(error: Error): void {
for (const [requestId, pending] of this.pendingActions) {
clearTimeout(pending.timer)
this.pendingActions.delete(requestId)
pending.reject(error)
}
}
private failPendingTests(error: Error): void {
for (const [requestId, pending] of this.testHandlers) {
clearTimeout(pending.timer)
this.testHandlers.delete(requestId)
pending.reject(error)
}
}
private refillTokens(): void {
const now = this.now()
const elapsed = Math.max(0, now - this.eventTokensAt)
if (elapsed <= 0) return
this.eventTokens = Math.min(
EVENT_BUCKET_CAPACITY,
this.eventTokens + (elapsed / 1000) * EVENT_REFILL_PER_SECOND
)
this.eventTokensAt = now
}
private setState(next: ExtensionRuntimeSnapshot['state'], lastError?: string): void {
this.state = {
state: next,
since: this.now(),
restarts: this.state.restarts,
...(lastError ? { lastError } : {})
}
this.dependencies.onStateChange?.(this.snapshot())
}
}
/** 结束进程树;taskkill 只在 exit 0 时算成功,发起成功不算。 */
export type ProcessTreeKillResult = 'group' | 'taskkill' | 'fallback'
export async function killProcessTree(
pid: number | undefined,
options: { platform?: NodeJS.Platform; signal?: NodeJS.Signals; timeoutMs?: number } = {}
): Promise<ProcessTreeKillResult> {
if (!pid) return 'fallback'
const platform = options.platform ?? process.platform
const signal = options.signal ?? 'SIGKILL'
if (platform === 'win32') {
return killWindowsProcessTree(pid, options.timeoutMs ?? TASKKILL_TIMEOUT_MS)
}
try {
process.kill(-pid, signal)
return 'group'
} catch {
try {
process.kill(pid, signal)
} catch {
// 进程已经退出。
}
return 'fallback'
}
}
/** Windows:等 taskkill 真实退出,只认 exit code 0。 */
function killWindowsProcessTree(
pid: number,
timeoutMs: number
): Promise<'taskkill' | 'fallback'> {
return new Promise((resolve) => {
let killer: ChildProcess
try {
killer = spawn('taskkill', ['/PID', String(pid), '/T', '/F'], {
windowsHide: true,
stdio: 'ignore'
})
} catch {
// 无法启动 taskkill(极少数受限环境):只能退化为「主进程可能已退出」。
resolve('fallback')
return
}
let settled = false
const finish = (result: 'taskkill' | 'fallback'): void => {
if (settled) return
settled = true
clearTimeout(timer)
resolve(result)
}
const timer = setTimeout(() => {
try {
killer.kill()
} catch {
// 已经退出。
}
finish('fallback')
}, timeoutMs)
killer.on('error', () => finish('fallback'))
killer.on('exit', (code) => finish(code === 0 ? 'taskkill' : 'fallback'))
})
}
/** 真实子进程:`ELECTRON_RUN_AS_NODE` 让 Electron 二进制以 Node 模式运行。 */
export function forkExtensionHost(
scriptPath: string
): (options: ExtensionHostSpawnOptions) => ExtensionHostChild {
return (options) => {
const child: ChildProcess = fork(scriptPath, [], {
stdio: ['ignore', 'ignore', 'pipe', 'ipc'],
serialization: 'advanced',
// POSIX 上建立独立进程组,停止时才能一次覆盖扩展派生的子进程。
// Windows 用 taskkill /T,不需要(也不支持)detached。
detached: process.platform !== 'win32',
env: {
...process.env,
ELECTRON_RUN_AS_NODE: '1',
TM_EXTENSION_ID: options.extensionId,
TM_EXTENSION_DIR: options.extensionDir
}
})
return {
send: (message) => {
if (!child.connected) throw new Error('扩展进程未连接')
child.send(message as object)
},
kill: () => child.kill(),
on: (event, listener) => {
if (event === 'message') child.on('message', listener as (message: unknown) => void)
else if (event === 'exit') child.on('exit', listener as (code: number | null) => void)
else child.on('error', listener as (error: Error) => void)
},
once: (event, listener) => {
child.once(event, listener)
},
stderr: child.stderr,
...(child.pid ? { pid: child.pid } : {})
}
}
}
+596
View File
@@ -0,0 +1,596 @@
import { promises as fs } from 'node:fs'
import * as nodeFs from 'node:fs'
import path from 'node:path'
import { Open } from 'unzipper'
import { ExtensionError } from '../../shared/extensions/errors'
import {
isSafeRelativeEntryPath,
parseExtensionManifest,
type ExtensionManifest
} from '../../shared/extensions/manifest'
import type { ExtensionRegistry, ExtensionRegistryRecord } from './extension-registry'
import { isPathInside, type ExtensionPaths } from './extension-paths'
import type { ExtensionSource } from '../../shared/extensions/source'
import { computeDirectoryDigest } from './extension-code-digest'
const MAX_FILES = 2_000
const MAX_TOTAL_BYTES = 50 * 1024 * 1024
const MAX_FILE_BYTES = 20 * 1024 * 1024
const MAX_PACKAGE_BYTES = 100 * 1024 * 1024
/** 从「文件夹安装」时跳过的目录名;与打包脚本的白名单保持同一套判断。 */
const EXCLUDED_SOURCE_DIRECTORIES = new Set([
'.git',
'.hg',
'.svn',
'node_modules',
'__pycache__',
'.venv',
'venv'
])
export interface InstallOptions {
/** 应用版本,用于 `minAppVersion` 兼容检查。 */
appVersion: string
source?: ExtensionSource
/** 模板安装时由可信入口填入;普通 ZIP/目录安装不得携带。 */
template?: { id: string; version: string }
/**
* 代码被替换之前的最后一步:用于停止旧的 Host。
*
* 抛错表示「不能安全替换」,安装整体中止,磁盘保持原样。
*/
beforeReplace?: (
manifest: ExtensionManifest,
previous: ExtensionRegistryRecord | undefined
) => Promise<void>
}
export interface InstallOutcome {
manifest: ExtensionManifest
installPath: string
previousVersion?: string
/** 安装前的 Registry 记录;首次安装时为 undefined。 */
previousRecord?: ExtensionRegistryRecord
upgraded: boolean
/**
* 把磁盘与 Registry 一起恢复到本次安装之前。
*
* 只在新版本启动失败时调用;调用后 `cleanup` 失效。
*/
rollback: () => Promise<void>
/**
* 删除旧版本的过渡备份。
*
* 新版本确认可用后调用;调用后 `rollback` 失效。
*/
cleanup: () => Promise<void>
}
export interface ExtensionInstallerDependencies {
paths: ExtensionPaths
registry: ExtensionRegistry
now?: () => number
}
interface TreeEntry {
relativePath: string
type: 'file' | 'directory'
size: number
}
/**
* 扩展安装 / 升级 / 卸载。
*
* 写入顺序固定为「临时目录 → 校验 → 原子改名」:任何一步失败都不会留下
* 半装目录;升级失败时旧版本仍在原位。
*/
export class ExtensionInstaller {
private readonly paths: ExtensionPaths
private readonly registry: ExtensionRegistry
private readonly now: () => number
constructor(dependencies: ExtensionInstallerDependencies) {
this.paths = dependencies.paths
this.registry = dependencies.registry
this.now = dependencies.now ?? (() => Date.now())
}
async installFromDirectory(sourceDir: string, options: InstallOptions): Promise<InstallOutcome> {
const root = path.resolve(sourceDir)
const stat = await fs.stat(root).catch(() => null)
if (!stat || !stat.isDirectory()) {
throw new ExtensionError('EXTENSION_INSTALL_FAILED', '选择的路径不是目录')
}
const manifest = await this.readManifest(root, options.appVersion)
const entries = await this.collectTree(root)
this.assertEntrypointsPresent(entries, manifest)
const staging = this.paths.stagingPath('dir')
await fs.mkdir(staging, { recursive: true })
try {
await copyTree(root, staging, entries)
return await this.finalize(staging, manifest, options.source ?? 'directory', options)
} finally {
await fs.rm(staging, { recursive: true, force: true }).catch(() => undefined)
}
}
async installFromPackage(packagePath: string, options: InstallOptions): Promise<InstallOutcome> {
const stat = await fs.stat(packagePath).catch(() => null)
if (!stat || !stat.isFile()) {
throw new ExtensionError('EXTENSION_INSTALL_FAILED', '选择的扩展包不存在')
}
if (stat.size > MAX_PACKAGE_BYTES) {
throw new ExtensionError('EXTENSION_INSTALL_FAILED', '扩展包超过大小限制')
}
const archive = await Open.file(packagePath)
if (!archive.files.length || archive.files.length > MAX_FILES) {
throw new ExtensionError('EXTENSION_INSTALL_FAILED', '扩展包文件数量不合法')
}
const seen = new Set<string>()
let declaredTotal = 0
const entries: Array<{
relativePath: string
directory: boolean
size: number
entry: (typeof archive.files)[number]
}> = []
for (const entry of archive.files) {
const normalized = normalizeZipPath(entry.path)
const collisionKey = normalized.toLowerCase()
if (seen.has(collisionKey)) {
throw new ExtensionError('EXTENSION_INSTALL_FAILED', `扩展包内路径重复:${normalized}`)
}
seen.add(collisionKey)
if (entry.type !== 'File' && entry.type !== 'Directory') {
throw new ExtensionError(
'EXTENSION_INSTALL_FAILED',
`扩展包条目类型不受支持:${normalized}`
)
}
const directory = entry.type === 'Directory'
const size = Number(entry.uncompressedSize || 0)
if (!directory && size > MAX_FILE_BYTES) {
throw new ExtensionError('EXTENSION_INSTALL_FAILED', `扩展包内文件过大:${normalized}`)
}
declaredTotal += size
if (declaredTotal > MAX_TOTAL_BYTES) {
throw new ExtensionError('EXTENSION_INSTALL_FAILED', '扩展包解压后体积超过限制')
}
entries.push({ relativePath: normalized, directory, size, entry })
}
const manifestFile = entries.find(
(item) => item.relativePath === 'manifest.json' && !item.directory
)
if (!manifestFile)
throw new ExtensionError('EXTENSION_INVALID_MANIFEST', '扩展包缺少 manifest.json')
const manifest = this.parseManifestText(
(await manifestFile.entry.buffer()).toString('utf8'),
options.appVersion
)
this.assertEntrypointsPresent(
entries.map((item) => ({
relativePath: item.relativePath,
type: item.directory ? 'directory' : 'file',
size: item.size
})),
manifest
)
const staging = this.paths.stagingPath('zip')
await fs.mkdir(staging, { recursive: true })
try {
let actualTotal = 0
for (const item of entries) {
const destination = path.resolve(staging, item.relativePath)
if (!isPathInside(staging, destination)) {
throw new ExtensionError('EXTENSION_INVALID_PATH', `扩展包条目越界:${item.relativePath}`)
}
if (item.directory) {
await fs.mkdir(destination, { recursive: true })
continue
}
await fs.mkdir(path.dirname(destination), { recursive: true })
const chunks: Buffer[] = []
for await (const chunk of item.entry.stream()) {
const buffer = Buffer.from(chunk as Uint8Array)
actualTotal += buffer.length
if (actualTotal > MAX_TOTAL_BYTES || buffer.length > MAX_FILE_BYTES) {
throw new ExtensionError('EXTENSION_INSTALL_FAILED', '扩展包实际解压体积超过限制')
}
chunks.push(buffer)
}
await fs.writeFile(destination, Buffer.concat(chunks))
const fileStat = await fs.lstat(destination)
if (!fileStat.isFile()) {
throw new ExtensionError(
'EXTENSION_INVALID_PATH',
`扩展包条目不是普通文件:${item.relativePath}`
)
}
}
return await this.finalize(staging, manifest, options.source ?? 'package', options)
} finally {
await fs.rm(staging, { recursive: true, force: true }).catch(() => undefined)
}
}
/**
* 卸载扩展。
*
* `keepData` 为 true 时**只**删除代码目录,用户配置保留在
* `extensions-data/<id>`,同名扩展重新安装后能读回。
*/
async uninstall(extensionId: string, options: { keepData: boolean }): Promise<void> {
const target = this.paths.installDir(extensionId)
if (!isPathInside(this.paths.extensionsDir, target)) {
throw new ExtensionError('EXTENSION_INVALID_PATH', '扩展安装路径越界')
}
const trash = `${target}.removed-${this.now()}`
// lstat 不跟随符号链接:目标断链时也要把链接本身清掉,否则会留下悬空目录项。
const exists = await fs
.lstat(target)
.then(() => true)
.catch(() => false)
if (exists) {
await fs.rename(target, trash)
const trashStat = await fs.lstat(trash).catch(() => null)
if (trashStat?.isSymbolicLink()) {
// 只删链接本身;递归删除可能跟随链接进入用户自己的目录。
await fs.unlink(trash).catch(() => undefined)
} else {
await fs.rm(trash, { recursive: true, force: true }).catch(() => undefined)
}
}
if (!options.keepData) {
await fs
.rm(this.paths.extensionDataDir(extensionId), { recursive: true, force: true })
.catch(() => undefined)
}
this.registry.remove(extensionId)
}
private async readManifest(root: string, appVersion: string): Promise<ExtensionManifest> {
const manifestPath = path.join(root, 'manifest.json')
const text = await fs.readFile(manifestPath, 'utf8').catch(() => '')
if (!text) throw new ExtensionError('EXTENSION_INVALID_MANIFEST', '扩展目录缺少 manifest.json')
return this.parseManifestText(text, appVersion)
}
private parseManifestText(text: string, appVersion: string): ExtensionManifest {
const result = parseExtensionManifestJsonWithDetail(text, appVersion)
if (!result.ok || !result.manifest) {
throw new ExtensionError(
result.code === 'EXTENSION_INCOMPATIBLE'
? 'EXTENSION_INCOMPATIBLE'
: 'EXTENSION_INVALID_MANIFEST',
result.message || '扩展 manifest 不合法'
)
}
return result.manifest
}
private assertEntrypointsPresent(entries: TreeEntry[], manifest: ExtensionManifest): void {
const files = new Set(
entries.filter((entry) => entry.type === 'file').map((entry) => entry.relativePath)
)
for (const [key, value] of Object.entries(manifest.entrypoints)) {
if (!value) continue
if (!files.has(value)) {
throw new ExtensionError(
'EXTENSION_INVALID_MANIFEST',
`entrypoints.${key} 指向的文件不存在:${value}`
)
}
}
for (const page of manifest.contributions.pages) {
const entry = page.entry || manifest.entrypoints.page
if (!entry || !files.has(entry)) {
throw new ExtensionError('EXTENSION_INVALID_MANIFEST', `页面 ${page.id} 的入口文件不存在`)
}
}
}
private async collectTree(root: string): Promise<TreeEntry[]> {
const entries: TreeEntry[] = []
let total = 0
const walk = async (directory: string, prefix: string): Promise<void> => {
const items = await fs.readdir(directory, { withFileTypes: true })
for (const item of items) {
// 版本库与依赖目录不属于扩展产物:复制它们既超体积上限,
// 也会把提交历史带进用户数据目录。
if (item.isDirectory() && EXCLUDED_SOURCE_DIRECTORIES.has(item.name)) continue
const relativePath = prefix ? `${prefix}/${item.name}` : item.name
if (!isSafeRelativeEntryPath(relativePath)) {
throw new ExtensionError('EXTENSION_INVALID_PATH', `文件名不受支持:${relativePath}`)
}
const absolute = path.join(directory, item.name)
const stat = await fs.lstat(absolute)
if (stat.isSymbolicLink()) {
throw new ExtensionError(
'EXTENSION_INVALID_PATH',
`扩展目录不能包含符号链接:${relativePath}`
)
}
if (stat.isDirectory()) {
entries.push({ relativePath, type: 'directory', size: 0 })
await walk(absolute, relativePath)
continue
}
if (!stat.isFile()) {
throw new ExtensionError('EXTENSION_INVALID_PATH', `不支持的文件类型:${relativePath}`)
}
if (stat.size > MAX_FILE_BYTES) {
throw new ExtensionError('EXTENSION_INSTALL_FAILED', `文件过大:${relativePath}`)
}
total += stat.size
if (total > MAX_TOTAL_BYTES) {
throw new ExtensionError('EXTENSION_INSTALL_FAILED', '扩展体积超过限制')
}
entries.push({ relativePath, type: 'file', size: stat.size })
if (entries.length > MAX_FILES) {
throw new ExtensionError('EXTENSION_INSTALL_FAILED', '扩展文件数量超过限制')
}
}
}
await walk(root, '')
return entries
}
/**
* 临时目录 → 目标目录的原子替换。升级时保留 registry 里的启用状态与授权。
*
* 事务边界(只覆盖「同一文件系统内的目录改名 + 一次 JSON 写入」):
* - 改名前先停旧 Host:Windows 上被进程占用的目录无法改名,且旧进程
* 继续运行会读到已被替换的代码。
* - 旧目录保留为 `.backup-<ts>`,由调用方在新版本确认可用后清理;
* 启动失败时用 `rollback()` 换回来。
* - Registry 写入失败时当场回滚目录,不把「代码已换、状态未换」留给上层。
*
* 不保证跨进程的强原子性:如果进程在 rename 之后、Registry 写入之前被杀,
* 磁盘上是新代码配旧记录;下次启动会以 manifest 为准做兼容性检查。
*/
private async finalize(
staging: string,
manifest: ExtensionManifest,
source: ExtensionSource,
options: InstallOptions
): Promise<InstallOutcome> {
const target = this.paths.installDir(manifest.id)
if (!isPathInside(this.paths.extensionsDir, target)) {
throw new ExtensionError('EXTENSION_INVALID_PATH', '扩展安装路径越界')
}
await fs.mkdir(this.paths.extensionsDir, { recursive: true })
const existingRecord = this.registry.get(manifest.id)
const backup = `${target}.backup-${this.now()}`
const targetExists = await fs
.stat(target)
.then(() => true)
.catch(() => false)
// 旧 Host 必须在代码被替换之前停下;这一步失败则不触碰磁盘。
await options.beforeReplace?.(manifest, existingRecord)
if (targetExists) await fs.rename(target, backup)
try {
await fs.rename(staging, target)
} catch (error) {
if (targetExists) await fs.rename(backup, target).catch(() => undefined)
throw new ExtensionError(
'EXTENSION_INSTALL_FAILED',
error instanceof Error ? error.message : '安装目录替换失败'
)
}
const timestamp = this.now()
const record: ExtensionRegistryRecord = {
id: manifest.id,
version: manifest.version,
apiVersion: manifest.apiVersion,
// 升级不改变启用状态:升级后突然开始跑代码是用户没有同意的行为变化。
enabled: existingRecord?.enabled ?? false,
// 只保留新 manifest 仍声明的授权:被删掉的权限必须立刻失效。
grantedPermissions: (existingRecord?.grantedPermissions ?? []).filter((permission) =>
manifest.permissions.includes(permission)
),
installedAt: existingRecord?.installedAt ?? timestamp,
updatedAt: timestamp,
source,
// 安装完成后立刻记录基线:之后判断「用户改没改」全靠它。
installedCodeDigest: computeDirectoryDigest(target),
...(options.template
? { templateId: options.template.id, templateVersion: options.template.version }
: existingRecord?.templateId
? {
templateId: existingRecord.templateId,
...(existingRecord.templateVersion
? { templateVersion: existingRecord.templateVersion }
: {})
}
: {})
}
try {
this.registry.upsert(record)
} catch (error) {
// 代码已经换进去了,但状态没写成:必须把磁盘也退回去,否则用户会看到
// 「旧版本号 + 新代码」。新目录直接删除,内容仍在安装源里。
await fs.rm(target, { recursive: true, force: true }).catch(() => undefined)
if (targetExists) await fs.rename(backup, target).catch(() => undefined)
if (existingRecord) {
await Promise.resolve(this.registry.upsert(existingRecord)).catch(() => undefined)
}
throw new ExtensionError(
'EXTENSION_INSTALL_FAILED',
error instanceof Error
? `扩展状态写入失败,已回滚:${error.message}`
: '扩展状态写入失败,已回滚'
)
}
let settled = false
return {
manifest,
installPath: target,
previousRecord: existingRecord,
...(existingRecord ? { previousVersion: existingRecord.version } : {}),
upgraded: Boolean(existingRecord),
rollback: async () => {
if (settled) {
throw new ExtensionError('EXTENSION_INSTALL_FAILED', '该安装结果已完成清理,无法回滚')
}
settled = true
await fs.rm(target, { recursive: true, force: true }).catch(() => undefined)
if (targetExists) await fs.rename(backup, target).catch(() => undefined)
if (existingRecord) this.registry.upsert(existingRecord)
else this.registry.remove(manifest.id)
},
cleanup: async () => {
if (settled) return
settled = true
if (targetExists) {
await fs.rm(backup, { recursive: true, force: true }).catch(() => undefined)
}
}
}
}
/**
* 把最近一次升级留下的过渡备份换回原位。
*
* 只在「新代码启动失败或状态不一致」时由用户显式触发;备份目录本身不删除,
* 换回来的旧目录会被移到 `.failed-<ts>` 后清理,留下的是可运行的旧版本。
*/
async restoreLatestBackup(
extensionId: string
): Promise<{ restored: boolean; manifest?: ExtensionManifest }> {
const target = this.paths.installDir(extensionId)
if (!isPathInside(this.paths.extensionsDir, target)) {
throw new ExtensionError('EXTENSION_INVALID_PATH', '扩展安装路径越界')
}
let backups: string[] = []
try {
backups = (await fs.readdir(this.paths.extensionsDir))
.filter((name) => name.startsWith(`${extensionId}.backup-`))
.sort()
} catch {
return { restored: false }
}
if (!backups.length) return { restored: false }
const latest = path.join(this.paths.extensionsDir, backups[backups.length - 1])
// 空 appVersion = 跳过兼容性拦截:用户要的是「回到能跑的那个版本」。
const manifest = await this.readManifest(latest, '')
const failed = `${target}.failed-${this.now()}`
const targetExists = await fs
.lstat(target)
.then(() => true)
.catch(() => false)
if (targetExists) await fs.rename(target, failed)
try {
await fs.rename(latest, target)
} catch (error) {
if (targetExists) await fs.rename(failed, target).catch(() => undefined)
throw new ExtensionError(
'EXTENSION_INSTALL_FAILED',
error instanceof Error ? error.message : '恢复备份失败'
)
}
if (targetExists) {
await fs.rm(failed, { recursive: true, force: true }).catch(() => undefined)
}
return { restored: true, manifest }
}
/**
* 扫描已安装目录,重建最小 Registry 记录。
*
* 只读取 manifest 的**身份字段**,不继承启用状态与授权:磁盘上有代码,
* 不等于用户同意运行它。manifest 无法解析的目录被跳过。
*
* 同步实现:Registry 的加载是同步的,恢复入口不能引入异步间隙。
*/
recoverFromDisk(): ExtensionRegistryRecord[] {
const records: ExtensionRegistryRecord[] = []
let entries: nodeFs.Dirent[] = []
try {
entries = nodeFs.readdirSync(this.paths.extensionsDir, { withFileTypes: true })
} catch {
return records
}
for (const entry of entries) {
if (!entry.isDirectory()) continue
if (entry.name.includes('.backup-') || entry.name.includes('.removed')) continue
const root = path.join(this.paths.extensionsDir, entry.name)
try {
const raw = JSON.parse(
nodeFs.readFileSync(path.join(root, 'manifest.json'), 'utf8')
) as unknown
const parsed = parseExtensionManifest(raw)
if (!parsed.ok || !parsed.manifest) continue
const stat = nodeFs.statSync(root)
records.push({
id: parsed.manifest.id,
version: parsed.manifest.version,
apiVersion: parsed.manifest.apiVersion,
enabled: false,
grantedPermissions: [],
installedAt: Math.round(stat.birthtimeMs || stat.mtimeMs || 0),
updatedAt: Math.round(stat.mtimeMs || 0),
source: 'directory'
})
} catch {
// 单个目录损坏不影响其余扩展的恢复。
}
}
return records
}
}
function normalizeZipPath(value: string): string {
const normalized = String(value || '')
.replace(/\\/g, '/')
.replace(/\/+$/, '')
if (!isSafeRelativeEntryPath(normalized)) {
throw new ExtensionError('EXTENSION_INVALID_PATH', `扩展包内路径不合法:${value}`)
}
return normalized
}
async function copyTree(root: string, destination: string, entries: TreeEntry[]): Promise<void> {
for (const entry of entries) {
const from = path.join(root, entry.relativePath)
const to = path.resolve(destination, entry.relativePath)
if (!isPathInside(destination, to)) {
throw new ExtensionError('EXTENSION_INVALID_PATH', `复制路径越界:${entry.relativePath}`)
}
if (entry.type === 'directory') {
await fs.mkdir(to, { recursive: true })
continue
}
await fs.mkdir(path.dirname(to), { recursive: true })
await fs.copyFile(from, to)
}
}
/**
* 与 shared 的 `parseExtensionManifestJson` 同构,但把「兼容性」与「格式」区分开,
* 好让安装界面给出可操作的提示(升级 TraceMemo vs 修 manifest)。
*/
function parseExtensionManifestJsonWithDetail(
text: string,
appVersion: string
): ReturnType<typeof parseExtensionManifest> {
let value: unknown
try {
value = JSON.parse(text)
} catch {
return { ok: false, code: 'EXTENSION_INVALID_MANIFEST', message: 'manifest.json 不是合法 JSON' }
}
return parseExtensionManifest(value, { appVersion })
}
+391
View File
@@ -0,0 +1,391 @@
import fs from 'fs-extra'
import path from 'node:path'
import { BrowserWindow, dialog, ipcMain, shell } from 'electron'
import { EXTENSION_IPC } from '../../shared/extensions/ipc'
import type {
ExtensionActionInfo,
ExtensionInstallResult,
ExtensionProjectResult,
ExtensionLogEntry,
ExtensionOperationResult,
ExtensionPageDescriptor,
ExtensionPageRequest,
ExtensionPageResponse,
InstalledExtension
} from '../../shared/extensions/types'
import type { ExtensionManager } from './extension-manager'
import type { ExtensionPaths } from './extension-paths'
export interface ExtensionIpcOptions {
/** 懒取:扩展系统在窗口创建之后才完成初始化。 */
getManager: () => ExtensionManager
paths: ExtensionPaths
/** 扩展页面 IPC 的调用方必须是主窗口;其它 webContents 一律拒绝。 */
isTrustedSender: (senderId: number) => boolean
}
/**
* 注册扩展中心的 IPC。
*
* 所有入参都在这一层收敛类型与长度:渲染层与扩展页面都是「不可信输入」,
* 不能把未校验的对象直接交给 manager。
*/
export function registerExtensionIpc(options: ExtensionIpcOptions): void {
const { paths } = options
const manager = (): ExtensionManager => options.getManager()
const guard = <Args extends unknown[], Result>(
handler: (...args: Args) => Promise<Result> | Result
): ((
event: Electron.IpcMainInvokeEvent,
...args: Args
) => Promise<Result | { success: false; error: { code: string; message: string } }>) => {
return async (event, ...args) => {
if (!options.isTrustedSender(event.sender.id)) {
return { success: false, error: { code: 'PERMISSION_DENIED', message: '不受信任的调用方' } }
}
try {
return await handler(...args)
} catch (error) {
return {
success: false,
error: {
code: 'ACTION_FAILED',
message: error instanceof Error ? error.message : '扩展操作失败'
}
}
}
}
}
ipcMain.handle(
EXTENSION_IPC.list,
guard((): InstalledExtension[] => manager().list())
)
ipcMain.handle(
EXTENSION_IPC.detail,
guard((extensionId: unknown): InstalledExtension | null =>
manager().get(requireId(extensionId))
)
)
ipcMain.handle(
EXTENSION_IPC.pickDirectory,
guard(async (): Promise<string | null> => {
const window = BrowserWindow.getFocusedWindow()
const result = window
? await dialog.showOpenDialog(window, { properties: ['openDirectory'] })
: await dialog.showOpenDialog({ properties: ['openDirectory'] })
return result.canceled || !result.filePaths.length ? null : result.filePaths[0]
})
)
ipcMain.handle(
EXTENSION_IPC.pickPackage,
guard(async (): Promise<string | null> => {
const window = BrowserWindow.getFocusedWindow()
const options: Electron.OpenDialogOptions = {
properties: ['openFile'],
filters: [
{ name: 'TraceMemo 扩展包', extensions: ['zip', 'tmext'] },
{ name: '全部文件', extensions: ['*'] }
]
}
const result = window
? await dialog.showOpenDialog(window, options)
: await dialog.showOpenDialog(options)
return result.canceled || !result.filePaths.length ? null : result.filePaths[0]
})
)
ipcMain.handle(
EXTENSION_IPC.installDirectory,
guard(
(directory: unknown): Promise<ExtensionInstallResult> =>
manager().installFromDirectory(requirePath(directory))
)
)
ipcMain.handle(
EXTENSION_IPC.installPackage,
guard(
(packagePath: unknown): Promise<ExtensionInstallResult> =>
manager().installFromPackage(requirePath(packagePath))
)
)
ipcMain.handle(
EXTENSION_IPC.setEnabled,
guard((payload: unknown): Promise<ExtensionOperationResult> => {
const input = (payload ?? {}) as { id?: unknown; enabled?: unknown }
return manager().setEnabled(requireId(input.id), input.enabled === true)
})
)
ipcMain.handle(
EXTENSION_IPC.health,
guard(() => manager().getHealth())
)
ipcMain.handle(
EXTENSION_IPC.grantPermissions,
guard((payload: unknown): Promise<ExtensionOperationResult> => {
const input = (payload ?? {}) as { id?: unknown; permissions?: unknown }
const permissions = Array.isArray(input.permissions)
? input.permissions.filter((item): item is string => typeof item === 'string')
: []
return manager().grantPermissions(
requireId(input.id),
permissions as Parameters<ExtensionManager['grantPermissions']>[1]
)
})
)
ipcMain.handle(
EXTENSION_IPC.revokePermission,
guard((payload: unknown): Promise<ExtensionOperationResult> => {
const input = (payload ?? {}) as { id?: unknown; permission?: unknown }
const permission = String(input.permission || '').trim()
if (!permission) throw new Error('权限名不合法')
return manager().revokePermission(
requireId(input.id),
permission as Parameters<ExtensionManager['revokePermission']>[1]
)
})
)
ipcMain.handle(
EXTENSION_IPC.resetStorage,
guard(
(extensionId: unknown): ExtensionOperationResult =>
manager().resetStorage(requireId(extensionId))
)
)
ipcMain.handle(
EXTENSION_IPC.templates,
guard(() => manager().listTemplates())
)
ipcMain.handle(
EXTENSION_IPC.installTemplate,
guard(
(templateId: unknown): Promise<ExtensionInstallResult> =>
manager().installTemplate(requireTemplateId(templateId))
)
)
ipcMain.handle(
EXTENSION_IPC.acknowledgeRecovery,
guard((): ExtensionOperationResult => manager().acknowledgeRegistryRecovery())
)
ipcMain.handle(
EXTENSION_IPC.acknowledgeStorage,
guard(
(extensionId: unknown): ExtensionOperationResult =>
manager().acknowledgeStorageRecovery(requireId(extensionId))
)
)
ipcMain.handle(
EXTENSION_IPC.adoptInstalledCode,
guard(
(extensionId: unknown): ExtensionOperationResult =>
manager().adoptInstalledCode(requireId(extensionId))
)
)
ipcMain.handle(
EXTENSION_IPC.pickProjectDirectory,
guard(async (): Promise<string | null> => {
const window = BrowserWindow.getFocusedWindow()
const options: Electron.OpenDialogOptions = {
properties: ['openDirectory', 'createDirectory'],
title: '选择扩展项目目录'
}
const result = window
? await dialog.showOpenDialog(window, options)
: await dialog.showOpenDialog(options)
return result.canceled || !result.filePaths.length ? null : result.filePaths[0]
})
)
ipcMain.handle(
EXTENSION_IPC.linkDevelopment,
guard(
(directory: unknown): Promise<ExtensionInstallResult> =>
manager().linkDevelopmentProject(requirePath(directory))
)
)
ipcMain.handle(
EXTENSION_IPC.reloadDevelopment,
guard(
(extensionId: unknown): Promise<ExtensionOperationResult> =>
manager().reloadDevelopment(requireId(extensionId))
)
)
ipcMain.handle(
EXTENSION_IPC.unlinkDevelopment,
guard((payload: unknown): Promise<ExtensionOperationResult> => {
const input = (payload ?? {}) as { id?: unknown; keepData?: unknown }
return manager().unlinkDevelopment(requireId(input.id), {
keepData: input.keepData !== false
})
})
)
ipcMain.handle(
EXTENSION_IPC.convertDevelopment,
guard(
(extensionId: unknown): Promise<ExtensionOperationResult> =>
manager().convertDevelopmentToInstalled(requireId(extensionId))
)
)
ipcMain.handle(
EXTENSION_IPC.createProjectFromTemplate,
guard((payload: unknown): Promise<ExtensionProjectResult> => {
const input = (payload ?? {}) as {
templateId?: unknown
targetDirectory?: unknown
extensionId?: unknown
name?: unknown
}
return manager().createProjectFromTemplate(
requireTemplateId(input.templateId),
requirePath(input.targetDirectory),
{
extensionId: requireId(input.extensionId),
...(typeof input.name === 'string' && input.name.trim()
? { name: input.name.trim().slice(0, 60) }
: {})
}
)
})
)
ipcMain.handle(
EXTENSION_IPC.exportInstalledAsProject,
guard((payload: unknown): Promise<ExtensionProjectResult> => {
const input = (payload ?? {}) as { id?: unknown; targetDirectory?: unknown }
return manager().exportInstalledAsProject(
requireId(input.id),
requirePath(input.targetDirectory)
)
})
)
ipcMain.handle(
EXTENSION_IPC.actions,
guard((): ExtensionActionInfo[] => manager().listActions())
)
ipcMain.handle(
EXTENSION_IPC.openDevelopmentSource,
guard(async (extensionId: unknown): Promise<ExtensionOperationResult> => {
const extension = manager().get(requireId(extensionId))
if (!extension?.development?.available) {
return {
success: false,
error: { code: 'EXTENSION_SOURCE_MISSING', message: '源码目录不可用' }
}
}
// 路径来自主进程的 registry,渲染层只能传 id,无法指定任意目录。
const error = await shell.openPath(extension.development.sourcePath)
return error
? { success: false, error: { code: 'ACTION_FAILED', message: error } }
: { success: true }
})
)
ipcMain.handle(
EXTENSION_IPC.rollbackUpgrade,
guard(
(extensionId: unknown): Promise<ExtensionOperationResult> =>
manager().rollbackInterruptedUpgrade(requireId(extensionId))
)
)
ipcMain.handle(
EXTENSION_IPC.uninstall,
guard((payload: unknown): Promise<ExtensionOperationResult> => {
const input = (payload ?? {}) as { id?: unknown; keepData?: unknown }
return manager().uninstall(requireId(input.id), input.keepData !== false)
})
)
ipcMain.handle(
EXTENSION_IPC.logs,
guard((payload: unknown): ExtensionLogEntry[] => {
const input = (payload ?? {}) as { id?: unknown; limit?: unknown }
const limit = Number(input.limit)
return manager().getLogs(requireId(input.id), Number.isFinite(limit) ? limit : 100)
})
)
ipcMain.handle(
EXTENSION_IPC.clearLogs,
guard((extensionId: unknown): { success: true } => {
manager().clearLogs(requireId(extensionId))
return { success: true }
})
)
ipcMain.handle(
EXTENSION_IPC.pageUrl,
guard((payload: unknown): ExtensionPageDescriptor => {
const input = (payload ?? {}) as { id?: unknown; pageId?: unknown }
const pageId =
typeof input.pageId === 'string' && input.pageId.trim() ? input.pageId.trim() : undefined
return manager().pageUrl(requireId(input.id), pageId)
})
)
ipcMain.handle(
EXTENSION_IPC.pageRequest,
guard((payload: unknown): Promise<ExtensionPageResponse> => {
const request = (payload ?? {}) as Partial<ExtensionPageRequest>
const extensionId = requireId(request.extensionId)
const method = String(request.method || '')
const params =
request.params && typeof request.params === 'object' && !Array.isArray(request.params)
? (request.params as Record<string, unknown>)
: {}
return manager().pageRequest(extensionId, method, params)
})
)
ipcMain.handle(
EXTENSION_IPC.openDataDir,
guard(async (extensionId: unknown): Promise<{ success: boolean; error?: string }> => {
const id = requireId(extensionId)
const directory = paths.extensionDataDir(id)
fs.ensureDirSync(directory)
const error = await shell.openPath(directory)
return error ? { success: false, error } : { success: true }
})
)
}
function requireId(value: unknown): string {
const id = String(value || '').trim()
if (!/^[a-z0-9.-]{3,128}$/.test(id)) throw new Error('扩展 id 不合法')
return id
}
/** 模板 id 只允许稳定的短标识,不允许携带路径片段。 */
function requireTemplateId(value: unknown): string {
const id = String(value || '').trim()
if (!/^[a-z0-9][a-z0-9-]{1,63}$/.test(id)) throw new Error('模板 id 不合法')
return id
}
function requirePath(value: unknown): string {
const target = String(value || '').trim()
if (!target || target.length > 4_096) throw new Error('路径不合法')
if (!path.isAbsolute(target)) throw new Error('必须使用绝对路径')
return target
}
+125
View File
@@ -0,0 +1,125 @@
import fs from 'fs-extra'
import path from 'node:path'
import { randomUUID } from 'node:crypto'
import type { ExtensionLogEntry } from '../../shared/extensions/types'
const MAX_ENTRIES_PER_EXTENSION = 200
const MAX_MESSAGE_LENGTH = 500
const MAX_FILE_BYTES = 256 * 1024
/**
* 扩展日志:内存环形缓冲 + 磁盘 JSONL(超过上限时轮转一份 `.1`)。
*
* 隐私边界:宿主只记录**生命周期与错误摘要**,不写聊天正文。
* 扩展主动写入的内容会原样落盘并展示给用户,作者必须自己遵守隐私约定。
*/
export class ExtensionLogStore {
private readonly logsDir: string
private readonly memory = new Map<string, ExtensionLogEntry[]>()
private readonly loaded = new Set<string>()
constructor(logsDir: string) {
this.logsDir = logsDir
}
append(
extensionId: string,
level: ExtensionLogEntry['level'],
source: ExtensionLogEntry['source'],
message: string
): ExtensionLogEntry {
this.ensureLoaded(extensionId)
const entry: ExtensionLogEntry = {
id: randomUUID(),
at: Date.now(),
level,
source,
message: sanitizeMessage(message)
}
const list = this.memory.get(extensionId) ?? []
list.push(entry)
if (list.length > MAX_ENTRIES_PER_EXTENSION)
list.splice(0, list.length - MAX_ENTRIES_PER_EXTENSION)
this.memory.set(extensionId, list)
this.appendToDisk(extensionId, entry)
return entry
}
list(extensionId: string, limit = MAX_ENTRIES_PER_EXTENSION): ExtensionLogEntry[] {
this.ensureLoaded(extensionId)
const list = this.memory.get(extensionId) ?? []
return list.slice(-Math.max(1, Math.min(limit, MAX_ENTRIES_PER_EXTENSION))).reverse()
}
clear(extensionId: string): void {
this.memory.set(extensionId, [])
this.loaded.add(extensionId)
fs.removeSync(this.filePath(extensionId))
fs.removeSync(`${this.filePath(extensionId)}.1`)
}
remove(extensionId: string): void {
this.memory.delete(extensionId)
this.loaded.delete(extensionId)
fs.removeSync(this.filePath(extensionId))
fs.removeSync(`${this.filePath(extensionId)}.1`)
}
private filePath(extensionId: string): string {
return path.join(this.logsDir, `${extensionId}.jsonl`)
}
private ensureLoaded(extensionId: string): void {
if (this.loaded.has(extensionId)) return
this.loaded.add(extensionId)
try {
const text = fs.readFileSync(this.filePath(extensionId), 'utf8')
const lines = text.split('\n').filter(Boolean).slice(-MAX_ENTRIES_PER_EXTENSION)
const entries: ExtensionLogEntry[] = []
for (const line of lines) {
try {
const raw = JSON.parse(line) as Partial<ExtensionLogEntry>
if (!raw || typeof raw !== 'object') continue
if (typeof raw.message !== 'string') continue
entries.push({
id: String(raw.id || randomUUID()),
at: Number(raw.at) || 0,
level: raw.level === 'warn' || raw.level === 'error' ? raw.level : 'info',
source: raw.source === 'extension' ? 'extension' : 'core',
message: sanitizeMessage(raw.message)
})
} catch {
// 单行损坏不影响其余日志。
}
}
this.memory.set(extensionId, entries)
} catch {
this.memory.set(extensionId, [])
}
}
private appendToDisk(extensionId: string, entry: ExtensionLogEntry): void {
try {
const filePath = this.filePath(extensionId)
fs.ensureDirSync(path.dirname(filePath))
const size = fs.statSync(filePath, { throwIfNoEntry: false })?.size ?? 0
if (size > MAX_FILE_BYTES) fs.moveSync(filePath, `${filePath}.1`, { overwrite: true })
fs.appendFileSync(filePath, `${JSON.stringify(entry)}\n`, 'utf8')
} catch {
// 日志写不进去不能影响扩展运行。
}
}
}
// eslint-disable-next-line no-control-regex -- 终端 ANSI 序列与控制字符要在落盘前剥掉
const ANSI_PATTERN = /\u001b\[[0-9;]*m/g
// eslint-disable-next-line no-control-regex -- 同上:日志里不允许出现不可见控制字符
const CONTROL_PATTERN = /[\u0000-\u0008\u000B\u000C\u000E-\u001F]/g
function sanitizeMessage(value: unknown): string {
const text = String(value ?? '')
.replace(ANSI_PATTERN, '')
.replace(CONTROL_PATTERN, '')
.trim()
return text.length > MAX_MESSAGE_LENGTH ? `${text.slice(0, MAX_MESSAGE_LENGTH)}…` : text
}
File diff suppressed because it is too large. Load diff
+83
View File
@@ -0,0 +1,83 @@
import path from 'node:path'
import { app } from 'electron'
/**
* 扩展相关目录的唯一解析器。
*
* **所有扩展文件都在 `userData` 下**,与安装目录 / `app.asar` / 源码树完全分离:
* 官方升级只替换应用本体,不会碰这三个目录。Windows 与 macOS 的差异由
* `app.getPath('userData')` 吸收,调用方不假设任何绝对路径。
*
* ```text
* <userData>/extensions/<id>/ 扩展代码(manifest + ui + background)
* <userData>/extensions-data/<id>/ 扩展私有数据(配置、缓存)
* <userData>/extensions-state/ 宿主状态(registry、日志)
* <userData>/extensions-staging/ 安装临时目录(成功后原子改名,不留半装状态)
* ```
*/
export interface ExtensionPaths {
userData: string
extensionsDir: string
dataDir: string
stateDir: string
stagingDir: string
registryFile: string
logsDir: string
installDir: (extensionId: string) => string
extensionDataDir: (extensionId: string) => string
logFile: (extensionId: string) => string
stagingPath: (prefix: string) => string
}
export function createExtensionPaths(userData: string): ExtensionPaths {
const extensionsDir = path.join(userData, 'extensions')
const dataDir = path.join(userData, 'extensions-data')
const stateDir = path.join(userData, 'extensions-state')
const stagingDir = path.join(userData, 'extensions-staging')
const logsDir = path.join(stateDir, 'logs')
return {
userData,
extensionsDir,
dataDir,
stateDir,
stagingDir,
registryFile: path.join(stateDir, 'registry.json'),
logsDir,
installDir: (extensionId) => path.join(extensionsDir, extensionId),
extensionDataDir: (extensionId) => path.join(dataDir, extensionId),
logFile: (extensionId) => path.join(logsDir, `${extensionId}.jsonl`),
stagingPath: (prefix) => path.join(stagingDir, `${prefix}-${Date.now().toString(36)}`)
}
}
let cached: ExtensionPaths | null = null
/** 懒解析:`app.getPath` 必须在 app ready 之后才可靠。 */
export function getExtensionPaths(): ExtensionPaths {
if (!cached) cached = createExtensionPaths(app.getPath('userData'))
return cached
}
/**
* 判断 `child` 是否在 `parent` 内(含自身)。符号链接需调用方先 realpath。
*
* Windows 上盘符大小写、分隔符与短文件名都可能让字符串比较失手,
* 这里统一把两侧规范化后再比:`path.resolve` 处理分隔符,Windows 额外折叠大小写。
*/
export function isPathInside(parent: string, child: string): boolean {
const normalize = (value: string): string => {
const resolved = path.resolve(value)
return process.platform === 'win32' ? resolved.toLowerCase() : resolved
}
const relative = path.relative(normalize(parent), normalize(child))
return relative === '' || (!relative.startsWith('..') && !path.isAbsolute(relative))
}
/** 只比路径本身,不跟随符号链接;用于判断两个字符串是否指向同一位置。 */
export function isSamePath(left: string, right: string): boolean {
const normalize = (value: string): string => {
const resolved = path.resolve(value)
return process.platform === 'win32' ? resolved.toLowerCase() : resolved
}
return normalize(left) === normalize(right)
}
@@ -0,0 +1,242 @@
import { promises as fs, existsSync } from 'node:fs'
import path from 'node:path'
import { Open } from 'unzipper'
import { ExtensionError } from '../../shared/extensions/errors'
import { isSafeRelativeEntryPath } from '../../shared/extensions/manifest'
import { isPathInside } from './extension-paths'
const MAX_FILES = 2_000
const MAX_TOTAL_BYTES = 50 * 1024 * 1024
/** 与安装器 / 指纹一致的排除规则:这些不属于扩展源码。 */
const EXCLUDED_DIRECTORIES = new Set([
'.git',
'.hg',
'.svn',
'node_modules',
'__pycache__',
'.venv',
'venv'
])
const EXCLUDED_FILES = new Set(['.DS_Store', 'Thumbs.db'])
const EXCLUDED_EXTENSIONS = new Set(['.pyc', '.log'])
/** 会被替换扩展 id 的文本文件类型。 */
const TEXT_FILE_PATTERN = /\.(js|mjs|cjs|ts|tsx|jsx|html|htm|css|json)$/i
export interface CreateProjectInput {
zipPath: string
targetDir: string
/** 新扩展 id(必须与模板里的旧 id 不同)。 */
extensionId: string
/** 模板里的旧 id;用于替换代码中的身份引用。 */
templateExtensionId: string
name?: string
}
export interface CreateProjectOutcome {
projectPath: string
rewrittenFiles: string[]
}
/**
* 目标目录必须是「不存在」或「空目录」。
*
* 这条检查在复制之前做,避免中途发现冲突时已经写了一半。
*/
export async function assertUsableTarget(targetDir: string): Promise<string> {
const resolved = path.resolve(targetDir)
try {
const stat = await fs.stat(resolved)
if (!stat.isDirectory()) {
throw new ExtensionError('EXTENSION_PROJECT_EXISTS', '目标路径已存在且不是目录')
}
const entries = await fs.readdir(resolved)
if (entries.length > 0) {
throw new ExtensionError('EXTENSION_PROJECT_EXISTS', '目标目录不是空目录,未写入任何文件')
}
} catch (error) {
if (error instanceof ExtensionError) throw error
const code = (error as { code?: string }).code
if (code !== 'ENOENT') {
throw new ExtensionError('EXTENSION_PROJECT_EXISTS', '目标目录不可用')
}
}
return resolved
}
/** 在目标旁边建暂存目录:同一磁盘才能用 rename 原子落位。 */
async function createStaging(parent: string): Promise<string> {
await fs.mkdir(parent, { recursive: true })
return fs.mkdtemp(path.join(parent, '.tm-project-'))
}
async function cleanup(directory: string): Promise<void> {
await fs.rm(directory, { recursive: true, force: true }).catch(() => undefined)
}
function shouldSkipFile(name: string): boolean {
return EXCLUDED_FILES.has(name) || EXCLUDED_EXTENSIONS.has(path.extname(name).toLowerCase())
}
/** 解压到暂存目录;条目路径逐条校验,拒绝穿越与非法字符。 */
async function extractZip(zipPath: string, staging: string): Promise<void> {
let archive: Awaited<ReturnType<typeof Open.file>>
try {
archive = await Open.file(zipPath)
} catch {
throw new ExtensionError('EXTENSION_INSTALL_FAILED', '模板压缩包无法读取')
}
let files = 0
let total = 0
for (const entry of archive.files) {
const relative = String(entry.path || '').replace(/\\/g, '/')
if (entry.type === 'Directory') continue
if (!isSafeRelativeEntryPath(relative)) {
throw new ExtensionError('EXTENSION_INVALID_PATH', `模板条目路径不合法:${relative}`)
}
const size = Number(entry.uncompressedSize || 0)
total += size
if (total > MAX_TOTAL_BYTES) {
throw new ExtensionError('EXTENSION_INSTALL_FAILED', '模板解压后体积超过限制')
}
files += 1
if (files > MAX_FILES) {
throw new ExtensionError('EXTENSION_INSTALL_FAILED', '模板文件数量超过限制')
}
const destination = path.resolve(staging, relative)
if (!isPathInside(staging, destination)) {
throw new ExtensionError('EXTENSION_INVALID_PATH', `模板条目越界:${relative}`)
}
await fs.mkdir(path.dirname(destination), { recursive: true })
const content = await entry.buffer()
await fs.writeFile(destination, content)
}
if (!files) throw new ExtensionError('EXTENSION_INSTALL_FAILED', '模板压缩包是空的')
}
async function listTextFiles(root: string, prefix = ''): Promise<string[]> {
const result: string[] = []
const items = await fs.readdir(path.join(root, prefix), { withFileTypes: true })
for (const item of items) {
if (item.isDirectory()) {
if (EXCLUDED_DIRECTORIES.has(item.name)) continue
const nested = prefix ? `${prefix}/${item.name}` : item.name
result.push(...(await listTextFiles(root, nested)))
continue
}
if (shouldSkipFile(item.name)) continue
const relative = prefix ? `${prefix}/${item.name}` : item.name
if (!TEXT_FILE_PATTERN.test(relative)) continue
result.push(relative)
}
return result.sort()
}
/**
* 把代码里的扩展身份改成新 id。
*
* 只替换精确字符串:模板示例里 id 至少出现在 manifest 与页面桥的
* `EXTENSION_ID` 常量中,漏掉任何一处都会让页面桥失联。
*/
export async function rewriteExtensionIdentity(
root: string,
oldId: string,
newId: string,
name?: string
): Promise<string[]> {
const rewritten: string[] = []
const manifestPath = path.join(root, 'manifest.json')
const manifest = JSON.parse(await fs.readFile(manifestPath, 'utf8')) as Record<string, unknown>
if (String(manifest.id) !== oldId) {
throw new ExtensionError(
'EXTENSION_INVALID_MANIFEST',
`模板 manifest.id 与索引不一致(${String(manifest.id)})`
)
}
manifest.id = newId
if (name) manifest.name = name
await fs.writeFile(manifestPath, `${JSON.stringify(manifest, null, 2)}\n`, 'utf8')
for (const relative of await listTextFiles(root)) {
if (relative === 'manifest.json') continue
const full = path.join(root, relative)
const text = await fs.readFile(full, 'utf8')
if (!text.includes(oldId)) continue
await fs.writeFile(full, text.split(oldId).join(newId), 'utf8')
rewritten.push(relative)
}
return rewritten
}
/** 生成后自检:任何残留的旧 id 都意味着页面桥或后台仍指向模板身份。 */
export async function assertNoIdentityLeftover(root: string, oldId: string): Promise<void> {
for (const relative of await listTextFiles(root)) {
const text = await fs.readFile(path.join(root, relative), 'utf8')
if (text.includes(oldId)) {
throw new ExtensionError(
'EXTENSION_INVALID_MANIFEST',
`生成的项目里仍残留旧扩展 id:${relative}`
)
}
}
}
/** 从模板 ZIP 生成独立项目;全过程在暂存目录完成,成功后才落位。 */
export async function createProjectFromTemplate(
input: CreateProjectInput
): Promise<CreateProjectOutcome> {
const target = await assertUsableTarget(input.targetDir)
if (input.extensionId === input.templateExtensionId) {
throw new ExtensionError('INVALID_REQUEST', '新项目必须使用不同的扩展 id')
}
const staging = await createStaging(path.dirname(target))
try {
await extractZip(input.zipPath, staging)
const rewritten = await rewriteExtensionIdentity(
staging,
input.templateExtensionId,
input.extensionId,
input.name
)
await assertNoIdentityLeftover(staging, input.templateExtensionId)
await fs.rename(staging, target)
return { projectPath: target, rewrittenFiles: rewritten }
} catch (error) {
await cleanup(staging)
throw error
}
}
/** 把已安装副本整体复制成外部项目(保留用户改过的代码)。 */
export async function exportInstalledCopy(
sourceDir: string,
targetDir: string
): Promise<{ projectPath: string }> {
if (!existsSync(path.join(sourceDir, 'manifest.json'))) {
throw new ExtensionError('EXTENSION_INVALID_MANIFEST', '安装副本不完整,无法导出')
}
const target = await assertUsableTarget(targetDir)
const staging = await createStaging(path.dirname(target))
try {
await fs.cp(sourceDir, staging, {
recursive: true,
filter: (source) => {
const name = path.basename(source)
if (EXCLUDED_DIRECTORIES.has(name)) return false
if (shouldSkipFile(name)) return false
return true
}
})
// 复制结果必须仍然可读,否则宁可失败也不留一个半成品项目。
await fs.access(path.join(staging, 'manifest.json'))
await fs.rename(staging, target)
return { projectPath: target }
} catch (error) {
await cleanup(staging)
throw error
}
}
+104
View File
@@ -0,0 +1,104 @@
import { promises as fs } from 'node:fs'
import path from 'node:path'
import { protocol } from 'electron'
import { isSafeRelativeEntryPath } from '../../shared/extensions/manifest'
import { isPathInside, type ExtensionPaths } from './extension-paths'
export const EXTENSION_SCHEME = 'tm-extension'
const MIME_TYPES: Record<string, string> = {
'.html': 'text/html; charset=utf-8',
'.htm': 'text/html; charset=utf-8',
'.js': 'text/javascript; charset=utf-8',
'.mjs': 'text/javascript; charset=utf-8',
'.css': 'text/css; charset=utf-8',
'.json': 'application/json; charset=utf-8',
'.txt': 'text/plain; charset=utf-8',
'.svg': 'image/svg+xml',
'.png': 'image/png',
'.jpg': 'image/jpeg',
'.jpeg': 'image/jpeg',
'.gif': 'image/gif',
'.webp': 'image/webp',
'.woff': 'font/woff',
'.woff2': 'font/woff2',
'.wasm': 'application/wasm'
}
/** 扩展页面协议:只接受 `tm-extension://<extensionId>/<path>`,realpath 必须仍在。 */
export function registerExtensionScheme(): void {
protocol.registerSchemesAsPrivileged([
{
scheme: EXTENSION_SCHEME,
privileges: {
standard: true,
secure: true,
supportFetchAPI: true,
corsEnabled: false,
stream: true
}
}
])
}
export interface ExtensionProtocolDependencies {
paths: ExtensionPaths
/** 解析代码根目录:开发模式指向外部源码,必须与后台/Manifest 用同一解析器。 */
resolveRoot: (extensionId: string) => string | null
}
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'
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('; '),
'X-Content-Type-Options': 'nosniff',
'Cache-Control': 'no-store'
}
})
} catch {
return notFound()
}
})
}
function notFound(): Response {
return new Response('Not found', {
status: 404,
headers: { 'Content-Type': 'text/plain; charset=utf-8' }
})
}
+554
View File
@@ -0,0 +1,554 @@
import fs from 'fs-extra'
import path from 'node:path'
import {
normalizeExtensionPermissions,
type ExtensionPermission
} from '../../shared/extensions/permissions'
import { EXTENSION_API_VERSION, isValidExtensionId } from '../../shared/extensions/manifest'
import { ExtensionError } from '../../shared/extensions/errors'
import { normalizeExtensionSource, type ExtensionSource } from '../../shared/extensions/source'
/**
* 宿主侧的扩展安装状态。
*
* **manifest 不是状态的一部分**:它以扩展目录里的 `manifest.json` 为准,
* 升级扩展只替换目录、不动这里的启用状态与权限授予。
*/
export interface ExtensionRegistryRecord {
id: string
version: string
apiVersion: string
enabled: boolean
grantedPermissions: ExtensionPermission[]
installedAt: number
updatedAt: number
source: ExtensionSource
/** 来源为 `template` 时,记录是哪个官方模板装入的。 */
templateId?: string
templateVersion?: string
/**
* 来源为 `development` 时的外部源码目录(本机绝对路径)。
*
* 只属于这台机器的安装状态,不随扩展源码分发;换机器要重新链接。
*/
developmentSourcePath?: string
/**
* 安装时的代码指纹;用于判断用户是否改过 `extensions/<id>` 里的副本。
* 缺失表示无法判断(旧版本安装或指纹计算失败),更新时必须保守处理。
*/
installedCodeDigest?: string
}
/**
* 一次恢复的记录。
*
* 写进状态文件而不是只放在内存里:用户看到「状态曾损坏」之后重启,
* 提示必须还在,否则他永远不知道自己的启用状态被重置过。
*/
export interface ExtensionRegistryRecovery {
at: number
kind: 'backup' | 'scan'
/** 损坏现场的**文件名**(不含目录)。 */
corruptFile?: string
}
interface RegistryFile {
version: number
extensions: ExtensionRegistryRecord[]
recovery?: ExtensionRegistryRecovery
}
const REGISTRY_VERSION = 1
/** 损坏现场最多保留的份数;超出时删除最旧的一份。 */
const CORRUPT_KEEP_LIMIT = 3
/**
* 状态文件的可信度。
*
* - `ok`:主文件有效,或文件不存在(全新安装,属于合法空状态)。
* - `recovered-from-backup`:主文件损坏,用 `.bak` 重建过;记录已降级。
* - `recovered-by-scan`:主文件与备份都不可用,由调用方扫描扩展目录重建;
* 记录一律降级为「未启用 + 无授权」。
* - `unreadable`:无法读取且无法重建。此状态下**拒绝任何写入**,
* 否则会用空状态覆盖唯一可能人工抢救的现场。
*/
export type ExtensionRegistryHealthState =
| 'ok'
| 'recovered-from-backup'
| 'recovered-by-scan'
| 'unreadable'
export interface ExtensionRegistryHealth {
state: ExtensionRegistryHealthState
at: number
/** 损坏现场的**文件名**(不含目录);用于日志与排查,不渲染绝对路径。 */
corruptFile?: string
message?: string
}
export interface ExtensionRegistryDependencies {
registryFile: string
now?: () => number
/**
* 主文件与备份均不可用时的重建来源。
*
* 返回的记录会被强制改写为 `enabled: false`、`grantedPermissions: []`:
* 扫描到磁盘上有代码,不等于用户同意运行它。
*/
recover?: () => ExtensionRegistryRecord[]
}
type ParseResult =
| { ok: true; extensions: ExtensionRegistryRecord[]; recovery?: ExtensionRegistryRecovery }
| { ok: false; reason: string }
function parseRegistryText(text: string): ParseResult {
if (!text.trim()) return { ok: false, reason: '状态文件为空' }
let raw: unknown
try {
raw = JSON.parse(text)
} catch {
return { ok: false, reason: '状态文件不是合法 JSON' }
}
if (!raw || typeof raw !== 'object' || Array.isArray(raw)) {
return { ok: false, reason: '状态文件顶层不是对象' }
}
const version = Number((raw as { version?: unknown }).version)
if (!Number.isInteger(version) || version < 1 || version > REGISTRY_VERSION) {
return { ok: false, reason: '状态文件版本不受支持' }
}
const list = (raw as { extensions?: unknown }).extensions
if (!Array.isArray(list)) return { ok: false, reason: 'extensions 不是数组' }
const extensions: ExtensionRegistryRecord[] = []
const seen = new Set<string>()
for (const [index, item] of list.entries()) {
const parsed = parseRecord(item)
if (!parsed) return { ok: false, reason: `第 ${index + 1} 条扩展记录不合法` }
if (seen.has(parsed.id)) return { ok: false, reason: `扩展 id 重复:${parsed.id}` }
seen.add(parsed.id)
extensions.push(parsed)
}
return { ok: true, extensions, recovery: parseRecovery((raw as { recovery?: unknown }).recovery) }
}
function parseRecovery(value: unknown): ExtensionRegistryRecovery | undefined {
if (!value || typeof value !== 'object' || Array.isArray(value)) return undefined
const raw = value as Record<string, unknown>
const at = Number(raw.at)
if (!Number.isFinite(at) || at <= 0) return undefined
const kind = raw.kind === 'backup' ? 'backup' : raw.kind === 'scan' ? 'scan' : null
if (!kind) return undefined
const corruptFile =
typeof raw.corruptFile === 'string' && raw.corruptFile.trim()
? raw.corruptFile.trim().slice(0, 200)
: undefined
return { at, kind, ...(corruptFile ? { corruptFile } : {}) }
}
/**
* 单条记录的严格解析。
*
* 与「尽量兼容」相反:字段类型明显不对时整份文件判为损坏,由上层进入恢复流程。
* 静默丢弃单条记录等于「部分数据丢失且不告知用户」。
*/
function parseRecord(value: unknown): ExtensionRegistryRecord | null {
if (!value || typeof value !== 'object' || Array.isArray(value)) return null
const raw = value as Record<string, unknown>
const id = String(raw.id ?? '').trim()
if (!isValidExtensionId(id)) return null
if (typeof raw.version !== 'string' || !raw.version.trim()) return null
const installedAt = Number(raw.installedAt)
const updatedAt = Number(raw.updatedAt)
const templateId =
typeof raw.templateId === 'string' && raw.templateId.trim()
? raw.templateId.trim().slice(0, 64)
: undefined
const templateVersion =
typeof raw.templateVersion === 'string' && raw.templateVersion.trim()
? raw.templateVersion.trim().slice(0, 32)
: undefined
const developmentSourcePath =
typeof raw.developmentSourcePath === 'string' && raw.developmentSourcePath.trim()
? raw.developmentSourcePath.trim().slice(0, 1024)
: undefined
const installedCodeDigest =
typeof raw.installedCodeDigest === 'string' && /^[a-f0-9]{64}$/.test(raw.installedCodeDigest)
? raw.installedCodeDigest
: undefined
return {
id,
version: raw.version.trim().slice(0, 32),
apiVersion:
typeof raw.apiVersion === 'string' && raw.apiVersion.trim()
? raw.apiVersion.trim().slice(0, 16)
: EXTENSION_API_VERSION,
// 缺字段一律视为未启用:不能因为文件被手工改坏就自动跑任意代码。
enabled: raw.enabled === true,
grantedPermissions: normalizeExtensionPermissions(raw.grantedPermissions),
installedAt: Number.isFinite(installedAt) && installedAt > 0 ? installedAt : 0,
updatedAt: Number.isFinite(updatedAt) && updatedAt > 0 ? updatedAt : 0,
// 未知来源归为 `directory`:来源只能由可信的安装入口赋予,不能从文件里猜。
source: normalizeExtensionSource(raw.source),
...(templateId ? { templateId } : {}),
...(templateVersion ? { templateVersion } : {}),
...(developmentSourcePath ? { developmentSourcePath } : {}),
...(installedCodeDigest ? { installedCodeDigest } : {})
}
}
export class ExtensionRegistry {
private readonly registryFile: string
private readonly backupFile: string
private readonly now: () => number
private readonly recoverByScan: (() => ExtensionRegistryRecord[]) | null
private state: RegistryFile = { version: REGISTRY_VERSION, extensions: [] }
private loaded = false
/**
* 主文件当前是否含可解析内容。
*
* 备份轮换只在这个标记为真时执行:主文件已经损坏时复制它,会把唯一的
* 有效备份也换成坏数据。
*/
private primaryValid = false
/** 只有 `unreadable` 需要内存态:连状态文件都写不进去,自然无法持久化。 */
private unreadable: ExtensionRegistryHealth | null = null
constructor(dependencies: ExtensionRegistryDependencies) {
this.registryFile = dependencies.registryFile
this.backupFile = `${dependencies.registryFile}.bak`
this.now = dependencies.now ?? (() => Date.now())
this.recoverByScan = dependencies.recover ?? null
}
list(): ExtensionRegistryRecord[] {
this.ensureLoaded()
return this.state.extensions.map((record) => ({
...record,
grantedPermissions: [...record.grantedPermissions]
}))
}
get(id: string): ExtensionRegistryRecord | undefined {
const key = String(id || '').trim()
if (!key) return undefined
return this.list().find((record) => record.id === key)
}
/** 状态文件的可信度;非 `ok` 时调用方必须向用户暴露,而不是当作「没装扩展」。 */
getHealth(): ExtensionRegistryHealth {
this.ensureLoaded()
if (this.unreadable) return { ...this.unreadable }
const recovery = this.state.recovery
if (!recovery) return { state: 'ok', at: this.now() }
return {
state: recovery.kind === 'backup' ? 'recovered-from-backup' : 'recovered-by-scan',
at: recovery.at,
...(recovery.corruptFile ? { corruptFile: recovery.corruptFile } : {}),
message:
recovery.kind === 'backup'
? '扩展状态文件损坏,已从备份重建;所有扩展已暂停,请重新确认后启用'
: '扩展状态文件与备份均不可用,已按磁盘目录重建;所有扩展已暂停,请重新确认后启用'
}
}
/**
* 用户确认「我知道发生过恢复」。
*
* 只清除提示标记,不改动任何扩展的启用状态与授权——那些已经由恢复流程
* 降级为「未启用 + 无授权」,需要用户逐个重新授权。
*/
acknowledgeRecovery(): boolean {
this.ensureLoaded()
if (!this.state.recovery) return false
const previous = this.state
this.state = { version: REGISTRY_VERSION, extensions: this.state.extensions }
try {
this.persist()
} catch (error) {
this.state = previous
throw error
}
return true
}
upsert(record: ExtensionRegistryRecord): ExtensionRegistryRecord {
this.ensureLoaded()
const exists = this.state.extensions.some((item) => item.id === record.id)
const next = exists
? this.state.extensions.map((item) => (item.id === record.id ? record : item))
: [...this.state.extensions, record]
this.commit(next)
return { ...record, grantedPermissions: [...record.grantedPermissions] }
}
remove(id: string): boolean {
this.ensureLoaded()
const next = this.state.extensions.filter((item) => item.id !== id)
if (next.length === this.state.extensions.length) return false
this.commit(next)
return true
}
setEnabled(id: string, enabled: boolean): ExtensionRegistryRecord | undefined {
const current = this.get(id)
if (!current) return undefined
return this.upsert({ ...current, enabled, updatedAt: this.now() })
}
setGrantedPermissions(
id: string,
permissions: ExtensionPermission[]
): ExtensionRegistryRecord | undefined {
const current = this.get(id)
if (!current) return undefined
return this.upsert({
...current,
grantedPermissions: normalizeExtensionPermissions(permissions),
updatedAt: this.now()
})
}
private ensureLoaded(): void {
if (this.loaded) return
this.loaded = true
this.load()
}
private load(): void {
const stamp = this.now()
if (!fs.existsSync(this.registryFile)) {
// 文件不存在是合法状态(首次安装),不是损坏。
this.state = { version: REGISTRY_VERSION, extensions: [] }
this.primaryValid = false
return
}
let text: string
try {
text = fs.readFileSync(this.registryFile, 'utf8')
} catch (error) {
// 读取失败(权限、IO)与「内容损坏」是两件事:不移动文件,也不尝试覆盖。
this.state = { version: REGISTRY_VERSION, extensions: [] }
this.primaryValid = false
this.unreadable = {
state: 'unreadable',
at: stamp,
message: error instanceof Error ? error.message.slice(0, 200) : '无法读取扩展状态文件'
}
return
}
const parsed = parseRegistryText(text)
if (parsed.ok) {
this.state = {
version: REGISTRY_VERSION,
extensions: parsed.extensions,
...(parsed.recovery ? { recovery: parsed.recovery } : {})
}
this.primaryValid = true
return
}
const corruptFile = this.preserveCorrupt(text)
const backup = this.tryLoadBackup()
if (backup) {
this.state = this.buildRecoveredState(backup, 'backup', corruptFile)
this.primaryValid = false
// 立即把降级后的状态写回主文件:恢复提示与「全部暂停」必须能跨重启保留。
try {
this.writeState(this.state)
this.primaryValid = true
} catch {
// 保留内存状态即可,启动不应因为一次修复失败而中断。
}
return
}
const scanned = this.scan()
if (scanned) {
this.state = this.buildRecoveredState(scanned, 'scan', corruptFile)
this.primaryValid = false
// 刻意不写盘:损坏现场仍留在原位,用户可以在修复后重新读取。
// 一旦用户执行任何写操作(启用/卸载),降级结果与恢复标记会一并落盘。
return
}
this.state = { version: REGISTRY_VERSION, extensions: [] }
this.primaryValid = false
this.unreadable = {
state: 'unreadable',
at: stamp,
...(corruptFile ? { corruptFile } : {}),
message: '扩展状态文件损坏且无法恢复;为避免覆盖现场,已停止写入'
}
}
/**
* 恢复出来的状态一律降级。
*
* 备份最多落后一版,它可能记录着用户随后撤销的授权或关闭的开关。
* 自动采纳等于「把用户已经收回的权限再发回去」,所以只保留身份与版本,
* 启用状态与授权全部清零,等用户重新确认。
*/
private buildRecoveredState(
records: ExtensionRegistryRecord[],
kind: 'backup' | 'scan',
corruptFile?: string
): RegistryFile {
return {
version: REGISTRY_VERSION,
extensions: records.map((record) => ({
...record,
enabled: false,
grantedPermissions: [],
updatedAt: this.now()
})),
recovery: {
at: this.now(),
kind,
...(corruptFile ? { corruptFile } : {})
}
}
}
private tryLoadBackup(): ExtensionRegistryRecord[] | null {
try {
if (!fs.existsSync(this.backupFile)) return null
const parsed = parseRegistryText(fs.readFileSync(this.backupFile, 'utf8'))
return parsed.ok ? parsed.extensions : null
} catch {
return null
}
}
private scan(): ExtensionRegistryRecord[] | null {
if (!this.recoverByScan) return null
let records: ExtensionRegistryRecord[]
try {
records = this.recoverByScan()
} catch {
return null
}
if (!Array.isArray(records)) return null
// 扫描结果只用于「知道有哪些扩展存在」,不继承任何授权或启用状态。
return records.map((record) => ({
...record,
enabled: false,
grantedPermissions: [],
source: 'directory' as const
}))
}
/**
* 把损坏内容写到 `.corrupt-<时间戳>`。
*
* 保留现场是恢复的前提:用户可能手工修好它,或者授权更高版本的 TraceMemo 读取。
*/
private preserveCorrupt(text: string): string | undefined {
const base = `${this.registryFile}.corrupt-${this.now().toString(36)}`
let target = base
let index = 1
while (fs.existsSync(target)) {
target = `${base}-${index}`
index += 1
}
try {
fs.writeFileSync(target, text, 'utf8')
this.pruneCorruptFiles()
return path.basename(target)
} catch {
return undefined
}
}
private pruneCorruptFiles(): void {
try {
const directory = path.dirname(this.registryFile)
const prefix = `${path.basename(this.registryFile)}.corrupt-`
const files = fs
.readdirSync(directory)
.filter((name) => name.startsWith(prefix))
.map((name) => ({ name, at: fs.statSync(path.join(directory, name)).mtimeMs }))
.sort((left, right) => left.at - right.at)
for (const file of files.slice(0, Math.max(0, files.length - CORRUPT_KEEP_LIMIT))) {
fs.removeSync(path.join(directory, file.name))
}
} catch {
// 清理失败不影响恢复本身。
}
}
private commit(extensions: ExtensionRegistryRecord[]): void {
const previous = this.state
const previousValid = this.primaryValid
// 恢复标记必须跟着普通写入一起保留:否则用户启用一个扩展就把
// 「其余扩展全部暂停过」的提示抹掉了。
this.state = {
version: REGISTRY_VERSION,
extensions,
...(previous.recovery ? { recovery: previous.recovery } : {})
}
try {
this.persist()
} catch (error) {
this.state = previous
this.primaryValid = previousValid
throw error
}
}
private persist(): void {
if (this.unreadable) {
throw new ExtensionError(
'EXTENSION_REGISTRY_UNREADABLE',
'扩展状态文件损坏且无法恢复,已拒绝写入以保留现场'
)
}
this.rotateBackup()
this.writeState(this.state)
this.primaryValid = true
}
/**
* 用当前主文件刷新 `.bak`。
*
* 三重保护:
* 1. 主文件不可信(`primaryValid === false`)时直接跳过;
* 2. 先写 `.bak.tmp` 并重新解析,拒绝把坏内容升级成备份;
* 3. 成功后才 rename 覆盖旧备份,失败时旧备份原样保留。
*/
private rotateBackup(): void {
if (!this.primaryValid) return
if (!fs.existsSync(this.registryFile)) return
const temporary = `${this.backupFile}.tmp`
try {
fs.copyFileSync(this.registryFile, temporary)
const parsed = parseRegistryText(fs.readFileSync(temporary, 'utf8'))
if (!parsed.ok) {
fs.removeSync(temporary)
return
}
fs.moveSync(temporary, this.backupFile, { overwrite: true })
} catch {
fs.removeSync(temporary)
}
}
/** 临时文件 → 读回校验 → 原子替换;中途失败不会留下半写的主文件。 */
private writeState(state: RegistryFile): void {
const directory = path.dirname(this.registryFile)
fs.ensureDirSync(directory)
const temporary = `${this.registryFile}.tmp`
fs.writeFileSync(temporary, JSON.stringify(state, null, 2), 'utf8')
const parsed = parseRegistryText(fs.readFileSync(temporary, 'utf8'))
if (!parsed.ok) {
fs.removeSync(temporary)
throw new ExtensionError('EXTENSION_REGISTRY_UNREADABLE', `写入前校验失败:${parsed.reason}`)
}
fs.moveSync(temporary, this.registryFile, { overwrite: true })
}
}
@@ -0,0 +1,143 @@
import fs from 'node:fs'
import os from 'node:os'
import path from 'node:path'
import { ExtensionError } from '../../shared/extensions/errors'
import type { ExtensionSource } from '../../shared/extensions/source'
import { isPathInside, isSamePath, type ExtensionPaths } from './extension-paths'
import type { ExtensionRegistryRecord } from './extension-registry'
export interface ExtensionRootInfo {
extensionId: string
/** 代码根目录(已 realpath)。 */
root: string
source: ExtensionSource
/** 开发模式下用户选择时的目录(同样是 realpath)。 */
developmentSourcePath?: string
}
export interface ExtensionRootResolver {
/**
* 解析扩展代码根目录。
*
* 抛 `EXTENSION_SOURCE_MISSING` 表示开发目录不可用;调用方必须保留 Registry
* 与配置,把扩展标成「源码目录不可用」,而不是当成「没装过」。
*/
resolve(extensionId: string): ExtensionRootInfo
/** 只看正式安装目录,用于导出、回滚等必须触碰安装副本的场景。 */
installedRoot(extensionId: string): string
}
export interface ExtensionRootResolverDependencies {
paths: ExtensionPaths
getRecord: (extensionId: string) => ExtensionRegistryRecord | undefined
/** 测试注入点。 */
realpath?: (target: string) => string
stat?: (target: string) => { isDirectory: () => boolean }
}
/**
* 所有扩展代码根目录的唯一来源。
*
* 在这之前,代码目录被 manager、protocol、catalog 各自拼 `paths.installDir(id)`,
* 开发模式一旦接入就会出现「后台读外部目录、页面读安装副本」的错位。
*/
export function createExtensionRootResolver(
dependencies: ExtensionRootResolverDependencies
): ExtensionRootResolver {
const realpath = dependencies.realpath ?? ((target: string) => fs.realpathSync(target))
const stat = dependencies.stat ?? ((target: string) => fs.statSync(target))
function resolveInstalled(extensionId: string): string {
return dependencies.paths.installDir(extensionId)
}
return {
installedRoot: resolveInstalled,
resolve(extensionId: string): ExtensionRootInfo {
const record = dependencies.getRecord(extensionId)
if (!record) throw new ExtensionError('EXTENSION_NOT_FOUND')
if (record.source !== 'development' || !record.developmentSourcePath) {
return { extensionId, root: resolveInstalled(extensionId), source: record.source }
}
const configured = record.developmentSourcePath
let realRoot: string
try {
realRoot = realpath(configured)
} catch {
throw new ExtensionError(
'EXTENSION_SOURCE_MISSING',
'开发源码目录不可用,请重新选择或移除链接'
)
}
let isDirectory = false
try {
isDirectory = stat(realRoot).isDirectory()
} catch {
isDirectory = false
}
if (!isDirectory) {
throw new ExtensionError('EXTENSION_SOURCE_MISSING', '开发源码路径不是目录')
}
assertSafeDevelopmentRoot(dependencies.paths, extensionId, realRoot)
return {
extensionId,
root: realRoot,
source: 'development',
developmentSourcePath: realRoot
}
}
}
}
/**
* 开发目录的安全边界。
*
* 拒绝三类位置:
* 1. 扩展自己的安装副本(否则「开发模式」等于原地打转,卸载还会误删);
* 2. 宿主的私有数据区(配置、状态、日志、暂存)——那里有用户凭据;
* 3. 文件系统根 / 用户主目录(自定义协议会把整个目录开放给 iframe)。
*/
function safeRealpath(target: string): string {
try {
return fs.realpathSync(target)
} catch {
return path.resolve(target)
}
}
export function assertSafeDevelopmentRoot(
paths: ExtensionPaths,
extensionId: string,
realRoot: string
): void {
const forbidden: Array<{ root: string; reason: string }> = [
{ root: paths.installDir(extensionId), reason: '不能指向扩展自己的安装目录' },
{ root: paths.extensionsDir, reason: '不能指向扩展安装根目录' },
{ root: paths.dataDir, reason: '不能指向宿主私有数据目录' },
{ root: paths.stateDir, reason: '不能指向宿主状态目录' },
{ root: paths.stagingDir, reason: '不能指向宿主暂存目录' }
]
for (const item of forbidden) {
// 两侧都必须 realpath:macOS 上 `/tmp` 指向 `/private/tmp`,
// 只比较字符串会让「extensions-data 里的目录」冒充外部项目。
const forbiddenRoot = safeRealpath(item.root)
if (isSamePath(forbiddenRoot, realRoot) || isPathInside(forbiddenRoot, realRoot)) {
throw new ExtensionError('EXTENSION_INVALID_PATH', item.reason)
}
}
const parsed = path.parse(realRoot)
if (realRoot === parsed.root) {
throw new ExtensionError('EXTENSION_INVALID_PATH', '不能把文件系统根目录作为扩展源码')
}
try {
if (isSamePath(os.homedir(), realRoot)) {
throw new ExtensionError('EXTENSION_INVALID_PATH', '不能把用户主目录作为扩展源码')
}
} catch (error) {
if (error instanceof ExtensionError) throw error
}
}
@@ -0,0 +1,174 @@
import fs from 'fs-extra'
import path from 'node:path'
import { ExtensionError } from '../../shared/extensions/errors'
/** 加密实现由主进程注入(Electron `safeStorage`),本模块不直接依赖 electron。 */
export interface ExtensionSecretCipher {
isAvailable: () => boolean
encrypt: (plain: string) => Buffer
decrypt: (payload: Buffer) => string
}
export interface ExtensionSecretStoreDependencies {
/** 通常是 `<userData>/extensions-state/secrets`。 */
root: string
cipher: ExtensionSecretCipher
now?: () => number
}
interface SecretFile {
version: 1
values: Record<string, string>
}
const MAX_KEY_LENGTH = 64
const MAX_VALUE_BYTES = 8 * 1024
const MAX_KEYS = 32
const SECRET_KEY_PATTERN = /^[a-zA-Z][a-zA-Z0-9._-]{0,63}$/
/**
* 扩展私有凭据。
*
* 设计取舍:
* - 每个扩展一个文件、一个命名空间,A 扩展拿不到 B 的键;
* - 落盘只有 `safeStorage` 加密后的密文,**不再产生明文 .txt**;
* - 加密不可用时直接失败,绝不退化成明文——宁可让用户知道「这台机器不支持」,
* 也不要把 Cookie 摊在磁盘上。
*
* 这不是操作系统级沙箱:扩展后台是拥有 Node 权限的本地进程,能读别的文件。
* 它能防的是「普通 SDK / 页面桥跨扩展取密钥」与「意外明文落盘」。
*/
export class ExtensionSecretStore {
private readonly root: string
private readonly cipher: ExtensionSecretCipher
private readonly now: () => number
private readonly cache = new Map<string, SecretFile>()
constructor(dependencies: ExtensionSecretStoreDependencies) {
this.root = dependencies.root
this.cipher = dependencies.cipher
this.now = dependencies.now ?? (() => Date.now())
}
isAvailable(): boolean {
try {
return this.cipher.isAvailable()
} catch {
return false
}
}
/** 只返回键名与数量,不返回值;供 UI 显示「是否已配置」。 */
listKeys(extensionId: string): string[] {
return Object.keys(this.read(extensionId).values).sort()
}
has(extensionId: string, key: string): boolean {
const name = assertKey(key)
return Object.prototype.hasOwnProperty.call(this.read(extensionId).values, name)
}
get(extensionId: string, key: string): string | null {
const name = assertKey(key)
const values = this.read(extensionId).values
return Object.prototype.hasOwnProperty.call(values, name) ? values[name] : null
}
set(extensionId: string, key: string, value: string): void {
const name = assertKey(key)
if (typeof value !== 'string') throw new ExtensionError('INVALID_REQUEST', '凭据值必须是字符串')
if (new TextEncoder().encode(value).length > MAX_VALUE_BYTES) {
throw new ExtensionError('INVALID_REQUEST', '凭据超过 8KB 上限')
}
const file = this.read(extensionId)
if (
!Object.prototype.hasOwnProperty.call(file.values, name) &&
Object.keys(file.values).length >= MAX_KEYS
) {
throw new ExtensionError('INVALID_REQUEST', `单个扩展最多保存 ${MAX_KEYS} 个凭据`)
}
file.values[name] = value
this.write(extensionId, file)
}
delete(extensionId: string, key: string): boolean {
const name = assertKey(key)
const file = this.read(extensionId)
if (!Object.prototype.hasOwnProperty.call(file.values, name)) return false
delete file.values[name]
this.write(extensionId, file)
return true
}
/** 卸载扩展且用户选择清除数据时调用。 */
clear(extensionId: string): void {
this.cache.delete(extensionId)
fs.removeSync(this.filePath(extensionId))
}
private filePath(extensionId: string): string {
return path.join(this.root, `${extensionId}.bin`)
}
private read(extensionId: string): SecretFile {
const cached = this.cache.get(extensionId)
if (cached) return { version: 1, values: { ...cached.values } }
const file = this.filePath(extensionId)
if (!fs.existsSync(file)) {
const empty: SecretFile = { version: 1, values: {} }
this.cache.set(extensionId, empty)
return { version: 1, values: {} }
}
this.assertAvailable()
let parsed: SecretFile
try {
const payload = fs.readFileSync(file)
const text = this.cipher.decrypt(payload)
const raw = JSON.parse(text) as unknown
if (!raw || typeof raw !== 'object' || Array.isArray(raw)) throw new Error('结构不合法')
const values: Record<string, string> = {}
for (const [key, value] of Object.entries((raw as { values?: unknown }).values ?? {})) {
if (SECRET_KEY_PATTERN.test(key) && typeof value === 'string') values[key] = value
}
parsed = { version: 1, values }
} catch {
// 解不开就当作没有:不能把损坏的密文当成空口令去覆盖(写盘会覆盖原文件)。
throw new ExtensionError(
'EXTENSION_STORAGE_CORRUPTED',
'扩展凭据无法解密(可能换了机器或系统密钥变更),请在扩展页面重新填写'
)
}
this.cache.set(extensionId, parsed)
return { version: 1, values: { ...parsed.values } }
}
private write(extensionId: string, file: SecretFile): void {
this.assertAvailable()
const payload = this.cipher.encrypt(JSON.stringify({ version: 1, values: file.values }))
fs.ensureDirSync(this.root)
const target = this.filePath(extensionId)
const temporary = `${target}.tmp`
fs.writeFileSync(temporary, payload, { mode: 0o600 })
fs.moveSync(temporary, target, { overwrite: true })
try {
fs.chmodSync(target, 0o600)
} catch {
// Windows 不支持 POSIX 权限位;忽略即可。
}
this.cache.set(extensionId, { version: 1, values: { ...file.values } })
void this.now
}
private assertAvailable(): void {
if (this.isAvailable()) return
throw new ExtensionError('CAPABILITY_UNAVAILABLE', '当前系统不支持安全存储,扩展凭据功能不可用')
}
}
function assertKey(value: string): string {
const key = String(value ?? '').trim()
if (!SECRET_KEY_PATTERN.test(key) || key.length > MAX_KEY_LENGTH) {
throw new ExtensionError('INVALID_REQUEST', '凭据键名不合法')
}
return key
}
@@ -0,0 +1,461 @@
import { createHash } from 'node:crypto'
import fs from 'node:fs'
import os from 'node:os'
import path from 'node:path'
import { ExtensionError } from '../../shared/extensions/errors'
import {
hasExtensionPermission,
type ExtensionPermission
} from '../../shared/extensions/permissions'
import type {
ExtensionSendImageRequest,
ExtensionSendTextRequest,
ExtensionSendTextResult,
ExtensionSendVideoRequest,
ExtensionSendVoiceRequest
} from '../../shared/extensions/rpc'
import type { PersonalWechatSendCapability } from '../../shared/personal-wechat'
import type { WechatActionRequest, WechatActionResult } from '../../shared/wechat-action'
import type { ExtensionEntitlementResult } from './extension-entitlement'
import { isPathInside } from './extension-paths'
const MAX_TEXT_LENGTH = 2_000
const MAX_VOICE_TEXT_LENGTH = 1_000
const MAX_RECIPIENT_LENGTH = 128
const MAX_MEDIA_BYTES = 100 * 1024 * 1024
const SEND_INTERVAL_MS = 2_000
const SEND_WINDOW_MS = 60_000
const SEND_WINDOW_LIMIT = 10
/** 原生发送端把视频按 `type: 'video'` 提交,这里只放行常见容器。 */
const IMAGE_EXTENSIONS = new Set(['.jpg', '.jpeg', '.png', '.gif', '.webp', '.bmp'])
const VIDEO_EXTENSIONS = new Set(['.mp4', '.mov', '.m4v'])
const VOICE_EXTENSIONS = new Set(['.mp3', '.wav', '.silk', '.amr', '.m4a', '.ogg'])
export interface ExtensionSendContext {
extensionId: string
permissions: ExtensionPermission[]
/** manifest 声明的会话范围;空数组表示不限制。 */
conversationScope: string[]
}
export interface ExtensionSendGatewayDependencies {
getCapability: () => Promise<PersonalWechatSendCapability>
checkEntitlement: () => Promise<ExtensionEntitlementResult>
executeAction: (request: WechatActionRequest) => Promise<WechatActionResult>
/** 扩展数据目录;媒体文件只允许从这里或系统临时目录发送。 */
getExtensionDataRoot?: (extensionId: string) => string
/** 使用宿主已配置的文字转语音服务生成临时音频文件。 */
synthesizeVoice?: (request: {
text: string
voiceId?: string
}) => Promise<{ filePath: string }>
cleanupVoice?: (filePath: string) => void
getFromId?: () => string | Promise<string>
now?: () => number
}
/** 扩展发送出口:权限 / 范围 / 授权 / 频率通过后交给 WechatActionGateway。 */
export class ExtensionSendGateway {
private readonly getCapability: () => Promise<PersonalWechatSendCapability>
private readonly checkEntitlement: () => Promise<ExtensionEntitlementResult>
private readonly executeAction: (request: WechatActionRequest) => Promise<WechatActionResult>
private readonly getExtensionDataRoot: (extensionId: string) => string
private readonly synthesizeVoice?: (request: {
text: string
voiceId?: string
}) => Promise<{ filePath: string }>
private readonly cleanupVoice?: (filePath: string) => void
private readonly getFromId?: () => string | Promise<string>
private readonly now: () => number
private readonly sendHistory = new Map<string, number[]>()
constructor(dependencies: ExtensionSendGatewayDependencies) {
this.getCapability = dependencies.getCapability
this.checkEntitlement = dependencies.checkEntitlement
this.executeAction = dependencies.executeAction
this.getExtensionDataRoot = dependencies.getExtensionDataRoot ?? (() => '')
this.synthesizeVoice = dependencies.synthesizeVoice
this.cleanupVoice = dependencies.cleanupVoice
this.getFromId = dependencies.getFromId
this.now = dependencies.now ?? (() => Date.now())
}
async sendText(
context: ExtensionSendContext,
request: ExtensionSendTextRequest
): Promise<ExtensionSendTextResult> {
if (!hasExtensionPermission(context.permissions, 'wechat.send.text')) {
throw new ExtensionError('PERMISSION_DENIED', '扩展没有 wechat.send.text 权限')
}
const to = String(request?.to || '').trim()
const text = String(request?.text || '').trim()
if (!to || to.length > MAX_RECIPIENT_LENGTH) {
throw new ExtensionError('INVALID_REQUEST', '接收会话 id 不合法')
}
if (!text || text.length > MAX_TEXT_LENGTH) {
throw new ExtensionError('INVALID_REQUEST', '发送内容不能为空且不能超过 2000 字')
}
if (context.conversationScope.length > 0 && !context.conversationScope.includes(to)) {
throw new ExtensionError('PERMISSION_DENIED', '目标会话超出扩展声明的范围')
}
const at = normalizeAt(request?.at, to)
this.assertRateLimit(context.extensionId)
const capability = await this.getCapability().catch(() => null)
if (!capability || !capability.supported) {
throw new ExtensionError(
'SEND_NOT_SUPPORTED',
capability?.message || '当前环境不支持微信发送'
)
}
if (!capability.ready || !capability.capabilities?.text) {
throw new ExtensionError(
'CAPABILITY_UNAVAILABLE',
capability.message || '个人微信发送能力尚未就绪'
)
}
const entitlement = await this.checkEntitlement()
if (!entitlement.ok) {
throw new ExtensionError('LICENSE_REQUIRED', entitlement.message)
}
const result = await this.executeAction({
...(request.dedupeKey
? { idempotencyKey: extensionIdempotencyKey(context.extensionId, request.dedupeKey) }
: {}),
origin: 'extension',
purpose: 'extension_send',
triggerType: 'automation',
recipient: { type: to.endsWith('@chatroom') ? 'group' : 'contact', id: to },
content: { type: 'text', text, ...(at ? { at } : {}) },
metadata: { extensionId: context.extensionId }
})
if (result.status === 'sent') {
return { actionId: result.actionId, status: 'sent' }
}
throw new ExtensionError(mapGatewayError(result.errorCode), result.reason || '微信发送失败')
}
/** 发送图片;文件边界是硬性的:只允许扩展数据目录或系统临时目录里的普通文件, 否则扩展就能借 TraceMemo 把本机任意文件发出去。 */
async sendImage(
context: ExtensionSendContext,
request: ExtensionSendImageRequest
): Promise<ExtensionSendTextResult> {
if (!hasExtensionPermission(context.permissions, 'wechat.send.image')) {
throw new ExtensionError('PERMISSION_DENIED', '扩展没有 wechat.send.image 权限')
}
const to = String(request?.to || '').trim()
if (!to || to.length > MAX_RECIPIENT_LENGTH) {
throw new ExtensionError('INVALID_REQUEST', '接收会话 id 不合法')
}
if (context.conversationScope.length > 0 && !context.conversationScope.includes(to)) {
throw new ExtensionError('PERMISSION_DENIED', '目标会话超出扩展声明的范围')
}
const mediaPath = assertSendableMediaPath(
request?.path,
this.getExtensionDataRoot(context.extensionId),
IMAGE_EXTENSIONS
)
this.assertRateLimit(context.extensionId)
const capability = await this.getCapability().catch(() => null)
if (!capability || !capability.supported) {
throw new ExtensionError(
'SEND_NOT_SUPPORTED',
capability?.message || '当前环境不支持微信发送'
)
}
if (!capability.ready || !capability.capabilities?.image) {
throw new ExtensionError(
'CAPABILITY_UNAVAILABLE',
capability.message || '个人微信发送能力尚未就绪'
)
}
const entitlement = await this.checkEntitlement()
if (!entitlement.ok) {
throw new ExtensionError('LICENSE_REQUIRED', entitlement.message)
}
const result = await this.executeAction({
...(request.dedupeKey
? { idempotencyKey: extensionIdempotencyKey(context.extensionId, request.dedupeKey) }
: {}),
origin: 'extension',
purpose: 'extension_send',
triggerType: 'automation',
recipient: { type: to.endsWith('@chatroom') ? 'group' : 'contact', id: to },
content: { type: 'image', path: mediaPath },
metadata: { extensionId: context.extensionId }
})
if (result.status === 'sent') {
return { actionId: result.actionId, status: 'sent' }
}
throw new ExtensionError(mapGatewayError(result.errorCode), result.reason || '微信发送失败')
}
/** 发送视频;与图片分开是刻意的:原生 Host 用 `type: 'video'` 提交,失败时不能悄悄降级成图片。 */
async sendVideo(
context: ExtensionSendContext,
request: ExtensionSendVideoRequest
): Promise<ExtensionSendTextResult> {
if (!hasExtensionPermission(context.permissions, 'wechat.send.video')) {
throw new ExtensionError('PERMISSION_DENIED', '扩展没有 wechat.send.video 权限')
}
const to = String(request?.to || '').trim()
if (!to || to.length > MAX_RECIPIENT_LENGTH) {
throw new ExtensionError('INVALID_REQUEST', '接收会话 id 不合法')
}
if (context.conversationScope.length > 0 && !context.conversationScope.includes(to)) {
throw new ExtensionError('PERMISSION_DENIED', '目标会话超出扩展声明的范围')
}
const mediaPath = assertSendableMediaPath(
request?.path,
this.getExtensionDataRoot(context.extensionId),
VIDEO_EXTENSIONS
)
this.assertRateLimit(context.extensionId)
const capability = await this.getCapability().catch(() => null)
if (!capability || !capability.supported) {
throw new ExtensionError(
'SEND_NOT_SUPPORTED',
capability?.message || '当前环境不支持微信发送'
)
}
if (!capability.ready || !capability.capabilities?.video) {
throw new ExtensionError(
'CAPABILITY_UNAVAILABLE',
capability.message || '当前微信发送能力不支持视频'
)
}
const entitlement = await this.checkEntitlement()
if (!entitlement.ok) {
throw new ExtensionError('LICENSE_REQUIRED', entitlement.message)
}
const result = await this.executeAction({
...(request.dedupeKey
? { idempotencyKey: extensionIdempotencyKey(context.extensionId, request.dedupeKey) }
: {}),
origin: 'extension',
purpose: 'extension_send',
triggerType: 'automation',
recipient: { type: to.endsWith('@chatroom') ? 'group' : 'contact', id: to },
content: { type: 'video', path: mediaPath },
metadata: { extensionId: context.extensionId }
})
if (result.status === 'sent') {
return { actionId: result.actionId, status: 'sent' }
}
throw new ExtensionError(mapGatewayError(result.errorCode), result.reason || '微信发送失败')
}
/** 发送语音气泡。 */
async sendVoice(
context: ExtensionSendContext,
request: ExtensionSendVoiceRequest
): Promise<ExtensionSendTextResult> {
if (!hasExtensionPermission(context.permissions, 'wechat.send.voice')) {
throw new ExtensionError('PERMISSION_DENIED', '扩展没有 wechat.send.voice 权限')
}
const to = String(request?.to || '').trim()
if (!to || to.length > MAX_RECIPIENT_LENGTH) {
throw new ExtensionError('INVALID_REQUEST', '接收会话 id 不合法')
}
if (context.conversationScope.length > 0 && !context.conversationScope.includes(to)) {
throw new ExtensionError('PERMISSION_DENIED', '目标会话超出扩展声明的范围')
}
const rawPath = String(request?.path || '').trim()
const rawText = String(request?.text || '').trim()
if (!rawPath && !rawText) {
throw new ExtensionError('INVALID_REQUEST', '发送语音需要提供 text 或音频文件 path')
}
if (rawText.length > MAX_VOICE_TEXT_LENGTH) {
throw new ExtensionError(
'INVALID_REQUEST',
`语音合成文字不能超过 ${MAX_VOICE_TEXT_LENGTH} 字`
)
}
let directMediaPath = ''
if (rawPath) {
directMediaPath = assertSendableMediaPath(
rawPath,
this.getExtensionDataRoot(context.extensionId),
VOICE_EXTENSIONS
)
} else if (!this.synthesizeVoice) {
throw new ExtensionError('CAPABILITY_UNAVAILABLE', '当前宿主未配置文字转语音合成能力')
}
this.assertRateLimit(context.extensionId)
const capability = await this.getCapability().catch(() => null)
if (!capability || !capability.supported) {
throw new ExtensionError(
'SEND_NOT_SUPPORTED',
capability?.message || '当前环境不支持微信发送'
)
}
if (!capability.ready || !capability.capabilities?.voice) {
throw new ExtensionError(
'CAPABILITY_UNAVAILABLE',
capability.message || '当前微信发送能力不支持语音'
)
}
const entitlement = await this.checkEntitlement()
if (!entitlement.ok) {
throw new ExtensionError('LICENSE_REQUIRED', entitlement.message)
}
let synthesizedFile = ''
try {
let mediaPath = directMediaPath
if (!mediaPath && this.synthesizeVoice) {
const voiceId = String(request?.voiceId || '').trim() || undefined
const synthesized = await this.synthesizeVoice({ text: rawText, voiceId })
synthesizedFile = String(synthesized?.filePath || '').trim()
mediaPath = assertSendableMediaPath(
synthesizedFile,
this.getExtensionDataRoot(context.extensionId),
VOICE_EXTENSIONS
)
}
const fromId = this.getFromId ? String((await this.getFromId()) || '').trim() : ''
const result = await this.executeAction({
...(request.dedupeKey
? { idempotencyKey: extensionIdempotencyKey(context.extensionId, request.dedupeKey) }
: {}),
origin: 'extension',
purpose: 'extension_send',
triggerType: 'automation',
recipient: { type: to.endsWith('@chatroom') ? 'group' : 'contact', id: to },
content: { type: 'voice', path: mediaPath },
metadata: {
extensionId: context.extensionId,
...(fromId ? { fromId } : {})
}
})
if (result.status === 'sent') {
return { actionId: result.actionId, status: 'sent' }
}
throw new ExtensionError(mapGatewayError(result.errorCode), result.reason || '微信语音发送失败')
} finally {
if (synthesizedFile && this.cleanupVoice) {
try {
this.cleanupVoice(synthesizedFile)
} catch {
// 临时语音清理失败不影响主流程结果。
}
}
}
}
/** 令牌窗口:同一扩展 60 秒内最多 10 条,且两条之间至少 2 秒。 */
private assertRateLimit(extensionId: string): void {
const now = this.now()
const history = (this.sendHistory.get(extensionId) ?? []).filter(
(timestamp) => now - timestamp < SEND_WINDOW_MS
)
const last = history[history.length - 1]
if (last !== undefined && now - last < SEND_INTERVAL_MS) {
throw new ExtensionError('RATE_LIMITED', '发送过于频繁,请稍后再试')
}
if (history.length >= SEND_WINDOW_LIMIT) {
throw new ExtensionError('RATE_LIMITED', '已达到每分钟发送上限')
}
history.push(now)
this.sendHistory.set(extensionId, history)
}
}
/** 媒体路径校验:必须是扩展数据目录或系统临时目录内的普通文件;用 realpath 复核,符号链接跳到目录外同样会被拒绝。 */
function assertSendableMediaPath(value: unknown, dataRoot: string, allowed: Set<string>): string {
const raw = String(value ?? '').trim()
if (!raw || raw.length > 4_096) {
throw new ExtensionError('INVALID_REQUEST', '媒体路径不合法')
}
if (!path.isAbsolute(raw)) {
throw new ExtensionError('INVALID_REQUEST', '媒体路径必须是绝对路径')
}
let realPath: string
try {
realPath = fs.realpathSync(raw)
} catch {
throw new ExtensionError('INVALID_REQUEST', '媒体文件不存在')
}
const stat = fs.statSync(realPath)
if (!stat.isFile()) {
throw new ExtensionError('INVALID_REQUEST', '媒体路径必须是普通文件')
}
if (stat.size <= 0 || stat.size > MAX_MEDIA_BYTES) {
throw new ExtensionError('INVALID_REQUEST', '媒体文件为空或超过 100MB')
}
const extension = path.extname(realPath).toLowerCase()
if (!allowed.has(extension)) {
throw new ExtensionError('SEND_NOT_SUPPORTED', `不支持发送 ${extension || '无扩展名'} 文件`)
}
const roots = [dataRoot, os.tmpdir()]
.filter(Boolean)
.map((root) => {
try {
return fs.realpathSync(root)
} catch {
return ''
}
})
.filter(Boolean)
if (!roots.some((root) => isPathInside(root, realPath))) {
throw new ExtensionError('PERMISSION_DENIED', '只能发送扩展数据目录或临时目录中的文件')
}
return realPath
}
function normalizeAt(value: unknown, recipientId: string): Record<string, string> | undefined {
if (!value || typeof value !== 'object' || Array.isArray(value)) return undefined
if (!recipientId.endsWith('@chatroom')) return undefined
const entries = Object.entries(value as Record<string, unknown>)
if (!entries.length || entries.length > 50) return undefined
const result: Record<string, string> = {}
for (const [wxid, name] of entries) {
const key = String(wxid).trim()
if (!key || typeof name !== 'string' || !name.trim()) continue
result[key] = name.trim()
}
return Object.keys(result).length ? result : undefined
}
/** 扩展提供的去重键只作为后缀,前缀固定,避免与官方自动化幂等键串台。 */
export function extensionIdempotencyKey(extensionId: string, dedupeKey: string): string {
const digest = createHash('sha1')
.update(`${extensionId}\u0001${String(dedupeKey).trim()}`)
.digest('hex')
return `extension:${extensionId}:${digest}`
}
function mapGatewayError(
code: string | undefined
): 'CAPABILITY_UNAVAILABLE' | 'PERMISSION_DENIED' | 'ACTION_FAILED' | 'INVALID_REQUEST' {
switch (code) {
case 'SEND_CAPABILITY_UNAVAILABLE':
case 'SEND_NOT_READY':
return 'CAPABILITY_UNAVAILABLE'
case 'ACTION_NOT_ALLOWED':
case 'RECIPIENT_SCOPE_VIOLATION':
return 'PERMISSION_DENIED'
case 'INVALID_REQUEST':
case 'INVALID_RECIPIENT':
return 'INVALID_REQUEST'
default:
return 'ACTION_FAILED'
}
}
+224
View File
@@ -0,0 +1,224 @@
import { app, safeStorage } from 'electron'
import path from 'node:path'
import { AIProviderService } from '../services/ai-provider-service'
import {
getChatDb,
getSelfAccountInfo,
isReady,
listContacts,
listMessagesAsync,
resolveMd5
} from '../services/chat-service'
import { personalWechatCapabilityService } from '../services/personal-wechat-capability-service'
import { TextToSpeechSettingsService } from '../services/text-to-speech-settings-service'
import { wechatActionGateway } from '../services/wechat-action-gateway'
import { ExtensionError } from '../../shared/extensions/errors'
import type {
ExtensionMessagesQueryRequest,
ExtensionQueriedMessage
} from '../../shared/extensions/rpc'
import { checkExtensionSendEntitlement } from './extension-entitlement'
import { ExtensionManager } from './extension-manager'
import { getExtensionPaths } from './extension-paths'
let manager: ExtensionManager | null = null
/** 官方模板资源根目录;两者都不指向 `examples/extensions`——源码树不是运行时依赖。 */
function resolveTemplateRoot(): string {
const override = process.env.TRACEMEMO_EXTENSION_TEMPLATES_DIR
if (override && override.trim()) return path.resolve(override.trim())
if (app.isPackaged) return path.join(process.resourcesPath, 'extension-templates')
return path.join(app.getAppPath(), 'build', 'extension-templates')
}
export interface ExtensionSystemOptions {
appVersion: string
onChange: (extensionId: string, reason: string) => void
}
/** 扩展系统的主进程接线。 */
export async function initExtensionSystem(options: ExtensionSystemOptions): Promise<void> {
if (manager) return
const ttsService = new TextToSpeechSettingsService()
manager = new ExtensionManager({
paths: getExtensionPaths(),
appVersion: options.appVersion,
getCapability: () => personalWechatCapabilityService.getPersonalWechatSendCapability(),
checkEntitlement: () => checkExtensionSendEntitlement(),
executeAction: (request) => wechatActionGateway.execute(request),
queryMessages: queryConversationMessages,
listGroups: async () => {
try {
return listContacts()
.filter((contact) => contact.type === 'group')
.map((contact) => ({
id: contact.m_nsUsrName,
name: contact.m_nsNickName || contact.m_nsUsrName
}))
} catch {
return []
}
},
aiChat: chatWithConfiguredProvider,
aiStatus: () => {
// 只读「是否已配置 + 模型显示名」,不返回 key 或 endpoint。
const config = new AIProviderService().getRuntimeConfig()
return { configured: config.configured, modelName: config.modelName }
},
ttsStatus: async () => {
const status = await ttsService.getVoiceStatus()
return {
configured: status.configured,
model: status.model,
selectedVoiceId: status.selectedVoiceId,
selectedVoice: status.selectedVoice
? {
id: status.selectedVoice.id,
name: status.selectedVoice.name,
description: status.selectedVoice.description,
tags: status.selectedVoice.tags,
languages: status.selectedVoice.languages,
...(status.selectedVoice.authorName
? { authorName: status.selectedVoice.authorName }
: {}),
...(status.selectedVoice.previewUrl
? { previewUrl: status.selectedVoice.previewUrl }
: {}),
...(status.selectedVoice.coverImage
? { coverImage: status.selectedVoice.coverImage }
: {})
}
: null
}
},
synthesizeVoice: async ({ text, voiceId }) => {
const current = ttsService.get()
const referenceId = String(voiceId || current.settings.selectedVoiceId || '').trim()
if (!referenceId) {
throw new ExtensionError('CAPABILITY_UNAVAILABLE', '请先在文字转语音设置中选择音色')
}
const synthesized = await ttsService.synthesize({ text, referenceId })
if (!synthesized.success || !synthesized.filePath) {
throw new ExtensionError(
'CAPABILITY_UNAVAILABLE',
synthesized.error || '文字转语音生成失败'
)
}
return { filePath: synthesized.filePath }
},
cleanupVoice: (filePath) => {
ttsService.removeGeneratedAudio(filePath)
},
getAccountId: () => String(getSelfAccountInfo()?.wxid || ''),
getSelfUsernames: () => {
try {
return (getChatDb()?.getWcdb4Client()?.getMyUsernameCandidates?.() ?? []).filter(Boolean)
} catch {
return []
}
},
isDatabaseReady: () => {
try {
return isReady()
} catch {
return false
}
},
templatesRoot: resolveTemplateRoot(),
secretCipher: {
isAvailable: () => safeStorage.isEncryptionAvailable(),
encrypt: (plain: string) => safeStorage.encryptString(plain),
decrypt: (payload: Buffer) => safeStorage.decryptString(payload)
},
onChange: (extensionId, reason) => options.onChange(extensionId, reason)
})
await manager.initialize()
}
export function getExtensionManager(): ExtensionManager {
if (!manager) throw new Error('扩展系统尚未初始化')
return manager
}
export function hasExtensionManager(): boolean {
return manager !== null
}
export async function disposeExtensionSystem(): Promise<void> {
const current = manager
manager = null
if (current) await current.dispose()
}
function normalizeQueriedMessageType(rawType: string | undefined): {
type: string
isTextLike: boolean
} {
const value = String(rawType ?? '').trim()
if (value === 'text' || value === '普通文本' || value === '1') {
return { type: 'text', isTextLike: true }
}
if (value === '引用消息') {
return { type: 'text', isTextLike: true }
}
if (value === '图片' || value === 'image') return { type: 'image', isTextLike: false }
if (value === '语音' || value === 'voice') return { type: 'voice', isTextLike: false }
if (value === '视频' || value === 'video') return { type: 'video', isTextLike: false }
if (value === '表情包' || value === 'sticker') return { type: 'sticker', isTextLike: false }
if (value === '系统消息' || value === 'system') return { type: 'system', isTextLike: false }
return { type: value || 'other', isTextLike: false }
}
async function queryConversationMessages(
request: ExtensionMessagesQueryRequest
): Promise<ExtensionQueriedMessage[]> {
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 rawMessages = await listMessagesAsync(
contact.md5,
Math.floor((request.startTime ?? Date.now() - 86_400_000) / 1000),
Math.floor((request.endTime ?? Date.now()) / 1000),
undefined,
'',
'unknown'
)
const sorted = [...rawMessages]
.sort((left, right) => (left.createTime ?? 0) - (right.createTime ?? 0))
.slice(-limit)
return sorted.map((message) => {
const normalizedType = normalizeQueriedMessageType(message.type)
const quoteText =
message.contentData &&
typeof message.contentData === 'object' &&
message.contentData.type === 'quote' &&
typeof message.contentData.content === 'string'
? message.contentData.content
: ''
const resolvedText = String(message.content || quoteText || '').trim()
return {
messageId: message.serverId || String(message.localId ?? message.id),
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)
}
})
}
async function chatWithConfiguredProvider(
messages: Array<{ role: string; content: string }>
): Promise<{ text: string }> {
const result = await new AIProviderService().chat(messages)
if (!result.success) {
throw new ExtensionError('CAPABILITY_UNAVAILABLE', result.error || 'AI 调用失败')
}
return { text: result.data || '' }
}
export function extensionManagerForTests(value: ExtensionManager | null): void {
manager = value
}
+388
View File
@@ -0,0 +1,388 @@
import fs from 'fs-extra'
import path from 'node:path'
import { ExtensionError } from '../../shared/extensions/errors'
import type { ExtensionStorageHealthState } from '../../shared/extensions/types'
const STORAGE_FILE = 'storage.json'
const STORAGE_VERSION = 1
const MAX_KEY_LENGTH = 64
const MAX_VALUE_BYTES = 256 * 1024
const MAX_TOTAL_BYTES = 1024 * 1024
const KEY_PATTERN = /^[A-Za-z0-9._-]{1,64}$/
/** 每个扩展最多保留的损坏现场份数;超出时删除最旧的。 */
const CORRUPT_KEEP_LIMIT = 3
interface StorageFile {
version: number
values: Record<string, unknown>
}
export interface ExtensionStorageHealth {
state: ExtensionStorageHealthState
at: number
/** 损坏现场的**文件名**(不含目录);不渲染绝对路径。 */
corruptFile?: string
message?: string
}
export interface ExtensionStorageDependencies {
/** 通常是 `<userData>/extensions-data`。 */
dataRoot: string
maxTotalBytes?: number
maxValueBytes?: number
now?: () => number
/**
* 健康状态发生变化时的通知。
*
* 运行期才发生损坏/回退时,宿主要靠这个立刻收住扩展——
* 只等下一次启动才处理,那台机器人已经用旧配置发完消息了。
*/
onHealthChange?: (extensionId: string, health: ExtensionStorageHealth) => void
}
type ParseResult = { ok: true; values: Record<string, unknown> } | { ok: false; reason: string }
function parseStorageText(text: string): ParseResult {
if (!text.trim()) return { ok: false, reason: '存储文件为空' }
let raw: unknown
try {
raw = JSON.parse(text)
} catch {
return { ok: false, reason: '存储文件不是合法 JSON' }
}
if (!raw || typeof raw !== 'object' || Array.isArray(raw)) {
return { ok: false, reason: '存储文件顶层不是对象' }
}
const version = Number((raw as { version?: unknown }).version)
if (!Number.isInteger(version) || version !== STORAGE_VERSION) {
return { ok: false, reason: '存储文件版本不受支持' }
}
const values = (raw as { values?: unknown }).values
if (!values || typeof values !== 'object' || Array.isArray(values)) {
return { ok: false, reason: 'values 不是对象' }
}
return { ok: true, values: values as Record<string, unknown> }
}
/**
* 扩展私有的键值存储。
*
* 边界:
* - 每个扩展一个独立目录,键空间互不可见;
* - 单值 / 总量都有上限,写入前先序列化,**不存无法序列化的值**;
* - 卸载时由 `ExtensionInstaller` 决定是否删除,本类不主动清理。
*
* 损坏语义:主文件解析失败时先尝试 `storage.json.bak`;两者都不可用时,
* 该扩展进入 `unrecovered` 状态,`set` 会被拒绝。宁可让扩展报错,
* 也不能用一次写入把用户唯一的一份配置覆盖成空。
*/
export class ExtensionStorage {
private readonly dataRoot: string
private readonly maxTotalBytes: number
private readonly maxValueBytes: number
private readonly now: () => number
private readonly onHealthChange?: ExtensionStorageDependencies['onHealthChange']
private readonly healthByExtension = new Map<string, ExtensionStorageHealth>()
constructor(dependencies: ExtensionStorageDependencies) {
this.dataRoot = dependencies.dataRoot
this.maxTotalBytes = dependencies.maxTotalBytes ?? MAX_TOTAL_BYTES
this.maxValueBytes = dependencies.maxValueBytes ?? MAX_VALUE_BYTES
this.now = dependencies.now ?? (() => Date.now())
this.onHealthChange = dependencies.onHealthChange
}
filePath(extensionId: string): string {
return path.join(this.dataRoot, extensionId, STORAGE_FILE)
}
directory(extensionId: string): string {
return path.join(this.dataRoot, extensionId)
}
get(extensionId: string, key: unknown): unknown {
const name = assertKey(key)
const values = this.read(extensionId).values
this.assertReadable(extensionId)
return Object.prototype.hasOwnProperty.call(values, name) ? clone(values[name]) : undefined
}
set(extensionId: string, key: unknown, value: unknown): void {
const name = assertKey(key)
const serialized = serializeValue(value)
if (Buffer.byteLength(serialized, 'utf8') > this.maxValueBytes) {
throw new ExtensionError('STORAGE_LIMIT_EXCEEDED', '单个存储值超出上限')
}
const file = this.read(extensionId)
this.assertReadable(extensionId)
file.values[name] = JSON.parse(serialized)
this.assertTotalSize(file)
this.write(extensionId, file)
}
remove(extensionId: string, key: unknown): boolean {
const name = assertKey(key)
const file = this.read(extensionId)
this.assertReadable(extensionId)
if (!Object.prototype.hasOwnProperty.call(file.values, name)) return false
delete file.values[name]
this.write(extensionId, file)
return true
}
list(extensionId: string): Array<{ key: string; value: unknown }> {
const values = this.read(extensionId).values
this.assertReadable(extensionId)
return Object.keys(values).map((key) => ({ key, value: clone(values[key]) }))
}
clear(extensionId: string): void {
this.write(extensionId, { version: STORAGE_VERSION, values: {} })
}
/**
* 显式重置:保留损坏现场,然后把存储清空。
*
* 只允许用户从界面触发;扩展自身不能调用(`tm.storage` 没有这个能力)。
*/
reset(extensionId: string): void {
this.read(extensionId)
this.writeState(extensionId, { version: STORAGE_VERSION, values: {} }, { rotateBackup: false })
this.healthByExtension.set(extensionId, { state: 'ok', at: this.now() })
}
/**
* 用户确认「接受从备份恢复出来的配置」。
*
* 恢复出来的内容可能落后一版——比如机器人开关还停在 `true`。
* 在用户点这一下之前,宿主不会启动该扩展(见 `ExtensionManager` 的启动前检查)。
*/
acknowledge(extensionId: string): void {
const current = this.health(extensionId)
if (current.state !== 'recovered-from-backup') {
throw new ExtensionError('INVALID_REQUEST', '当前没有待确认的配置恢复')
}
this.healthByExtension.set(extensionId, { state: 'ok', at: this.now() })
}
/**
* 未确认的恢复 / 无法恢复时,读写一律拒绝。
*
* 只让 `health()` 与 `reset()` / `acknowledge()` 能穿过这道闸:
* 前者给界面看状态,后两者是用户的显式处理动作。
*/
private assertReadable(extensionId: string): void {
const health = this.healthByExtension.get(extensionId)
if (!health || health.state === 'ok') return
if (health.state === 'recovered-from-backup') {
throw new ExtensionError(
'EXTENSION_STORAGE_CORRUPTED',
'扩展配置刚从备份恢复,用户确认前读写已暂停'
)
}
throw new ExtensionError('EXTENSION_STORAGE_CORRUPTED', '扩展配置已损坏且没有可用备份')
}
private reportHealth(extensionId: string, health: ExtensionStorageHealth): void {
this.healthByExtension.set(extensionId, health)
if (health.state === 'ok') return
try {
this.onHealthChange?.(extensionId, health)
} catch {
// 通知失败不能反过来影响存储读写。
}
}
health(extensionId: string): ExtensionStorageHealth {
this.read(extensionId)
return { ...(this.healthByExtension.get(extensionId) ?? { state: 'ok', at: this.now() }) }
}
private read(extensionId: string): StorageFile {
const filePath = this.filePath(extensionId)
if (!fs.existsSync(filePath)) {
this.reportHealth(extensionId, { state: 'ok', at: this.now() })
return { version: STORAGE_VERSION, values: {} }
}
let text: string
try {
text = fs.readFileSync(filePath, 'utf8')
} catch (error) {
this.reportHealth(extensionId, {
state: 'unrecovered',
at: this.now(),
message: error instanceof Error ? error.message.slice(0, 200) : '无法读取扩展配置'
})
return { version: STORAGE_VERSION, values: {} }
}
const parsed = parseStorageText(text)
if (parsed.ok) {
// `recovered-from-backup` 要保留到用户看到它为止:恢复成功后立刻改回 `ok`,
// 界面就再也不会提示「这份配置曾经损坏过」。
const current = this.healthByExtension.get(extensionId)
if (current?.state !== 'recovered-from-backup') {
this.reportHealth(extensionId, { state: 'ok', at: this.now() })
}
return { version: STORAGE_VERSION, values: parsed.values }
}
const corruptFile = this.preserveCorrupt(extensionId, text)
const backup = this.tryLoadBackup(extensionId)
if (backup) {
this.reportHealth(extensionId, {
state: 'recovered-from-backup',
at: this.now(),
...(corruptFile ? { corruptFile } : {}),
message: '扩展配置损坏,已从备份恢复'
})
try {
// 主文件此刻是坏的,不能让它进入备份轮换,否则会覆盖刚读到的有效备份。
this.writeState(
extensionId,
{ version: STORAGE_VERSION, values: backup },
{ rotateBackup: false }
)
} catch {
// 提升备份失败时仍返回备份内容,下次写入会再试。
}
return { version: STORAGE_VERSION, values: backup }
}
this.reportHealth(extensionId, {
state: 'unrecovered',
at: this.now(),
...(corruptFile ? { corruptFile } : {}),
message: '扩展配置损坏且没有可用备份;写入已停止以保留现场'
})
return { version: STORAGE_VERSION, values: {} }
}
private tryLoadBackup(extensionId: string): Record<string, unknown> | null {
const backupPath = `${this.filePath(extensionId)}.bak`
try {
if (!fs.existsSync(backupPath)) return null
const parsed = parseStorageText(fs.readFileSync(backupPath, 'utf8'))
return parsed.ok ? parsed.values : null
} catch {
return null
}
}
private preserveCorrupt(extensionId: string, text: string): string | undefined {
const filePath = this.filePath(extensionId)
const base = `${filePath}.corrupt-${this.now().toString(36)}`
let target = base
let index = 1
while (fs.existsSync(target)) {
target = `${base}-${index}`
index += 1
}
try {
fs.ensureDirSync(path.dirname(filePath))
fs.writeFileSync(target, text, 'utf8')
this.pruneCorruptFiles(extensionId)
return path.basename(target)
} catch {
return undefined
}
}
private pruneCorruptFiles(extensionId: string): void {
try {
const directory = path.dirname(this.filePath(extensionId))
const prefix = `${STORAGE_FILE}.corrupt-`
const files = fs
.readdirSync(directory)
.filter((name) => name.startsWith(prefix))
.map((name) => ({ name, at: fs.statSync(path.join(directory, name)).mtimeMs }))
.sort((left, right) => left.at - right.at)
for (const file of files.slice(0, Math.max(0, files.length - CORRUPT_KEEP_LIMIT))) {
fs.removeSync(path.join(directory, file.name))
}
} catch {
// 清理失败不影响恢复本身。
}
}
private write(extensionId: string, file: StorageFile): void {
this.writeState(extensionId, file, { rotateBackup: true })
this.reportHealth(extensionId, { state: 'ok', at: this.now() })
}
/**
* 主文件 → `.bak` → 新内容。
*
* `rotateBackup` 只在主文件可信时为真:从备份恢复、显式重置这两条路径
* 面对的主文件都是坏的,让它们参与轮换会把有效备份一起换掉。
*/
private writeState(
extensionId: string,
file: StorageFile,
options: { rotateBackup: boolean }
): void {
const filePath = this.filePath(extensionId)
fs.ensureDirSync(path.dirname(filePath))
if (options.rotateBackup) this.rotateBackup(extensionId)
const temporary = `${filePath}.tmp`
fs.writeFileSync(temporary, JSON.stringify(file, null, 2), 'utf8')
const parsed = parseStorageText(fs.readFileSync(temporary, 'utf8'))
if (!parsed.ok) {
fs.removeSync(temporary)
throw new ExtensionError('STORAGE_LIMIT_EXCEEDED', `写入前校验失败:${parsed.reason}`)
}
fs.moveSync(temporary, filePath, { overwrite: true })
}
private rotateBackup(extensionId: string): void {
const filePath = this.filePath(extensionId)
if (!fs.existsSync(filePath)) return
const backupPath = `${filePath}.bak`
const temporary = `${backupPath}.tmp`
try {
fs.copyFileSync(filePath, temporary)
const parsed = parseStorageText(fs.readFileSync(temporary, 'utf8'))
if (!parsed.ok) {
fs.removeSync(temporary)
return
}
fs.moveSync(temporary, backupPath, { overwrite: true })
} catch {
fs.removeSync(temporary)
}
}
private assertTotalSize(file: StorageFile): void {
const bytes = Buffer.byteLength(JSON.stringify(file.values), 'utf8')
if (bytes > this.maxTotalBytes) {
throw new ExtensionError('STORAGE_LIMIT_EXCEEDED', '扩展存储总量超出上限')
}
}
}
function assertKey(value: unknown): string {
if (typeof value !== 'string') throw new ExtensionError('INVALID_REQUEST', '存储键必须是字符串')
const key = value.trim()
if (!KEY_PATTERN.test(key)) {
throw new ExtensionError('INVALID_REQUEST', '存储键只能包含字母、数字、点、下划线与短横线')
}
if (key.length > MAX_KEY_LENGTH) throw new ExtensionError('INVALID_REQUEST', '存储键过长')
return key
}
function serializeValue(value: unknown): string {
if (value === undefined) throw new ExtensionError('INVALID_REQUEST', '不能存储 undefined')
try {
const serialized = JSON.stringify(value)
if (serialized === undefined) throw new Error('unsupported')
return serialized
} catch {
throw new ExtensionError('INVALID_REQUEST', '存储值必须可序列化为 JSON')
}
}
function clone<T>(value: T): T {
if (value === null || typeof value !== 'object') return value
return JSON.parse(JSON.stringify(value)) as T
}
@@ -0,0 +1,407 @@
import { existsSync, promises as fs } from 'node:fs'
import path from 'node:path'
import { createHash } from 'node:crypto'
import { ExtensionError } from '../../shared/extensions/errors'
import { compareSemver } from '../../shared/extensions/manifest'
import type { ExtensionRegistryRecord } from './extension-registry'
import { normalizeExtensionPermissions } from '../../shared/extensions/permissions'
import type {
ExtensionTemplateEntry,
ExtensionTemplateRequirement,
ExtensionTemplateStatus,
TemplateDependencyCheck
} from '../../shared/extensions/templates'
export type {
ExtensionTemplateEntry,
ExtensionTemplateRequirement,
ExtensionTemplateState,
ExtensionTemplateStatus,
TemplateDependencyCheck
} from '../../shared/extensions/templates'
export interface ExtensionTemplateCatalogDependencies {
/** 模板资源根目录;打包后是 `<resources>/extension-templates`。 */
templateRoot: string
getRecord: (extensionId: string) => ExtensionRegistryRecord | undefined
/** 已安装扩展的代码目录;用来看依赖脚本在不在。 */
resolveInstallDir: (extensionId: string) => string
platform?: NodeJS.Platform
/** 测试注入点:默认用真实文件系统。 */
exists?: (filePath: string) => boolean
readFile?: (filePath: string) => Promise<Buffer>
/** 依赖探测注入点:默认读本机 PATH 与常见安装位置。 */
probePython?: () => string | null
probeChrome?: () => string | null
}
const INDEX_FILE = 'index.json'
const SUPPORTED_INDEX_VERSION = 1
interface TemplateIndexFile {
version: number
templates: unknown[]
}
function parseRequirement(input: unknown): ExtensionTemplateRequirement {
if (!input || typeof input !== 'object' || Array.isArray(input)) return {}
const raw = input as Record<string, unknown>
const result: ExtensionTemplateRequirement = {}
for (const key of ['python', 'chrome', 'externalScript'] as const) {
const value = raw[key]
if (value === true || value === false) {
result[key] = value as never
continue
}
if (value && typeof value === 'object' && !Array.isArray(value)) {
const item = value as Record<string, unknown>
const required = item.required === true
if (key === 'externalScript') {
const scriptPath = typeof item.path === 'string' ? item.path.trim() : ''
if (!scriptPath) continue
result.externalScript = {
required,
path: scriptPath,
...(typeof item.reason === 'string' ? { reason: item.reason.slice(0, 200) } : {})
}
continue
}
if (key === 'python') {
result.python = {
required,
...(typeof item.minVersion === 'string' ? { minVersion: item.minVersion } : {}),
...(typeof item.reason === 'string' ? { reason: item.reason.slice(0, 200) } : {})
}
continue
}
result.chrome = {
required,
...(typeof item.reason === 'string' ? { reason: item.reason.slice(0, 200) } : {})
}
}
}
return result
}
function parseEntry(input: unknown): ExtensionTemplateEntry | null {
if (!input || typeof input !== 'object' || Array.isArray(input)) return null
const raw = input as Record<string, unknown>
const templateId = String(raw.templateId ?? '').trim()
const extensionId = String(raw.extensionId ?? '').trim()
const name = String(raw.name ?? '').trim()
const version = String(raw.version ?? '').trim()
const file = String(raw.file ?? '').trim()
const sha256 = String(raw.sha256 ?? '').trim()
if (!templateId || !extensionId || !name || !version || !file || !sha256) return null
// 索引来自资源目录,但依然不接受任何路径片段:读取时只拼在模板根目录下。
if (file.includes('/') || file.includes('\\') || file.includes('..')) return null
if (!/^[a-f0-9]{64}$/.test(sha256)) return null
const platforms = Array.isArray(raw.platforms)
? raw.platforms.filter((item): item is NodeJS.Platform => typeof item === 'string')
: []
return {
templateId,
extensionId,
name,
version,
...(typeof raw.description === 'string' ? { description: raw.description.slice(0, 500) } : {}),
permissions: normalizeExtensionPermissions(raw.permissions),
file,
sha256,
bytes: Number(raw.bytes) || 0,
fileCount: Number(raw.fileCount) || 0,
platforms,
requires: parseRequirement(raw.requires)
}
}
/**
* 官方模板目录。
*
* 只做三件事:读索引、校验资源、把模板与已安装状态对上。
* 安装动作本身不在这里——它由 `ExtensionManager` 走统一的安装器,
* 避免出现第二套 ZIP 解压逻辑。
*/
export class ExtensionTemplateCatalog {
private readonly dependencies: ExtensionTemplateCatalogDependencies
private readonly platform: NodeJS.Platform
private cachedIndex: ExtensionTemplateEntry[] | null = null
constructor(dependencies: ExtensionTemplateCatalogDependencies) {
this.dependencies = dependencies
this.platform = dependencies.platform ?? process.platform
}
/** 索引读取失败时返回空列表:模板资源缺失不应该让扩展中心整页崩掉。 */
async list(): Promise<ExtensionTemplateStatus[]> {
const entries = await this.loadIndex()
const result: ExtensionTemplateStatus[] = []
for (const template of entries) {
result.push(await this.describe(template))
}
return result.sort((left, right) =>
left.template.templateId.localeCompare(right.template.templateId)
)
}
get(templateId: string): ExtensionTemplateEntry | undefined {
return this.cachedIndex?.find((item) => item.templateId === templateId)
}
/**
* 取模板 ZIP 的绝对路径,并校验内容哈希。
*
* 这一步是安装前的最后一道闸:索引与 ZIP 若被单独替换,哈希就对不上,
* 直接拒绝安装而不是把未知内容装进用户目录。
*/
async resolveZip(
templateId: string
): Promise<{ path: string; template: ExtensionTemplateEntry }> {
const entries = await this.loadIndex()
const template = entries.find((item) => item.templateId === templateId)
if (!template) {
throw new ExtensionError('EXTENSION_NOT_FOUND', `找不到模板:${templateId}`)
}
const zipPath = path.join(this.dependencies.templateRoot, template.file)
const exists = this.dependencies.exists ?? defaultExists
if (!exists(zipPath)) {
throw new ExtensionError('EXTENSION_INSTALL_FAILED', `模板资源缺失:${template.file}`)
}
const readFile = this.dependencies.readFile ?? fs.readFile
let buffer: Buffer
try {
buffer = await readFile(zipPath)
} catch {
throw new ExtensionError('EXTENSION_INSTALL_FAILED', `模板资源不可读:${template.file}`)
}
const digest = createHash('sha256').update(buffer).digest('hex')
if (digest !== template.sha256) {
throw new ExtensionError(
'EXTENSION_INSTALL_FAILED',
'模板资源校验失败:文件内容与索引不一致,已拒绝安装'
)
}
return { path: zipPath, template }
}
private async loadIndex(): Promise<ExtensionTemplateEntry[]> {
if (this.cachedIndex) return this.cachedIndex
const indexPath = path.join(this.dependencies.templateRoot, INDEX_FILE)
const readFile = this.dependencies.readFile ?? fs.readFile
let parsed: TemplateIndexFile
try {
const text = await readFile(indexPath)
parsed = JSON.parse(text.toString('utf8')) as TemplateIndexFile
} catch {
this.cachedIndex = []
return this.cachedIndex
}
if (
!parsed ||
Number(parsed.version) !== SUPPORTED_INDEX_VERSION ||
!Array.isArray(parsed.templates)
) {
this.cachedIndex = []
return this.cachedIndex
}
const entries: ExtensionTemplateEntry[] = []
const seen = new Set<string>()
for (const item of parsed.templates) {
const entry = parseEntry(item)
if (!entry) continue
if (seen.has(entry.templateId)) continue
seen.add(entry.templateId)
entries.push(entry)
}
this.cachedIndex = entries
return entries
}
private async describe(template: ExtensionTemplateEntry): Promise<ExtensionTemplateStatus> {
const record = this.dependencies.getRecord(template.extensionId)
const dependencies = await this.checkDependencies(template, record)
const base = {
template,
...(record ? { installedVersion: record.version, installedSource: record.source } : {}),
dependencies
}
if (template.platforms.length > 0 && !template.platforms.includes(this.platform)) {
return {
...base,
state: 'unsupported',
message: `当前平台(${this.platform})不在模板支持范围内`
}
}
const damaged = await this.isDamaged(template)
if (damaged) {
return { ...base, state: 'damaged', message: '模板资源缺失或校验失败,请重新安装 TraceMemo' }
}
if (!record) return { ...base, state: 'not-installed' }
// 同 id 但不是这个模板装的:不能静默接管用户自己的扩展。
if (record.source !== 'template' || record.templateId !== template.templateId) {
return {
...base,
state: 'conflict',
message: '已安装同 ID 的非官方扩展,不会自动替换'
}
}
const compared = compareSemver(template.version, record.version)
if (compared !== null && compared > 0) {
return { ...base, state: 'update-available' }
}
return { ...base, state: 'installed' }
}
private async isDamaged(template: ExtensionTemplateEntry): Promise<boolean> {
const zipPath = path.join(this.dependencies.templateRoot, template.file)
const exists = this.dependencies.exists ?? defaultExists
if (!exists(zipPath)) return true
const readFile = this.dependencies.readFile ?? fs.readFile
try {
const buffer = await readFile(zipPath)
if (template.bytes > 0 && buffer.length !== template.bytes) return true
return createHash('sha256').update(buffer).digest('hex') !== template.sha256
} catch {
return true
}
}
/**
* 依赖检测只做本地文件探测:不执行脚本、不访问网络、不触发解析。
*
* `externalScript` 只在扩展已安装后才能判断——安装前它一定不存在,
* 报「缺失」只会让用户以为模板坏了。
*/
private async checkDependencies(
template: ExtensionTemplateEntry,
record: ExtensionRegistryRecord | undefined
): Promise<ExtensionTemplateStatus['dependencies']> {
const checks: TemplateDependencyCheck[] = []
const requires = template.requires
const python = requires.python
if (python) {
const required = typeof python === 'boolean' ? python : python.required
const executable = (this.dependencies.probePython ?? (() => findPython(this.platform)))()
checks.push({
id: 'python',
label: 'Python',
ok: Boolean(executable),
blocking: required,
...(executable
? { detail: '已找到可执行文件' }
: {
detail:
typeof python === 'object' && python.reason
? python.reason
: '未在 PATH 中找到 Python'
})
})
}
const chrome = requires.chrome
if (chrome) {
const required = typeof chrome === 'boolean' ? chrome : chrome.required
const found = (this.dependencies.probeChrome ?? (() => findChrome(this.platform)))()
checks.push({
id: 'chrome',
label: 'Chrome',
ok: Boolean(found),
blocking: required,
...(found
? { detail: '已找到 Chrome' }
: {
detail: typeof chrome === 'object' && chrome.reason ? chrome.reason : '未找到 Chrome'
})
})
}
const externalScript = requires.externalScript
if (externalScript) {
const spec = typeof externalScript === 'object' ? externalScript : null
const relative = spec?.path ?? 'scripts/douyin.py'
if (!record) {
checks.push({
id: 'externalScript',
label: '解析脚本',
ok: false,
blocking: false,
detail: '安装后检测;该脚本不随应用分发'
})
} else {
const scriptPath = path.join(
this.dependencies.resolveInstallDir(template.extensionId),
relative
)
const exists = this.dependencies.exists ?? defaultExists
checks.push({
id: 'externalScript',
label: '解析脚本',
ok: exists(scriptPath),
blocking: spec?.required !== false,
detail: exists(scriptPath)
? '已找到解析脚本'
: spec?.reason || '缺少解析脚本,模板暂时无法处理视频'
})
}
}
const blockingMissing = checks.some((check) => check.blocking && !check.ok)
return { ready: !blockingMissing, checks }
}
}
function defaultExists(filePath: string): boolean {
// 只查存在性,不读内容:检测阶段不触碰文件内容。
return existsSync(filePath)
}
/** 只在 PATH 里找可执行文件,**不执行**它——检测阶段不能启动任何外部进程。 */
function findPython(platform: NodeJS.Platform): string | null {
const names =
platform === 'win32' ? ['python.exe', 'python3.exe', 'py.exe'] : ['python3', 'python']
return findOnPath(names, platform)
}
function findChrome(platform: NodeJS.Platform): string | null {
const candidates: string[] = []
if (platform === 'darwin') {
candidates.push(
'/Applications/Google Chrome.app/Contents/MacOS/Google Chrome',
path.join(
process.env.HOME || '',
'Applications/Google Chrome.app/Contents/MacOS/Google Chrome'
)
)
} else if (platform === 'win32') {
for (const root of [
process.env['PROGRAMFILES'] || '',
process.env['PROGRAMFILES(X86)'] || '',
process.env['LOCALAPPDATA'] || ''
]) {
if (!root) continue
candidates.push(path.join(root, 'Google', 'Chrome', 'Application', 'chrome.exe'))
}
}
return candidates.find((candidate) => defaultExists(candidate)) || null
}
function findOnPath(names: string[], platform: NodeJS.Platform): string | null {
const separator = platform === 'win32' ? ';' : ':'
const directories = String(process.env.PATH || '')
.split(separator)
.filter(Boolean)
for (const name of names) {
for (const directory of directories) {
const candidate = path.join(directory, name)
if (defaultExists(candidate)) return candidate
}
}
return null
}
+625
View File
@@ -0,0 +1,625 @@
/** 扩展后台进程入口;这个文件**跑在子进程里**,不是主进程:它只负责加载扩展代码、构造受限 SDK、 把请求转成白名单 RPC。 */
import fs from 'node:fs'
import path from 'node:path'
import { randomUUID } from 'node:crypto'
import { validateActionInput as validateWithSchema } from '../../shared/extensions/action-schema'
import {
EXTENSION_HOST_PROTOCOL_VERSION,
type ExtensionAutomationActionOutput,
type ExtensionHostActivate,
type ExtensionHostCall,
type ExtensionHostCallResult,
type ExtensionHostEvent,
type ExtensionHostInboundMessage,
type ExtensionHostPageRequest,
type ExtensionHostInvokeAction,
type ExtensionHostTestSend,
type ExtensionHostOutboundMessage,
type ExtensionHostRegisterAction
} from '../../shared/extensions/rpc'
import type { ExtensionMessageEvent } from '../../shared/extensions/events'
type MessageHandler = (event: ExtensionMessageEvent) => void | Promise<void>
interface RegisteredActionDefinition {
id: string
title: string
description?: string
inputSchema?: Record<string, unknown>
handler: (input: Record<string, unknown>) => unknown
}
interface PendingCall {
resolve: (value: unknown) => void
reject: (error: Error) => void
timer: ReturnType<typeof setTimeout>
}
const pendingCalls = new Map<string, PendingCall>()
const eventHandlers = new Set<MessageHandler>()
const actions = new Map<string, RegisteredActionDefinition>()
const pageHandlers = new Map<string, (params: Record<string, unknown>) => unknown>()
/** 页面请求方法名:小写开头,允许点号分段,长度受限。 */
const PAGE_REQUEST_METHOD = /^[a-z][a-zA-Z0-9]*(?:[._-][a-zA-Z0-9]+){0,3}$/
const PAGE_RESULT_MAX_BYTES = 64 * 1024
let permissions: string[] = []
let activated = false
let extensionDir = ''
let extensionDataDir = ''
let extensionId = process.env.TM_EXTENSION_ID || ''
function post(message: ExtensionHostOutboundMessage): void {
if (typeof process.send !== 'function') return
try {
process.send(message)
} catch {
// 父进程已断开;子进程会在 shutdown 或退出时结束。
}
}
function sendLog(level: 'info' | 'warn' | 'error', message: string): void {
post({ type: 'log', version: EXTENSION_HOST_PROTOCOL_VERSION, level, message })
}
function requirePermission(permission: string): void {
if (!permissions.includes(permission)) {
const error = new Error(`扩展没有 ${permission} 权限`)
;(error as Error & { code?: string }).code = 'PERMISSION_DENIED'
throw error
}
}
/** 白名单 RPC:扩展只能申请这些能力,且每次都要过权限检查。 */
function callHost(
method: ExtensionHostCall['method'],
params: Record<string, unknown>,
timeoutMs = 8_000
): Promise<unknown> {
if (!activated) return Promise.reject(new Error('扩展尚未激活'))
const callId = randomUUID()
return new Promise((resolve, reject) => {
const timer = setTimeout(() => {
pendingCalls.delete(callId)
reject(Object.assign(new Error('宿主调用超时'), { code: 'ACTION_TIMEOUT' }))
}, timeoutMs)
pendingCalls.set(callId, { resolve, reject, timer })
post({ type: 'call', version: EXTENSION_HOST_PROTOCOL_VERSION, callId, method, params })
})
}
const tm = {
extension: {
get id(): string {
return extensionId
},
/** 扩展私有数据目录;下载/生成的媒体应放在这里。 */
get dataDir(): string {
return extensionDataDir
},
get permissions(): string[] {
return [...permissions]
}
},
/** 页面 → 同扩展后台的通用请求处理器注册。 */
page: {
onRequest(method: string, handler: (params: Record<string, unknown>) => unknown): void {
const name = String(method || '').trim()
if (!PAGE_REQUEST_METHOD.test(name)) throw new Error(`页面请求方法名不合法:${name}`)
if (typeof handler !== 'function') throw new Error('页面请求必须提供 handler')
if (pageHandlers.has(name)) throw new Error(`页面请求重复注册:${name}`)
pageHandlers.set(name, handler)
}
},
/** 扩展私有凭据。 */
secrets: {
async get(key: string): Promise<string | null> {
requirePermission('secrets')
return (await callHost('secrets.get', { key })) as string | null
},
async set(key: string, value: string): Promise<void> {
requirePermission('secrets')
await callHost('secrets.set', { key, value })
},
async delete(key: string): Promise<void> {
requirePermission('secrets')
await callHost('secrets.delete', { key })
},
async has(key: string): Promise<boolean> {
requirePermission('secrets')
return (await callHost('secrets.has', { key })) as boolean
}
},
events: {
on(name: 'message.received', handler: MessageHandler): () => void {
if (name !== 'message.received' || typeof handler !== 'function') return () => undefined
eventHandlers.add(handler)
return () => eventHandlers.delete(handler)
},
off(name: 'message.received', handler: MessageHandler): void {
if (name !== 'message.received') return
eventHandlers.delete(handler)
}
},
messages: {
async query(request: {
conversationId: string
startTime?: number
endTime?: number
limit?: number
}): Promise<{ messages: unknown[] }> {
requirePermission('messages.query')
const result = (await callHost('messages.query', { ...request }, 25_000)) as {
messages: unknown[]
}
return result
}
},
wechat: {
/** 发送文本、图片、视频或语音。 */
async send(request: {
type?: 'text' | 'image' | 'video' | 'voice'
to: string
text?: string
path?: string
voiceId?: string
at?: Record<string, string>
dedupeKey?: string
}) {
const type =
request &&
(request.type === 'image' || request.type === 'video' || request.type === 'voice')
? request.type
: 'text'
if (type === 'voice') {
requirePermission('wechat.send.voice')
return (await callHost(
'wechat.send.voice',
{
to: request.to,
...(request.path ? { path: request.path } : {}),
...(request.text ? { text: request.text } : {}),
...(request.voiceId ? { voiceId: request.voiceId } : {}),
...(request.dedupeKey ? { dedupeKey: request.dedupeKey } : {})
},
150_000
)) as {
actionId: string
status: 'sent'
}
}
if (type === 'image' || type === 'video') {
requirePermission(type === 'video' ? 'wechat.send.video' : 'wechat.send.image')
return (await callHost(
type === 'video' ? 'wechat.send.video' : 'wechat.send.image',
{
to: request.to,
path: request.path,
...(request.dedupeKey ? { dedupeKey: request.dedupeKey } : {})
},
180_000
)) as {
actionId: string
status: 'sent'
}
}
requirePermission('wechat.send.text')
return (await callHost(
'wechat.send.text',
{
to: request.to,
text: request.text,
...(request.at ? { at: request.at } : {}),
...(request.dedupeKey ? { dedupeKey: request.dedupeKey } : {})
},
20_000
)) as {
actionId: string
status: 'sent'
}
}
},
ai: {
async chat(messages: Array<{ role: string; content: string }>) {
requirePermission('ai.chat')
return (await callHost('ai.chat', { messages }, 60_000)) as { text: string }
}
},
storage: {
async get(key: string): Promise<unknown> {
requirePermission('storage')
return callHost('storage.get', { key })
},
async set(key: string, value: unknown): Promise<void> {
requirePermission('storage')
await callHost('storage.set', { key, value })
},
async remove(key: string): Promise<boolean> {
requirePermission('storage')
const result = (await callHost('storage.remove', { key })) as { removed?: boolean }
return result.removed === true
},
async list(): Promise<Array<{ key: string; value: unknown }>> {
requirePermission('storage')
const result = (await callHost('storage.list', {})) as {
entries?: Array<{ key: string; value: unknown }>
}
return result.entries ?? []
}
},
automation: {
registerAction(definition: {
id: string
title: string
description?: string
inputSchema?: Record<string, unknown>
handler: (input: Record<string, unknown>) => unknown
}): void {
requirePermission('automation.action')
const id = String(definition?.id || '').trim()
if (!/^[a-z0-9][a-z0-9._-]{1,63}$/.test(id)) throw new Error('动作 id 不合法')
if (typeof definition.handler !== 'function') throw new Error('动作必须提供 handler')
const title = String(definition.title || id)
.trim()
.slice(0, 60)
if (!title) throw new Error('动作 title 不能为空')
actions.set(id, {
id,
title,
...(definition.description
? { description: String(definition.description).slice(0, 200) }
: {}),
...(definition.inputSchema ? { inputSchema: definition.inputSchema } : {}),
handler: definition.handler
})
const message: ExtensionHostRegisterAction = {
type: 'register-action',
version: EXTENSION_HOST_PROTOCOL_VERSION,
action: {
id,
title,
...(definition.description
? { description: String(definition.description).slice(0, 200) }
: {}),
hasInputSchema: Boolean(definition.inputSchema)
}
}
post(message)
}
},
capabilities: {
async get(): Promise<unknown> {
return callHost('capabilities.get', {})
}
},
log: {
info(message: unknown): void {
sendLog('info', String(message ?? ''))
},
warn(message: unknown): void {
sendLog('warn', String(message ?? ''))
},
error(message: unknown): void {
sendLog('error', String(message ?? ''))
}
}
}
/** 入口文件必须真实位于扩展目录内;符号链接与越界路径都会被拒绝。 */
function resolveBackgroundEntry(dir: string): string | null {
const manifestPath = path.join(dir, 'manifest.json')
let manifest: { entrypoints?: { background?: unknown } }
try {
manifest = JSON.parse(fs.readFileSync(manifestPath, 'utf8')) as typeof manifest
} catch {
return null
}
const relative = String(manifest.entrypoints?.background || '')
if (!relative) return null
const resolved = path.resolve(dir, relative)
try {
const realDir = fs.realpathSync(dir)
const realEntry = fs.realpathSync(resolved)
const inside = path.relative(realDir, realEntry)
if (!inside || inside.startsWith('..') || path.isAbsolute(inside)) return null
return realEntry
} catch {
return null
}
}
function pickExportedActivator(loaded: unknown): ((api: typeof tm) => unknown) | null {
if (typeof loaded === 'function') return loaded as (api: typeof tm) => unknown
if (loaded && typeof loaded === 'object') {
const candidate = (loaded as { activate?: unknown }).activate
if (typeof candidate === 'function') return candidate as (api: typeof tm) => unknown
}
return null
}
async function activate(message: ExtensionHostActivate): Promise<void> {
extensionId = message.extensionId
extensionDir = message.extensionDir
extensionDataDir = message.dataDir
permissions = Array.isArray(message.permissions) ? message.permissions : []
const entry = resolveBackgroundEntry(extensionDir)
if (!entry) {
post({
type: 'activated',
version: EXTENSION_HOST_PROTOCOL_VERSION,
ok: false,
error: { code: 'EXTENSION_INVALID_PATH', message: '后台入口文件不合法或不存在' }
})
return
}
try {
// eslint-disable-next-line @typescript-eslint/no-require-imports
const loaded = require(entry) as unknown
const activator = pickExportedActivator(loaded)
if (activator) await activator(tm)
activated = true
post({ type: 'activated', version: EXTENSION_HOST_PROTOCOL_VERSION, ok: true })
} catch (error) {
activated = false
post({
type: 'activated',
version: EXTENSION_HOST_PROTOCOL_VERSION,
ok: false,
error: {
code: 'ACTION_FAILED',
message: error instanceof Error ? error.message.slice(0, 300) : '扩展激活失败'
}
})
}
}
async function dispatchEvent(message: ExtensionHostEvent): Promise<void> {
if (!activated) return
for (const handler of eventHandlers) {
try {
await withTimeout(Promise.resolve(handler(message.envelope.event)), 10_000)
} catch (error) {
sendLog('error', `消息处理失败:${error instanceof Error ? error.message : String(error)}`)
}
}
}
/** 与 UI 共用同一套校验规则。 */
function validateActionInput(
schema: Record<string, unknown> | undefined,
input: Record<string, unknown>
): void {
if (!schema) return
const result = validateWithSchema(schema as never, input)
if (result.ok) return
const [key, message] = Object.entries(result.errors)[0] ?? ['参数', '不合法']
throw new Error(`参数 ${key} ${message}`)
}
async function handlePageRequest(message: ExtensionHostPageRequest): Promise<void> {
const handler = pageHandlers.get(message.method)
if (!handler) {
post({
type: 'page-result',
version: EXTENSION_HOST_PROTOCOL_VERSION,
requestId: message.requestId,
ok: false,
error: { code: 'ACTION_FAILED', message: `页面请求未注册:${message.method}` }
})
return
}
try {
const raw = await withTimeout(
Promise.resolve(handler(message.params ?? {})),
Math.max(1_000, Math.min(message.timeoutMs - 500, 90_000))
)
// 只允许纯 JSON:函数、循环引用、类实例都在这一步被拒绝。
const serialized = JSON.stringify(raw ?? null)
if (new TextEncoder().encode(serialized).length > PAGE_RESULT_MAX_BYTES) {
throw new Error('页面请求响应超过 64KB')
}
post({
type: 'page-result',
version: EXTENSION_HOST_PROTOCOL_VERSION,
requestId: message.requestId,
ok: true,
result: JSON.parse(serialized) as unknown
})
} catch (error) {
post({
type: 'page-result',
version: EXTENSION_HOST_PROTOCOL_VERSION,
requestId: message.requestId,
ok: false,
error: {
code: 'ACTION_FAILED',
message: error instanceof Error ? error.message.slice(0, 200) : '页面请求失败'
}
})
}
}
async function invokeAction(message: ExtensionHostInvokeAction): Promise<void> {
const definition = actions.get(message.actionId)
if (!definition) {
post({
type: 'action-result',
version: EXTENSION_HOST_PROTOCOL_VERSION,
requestId: message.requestId,
ok: false,
error: { code: 'ACTION_FAILED', message: `动作不存在:${message.actionId}` }
})
return
}
try {
validateActionInput(definition.inputSchema, message.input)
const raw = await withTimeout(
Promise.resolve(definition.handler(message.input)),
Math.max(1_000, Math.min(message.timeoutMs - 500, 60_000))
)
const output = normalizeActionOutput(raw)
post({
type: 'action-result',
version: EXTENSION_HOST_PROTOCOL_VERSION,
requestId: message.requestId,
ok: output.success,
output,
...(output.success
? {}
: {
error: { code: 'ACTION_FAILED' as const, message: output.error || '扩展动作返回失败' }
})
})
} catch (error) {
post({
type: 'action-result',
version: EXTENSION_HOST_PROTOCOL_VERSION,
requestId: message.requestId,
ok: false,
error: {
code:
error instanceof Error && /超时/.test(error.message) ? 'ACTION_TIMEOUT' : 'ACTION_FAILED',
message: error instanceof Error ? error.message.slice(0, 300) : '扩展动作执行失败'
}
})
}
}
function normalizeActionOutput(raw: unknown): ExtensionAutomationActionOutput {
if (!raw || typeof raw !== 'object') {
return { success: false, error: '动作必须返回对象' }
}
const value = raw as Partial<ExtensionAutomationActionOutput>
const reply = value.reply
const hasReply =
reply && reply.type === 'text' && typeof reply.text === 'string' && reply.text.trim().length > 0
return {
success: value.success !== false,
...(value.output && typeof value.output === 'object' ? { output: value.output } : {}),
...(hasReply
? {
reply: {
type: 'text' as const,
text: reply!.text.trim().slice(0, 2_000),
...(reply!.at && typeof reply!.at === 'object' ? { at: reply!.at } : {})
}
}
: {}),
...(typeof value.error === 'string' && value.error.trim()
? { error: value.error.trim().slice(0, 300) }
: {})
}
}
function withTimeout<T>(promise: Promise<T>, timeoutMs: number): Promise<T> {
return new Promise<T>((resolve, reject) => {
const timer = setTimeout(() => reject(new Error('扩展处理超时')), timeoutMs)
promise.then(
(value) => {
clearTimeout(timer)
resolve(value)
},
(error) => {
clearTimeout(timer)
reject(error)
}
)
})
}
process.on('message', (raw: unknown) => {
if (!raw || typeof raw !== 'object') return
const message = raw as ExtensionHostInboundMessage
if (message.version !== EXTENSION_HOST_PROTOCOL_VERSION) return
switch (message.type) {
case 'activate':
void activate(message)
return
case 'event':
void dispatchEvent(message)
return
case 'invoke-action':
void invokeAction(message)
return
case 'test-send':
// 旧协议:只有抖音扩展认这个入口。新代码统一走 page-request。
if (extensionId !== 'com.example.douyin-sender') return
void dispatchTestSend(message)
return
case 'page-request':
void handlePageRequest(message)
return
case 'call-result': {
const result = message as ExtensionHostCallResult
const pending = pendingCalls.get(result.callId)
if (!pending) return
clearTimeout(pending.timer)
pendingCalls.delete(result.callId)
if (result.ok) {
pending.resolve(result.result)
} else {
pending.reject(
Object.assign(new Error(result.error?.message || '宿主调用失败'), {
code: result.error?.code || 'ACTION_FAILED'
})
)
}
return
}
case 'shutdown':
process.exit(0)
}
})
async function dispatchTestSend(message: ExtensionHostTestSend): Promise<void> {
const handler = (
globalThis as typeof globalThis & {
__tmTestSend?: (params: Record<string, unknown>) => Promise<unknown>
}
).__tmTestSend
if (!handler) {
post({
type: 'test-result',
version: EXTENSION_HOST_PROTOCOL_VERSION,
requestId: message.requestId,
ok: false,
error: { code: 'ACTION_FAILED', message: '测试处理器不可用' }
})
return
}
try {
const result = await handler(message.params)
post({
type: 'test-result',
version: EXTENSION_HOST_PROTOCOL_VERSION,
requestId: message.requestId,
ok: true,
result
})
} catch (error) {
post({
type: 'test-result',
version: EXTENSION_HOST_PROTOCOL_VERSION,
requestId: message.requestId,
ok: false,
error: {
code: 'ACTION_FAILED',
message: error instanceof Error ? error.message : '测试任务失败'
}
})
}
}
process.on('uncaughtException', (error) => {
sendLog('error', `未捕获异常:${error.message}`)
process.exit(1)
})
process.on('unhandledRejection', (reason) => {
sendLog(
'warn',
`未处理的 Promise 拒绝:${reason instanceof Error ? reason.message : String(reason)}`
)
})
// 让宿主知道进程已就绪,可以发 activate。必须在监听器之后发送。
post({ type: 'ready', version: EXTENSION_HOST_PROTOCOL_VERSION })
+41 -7
View File
@@ -6,7 +6,7 @@ import {
isReady,
listContacts,
listContactsAsync,
listMessages,
listMessagesAsync,
getGroupSnapshot,
listRecentChat,
resolveMd5,
@@ -433,7 +433,7 @@ const routes: Record<string, RouteHandler> = {
sendJson(res, 200, { count: items.length, items })
}),
'/api/v1/chatlog': withMethods(['GET'], ({ res, url }) => {
'/api/v1/chatlog': withMethods(['GET'], async ({ res, url }) => {
if (!isReady()) return sendError(res, 503, 'TraceMemo 数据库未初始化')
const talker = url.searchParams.get('talker')
if (!talker) return sendError(res, 400, '缺少必要参数 talker')
@@ -462,7 +462,15 @@ const routes: Record<string, RouteHandler> = {
}
}
const messages = listMessages(resolved.md5, startTime, endTime)
// A quiet time window can fall back to a long native history scan. Use the
// asynchronous, time-filtered shard reader so it cannot block /health or the UI.
const messages = await listMessagesAsync(
resolved.md5,
startTime,
endTime,
undefined,
String(res.getHeader('X-Request-Id') || '')
)
sendJson(res, 200, {
contact: resolved,
query: { talker, time: timeParam, startTime, endTime },
@@ -579,7 +587,7 @@ const WECHAT_SEND_MAX_TEXT_LENGTH = 2_000
const WECHAT_SEND_MAX_RECIPIENT_LENGTH = 512
const WECHAT_SEND_MAX_IDEMPOTENCY_KEY_LENGTH = 200
const WECHAT_SEND_CONTENT_TYPES = ['text', 'image', 'voice'] as const
const WECHAT_SEND_CONTENT_TYPES = ['text', 'image', 'voice', 'file'] as const
type WechatSendContentType = (typeof WECHAT_SEND_CONTENT_TYPES)[number]
interface WechatSendApiDependencies {
@@ -690,7 +698,21 @@ function parseWechatSendPayload(payload: unknown): ParsedWechatSend {
message: `text 长度 ${text.length} 超过上限 ${WECHAT_SEND_MAX_TEXT_LENGTH} 字符`
}
}
content = { type: 'text', text }
let at: Record<string, string> | undefined
if (body.at !== undefined) {
if (!body.at || typeof body.at !== 'object' || Array.isArray(body.at)) {
return { ok: false, status: 400, code: 'INVALID_REQUEST', message: 'at 必须是 wxid 到显示名称的对象' }
}
const entries = Object.entries(body.at as Record<string, unknown>)
if (entries.length > 50 || entries.some(([wxid, name]) => !wxid.trim() || typeof name !== 'string')) {
return { ok: false, status: 400, code: 'INVALID_REQUEST', message: 'at 最多支持 50 个有效成员' }
}
if (recipient.type !== 'group') {
return { ok: false, status: 400, code: 'INVALID_REQUEST', message: 'at 只能用于群聊' }
}
at = Object.fromEntries(entries.map(([wxid, name]) => [wxid.trim(), String(name).trim()]))
}
content = { type: 'text', text, ...(at ? { at } : {}) }
} else {
const filePath = readSendString(body.filePath)
if (!filePath) {
@@ -709,7 +731,12 @@ function parseWechatSendPayload(payload: unknown): ParsedWechatSend {
message: `filePath 指向的文件不存在:${filePath}`
}
}
content = { type, path: filePath }
if (type === 'file') {
const fileName = readSendString(body.fileName)
content = { type: 'file', path: filePath, ...(fileName ? { name: fileName } : {}) }
} else {
content = { type, path: filePath }
}
}
return {
@@ -819,7 +846,14 @@ function createWechatSendRoute(
}
const contentType = parsed.content.type
if (!capability.capabilities[contentType]) {
const label = contentType === 'text' ? '文字' : contentType === 'image' ? '图片' : '语音'
const label =
contentType === 'text'
? '文字'
: contentType === 'image'
? '图片'
: contentType === 'file'
? '文件'
: '语音'
return sendWechatSendError(res, 503, 'SEND_NOT_READY', `当前微信发送能力不支持发送${label}`, {
capabilityStatus: capability.status,
capabilities: capability.capabilities
+110 -8
View File
@@ -141,6 +141,16 @@ import {
leaveNotificationContactDisplayName
} from './services/leave-notification-target'
import { MessageListenerService } from './services/message-listener-service'
import { EXTENSION_IPC } from '../shared/extensions/ipc'
import { installExtensionProtocolHandler, registerExtensionScheme } from './extensions/extension-protocol'
import { registerExtensionIpc } from './extensions/extension-ipc'
import { getExtensionPaths } from './extensions/extension-paths'
import {
disposeExtensionSystem,
getExtensionManager,
hasExtensionManager,
initExtensionSystem
} from './extensions/extension-service'
import { automationRuleStore } from './services/automation-rule-store'
import { automationExecutionLogService } from './services/automation-execution-log-service'
import { initAutomationService, getAutomationService } from './services/automation-service'
@@ -1079,8 +1089,10 @@ function createWindow(): void {
// Electron 初始化完成并准备创建浏览器窗口后,将调用此方法
// 某些 API 只能在此事件发生后使用
app.whenReady().then(async () => {
if (isLegacyMigrationHelper) {
/* 扩展页面走自定义协议;scheme 必须在 app ready 之前登记为特权协议。 */
registerExtensionScheme()
app.whenReady().then(async () => { if (isLegacyMigrationHelper) {
try {
runLegacySafeStorageHelper()
app.exit(0)
@@ -1442,7 +1454,36 @@ app.whenReady().then(async () => {
// Create the renderer before native WCDB bootstrap so startup progress is visible immediately.
await reportTemplateService.recover()
registerReportTemplateIpc()
installExtensionProtocolHandler({
paths: getExtensionPaths(),
// 开发模式下代码在用户自己的目录里:协议必须走同一个解析器,
// 否则页面会读到旧的安装副本。管理器尚未就绪时回退到安装目录。
resolveRoot: (extensionId) => {
if (!hasExtensionManager()) return getExtensionPaths().installDir(extensionId)
try {
return getExtensionManager().resolveExtensionRoot(extensionId)
} catch {
return null
}
}
})
registerExtensionIpc({
getManager: getExtensionManager,
paths: getExtensionPaths(),
isTrustedSender: (senderId) =>
BrowserWindow.getAllWindows().some((window) => window.webContents.id === senderId)
})
createWindow()
void initExtensionSystem({
appVersion: app.getVersion(),
onChange: (extensionId, reason) => {
for (const window of BrowserWindow.getAllWindows()) {
if (!window.isDestroyed()) {
window.webContents.send(EXTENSION_IPC.changed, { extensionId, reason })
}
}
}
})
wcdbBootstrapPromise = bootstrapWcdbNativeAsync().then(() => {
console.log('[WCDB4] async bootstrap complete')
})
@@ -1706,6 +1747,21 @@ app.whenReady().then(async () => {
}`
)
}
/*
* 扩展事件分发:与 Automation 并行、互不影响。
* 扩展侧的异常不能污染 MessageListener 的投递循环,也不能阻断 Automation。
*/
if (hasExtensionManager()) {
try {
getExtensionManager().handleMessage(message)
} catch (error) {
console.warn(
`[Extension] handleMessage failed: ${
error instanceof Error ? error.message : String(error)
}`
)
}
}
})
const sessions = await wcdb4Client.getSessionsAsync({ hydrateDisplayNames: false })
configureRecallProtection(wcdb4Client, resolvedRoot, settings.recallProtectionEnabled)
@@ -1884,7 +1940,12 @@ app.whenReady().then(async () => {
// 排查「消息到底发没发出去」时恰好缺的就是那份证据。
// 普通手动发送保持 triggerType=user;带 postfixText 的日报图片由 Gateway 编排成
// 两个 automation action,以复用同一条 3s 队列,并严格在图片 sent 后才发后置词。
if (request.type === 'text' || request.type === 'image') {
if (
request.type === 'text' ||
request.type === 'image' ||
request.type === 'video' ||
request.type === 'file'
) {
const to = String(request.to || '').trim()
const recipient = {
type:
@@ -1912,13 +1973,32 @@ app.whenReady().then(async () => {
}
const action = await wechatActionGateway.execute({
origin: 'user_manual',
purpose: request.type === 'text' ? 'manual_text' : 'manual_image',
purpose:
request.type === 'text'
? 'manual_text'
: request.type === 'video'
? 'manual_video'
: request.type === 'file'
? 'manual_file'
: 'manual_image',
triggerType: 'user',
recipient,
content:
request.type === 'text'
? { type: 'text', text: String(request.text || '') }
: { type: 'image', path: String(request.filePath || '') }
? {
type: 'text',
text: String(request.text || ''),
...(request.at ? { at: request.at } : {})
}
: request.type === 'video'
? { type: 'video', path: String(request.filePath || '') }
: request.type === 'file'
? {
type: 'file',
path: String(request.filePath || ''),
...(request.fileName ? { name: request.fileName } : {})
}
: { type: 'image', path: String(request.filePath || '') }
})
// 返回契约保持 `PersonalWechatSendResult`,界面判读不用改。
return toPersonalWechatSendResult(action, await currentPersonalWechatSenderStatus())
@@ -3517,8 +3597,13 @@ app.whenReady().then(async () => {
undefined,
(targets) => {
if (
macWechatRuntimeManager.getPort() === 4290 &&
targets.some((target) => target.targets.includes('port_4290'))
targets.some(
(target) =>
target.targets.includes('host') ||
target.targets.includes('frida_helper') ||
(macWechatRuntimeManager.getPort() === 4290 &&
target.targets.includes('port_4290'))
)
) {
macWechatRuntimeManager.prepareForResidualCleanup()
runtimeStopped = true
@@ -3603,6 +3688,22 @@ app.whenReady().then(async () => {
ipcMain.handle('wechat-personal:getVoiceDiagnostic', () =>
personalWechatSendService.getLatestVoiceDiagnostic()
)
ipcMain.handle('wechat-personal:selectFile', async (event) => {
const window = BrowserWindow.fromWebContents(event.sender)
const result = await dialog.showOpenDialog(window!, {
title: '选择要发送的文件',
properties: ['openFile']
})
if (result.canceled || result.filePaths.length === 0) return { canceled: true }
const filePath = result.filePaths[0]
let size = 0
try {
size = (await fsPromises.stat(filePath)).size
} catch {
return { canceled: true }
}
return { canceled: false, path: filePath, name: path.basename(filePath), size }
})
ipcMain.handle('agent-hub:selectTestImage', async (event) => {
const window = BrowserWindow.fromWebContents(event.sender)
const result = await dialog.showOpenDialog(window!, {
@@ -3665,6 +3766,7 @@ app.on('before-quit', (event) => {
agentHubService.stop()
scheduledReportService.stop()
groupExitMonitorService.stop()
await disposeExtensionSystem().catch(() => undefined)
flushBootstrapCacheWritesSync()
const [, nativeCallsDrained] = await Promise.all([
apiServer.stop().catch(() => undefined),
+195 -26
View File
@@ -1,5 +1,6 @@
import {
AUTOMATION_STEP_LABELS,
BUILTIN_DAILY_REPORT_RULE_ID,
AUTOMATION_SEND_ORIGIN,
AUTOMATION_SEND_PURPOSE,
DEFAULT_REPLY_TEXT,
@@ -18,8 +19,21 @@ import {
renderLeaveNotificationText,
type GroupMemberExitedEvent
} from '../../shared/group-exit-event'
import type { WechatActionContent, WechatActionRequest, WechatActionResult } from '../../shared/wechat-action'
import type { SaveGeneratedReportRequest, SaveGeneratedReportResult } from '../../shared/report-history'
import type {
WechatActionContent,
WechatActionRequest,
WechatActionResult
} from '../../shared/wechat-action'
import type { ExtensionMessageEvent } from '../../shared/extensions/events'
import type { ExtensionAutomationActionOutput } from '../../shared/extensions/rpc'
import {
canExtensionSendText,
invokeExtensionAction
} from '../extensions/extension-automation-bridge'
import type {
SaveGeneratedReportRequest,
SaveGeneratedReportResult
} from '../../shared/report-history'
import {
generateAgentGroupReport,
type AgentGroupReportRequest,
@@ -44,6 +58,21 @@ import type { AutomationTargetResolution } from './automation-wechat-target'
/** 一步执行完毕后,后续步骤的处置方式。 */
const STEP_ORDER: AutomationStepKey[] = ['received', 'matched', 'reply', 'report', 'send']
/**
* 配了扩展动作时的步骤顺序。
*
* 只有规则真的配了扩展动作才把这一步加进来:给每条日报都渲染一条
* 「执行扩展动作 已跳过」是纯噪声,用户会以为规则配错了。
*/
const EXTENSION_STEP_ORDER: AutomationStepKey[] = [
'received',
'matched',
'extension_action',
'reply',
'report',
'send'
]
/** 退群通知的步骤顺序(与消息型规则**不共用**)。 */
const LEAVE_NOTIFICATION_STEP_ORDER: AutomationStepKey[] = [
'exit_received',
@@ -73,6 +102,7 @@ const SCHEDULED_REPORT_STEP_ORDER: AutomationStepKey[] = [
*/
const SKIPPED_AFTER_REPLY_FAILURE = '前置步骤失败(回复确认未成功),本次不再继续。'
const SKIPPED_AFTER_REPORT_FAILURE = '前置步骤失败(日报未生成),没有图片可发送。'
const SKIPPED_AFTER_EXTENSION_FAILURE = '前置步骤失败(扩展动作未成功),本次不再继续。'
/**
* 定时日报「生成 / 落库」失败时,后续步骤的 `skipReason`。
@@ -99,6 +129,10 @@ export interface AutomationRunInput {
isGroup: boolean
/** 用户可读的来源名(群名 / 昵称)。**不是** id。 */
sourceDisplayName: string
/** 群消息触发者;仅内置日报确认回复会使用它构造 @。 */
triggerSender?: { wxid: string; displayName: string }
/** 触发本次执行的消息(扩展动作的运行时上下文)。 */
message?: ExtensionMessageEvent
}
export interface AutomationRunResult {
@@ -182,6 +216,22 @@ export interface ScheduledReportRunResult {
export interface AutomationActionRunnerDependencies {
generateReport?: (request: AgentGroupReportRequest) => Promise<AgentGroupReportResult>
executeAction?: (request: WechatActionRequest) => Promise<WechatActionResult>
/**
* 扩展动作调用。默认走 `ExtensionManager`;单测注入假实现即可绕开子进程。
*/
invokeExtensionAction?: (
extensionId: string,
actionId: string,
input: Record<string, unknown>,
context: {
conversationId: string
isGroup: boolean
accountId: string
message?: ExtensionMessageEvent
}
) => Promise<ExtensionAutomationActionOutput>
/** 扩展是否具备发送文本的权限。默认读扩展中心授予集合。 */
canExtensionSendText?: (extensionId: string) => boolean
now?: () => number
/** 延迟实现。默认真 sleep;单测注入即时 resolve 的假实现,避免真的等 2 秒。 */
delay?: (ms: number) => Promise<void>
@@ -243,7 +293,9 @@ function actionErrorMessage(code: string | undefined, fallback: string | undefin
}
export class AutomationActionRunner {
private readonly generateReport: (request: AgentGroupReportRequest) => Promise<AgentGroupReportResult>
private readonly generateReport: (
request: AgentGroupReportRequest
) => Promise<AgentGroupReportResult>
private readonly executeAction: (request: WechatActionRequest) => Promise<WechatActionResult>
private readonly now: () => number
private readonly delay: (ms: number) => Promise<void>
@@ -254,21 +306,31 @@ export class AutomationActionRunner {
AutomationActionRunnerDependencies['resolveReportContact']
>
private readonly getContactAvatars: (usernames: string[]) => Promise<Record<string, string>>
private readonly invokeExtensionAction: NonNullable<
AutomationActionRunnerDependencies['invokeExtensionAction']
>
private readonly canExtensionSendText: (extensionId: string) => boolean
constructor(dependencies: AutomationActionRunnerDependencies = {}) {
this.generateReport = dependencies.generateReport ?? generateAgentGroupReport
this.executeAction = dependencies.executeAction ?? ((request) => wechatActionGateway.execute(request))
this.executeAction =
dependencies.executeAction ?? ((request) => wechatActionGateway.execute(request))
this.now = dependencies.now ?? (() => Date.now())
this.delay =
dependencies.delay ??
((ms) => new Promise<void>((resolve) => setTimeout(resolve, ms)))
dependencies.delay ?? ((ms) => new Promise<void>((resolve) => setTimeout(resolve, ms)))
this.saveGeneratedReport = dependencies.saveGeneratedReport ?? saveGeneratedReport
this.resolveReportContact = dependencies.resolveReportContact ?? ((raw) => resolveMd5(raw))
this.getContactAvatars = dependencies.getContactAvatars ?? ((ids) => getContactAvatars(ids))
this.invokeExtensionAction =
dependencies.invokeExtensionAction ??
((id, actionId, input, context) => invokeExtensionAction(id, actionId, input, context))
this.canExtensionSendText = dependencies.canExtensionSendText ?? canExtensionSendText
}
async run(input: AutomationRunInput): Promise<AutomationRunResult> {
const steps = STEP_ORDER.map((key) => createStep(key))
const extensionAction = findAction(input.rule, 'extensionAction')
const order = extensionAction ? EXTENSION_STEP_ORDER : STEP_ORDER
const steps = order.map((key) => createStep(key))
const stepAt = (key: AutomationStepKey): AutomationStep =>
steps.find((step) => step.key === key) as AutomationStep
@@ -279,36 +341,98 @@ export class AutomationActionRunner {
const reportAction = findAction(input.rule, 'generateReport')
const sendAction = findAction(input.rule, 'sendReportImage')
// ---- 步骤 3:回复确认 ----
// ---- 步骤 3:扩展动作 ----
//
// 回复等待:规则一命中就秒回,看起来就是个机器人(消息刚到、回复就到)。
// 等待时长是**规则自己的一项执行参数**(`rule.replyDelaySeconds`,在
// 「编辑自动化 → 3 · 触发后执行」里配),所以不同规则可以不一样。
//
// 等待刻意放在 `reply` 步骤计时**之外** —— `reply.durationMs` 只应该反映发送本身,
// 否则用户看到「回复确认 2000ms」会误以为是发送慢。
// 已经命中就不再回头重判规则:等待窗口里规则被停用/删掉也不中断本次执行,
// 与 cooldown、同消息幂等的口径一致(都是「命中那一刻」的快照)。
if (replyAction) {
// 扩展动作先跑,它产出的 `reply` 会成为下一步「回复确认」的内容。
// 扩展本身**不发送**:内容交回宿主,由宿主在权限与授权都通过后经 Gateway 发出。
let extensionOutput: ExtensionAutomationActionOutput | undefined
if (extensionAction) {
const extensionStep = stepAt('extension_action')
extensionStep.status = 'running'
extensionStep.startedAt = this.now()
try {
extensionOutput = await this.invokeExtensionAction(
String(extensionAction.extensionId || ''),
String(extensionAction.actionId || ''),
extensionAction.input ?? {},
{
conversationId: input.conversationId,
isGroup: input.isGroup,
accountId: input.message?.accountId ?? '',
...(input.message ? { message: input.message } : {})
}
)
} catch (error) {
markFailed(
extensionStep,
this.now(),
error instanceof Error ? error.message : '扩展动作执行失败'
)
markRemainingSkipped(steps, order, 'extension_action', SKIPPED_AFTER_EXTENSION_FAILURE)
return { steps, status: 'failed', errorSummary: extensionStep.error }
}
if (!extensionOutput || extensionOutput.success === false) {
markFailed(extensionStep, this.now(), extensionOutput?.error || '扩展动作返回失败')
markRemainingSkipped(steps, order, 'extension_action', SKIPPED_AFTER_EXTENSION_FAILURE)
return { steps, status: 'failed', errorSummary: extensionStep.error }
}
if (extensionOutput.reply) extensionStep.detail = '已生成回复内容'
markSuccess(extensionStep, this.now())
}
const extensionReply = extensionOutput?.reply
// 步骤 4:回复确认。
// 命中即视为快照:等待窗口内规则被停用/删除也不中断本次执行。
// 等待时长来自 rule.replyDelaySeconds,且不计入 reply.durationMs。
const willReply = Boolean(extensionReply) || Boolean(replyAction)
if (willReply) {
// 用共享的归一化函数,而不是 `Number(...) || 0`:旧版 rules.json 里没有这个字段,
// 那应该按**默认 2 秒**处理(否则「默认 2 秒」要等用户手动进编辑页才会生效)。
const replyDelayMs = normalizeReplyDelaySeconds(input.rule.replyDelaySeconds) * 1_000
if (replyDelayMs > 0) await this.delay(replyDelayMs)
}
if (!replyAction) {
if (!willReply) {
markSkipped(stepAt('reply'))
} else if (extensionReply) {
const replyStep = stepAt('reply')
const extensionId = String(extensionAction?.extensionId || '')
if (!this.canExtensionSendText(extensionId)) {
markFailed(replyStep, this.now(), '扩展没有 wechat.send.text 权限,回复未发送')
markRemainingSkipped(steps, order, 'reply', SKIPPED_AFTER_REPLY_FAILURE)
return { steps, status: 'failed', errorSummary: replyStep.error }
}
replyStep.status = 'running'
replyStep.startedAt = this.now()
const sent = await this.sendExtensionReply(input, extensionId, extensionReply)
if (!sent.ok) {
markFailed(replyStep, this.now(), sent.error || '回复确认失败')
markRemainingSkipped(steps, order, 'reply', SKIPPED_AFTER_REPLY_FAILURE)
return { steps, status: 'failed', errorSummary: replyStep.error }
}
markSuccess(replyStep, this.now())
} else {
const replyStep = stepAt('reply')
replyStep.status = 'running'
replyStep.startedAt = this.now()
const triggerWxid = input.triggerSender?.wxid.trim()
const triggerDisplayName = input.triggerSender?.displayName.trim()
const confirmationAt =
input.rule.id === BUILTIN_DAILY_REPORT_RULE_ID &&
input.isGroup &&
triggerWxid &&
triggerDisplayName
? { [triggerWxid]: triggerDisplayName }
: undefined
const sent = await this.sendThroughGateway(input, 'reply', {
type: 'text',
text: replyAction.text?.trim() || DEFAULT_REPLY_TEXT
text: replyAction?.text?.trim() || DEFAULT_REPLY_TEXT,
...(confirmationAt ? { at: confirmationAt } : {})
})
if (!sent.ok) {
markFailed(replyStep, this.now(), sent.error || '回复确认失败')
markRemainingSkipped(steps, 'reply', SKIPPED_AFTER_REPLY_FAILURE)
markRemainingSkipped(steps, order, 'reply', SKIPPED_AFTER_REPLY_FAILURE)
return { steps, status: 'failed', errorSummary: replyStep.error }
}
markSuccess(replyStep, this.now())
@@ -333,7 +457,7 @@ export class AutomationActionRunner {
}
if (!result.success || !result.pngPath) {
markFailed(reportStep, this.now(), result.error || '日报生成失败')
markRemainingSkipped(steps, 'report', SKIPPED_AFTER_REPORT_FAILURE)
markRemainingSkipped(steps, order, 'report', SKIPPED_AFTER_REPORT_FAILURE)
return { steps, status: 'failed', errorSummary: reportStep.error }
}
pngPath = result.pngPath
@@ -382,6 +506,43 @@ export class AutomationActionRunner {
return { steps, status: 'success', pngPath }
}
/**
* 发送扩展产出的回复。
*
* 内容来自扩展,**发送动作来自宿主**:`origin` / `purpose` / 幂等键都在这里填,
* 扩展返回的只是「想说什么」。所以扩展无法借这条链路绕过发送策略。
*/
private async sendExtensionReply(
input: AutomationRunInput,
extensionId: string,
reply: NonNullable<ExtensionAutomationActionOutput['reply']>
): Promise<{ ok: boolean; error?: string }> {
try {
const result = await this.executeAction({
idempotencyKey: `extension_action:${input.executionId}`,
origin: 'extension',
purpose: 'extension_action',
triggerType: 'automation',
executionId: input.executionId,
recipient: {
type: input.isGroup ? 'group' : 'contact',
id: input.conversationId,
name: input.sourceDisplayName
},
content: {
type: 'text',
text: reply.text,
...(reply.at ? { at: reply.at } : {})
},
metadata: { extensionId }
})
if (result.status === 'sent') return { ok: true }
return { ok: false, error: actionErrorMessage(result.errorCode, result.reason) }
} catch (error) {
return { ok: false, error: error instanceof Error ? error.message : String(error) }
}
}
/**
* 把「@我生成日报」产出的日报写进**日报历史**。
*
@@ -509,7 +670,9 @@ export class AutomationActionRunner {
generated.groupName || reportContact?.m_nsNickName || input.sourceDisplayName || '群聊',
contactAvatar,
source: 'scheduled',
dateRange: generated.reportMetadata?.dateRange || scheduledReportRangeLabel(input.config.report.range),
dateRange:
generated.reportMetadata?.dateRange ||
scheduledReportRangeLabel(input.config.report.range),
reportDate: generated.reportMetadata?.reportDate,
messageCount: generated.messageCount ?? generated.reportMetadata?.messageCount ?? 0,
generatedAt: new Date(this.now()).toISOString(),
@@ -661,7 +824,9 @@ export class AutomationActionRunner {
* 与 `run()` 的差别:没有动作链、没有回复等待、没有 cooldown
* (退群是低频事件,且**不能被时间窗合并** —— 两个成员先后退出就是两条通知)。
*/
async runLeaveNotification(input: LeaveNotificationRunInput): Promise<LeaveNotificationRunResult> {
async runLeaveNotification(
input: LeaveNotificationRunInput
): Promise<LeaveNotificationRunResult> {
const steps = LEAVE_NOTIFICATION_STEP_ORDER.map((key) => createStep(key))
const stepAt = (key: AutomationStepKey): AutomationStep =>
steps.find((step) => step.key === key) as AutomationStep
@@ -779,18 +944,22 @@ export class AutomationActionRunner {
}
}
function findAction(rule: AutomationRule, type: AutomationAction['type']): AutomationAction | undefined {
function findAction(
rule: AutomationRule,
type: AutomationAction['type']
): AutomationAction | undefined {
return rule.actions.find((action) => action.type === type && action.enabled)
}
/** 把 `after` 之后的步骤全部标成 `skipped`(前一步挂了,后面的不许再动)。 */
function markRemainingSkipped(
steps: AutomationStep[],
order: AutomationStepKey[],
after: AutomationStepKey,
skipReason?: string
): void {
const from = STEP_ORDER.indexOf(after) + 1
for (const key of STEP_ORDER.slice(from)) {
const from = order.indexOf(after) + 1
for (const key of order.slice(from)) {
const step = steps.find((item) => item.key === key)
if (step) markSkipped(step, skipReason)
}
+40 -19
View File
@@ -1,8 +1,5 @@
import { createHash, randomUUID } from 'node:crypto'
import {
matchAutomationRule,
type AutomationMatchInput
} from '../../shared/automation-matcher'
import { matchAutomationRule, type AutomationMatchInput } from '../../shared/automation-matcher'
import {
AUTOMATION_SEND_PURPOSE,
BUILTIN_LEAVE_NOTIFICATION_RULE_ID,
@@ -14,6 +11,8 @@ import {
type ScheduledRuleRunOutcome
} from '../../shared/automation'
import type { GroupMemberExitedEvent } from '../../shared/group-exit-event'
import { buildExtensionMessageEvent } from '../../shared/extensions/events'
import { buildEventId } from '../extensions/extension-event-bus'
import type { PersonalWechatSendCapability } from '../../shared/personal-wechat'
import type { Wcdb4Client } from '../wcdb4-client'
import type { NormalizedIncomingMessage } from './message-listener-service'
@@ -28,18 +27,12 @@ import {
scheduledReportSourceDisplayName
} from './scheduled-report-target'
import type { AutomationTargetContact } from './automation-wechat-target'
import {
automationRuleStore,
type AutomationRuleStore
} from './automation-rule-store'
import { automationRuleStore, type AutomationRuleStore } from './automation-rule-store'
import {
automationExecutionLogService,
type AutomationExecutionLogService
} from './automation-execution-log-service'
import {
automationActionRunner,
type AutomationActionRunner
} from './automation-action-runner'
import { automationActionRunner, type AutomationActionRunner } from './automation-action-runner'
/**
* AutomationService —— Automation v1 的编排层。
*
@@ -137,9 +130,7 @@ export function leaveNotificationIdempotencyKey(eventId: string): string {
* 「立即执行」会因为幂等而被静默吞掉。
*/
export function scheduledReportExecutionId(ruleId: string, slot: string): string {
return createHash('sha1')
.update(`scheduled_report\u0001${ruleId}\u0001${slot}`)
.digest('hex')
return createHash('sha1').update(`scheduled_report\u0001${ruleId}\u0001${slot}`).digest('hex')
}
/** 定时日报一次执行的结果(定义在 shared 层,便于 IPC / 渲染层共用)。 */
@@ -291,7 +282,7 @@ export class AutomationService {
const sourceDisplayName = this.resolveDisplayName(message)
try {
await this.execute(rule, message, sourceDisplayName)
await this.execute(rule, message, sourceDisplayName, selfUsernames)
} finally {
// 无论 success / failed / 抛异常都要解除 in-flight。
// 漏掉这一步会让这条规则在这个会话里**永久锁死**。
@@ -660,7 +651,10 @@ export class AutomationService {
return true
}
/** 「在哪些聊天生效」的可选项。`id` 必须是 `xxx@chatroom`,与 message.sessionId 对齐。 */ listGroups(): Array<{ id: string; name: string }> {
/** 「在哪些聊天生效」的可选项。`id` 必须是 `xxx@chatroom`,与 message.sessionId 对齐。 */ listGroups(): Array<{
id: string
name: string
}> {
try {
return listContacts()
.filter((contact) => contact.type === 'group' || contact.m_nsUsrName?.endsWith('@chatroom'))
@@ -683,7 +677,8 @@ export class AutomationService {
private async execute(
rule: AutomationRule,
message: NormalizedIncomingMessage,
sourceDisplayName: string
sourceDisplayName: string,
selfUsernames: string[]
): Promise<void> {
const executionId = randomUUID()
const startedAt = this.now()
@@ -719,7 +714,33 @@ export class AutomationService {
rule,
conversationId: message.sessionId,
isGroup,
sourceDisplayName
sourceDisplayName,
...(message.senderId && message.senderNickname
? {
triggerSender: {
wxid: message.senderId,
displayName: message.senderNickname
}
}
: {}),
...(rule.actions.some((action) => action.type === 'extensionAction' && action.enabled)
? {
message: buildExtensionMessageEvent({
eventId: buildEventId(message.sessionId, message.localId),
accountId: String(getSelfAccountInfo()?.wxid || ''),
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 } : {}),
mentionsMe: message.mentionTargets.some((target) => selfUsernames.includes(target)),
createTimeSeconds: message.createTime
})
}
: {})
})
} catch (error) {
result = {
+382 -44
View File
@@ -55,6 +55,8 @@ interface CachedGroupSnapshotFile {
interface ScheduledWrite {
value: unknown
/** 内容指纹,与 value 一一对应;用于判断"磁盘上是否已经是这份内容" */
signature: string
revision: number
generation: number
cleanupFile?: string
@@ -78,6 +80,27 @@ const MAX_MEMORY_GROUP_SNAPSHOTS = 32
const WRITE_DEBOUNCE_MS = 300
const PRUNE_INTERVAL_MS = 30_000
/**
* 替换目标文件时的重试节奏(毫秒)。
*
* 覆盖写走 `rename`(Windows 上是 MoveFileEx+REPLACE_EXISTING),杀软扫描、索引器
* 短暂持有句柄都会让它抛 EPERM/EBUSY/EACCES —— 这类占用是瞬时的,重试即可。
* 4 次总计约 0.5s,超过这个量级说明是真的写不进去,应该保留旧缓存而不是继续磨。
*/
const REPLACE_RETRY_DELAYS_MS = [40, 120, 300] as const
/** 可重试的瞬时错误码。除此以外的错误重试也不会好。 */
const REPLACE_RETRYABLE_CODES = new Set(['EPERM', 'EACCES', 'EBUSY', 'ENOTEMPTY', 'EAGAIN'])
/**
* 退出刷盘的重试总预算(毫秒)。
*
* 单文件最坏重试等待 40+120+300=460ms;待写文件一多,累加起来就是肉眼可见的
* 退出卡顿。这里给整批一个固定预算,预算耗尽后不再等待重试,剩余文件各试一次。
* 首次尝试(真正的 writeFileSync + renameSync)不受预算限制 —— 那是必须做的写。
*/
const FLUSH_RETRY_BUDGET_MS = 120
/** 恢复写入用临时文件名的偏移量,避免与普通 revision 撞名。 */
const RESTORE_REVISION_OFFSET = 1_000_000
const startupMemory = new Map<string, StartupCacheFile>()
const messageMemory = new Map<string, CachedMessageBucketFile>()
const groupMemory = new Map<string, CachedGroupSnapshotFile>()
@@ -86,6 +109,32 @@ const writeQueues = new Map<string, Promise<void>>()
const scheduledWrites = new Map<string, ScheduledWrite>()
const writeRevisions = new Map<string, number>()
const lastPrunedAt = new Map<string, number>()
/**
* 磁盘上**已经确认写入成功**的内容指纹。
*
* 与 `startupMemory` / `scheduledWrites` 是三份独立状态:
* - startupMemory = 最新内存状态(可能是还没落盘的)
* - scheduledWrites = 待写入队列(可能被后来的调用顶掉)
* - persistedSignatures = 上一次真正 rename 成功的内容
* 只有 rename 成功才更新它;失败的写入绝不能把内存态标记成"已持久化",
* 否则后续相同内容的保存会被指纹闸门静默丢掉,缓存永远追不上内存。
*/
const persistedSignatures = new Map<string, string>()
/**
* 最近一次成功落盘的内容(只记启动缓存这类带指纹的文件)。
*
* 存在的唯一理由:rename 是"检查-执行"两段,检查通过之后到 rename 真正生效之间,
* 退出刷盘或清缓存仍可能插进来。事后靠这份日志判断"我这一笔是不是把更新的内容踩了",
* 是就把它恢复回来。只留一条/文件,内存占用与一个 startup.json 同级。
*/
const lastCommits = new Map<string, { value: unknown; signature: string; generation: number }>()
/**
* 退出刷盘纪元。
*
* `flushBootstrapCacheWritesSync()` 自增它,让已经越过检查点、正在飞行的异步写入
* 在最后一步放弃 —— 退出时同步写的内容不应该被一个更早发起的异步写覆盖回去。
*/
let flushEpoch = 0
let cacheGeneration = 0
function normalizeRoot(accountRoot?: string): string {
@@ -96,6 +145,151 @@ function digest(value: string): string {
return crypto.createHash('sha1').update(value).digest('hex').slice(0, 24)
}
/**
* 按 JSON 语义递归规范化:对象键排序、跳过值为 `undefined` 的属性。
*
* 与 `JSON.stringify` 的行为保持一致(后者同样丢弃 undefined 属性、保留 null),
* 这样"指纹看到的"和"写进磁盘的"是同一份内容。
*/
function sortForStable(value: unknown): unknown {
if (Array.isArray(value)) return value.map((item) => sortForStable(item))
if (value === null || typeof value !== 'object') return value
const source = value as Record<string, unknown>
const sorted: Record<string, unknown> = {}
for (const key of Object.keys(source).sort()) {
const item = source[key]
if (item === undefined) continue
sorted[key] = sortForStable(item)
}
return sorted
}
/** 稳定序列化:同一份数据不论键序如何,结果一致。 */
function stableStringify(value: unknown): string {
return JSON.stringify(sortForStable(value))
}
/**
* 启动缓存内容指纹。
*
* 覆盖**实际会被持久化的全部内容**:直接对 `self` 和每个 `contact` 做稳定序列化,
* 不维护字段白名单 —— 白名单漏一个字段就会出现"字段变了却不写盘"的静默失效,
* 这比多写一次严重得多。`updatedAt` / `version` / `platform` 因为不属于 self 或
* 任一 contact,天然不参与计算。
*
* 联系人顺序不参与语义:先压成规范串再对**字符串数组**排序;
* 排序的是派生副本,传入数组本身不会被原地修改。
*
* 复杂度 O(n·k log k),n = 联系人数、k = 单条字段数;相比写 2MB 磁盘可忽略。
*/
function startupSignature(cache: StartupCacheFile): string {
const contacts = Array.isArray(cache.contacts) ? cache.contacts : []
const contactKeys = contacts.map((contact) => stableStringify(contact))
contactKeys.sort()
const selfKey = cache.self ? stableStringify(cache.self) : 'none'
return crypto
.createHash('sha1')
.update(`v${CACHE_VERSION}|${cache.platform}|${normalizeRoot(cache.accountRoot)}`)
.update('|self|')
.update(selfKey)
.update('|contacts|')
.update(contactKeys.join('\n'))
.digest('hex')
}
function delay(ms: number): Promise<void> {
return new Promise((resolve) => setTimeout(resolve, ms))
}
/** 同步 sleep:退出路径不能用 setTimeout,用 Atomics.wait 才不会空转烧 CPU。 */
function delaySync(ms: number): void {
if (ms <= 0) return
try {
Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms)
} catch {
const until = Date.now() + ms
while (Date.now() < until) {
/* 极端环境下退化:没有 SharedArrayBuffer 时只能忙等 */
}
}
}
/**
* 原子替换:临时文件 → 目标文件,全程不删除目标。
*
* `fs.rename` 在 Windows 上走 MoveFileExW(MOVEFILE_REPLACE_EXISTING),在 POSIX 上是
* rename(2):两者都是"用新名字替换旧名字",旧文件内容由文件系统在提交点丢弃,
* 不存在"先删掉目标再尝试改名"的空窗期。
*
* EXDEV(跨卷)在这里是**不可恢复**的:临时文件天生建在目标同目录,正常永远跨不了卷。
* 真出现 EXDEV 说明路径本身出了问题,此时唯一安全的动作是放弃本次写入 ——
* `copyFile` 覆盖没有原子性,写到一半断电/磁盘满会把旧缓存截成半截 JSON,
* 比"这次没更新"严重得多。所以这里直接抛出,旧文件原样保留。
*/
async function replaceFileAtomic(tempFile: string, file: string): Promise<void> {
let lastError: unknown = null
for (let attempt = 0; attempt <= REPLACE_RETRY_DELAYS_MS.length; attempt += 1) {
try {
await fs.rename(tempFile, file)
return
} catch (error) {
const code = (error as NodeJS.ErrnoException)?.code || ''
if (code === 'EXDEV') throw error
if (!REPLACE_RETRYABLE_CODES.has(code)) throw error
lastError = error
if (attempt < REPLACE_RETRY_DELAYS_MS.length) {
await delay(REPLACE_RETRY_DELAYS_MS[attempt])
}
}
}
throw lastError instanceof Error ? lastError : new Error('replace failed')
}
/**
* `replaceFileAtomic` 的同步版本,供退出时的 `flushBootstrapCacheWritesSync` 使用。
*
* `deadline` 是整批刷盘的重试预算:超过它就不再等待重试,直接把这个文件的失败
* 算掉(旧缓存保留)。不设预算的话,N 个待写文件 × 460ms 能把退出拖成分钟级。
*/
function replaceFileAtomicSync(
tempFile: string,
file: string,
deadline = Number.POSITIVE_INFINITY
): void {
let lastError: unknown = null
for (let attempt = 0; attempt <= REPLACE_RETRY_DELAYS_MS.length; attempt += 1) {
try {
fs.renameSync(tempFile, file)
return
} catch (error) {
const code = (error as NodeJS.ErrnoException)?.code || ''
// 与异步路径同样的判断:跨卷不做覆盖复制,直接失败、旧文件保留。
if (code === 'EXDEV') throw error
if (!REPLACE_RETRYABLE_CODES.has(code)) throw error
lastError = error
if (attempt < REPLACE_RETRY_DELAYS_MS.length) {
const wait = REPLACE_RETRY_DELAYS_MS[attempt]
if (Date.now() + wait > deadline) break
delaySync(wait)
}
}
}
throw lastError instanceof Error ? lastError : new Error('replace failed')
}
function makeTempFile(file: string, revision: number): string {
// 临时文件必须与目标同目录:跨卷 rename 会退化成 EXDEV。
return `${file}.${process.pid}.${revision}.tmp`
}
function removeTempFileSync(tempFile: string): void {
try {
if (fs.existsSync(tempFile)) fs.removeSync(tempFile)
} catch {
// 清理失败不改变本次写入的结论,只是留下一个 .tmp
}
}
function getAccountCachePaths(accountRoot: string): AccountCachePaths {
const normalizedRoot = normalizeRoot(accountRoot)
const accountKey = digest(`${process.platform}:${normalizedRoot}`)
@@ -192,7 +386,7 @@ function readStartupCacheFile(accountRoot: string): StartupCacheFile | null {
contacts: Array.isArray(legacy.contacts) ? legacy.contacts : []
}
startupMemory.set(file, migrated)
scheduleWrite(file, migrated, { cleanupFile: paths.legacy })
scheduleWrite(file, migrated, startupSignature(migrated), { cleanupFile: paths.legacy })
return migrated
}
const raw = fs.readJsonSync(file) as Partial<StartupCacheFile>
@@ -206,6 +400,9 @@ function readStartupCacheFile(accountRoot: string): StartupCacheFile | null {
contacts: Array.isArray(raw.contacts) ? raw.contacts : []
}
startupMemory.set(file, result)
// 刚从磁盘读出来的内容就等于磁盘内容,直接登记为"已持久化"。
// 不登记的话,每次启动后的第一次保存都会无条件重写一遍 —— 正是要消掉的放大。
if (!persistedSignatures.has(file)) persistedSignatures.set(file, startupSignature(result))
return result
} catch (error) {
console.warn('[BootstrapCache] startup read failed:', error)
@@ -322,6 +519,7 @@ async function pruneCacheDirectory(directory: string, maxFiles: number): Promise
function queueWrite(file: string): void {
const scheduled = scheduledWrites.get(file)
if (!scheduled) return
const epochAtSchedule = flushEpoch
const previous = writeQueues.get(file) || Promise.resolve()
const next = previous
.catch(() => undefined)
@@ -335,19 +533,91 @@ function queueWrite(file: string): void {
return
}
const tempFile = `${file}.${process.pid}.${scheduled.revision}.tmp`
const tempFile = makeTempFile(file, scheduled.revision)
await fs.ensureDir(path.dirname(file))
// 先把完整内容写进临时文件:目标文件在整个过程中始终是上一份完整数据。
await fs.writeFile(tempFile, JSON.stringify(current.value), 'utf8')
const latest = scheduledWrites.get(file)
if (
!latest ||
latest.revision !== scheduled.revision ||
latest.generation !== cacheGeneration
latest.generation !== cacheGeneration ||
flushEpoch !== epochAtSchedule
) {
await fs.remove(tempFile)
await fs.remove(tempFile).catch(() => undefined)
return
}
await fs.move(tempFile, file, { overwrite: true })
// 替换前的最后一道闸:被 clear 掉(generation 变)或退出刷盘(epoch 变)就不提交。
if (flushEpoch !== epochAtSchedule || scheduled.generation !== cacheGeneration) {
await fs.remove(tempFile).catch(() => undefined)
return
}
try {
await replaceFileAtomic(tempFile, file)
} catch (error) {
// 失败:目标文件仍是旧内容(rename 是原子替换,没有"先删后改"的中间态),
// 本次临时文件必须清掉,否则反复失败会堆 .tmp。
await fs.remove(tempFile).catch(() => undefined)
// 同时撤掉这条待写入记录:留着它会让下一次 commitStartupCache 误以为
// "队列里还有一份不同内容",白写一次。
const failed = scheduledWrites.get(file)
if (failed?.revision === scheduled.revision) scheduledWrites.delete(file)
throw error
}
// 落盘之后核一次账:rename 是原子的,但"检查 epoch/generation"和"rename 生效"
// 之间仍有窗口 —— 退出刷盘或清缓存可能正好插在中间。
// 这时我们刚写下去的可能是旧内容,必须按日志把更新的那份放回去。
const clobberedByFlush = flushEpoch !== epochAtSchedule
const clobberedByClear = scheduled.generation !== cacheGeneration
let committedSignature = scheduled.signature
let committedValue: unknown = scheduled.value
if (scheduled.signature && (clobberedByFlush || clobberedByClear)) {
const newer = lastCommits.get(file)
if (newer && newer.signature !== scheduled.signature) {
// 有比我们更新的一份已经落过盘:恢复它。
const restoreTemp = makeTempFile(file, scheduled.revision + RESTORE_REVISION_OFFSET)
try {
fs.writeFileSync(restoreTemp, JSON.stringify(newer.value), 'utf8')
replaceFileAtomicSync(restoreTemp, file)
committedSignature = newer.signature
committedValue = newer.value
} catch (error) {
removeTempFileSync(restoreTemp)
console.warn('[BootstrapCache] restore after race failed:', error)
}
} else if (clobberedByClear) {
// 清缓存之后才落地的旧数据:不该留在磁盘上(否则等于缓存复活)。
try {
fs.removeSync(file)
} catch {
// 删不掉也不阻塞后续流程,下一次保存会覆盖它
}
committedSignature = ''
committedValue = undefined
}
}
// 只有 rename 成功才承认"磁盘上是这份内容"。superseded 的情况下也照记:
// persistedSignatures 描述的是磁盘现状,不是"最新意图"。
if (scheduled.signature) {
if (committedSignature) {
persistedSignatures.set(file, committedSignature)
lastCommits.set(file, {
value: committedValue,
signature: committedSignature,
generation: scheduled.generation
})
} else {
persistedSignatures.delete(file)
lastCommits.delete(file)
}
}
const completed = scheduledWrites.get(file)
if (
completed?.revision === scheduled.revision &&
@@ -372,6 +642,7 @@ function queueWrite(file: string): void {
function scheduleWrite(
file: string,
value: unknown,
signature: string,
options?: { cleanupFile?: string; prune?: { directory: string; maxFiles: number } }
): void {
const existingTimer = writeTimers.get(file)
@@ -380,6 +651,7 @@ function scheduleWrite(
writeRevisions.set(file, revision)
scheduledWrites.set(file, {
value,
signature,
revision,
generation: cacheGeneration,
cleanupFile: options?.cleanupFile,
@@ -394,6 +666,17 @@ function scheduleWrite(
)
}
/** 取消待写入任务(不动磁盘、不动内存态)。revision 递增让在途写入失效。 */
function cancelScheduledWrite(file: string): void {
const timer = writeTimers.get(file)
if (timer) {
clearTimeout(timer)
writeTimers.delete(file)
}
writeRevisions.set(file, (writeRevisions.get(file) || 0) + 1)
scheduledWrites.delete(file)
}
function loadOrCreateStartupCache(accountRoot: string): StartupCacheFile | null {
const normalizedRoot = normalizeRoot(accountRoot)
if (!normalizedRoot) return null
@@ -410,10 +693,39 @@ function loadOrCreateStartupCache(accountRoot: string): StartupCacheFile | null
return created
}
function writeStartupCache(cache: StartupCacheFile): void {
const paths = getAccountCachePaths(cache.accountRoot)
startupMemory.set(paths.startup, cache)
scheduleWrite(paths.startup, cache, { cleanupFile: paths.legacy })
/**
* 提交一份新的启动缓存状态。
*
* 调用方必须传**新建的对象**(copy-on-write),不能传 `loadOrCreateStartupCache()`
* 返回的那个内存对象本身 —— 否则"旧状态"和"新状态"是同一个引用,
* 指纹永远相等,缓存就再也写不下去了。
*/
function commitStartupCache(next: StartupCacheFile): void {
const paths = getAccountCachePaths(next.accountRoot)
const file = paths.startup
const signature = startupSignature(next)
const persisted = persistedSignatures.get(file)
const pending = scheduledWrites.get(file)
startupMemory.set(file, next)
if (persisted === signature) {
// 磁盘上已经是这份内容。
if (!pending) return
if (pending.signature === signature) {
// 队列里排着的就是要写的同一份内容:撤掉它,别做无意义的一次替换。
cancelScheduledWrite(file)
return
}
// 队列里排着一份**不同**的内容(A→B→A 的收尾):必须再写一次,
// 否则 B 落盘后内存里的 A 就永远丢了。
}
// 只有真正要写盘时才推进 updatedAt:内容没变却刷新时间戳,
// 会让上层"上次更新时间"变成噪音。
const value: StartupCacheFile = { ...next, updatedAt: Date.now() }
startupMemory.set(file, value)
scheduleWrite(file, value, signature, { cleanupFile: paths.legacy })
}
function containsLegacyMisparsedAppMessage(items: Message[]): boolean {
@@ -523,9 +835,8 @@ export function mergeCachedContactAvatars(accountRoot: string, contacts: Contact
export function saveBootstrapSelf(accountRoot: string, self: CachedSelfInfo): void {
const cache = loadOrCreateStartupCache(accountRoot)
if (!cache) return
cache.self = self
cache.updatedAt = Date.now()
writeStartupCache(cache)
// copy-on-write:不原地改内存对象,指纹才可能是"这次的新内容"。
commitStartupCache({ ...cache, self })
}
export function saveBootstrapContacts(accountRoot: string, contacts: Contact[]): void {
@@ -543,7 +854,8 @@ export function saveBootstrapContacts(accountRoot: string, contacts: Contact[]):
)
.map((contact) => [contact.m_nsUsrName, contact.m_nsNickName])
)
cache.contacts = contacts.map((contact) => ({
// 注意:`contacts.map` 产出新数组,传入的数组本身不会被排序或改写。
const merged = contacts.map((contact) => ({
...contact,
avatar:
contact.avatar || !avatarByUsername.has(contact.m_nsUsrName)
@@ -554,23 +866,21 @@ export function saveBootstrapContacts(accountRoot: string, contacts: Contact[]):
? contact.m_nsNickName
: nameByUsername.get(contact.m_nsUsrName) || contact.m_nsNickName
}))
cache.updatedAt = Date.now()
writeStartupCache(cache)
commitStartupCache({ ...cache, contacts: merged })
}
export function mergeBootstrapAvatars(accountRoot: string, avatars: Record<string, string>): void {
const cache = loadOrCreateStartupCache(accountRoot)
if (!cache?.contacts.length) return
let changed = false
cache.contacts = cache.contacts.map((contact) => {
const merged = cache.contacts.map((contact) => {
const avatar = avatars[contact.m_nsUsrName]
if (!avatar || contact.avatar === avatar) return contact
changed = true
return { ...contact, avatar }
})
if (!changed) return
cache.updatedAt = Date.now()
writeStartupCache(cache)
commitStartupCache({ ...cache, contacts: merged })
}
export function getCachedMessages(
@@ -610,29 +920,29 @@ export function saveCachedGroupSnapshot(
const file = getGroupCacheFile(normalizedRoot, userMd5)
const previous = readGroupSnapshotFile(normalizedRoot, userMd5)?.snapshot
const previousByWxid = new Map((previous?.members || []).map((member) => [member.wxid, member]))
const mergedSnapshot: CachedGroupSnapshot = previous && previous.roomId === snapshot.roomId
? {
...snapshot,
members: snapshot.members.map((member) => {
const oldMember = previousByWxid.get(member.wxid)
const freshGroupNickname = String(member.groupNickname || '').trim()
const freshWechatNickname = String(member.wechatNickname || '').trim()
const oldGroupNickname = String(oldMember?.groupNickname || '').trim()
const freshLooksLikeContactFallback =
!freshGroupNickname ||
freshGroupNickname === freshWechatNickname
const groupNickname =
freshLooksLikeContactFallback && oldGroupNickname
? oldGroupNickname
: freshGroupNickname
return {
...member,
groupNickname,
nickname: groupNickname || member.nickname
}
})
}
: snapshot
const mergedSnapshot: CachedGroupSnapshot =
previous && previous.roomId === snapshot.roomId
? {
...snapshot,
members: snapshot.members.map((member) => {
const oldMember = previousByWxid.get(member.wxid)
const freshGroupNickname = String(member.groupNickname || '').trim()
const freshWechatNickname = String(member.wechatNickname || '').trim()
const oldGroupNickname = String(oldMember?.groupNickname || '').trim()
const freshLooksLikeContactFallback =
!freshGroupNickname || freshGroupNickname === freshWechatNickname
const groupNickname =
freshLooksLikeContactFallback && oldGroupNickname
? oldGroupNickname
: freshGroupNickname
return {
...member,
groupNickname,
nickname: groupNickname || member.nickname
}
})
}
: snapshot
const value: CachedGroupSnapshotFile = {
version: CACHE_VERSION,
platform: process.platform,
@@ -642,7 +952,9 @@ export function saveCachedGroupSnapshot(
snapshot: mergedSnapshot
}
touchMemory(groupMemory, file, value, MAX_MEMORY_GROUP_SNAPSHOTS)
scheduleWrite(file, value, {
// 消息桶/群快照不做内容指纹(每次读都是一份新数据),signature 传空串,
// queueWrite 会跳过 persistedSignatures 登记。
scheduleWrite(file, value, '', {
prune: { directory: paths.groups, maxFiles: MAX_GROUP_SNAPSHOTS }
})
return mergedSnapshot
@@ -671,22 +983,43 @@ export function saveCachedMessages(
items: messages.slice(-MAX_MESSAGES_PER_BUCKET)
}
touchMemory(messageMemory, file, value, MAX_MEMORY_MESSAGE_BUCKETS)
scheduleWrite(file, value, {
scheduleWrite(file, value, '', {
prune: { directory: paths.messages, maxFiles: MAX_MESSAGE_BUCKETS }
})
}
export function flushBootstrapCacheWritesSync(): void {
// 自增纪元:已经越过检查点、正在飞行的异步写会在 rename 前发现自己过期并放弃,
// 避免退出时的同步内容被一个更早发起的异步写覆盖回去。
flushEpoch += 1
for (const timer of writeTimers.values()) clearTimeout(timer)
writeTimers.clear()
const writes = Array.from(scheduledWrites.entries())
scheduledWrites.clear()
// 整批共享一份重试预算,避免 N 个文件各自重试把退出拖成分钟级。
const deadline = Date.now() + FLUSH_RETRY_BUDGET_MS
for (const [file, scheduled] of writes) {
// 退出时同步写也算一次 revision 变更,让队列里同一文件的任务作废。
writeRevisions.set(file, (writeRevisions.get(file) || 0) + 1)
const tempFile = makeTempFile(file, scheduled.revision)
try {
fs.ensureDirSync(path.dirname(file))
fs.writeFileSync(file, JSON.stringify(scheduled.value), 'utf8')
// 与异步路径保持同一套语义:先写完整临时文件,再原子换名,绝不先删目标。
fs.writeFileSync(tempFile, JSON.stringify(scheduled.value), 'utf8')
replaceFileAtomicSync(tempFile, file, deadline)
if (scheduled.signature) {
persistedSignatures.set(file, scheduled.signature)
// 记进提交日志:若此时还有一笔在途异步写正好落在我们之后,
// 它会在核账时发现自己踩了更新的内容,并按这条日志恢复。
lastCommits.set(file, {
value: scheduled.value,
signature: scheduled.signature,
generation: scheduled.generation
})
}
if (scheduled.cleanupFile) fs.removeSync(scheduled.cleanupFile)
} catch (error) {
removeTempFileSync(tempFile)
console.warn('[BootstrapCache] flush failed:', error)
}
}
@@ -694,12 +1027,17 @@ export function flushBootstrapCacheWritesSync(): void {
export function clearBootstrapCache(): void {
cacheGeneration += 1
// 清缓存同样让在途写入作废,并且丢掉"已持久化"记录 —— 磁盘上的文件可能马上被删,
// 留着旧指纹会让下一次保存误以为"磁盘上已经有了"而不写。
flushEpoch += 1
for (const timer of writeTimers.values()) clearTimeout(timer)
writeTimers.clear()
scheduledWrites.clear()
writeQueues.clear()
writeRevisions.clear()
lastPrunedAt.clear()
persistedSignatures.clear()
lastCommits.clear()
startupMemory.clear()
messageMemory.clear()
groupMemory.clear()
@@ -55,7 +55,12 @@ export class ImageKeyConfigService {
return migrated.success ? this.getConfig() : legacy
}
const envAesKey = String(import.meta.env.VITE_IMAGE_AES_KEY || '').trim()
// 只有 dev 构建读 .env:生产包里带上开发者的 key,会让所有用户拿同一个人的密钥
// 去解自己的图,直接表现为「图片解密失败」。VITE_* 是编译期字面量,不加这道闸
// 就会被打进 app.asar。
const envAesKey = import.meta.env.DEV
? String(import.meta.env.VITE_IMAGE_AES_KEY || '').trim()
: ''
if (!settings.imageKeyFallbackDisabled && envAesKey) {
return this.buildResult({
source: 'environment',
+290 -49
View File
@@ -13,13 +13,94 @@ type PidCommandRunner = (
export interface MacWechatResidualCleanupDependencies {
platform: NodeJS.Platform
listWechatPids: () => Promise<number[]>
listHostPids: () => Promise<number[]>
listFridaHelperPids: () => Promise<number[]>
listPortPids: () => Promise<number[]>
processName: (pid: number) => Promise<string>
processCommand: (pid: number) => Promise<string>
processCwd: (pid: number) => Promise<string>
processState: (pid: number) => Promise<string>
processIdentity: (pid: number) => Promise<string>
signal: (pid: number, signal: NodeJS.Signals) => void
wait: (milliseconds: number) => Promise<void>
}
const SEND_HOST_PORT = Number(process.env.TM_WECHAT_HOST_PORT) || 4290
function isTraceMemoRuntimePath(value: string): boolean {
const normalized = value.replace(/\\/g, '/').toLowerCase()
return /\/tracememo(?:\.app\/contents)?\/resources\/runtime\/darwin-arm64(?:\/|$)/.test(
normalized
)
}
export function isTraceMemoFridaHelper(command: string, cwd: string): boolean {
return isTraceMemoRuntimePath(command) || isTraceMemoRuntimePath(cwd)
}
/* 不要把进程信息不可读当作进程已退出:TCC 限制下仍可能有存活进程。 */
function resolveProcessName(
name: string,
command: string,
cwd: string,
isFridaHelper: boolean
): string {
const trimmed = name.trim()
if (/^frida-hel/.test(trimmed)) return 'frida-helper'
if (/^tm-wechat/.test(trimmed)) return 'tm-wechat-host'
if (trimmed && trimmed !== 'unknown') return trimmed
if (/tm-wechat-host/.test(command)) return 'tm-wechat-host'
if (/frida-helper/.test(command)) return 'frida-helper'
if (isFridaHelper) return 'frida-helper'
if (isTraceMemoRuntimePath(cwd)) return 'tm-wechat-host'
return 'unknown'
}
async function readShortProcessName(pid: number): Promise<string> {
try {
const { stdout } = await execFileAsync(
'/usr/sbin/lsof',
['-a', '-p', String(pid), '-d', 'cwd'],
{ timeout: 2_000 }
)
/* lsof 可能忽略失效的 -p 参数,因此必须核对返回行的 PID。 */
for (const line of stdout.split('\n')) {
const columns = line.trim().split(/\s+/)
if (columns[1] === String(pid)) return columns[0] || ''
}
return ''
} catch {
return ''
}
}
async function readProcessField(pid: number, field: string): Promise<string> {
try {
const { stdout } = await execFileAsync('/bin/ps', ['-p', String(pid), '-o', `${field}=`], {
timeout: 2_000
})
return stdout.trim()
} catch {
return ''
}
}
async function readProcessCwd(pid: number): Promise<string> {
try {
const { stdout } = await execFileAsync(
'/usr/sbin/lsof',
['-a', '-p', String(pid), '-d', 'cwd', '-Fn'],
{ timeout: 2_000 }
)
const lines = stdout.split('\n')
/* lsof 可能忽略失效的 -p 参数,因此必须核对记录的 PID。 */
if (lines.find((line) => line.startsWith('p')) !== `p${pid}`) return ''
return lines.find((line) => line.startsWith('n'))?.slice(1) || ''
} catch {
return ''
}
}
export async function readPids(
executable: string,
args: string[],
@@ -48,25 +129,58 @@ const defaultDependencies: MacWechatResidualCleanupDependencies = {
])
return [...new Set(results.flat())]
},
listPortPids: () => readPids('/usr/sbin/lsof', ['-nP', '-t', '-iTCP:4290', '-sTCP:LISTEN']),
listPortPids: () =>
readPids('/usr/sbin/lsof', [
'-nP',
'-t',
`-iTCP:${SEND_HOST_PORT}`,
'-sTCP:LISTEN'
]),
listHostPids: async () => {
const pids = await readPids('/usr/bin/pgrep', ['-x', 'tm-wechat-host'])
const [commands, directories] = await Promise.all([
Promise.all(pids.map((pid) => readProcessField(pid, 'command'))),
Promise.all(pids.map(readProcessCwd))
])
return pids.filter(
(_, index) =>
isTraceMemoRuntimePath(commands[index]) || isTraceMemoRuntimePath(directories[index])
)
},
listFridaHelperPids: async () => {
const pids = await readPids('/usr/bin/pgrep', ['-f', 'frida-helper'])
const [commands, directories] = await Promise.all([
Promise.all(pids.map((pid) => readProcessField(pid, 'command'))),
Promise.all(pids.map(readProcessCwd))
])
return pids.filter((_, index) => isTraceMemoFridaHelper(commands[index], directories[index]))
},
processName: async (pid) => {
try {
const { stdout } = await execFileAsync('/bin/ps', ['-p', String(pid), '-o', 'comm='], {
timeout: 2_000
})
return stdout.trim().split('/').pop() || 'unknown'
const name = stdout.trim().split('/').pop() || ''
if (name) return name
} catch {
return 'unknown'
/* ps 对同用户外部进程可能整体不可用,落到 lsof。 */
}
return readShortProcessName(pid) || 'unknown'
},
processCommand: (pid) => readProcessField(pid, 'command'),
processCwd: readProcessCwd,
processState: (pid) => readProcessField(pid, 'state'),
processIdentity: async (pid) => {
try {
const { stdout } = await execFileAsync(
'/bin/ps',
['-p', String(pid), '-o', 'lstart=', '-o', 'comm='],
{ timeout: 2_000 }
)
return createHash('sha256').update(stdout.trim()).digest('hex')
const [startTime, command, cwd] = await Promise.all([
readProcessField(pid, 'lstart'),
readProcessField(pid, 'command'),
readProcessCwd(pid)
])
/* 纳入 PID,避免进程退出后复用同一工作目录导致身份碰撞。 */
return createHash('sha256')
.update([String(pid), startTime, command, cwd].join('\0'))
.digest('hex')
} catch {
return ''
}
@@ -81,51 +195,132 @@ interface ObservedTarget extends MacWechatResidualProcess {
function mergeTargets(
wechatPids: number[],
hostPids: number[],
portPids: number[],
processNames: Map<number, string>,
processIdentities: Map<number, string>
processIdentities: Map<number, string>,
processStates: Map<number, string>,
fridaHelperPids: number[]
): ObservedTarget[] {
const targets = new Map<number, Set<'wechat' | 'port_4290'>>()
const targets = new Map<number, Set<'wechat' | 'host' | 'port_4290' | 'frida_helper'>>()
for (const pid of wechatPids) {
if (!Number.isSafeInteger(pid) || pid <= 0) continue
const reasons = targets.get(pid) || new Set<'wechat' | 'port_4290'>()
const reasons = targets.get(pid) || new Set<'wechat' | 'host' | 'port_4290' | 'frida_helper'>()
reasons.add('wechat')
targets.set(pid, reasons)
}
for (const pid of hostPids) {
if (!Number.isSafeInteger(pid) || pid <= 0) continue
const reasons = targets.get(pid) || new Set<'wechat' | 'host' | 'port_4290' | 'frida_helper'>()
reasons.add('host')
targets.set(pid, reasons)
}
for (const pid of portPids) {
if (!Number.isSafeInteger(pid) || pid <= 0) continue
const reasons = targets.get(pid) || new Set<'wechat' | 'port_4290'>()
const reasons = targets.get(pid) || new Set<'wechat' | 'host' | 'port_4290' | 'frida_helper'>()
reasons.add('port_4290')
targets.set(pid, reasons)
}
for (const pid of fridaHelperPids) {
if (!Number.isSafeInteger(pid) || pid <= 0) continue
const reasons = targets.get(pid) || new Set<'wechat' | 'host' | 'port_4290' | 'frida_helper'>()
reasons.add('frida_helper')
targets.set(pid, reasons)
}
return [...targets.entries()]
.sort(([first], [second]) => first - second)
.map(([pid, reasons]) => ({
pid,
name: processNames.get(pid) || 'unknown',
targets: [...reasons].sort(),
confirmationToken: processIdentities.get(pid) || ''
}))
.map(([pid, reasons]) => {
const state = processStates.get(pid) || ''
return {
pid,
name: processNames.get(pid) || 'unknown',
...(state ? { state } : {}),
/* 只有明确的 U 状态才标记为不可中断;状态未知不做推断。 */
...(/U/.test(state) ? { uninterruptible: true } : {}),
targets: [...reasons].sort(),
confirmationToken: processIdentities.get(pid) || ''
}
})
}
async function inspectObservedTargets(
dependencies: MacWechatResidualCleanupDependencies
): Promise<ObservedTarget[]> {
if (dependencies.platform !== 'darwin') return []
const [rawWechatPids, rawPortPids] = await Promise.all([
const [rawWechatPids, rawHostPids, rawPortPids, rawFridaHelperPids] = await Promise.all([
dependencies.listWechatPids(),
dependencies.listPortPids()
dependencies.listHostPids(),
dependencies.listPortPids(),
dependencies.listFridaHelperPids()
])
const wechatPids = rawWechatPids.filter((pid) => pid !== process.pid)
const hostPids = rawHostPids.filter((pid) => pid !== process.pid)
const portPids = rawPortPids.filter((pid) => pid !== process.pid)
const pids = [...new Set([...wechatPids, ...portPids])].filter(
const fridaHelperPids = rawFridaHelperPids.filter((pid) => pid !== process.pid)
const pids = [...new Set([...wechatPids, ...portPids, ...fridaHelperPids])].filter(
(pid) => Number.isSafeInteger(pid) && pid > 0
)
const [names, identities] = await Promise.all([
for (const pid of hostPids) {
if (Number.isSafeInteger(pid) && pid > 0 && !pids.includes(pid)) pids.push(pid)
}
const [names, identities, states] = await Promise.all([
Promise.all(pids.map(async (pid) => [pid, await dependencies.processName(pid)] as const)),
Promise.all(pids.map(async (pid) => [pid, await dependencies.processIdentity(pid)] as const))
Promise.all(pids.map(async (pid) => [pid, await dependencies.processIdentity(pid)] as const)),
Promise.all(pids.map(async (pid) => [pid, await dependencies.processState(pid)] as const))
])
return mergeTargets(wechatPids, portPids, new Map(names), new Map(identities))
const [commands, directories] = await Promise.all([
Promise.all(pids.map(async (pid) => [pid, await dependencies.processCommand(pid)] as const)),
Promise.all(pids.map(async (pid) => [pid, await dependencies.processCwd(pid)] as const))
])
const commandByPid = new Map(commands)
const cwdByPid = new Map(directories)
const nameByPid = new Map(names)
const filteredFridaHelpers = fridaHelperPids.filter((pid) =>
isTraceMemoFridaHelper(commandByPid.get(pid) || '', cwdByPid.get(pid) || '')
)
const fridaHelperSet = new Set(filteredFridaHelpers)
const resolvedNames = new Map<number, string>()
for (const pid of pids) {
resolvedNames.set(
pid,
resolveProcessName(
nameByPid.get(pid) || '',
commandByPid.get(pid) || '',
cwdByPid.get(pid) || '',
fridaHelperSet.has(pid)
)
)
}
return mergeTargets(
wechatPids,
hostPids,
portPids,
resolvedNames,
new Map(identities),
new Map(states),
filteredFridaHelpers
)
}
async function waitForConfirmedTargets(
dependencies: MacWechatResidualCleanupDependencies,
selected: ObservedTarget[],
attempts: number,
intervalMs: number
): Promise<ObservedTarget[]> {
const expected = new Map(selected.map((target) => [target.pid, target.confirmationToken]))
let remaining = selected.filter((target) => !/U/.test(target.state || ''))
if (remaining.length === 0) return selected
for (let attempt = 0; attempt < attempts && remaining.length > 0; attempt++) {
await dependencies.wait(intervalMs)
const current = await inspectObservedTargets(dependencies)
remaining = current.filter(
(target) =>
expected.get(target.pid) === target.confirmationToken && !/U/.test(target.state || '')
)
}
const blocked = selected.filter((target) => /U/.test(target.state || ''))
return [...remaining, ...blocked]
}
export async function inspectMacWechatResidualProcesses(
@@ -156,10 +351,11 @@ export async function cleanupMacWechatResidualProcesses(
const selected = current.filter(
(target) => confirmed.get(target.pid) === target.confirmationToken
)
const selectedIdentities = new Map(selected.map((target) => [target.pid, target.confirmationToken]))
if (selected.length === 0) {
return {
stopped: [],
remaining: current.filter((target) => confirmed.has(target.pid))
remaining: current
}
}
let cleanupTargetsNotified = false
@@ -170,44 +366,89 @@ export async function cleanupMacWechatResidualProcesses(
): Promise<void> => {
const identity = await dependencies.processIdentity(target.pid)
if (!expectedIdentity || identity !== expectedIdentity) return
if (
(target.targets.includes('host') ||
target.targets.includes('port_4290') ||
target.targets.includes('frida_helper')) &&
!cleanupTargetsNotified
) {
cleanupTargetsNotified = true
onTargetsConfirmed?.([target])
}
try {
dependencies.signal(target.pid, signal)
} catch (error) {
if ((error as NodeJS.ErrnoException).code !== 'ESRCH') throw error
}
if (target.targets.includes('port_4290') && !cleanupTargetsNotified) {
cleanupTargetsNotified = true
onTargetsConfirmed?.([target])
}
}
for (const target of selected.filter((item) => item.targets.includes('wechat'))) {
await signalMatchingTarget(target, confirmed.get(target.pid) || '', 'SIGTERM')
}
if (selected.some((item) => item.targets.includes('wechat'))) await dependencies.wait(1_000)
let remaining = (await inspectObservedTargets(dependencies)).filter((target) =>
confirmed.has(target.pid)
let activeTargets = (await inspectObservedTargets(dependencies)).filter(
(target) =>
confirmed.has(target.pid) &&
selectedIdentities.get(target.pid) === target.confirmationToken
)
for (const target of remaining) {
const selectedTarget = selected.find((item) => item.pid === target.pid)
if (!selectedTarget || target.confirmationToken !== selectedTarget.confirmationToken) continue
await signalMatchingTarget(target, selectedTarget.confirmationToken, 'SIGTERM')
const hostTargets = activeTargets.filter((target) => target.targets.includes('host'))
for (const target of hostTargets) {
await signalMatchingTarget(target, target.confirmationToken, 'SIGTERM')
}
if (hostTargets.some((target) => !/U/.test(target.state || ''))) {
await dependencies.wait(1_000)
await waitForConfirmedTargets(dependencies, hostTargets, 8, 250)
}
if (remaining.length > 0) await dependencies.wait(1_000)
remaining = (await inspectObservedTargets(dependencies)).filter((target) =>
confirmed.has(target.pid)
activeTargets = (await inspectObservedTargets(dependencies)).filter((target) =>
confirmed.has(target.pid) && selectedIdentities.get(target.pid) === target.confirmationToken
)
for (const target of remaining) {
const helperTargets = activeTargets.filter(
(target) =>
!target.targets.includes('host') &&
target.targets.includes('frida_helper') &&
selectedIdentities.get(target.pid) === target.confirmationToken
)
const unrelatedPortTargets = activeTargets.filter(
(target) =>
!target.targets.includes('host') &&
!target.targets.includes('frida_helper') &&
selectedIdentities.get(target.pid) === target.confirmationToken
)
for (const target of helperTargets) {
await signalMatchingTarget(target, target.confirmationToken, 'SIGTERM')
}
for (const target of unrelatedPortTargets) {
await signalMatchingTarget(target, target.confirmationToken, 'SIGTERM')
}
await waitForConfirmedTargets(dependencies, helperTargets, 4, 250)
await waitForConfirmedTargets(dependencies, unrelatedPortTargets, 4, 250)
activeTargets = (await inspectObservedTargets(dependencies)).filter(
(target) =>
confirmed.has(target.pid) &&
selectedIdentities.get(target.pid) === target.confirmationToken
)
const wechatTargets = activeTargets.filter((target) => target.targets.includes('wechat'))
for (const target of wechatTargets) {
await signalMatchingTarget(target, target.confirmationToken, 'SIGTERM')
}
await waitForConfirmedTargets(dependencies, wechatTargets, 8, 250)
const remainingTargets = activeTargets.filter(
(target) =>
!target.targets.includes('host') &&
!target.targets.includes('frida_helper') &&
!target.targets.includes('wechat') &&
selectedIdentities.get(target.pid) === target.confirmationToken
)
await waitForConfirmedTargets(dependencies, remainingTargets, 10, 500)
activeTargets = (await inspectObservedTargets(dependencies)).filter((target) =>
confirmed.has(target.pid) && selectedIdentities.get(target.pid) === target.confirmationToken
)
for (const target of activeTargets) {
const selectedTarget = selected.find((item) => item.pid === target.pid)
if (!selectedTarget || target.confirmationToken !== selectedTarget.confirmationToken) continue
await signalMatchingTarget(target, selectedTarget.confirmationToken, 'SIGKILL')
}
if (remaining.length > 0) await dependencies.wait(250)
remaining = (await inspectObservedTargets(dependencies)).filter((target) =>
confirmed.has(target.pid)
)
await waitForConfirmedTargets(dependencies, activeTargets, 8, 250)
const remaining = await inspectObservedTargets(dependencies)
return {
stopped: selected
.filter((target) => !remaining.some((item) => item.pid === target.pid))
@@ -11,8 +11,7 @@ function assertFile(path: string, label: string): void {
}
}
function assertMachOArm64(path: string, label: string): void {
const binary = readFileSync(path)
function assertMachOArm64(binary: Buffer, label: string): void {
if (binary.length < 8 || binary.readUInt32LE(0) !== 0xfeedfacf) {
throw new Error(`${label} is not a 64-bit Mach-O binary`)
}
@@ -71,17 +70,74 @@ export function readMacWechatRuntimeManifest(
throw new Error(`runtime manifest capability missing: ${capability}`)
}
}
assertMachOArm64(hostPath, 'runtime host')
assertMachOArm64(dylibPath, 'runtime dylib')
if (!readFileSync(dylibPath).includes(Buffer.from(manifest.tmSendSourceSha256, 'utf8'))) {
assertMachOArm64(readFileSync(hostPath), 'runtime host')
const dylib = readFileSync(dylibPath)
assertMachOArm64(dylib, 'runtime dylib')
if (!dylib.includes(Buffer.from(manifest.tmSendSourceSha256, 'utf8'))) {
throw new Error('runtime dylib embedded agent hash does not match manifest')
}
if (!readFileSync(dylibPath).includes(Buffer.from(manifest.addressProfileSha256, 'utf8'))) {
if (!dylib.includes(Buffer.from(manifest.addressProfileSha256, 'utf8'))) {
throw new Error('runtime dylib embedded address profile hash does not match manifest')
}
return manifest
}
type RuntimeFileSignature = readonly [
path: string,
device: string,
inode: string,
size: string,
modifiedNs: string,
changedNs: string
]
function getRuntimeFileSignatures(runtimeDir: string): RuntimeFileSignature[] {
return ['runtime-manifest.json', 'tm-wechat-host', 'libtmwechat.dylib'].map((name) => {
const filePath = join(runtimeDir, name)
assertFile(filePath, name)
const stats = statSync(filePath, { bigint: true })
if (!stats.isFile()) throw new Error(`runtime artifact is not a file: ${filePath}`)
return [
filePath,
stats.dev.toString(),
stats.ino.toString(),
stats.size.toString(),
stats.mtimeNs.toString(),
stats.ctimeNs.toString()
]
})
}
export class MacWechatRuntimeManifestCache {
private entry: {
runtimeDir: string
architecture: string
signatures: RuntimeFileSignature[]
manifest: MacWechatRuntimeManifest
} | null = null
read(runtimeDir: string, architecture = process.arch): MacWechatRuntimeManifest {
const signatures = getRuntimeFileSignatures(runtimeDir)
if (
this.entry?.runtimeDir === runtimeDir &&
this.entry.architecture === architecture &&
signatures.every((signature, index) =>
signature.every((value, part) => value === this.entry?.signatures[index]?.[part])
)
) {
return this.entry.manifest
}
const manifest = readMacWechatRuntimeManifest(runtimeDir, architecture)
this.entry = { runtimeDir, architecture, signatures, manifest }
return manifest
}
clear(): void {
this.entry = null
}
}
export function bindingMatchesRuntimeManifest(
binding: {
hostPid?: number
+329 -95
View File
@@ -1,4 +1,5 @@
import { spawn, type ChildProcess } from 'child_process'
import { execFile, execFileSync, spawn, type ChildProcess } from 'child_process'
import { promisify } from 'node:util'
import { chmodSync, existsSync } from 'fs'
import { get, request as httpRequest } from 'http'
import { join } from 'path'
@@ -27,9 +28,11 @@ import type { PersonalWechatSenderStatus } from '../../shared/personal-wechat'
import { hasValidWechatLicense } from '../../shared/personal-wechat-mac-send-action'
import {
bindingMatchesRuntimeManifest,
readMacWechatRuntimeManifest
MacWechatRuntimeManifestCache
} from './mac-wechat-runtime-artifact'
const execFileAsync = promisify(execFile)
/*
* MacWechatRuntimeManager — lifecycle owner of the built-in macOS native
* WeChat runtime (tm-wechat-host + libtmwechat.dylib).
@@ -48,10 +51,10 @@ import {
* auto-binding, that path dead-ends in a 20s attach timeout every time.
*/
/* 默认 4290。进程会 fork 继承监听 fd(CLOEXEC 只挡 exec),
* host 崩溃后孤儿进程仍扣着端口,新 host bind 失败会返回 1 无限重启。
* 被占用时用 TM_WECHAT_HOST_PORT 指到备用端口。 */
const PORT = Number(process.env.TM_WECHAT_HOST_PORT) || 4290
/* Helper 会继承监听 fd,并在 Host 退出后继续持有;它卡在内核不可中断态时
* SIGKILL 也不回收,重试同一端口永远失败,所以启动必须允许备用端口。 */
const DEFAULT_PORT = Number(process.env.TM_WECHAT_HOST_PORT) || 4290
const PORT_FALLBACK_SPAN = 3
const HOST = '127.0.0.1'
const START_TIMEOUT_MS = 15_000
const REQUEST_TIMEOUT_MS = 30_000
@@ -61,6 +64,36 @@ const CRASH_RESTART_DELAY_MS = 1_500
const LICENSE_STATUS_TIMEOUT_MS = 8_000
const LICENSE_REFRESH_TIMEOUT_MS = 20_000
/* 仅地址占用可以通过切换端口恢复。 */
function isPortConflictDiagnostic(diagnostic: string): boolean {
return /address already in use|EADDRINUSE|bind .*failed/i.test(diagnostic)
}
async function describePortHolder(port: number): Promise<string> {
try {
const { stdout } = await execFileAsync(
'/usr/sbin/lsof',
['-nP', '-t', `-iTCP:${port}`, '-sTCP:LISTEN'],
{ timeout: 2_000 }
)
const pid = Number(stdout.trim().split(/\s+/)[0])
if (!Number.isSafeInteger(pid) || pid <= 0) return ''
try {
const { stdout: command } = await execFileAsync(
'/bin/ps',
['-p', String(pid), '-o', 'comm='],
{ timeout: 2_000 }
)
const name = command.trim().split('/').pop() || 'unknown'
return `${name}(PID ${pid})`
} catch {
return `PID ${pid}(进程信息不可读,可能卡在退出中)`
}
} catch {
return ''
}
}
interface MacWechatSenderStatusInput {
snapshot: MacWechatRuntimeSnapshot
binding: MacWechatBindingStatus | null
@@ -75,6 +108,23 @@ export function shouldClearWechatRestartRequired(
return orphanWechatPid > 0 && currentWechatPid > 0 && orphanWechatPid !== currentWechatPid
}
export function formatMacWechatHostStartupFailure(code: number | null, diagnostic: string): string {
const lines = diagnostic.trim().split('\n').filter(Boolean)
const detail = lines[lines.length - 1]
if (detail) return `发送运行时启动失败(进程退出码 ${code ?? '未知'}):${detail}`
return code === null ? '发送运行时在启动过程中退出' : `发送运行时启动失败(进程退出码 ${code})`
}
export function resolveMacWechatSendMechanism(
binding: MacWechatBindingStatus | null,
manifest: MacWechatRuntimeManifest | null
): string | undefined {
if (!binding || !manifest || !bindingMatchesRuntimeManifest(binding, manifest)) return undefined
return binding.wechatVersion
? manifest.capabilitiesByVersion?.[binding.wechatVersion]?.textMechanism
: undefined
}
export function deriveMacWechatSenderStatus({
snapshot,
binding,
@@ -86,10 +136,12 @@ export function deriveMacWechatSenderStatus({
const versionCapabilities = binding?.wechatVersion
? manifest.capabilitiesByVersion?.[binding.wechatVersion]
: undefined
const nativeMechanism = versionCapabilities?.textMechanism === 'native-msg-object'
const contextIndependentMechanism =
versionCapabilities?.textMechanism === 'native-msg-object' ||
versionCapabilities?.textMechanism === 'tm-message-source-send'
const nativeBindingReady =
identityMatches &&
nativeMechanism &&
contextIndependentMechanism &&
binding?.runtimeState === 'ready' &&
binding.sessionAttached &&
binding.scriptLoaded
@@ -99,6 +151,12 @@ export function deriveMacWechatSenderStatus({
if (snapshot.wechatRestartRequired) {
state = 'error'
message = '微信发送组件异常退出。由于当前微信进程中可能残留上一发送会话,请重启微信后重新绑定。'
} else if (snapshot.lifecycle === 'crashed_unbound') {
state = 'error'
message = snapshot.error || '微信发送运行时启动失败,请重新启动发送组件。'
} else if (snapshot.lifecycle === 'stopped' && snapshot.error) {
state = 'error'
message = snapshot.error
} else if (binding && !identityMatches) {
state = 'error'
message = '运行中的微信发送 host 与当前 Native Runtime 不一致,请退出旧 host 后重启 TraceMemo。'
@@ -115,7 +173,9 @@ export function deriveMacWechatSenderStatus({
message = '个人微信已准备好发送日报'
} else if (binding?.bindingState === 'bound' || binding?.bindingState === 'binding') {
state = 'hook_not_ready'
message = nativeMechanism ? '已绑定,等待原生发送 hook 就绪' : '已绑定,等待捕获微信发送上下文'
message = contextIndependentMechanism
? '已绑定,等待原生发送 hook 就绪'
: '已绑定,等待捕获微信发送上下文'
} else if (stale) {
state = 'stopped'
message = '检测到微信已重启,请重新绑定'
@@ -128,7 +188,7 @@ export function deriveMacWechatSenderStatus({
}
const runtimeCapabilities = new Set(manifest.capabilities)
const supportsCapability = (name: 'text' | 'image' | 'voice'): boolean => {
const supportsCapability = (name: 'text' | 'image' | 'voice' | 'file'): boolean => {
if (manifest.capabilitiesByVersion) return versionCapabilities?.[name] === 'verified'
return runtimeCapabilities.has(name)
}
@@ -139,6 +199,16 @@ export function deriveMacWechatSenderStatus({
const canSendText = bindingReady && supportsCapability('text') && binding?.canSendText === true
const canSendImage = bindingReady && supportsCapability('image') && binding?.canSendImage === true
const canSendVoice = bindingReady && supportsCapability('voice') && binding?.canSendVoice === true
/*
* 视频复用图片的媒体通道(Host 的 `/SendMsg` type=video)。
* Runtime manifest 不单独声明 video 能力,因此以图片通道是否可用作为判据;
* 真正的发送结果仍以 Host 返回为准,不在 UI 层假装支持。
*/
const canSendVideo = bindingReady && binding?.canSendImage === true
const canSendFile =
bindingReady &&
supportsCapability('file') &&
versionCapabilities?.textMechanism === 'tm-message-source-send'
const sessionAttached = identityMatches && (binding?.sessionAttached ?? false)
const scriptLoaded = identityMatches && (binding?.scriptLoaded ?? false)
@@ -162,10 +232,12 @@ export function deriveMacWechatSenderStatus({
imageHookInstalled: identityMatches && (binding?.canSendImage ?? false),
imageHookReady: identityMatches && (binding?.canSendImage ?? false),
messageListenerReady: scriptLoaded,
canSend: canSendText || canSendImage || canSendVoice,
canSend: canSendText || canSendImage || canSendVoice || canSendVideo || canSendFile,
canSendText,
canSendImage,
canSendVoice,
canSendVideo,
canSendFile,
message,
error: state === 'error' ? message : undefined
}
@@ -190,8 +262,9 @@ export function resolveLicenseRefreshFailure(
return offlineMacLicenseStatus('server_unavailable', diagnostic)
}
class MacWechatRuntimeManager {
export class MacWechatRuntimeManager {
private child: ChildProcess | null = null
private startInFlight: Promise<MacWechatRuntimeSnapshot> | null = null
private lifecycle: MacWechatRuntimeLifecycle = 'stopped'
private wechatRestartRequired = false
/* The WeChat pid that was bound when the host died / bind hit the orphan
@@ -200,20 +273,25 @@ class MacWechatRuntimeManager {
private orphanWechatPid = 0
private lastBinding: MacWechatBindingStatus | null = null
private manifest: MacWechatRuntimeManifest | null = null
private readonly manifestCache = new MacWechatRuntimeManifestCache()
private senderStatusInFlight: Promise<PersonalWechatSenderStatus> | null = null
private lastError: string | null = null
private restartTimer: NodeJS.Timeout | null = null
private manuallyStopped = false
private activePort = DEFAULT_PORT
private portFallbackFrom: number | null = null
getPort(): number {
return PORT
return this.activePort
}
getSnapshot(): MacWechatRuntimeSnapshot {
return {
lifecycle: this.lifecycle,
wechatRestartRequired: this.wechatRestartRequired,
endpoint: `http://${HOST}:${PORT}`,
port: PORT,
endpoint: `http://${HOST}:${this.activePort}`,
port: this.activePort,
...(this.portFallbackFrom === null ? {} : { portFallbackFrom: this.portFallbackFrom }),
runtimeDir: this.resolveRuntimeDir() ?? undefined,
error: this.lastError ?? undefined,
binding: this.lastBinding ?? undefined
@@ -254,7 +332,7 @@ class MacWechatRuntimeManager {
try {
const runtimeDir = this.resolveRuntimeDir()
if (!runtimeDir) return false
this.manifest = readMacWechatRuntimeManifest(runtimeDir)
this.manifest = this.manifestCache.read(runtimeDir)
return true
} catch {
return false
@@ -268,7 +346,7 @@ class MacWechatRuntimeManager {
try {
const runtimeDir = this.resolveRuntimeDir()
if (!runtimeDir) throw new Error('发送 Runtime 目录缺失')
this.manifest = readMacWechatRuntimeManifest(runtimeDir)
this.manifest = this.manifestCache.read(runtimeDir)
return { state: 'available', message: '微信发送组件可用' }
} catch (error) {
const detail = error instanceof Error ? error.message : String(error)
@@ -281,9 +359,25 @@ class MacWechatRuntimeManager {
* comes up WITHOUT touching WeChat (lazy init inside the host), so "runtime
* online" and "WeChat bound" stay two independent states.
*/
async ensureStarted(
options: { allowManualRestart?: boolean } = {}
): Promise<MacWechatRuntimeSnapshot> {
ensureStarted(options: { allowManualRestart?: boolean } = {}): Promise<MacWechatRuntimeSnapshot> {
if (this.startInFlight) return this.startInFlight
const startPromise = this.ensureStartedOnce(options)
this.startInFlight = startPromise
void startPromise.then(
() => {
if (this.startInFlight === startPromise) this.startInFlight = null
},
() => {
if (this.startInFlight === startPromise) this.startInFlight = null
}
)
return startPromise
}
protected async ensureStartedOnce(options: {
allowManualRestart?: boolean
}): Promise<MacWechatRuntimeSnapshot> {
if (this.manuallyStopped && !options.allowManualRestart) return this.getSnapshot()
if (options.allowManualRestart) this.manuallyStopped = false
if (isMacNativeRuntimeUnavailable()) {
@@ -303,7 +397,7 @@ class MacWechatRuntimeManager {
return this.getSnapshot()
}
try {
this.manifest = readMacWechatRuntimeManifest(runtimeDir)
this.manifest = this.manifestCache.read(runtimeDir)
appLogger.write({
level: 'info',
scope: 'mac-wechat-runtime',
@@ -353,7 +447,7 @@ class MacWechatRuntimeManager {
* frida session, so the app is immediately ready with NO re-bind, exactly
* the "keep the send capability process" behaviour the user asked to carry over.
*/
if (await this.ping()) {
if (await this.adoptRunningHost()) {
this.lifecycle = 'online'
this.child = null
this.wechatRestartRequired = false
@@ -393,46 +487,169 @@ class MacWechatRuntimeManager {
} catch {
/* best effort — dev checkouts usually keep the exec bit */
}
this.lifecycle = 'starting'
this.lastError = null
try {
/* Host stderr goes to /dev/null (stdio ignored, see note above), so the
* host writes its own log file via TM_WECHAT_LOG_FILE. Without this the
* agent's stage beacons (send-enter / cdn-enter / …) are invisible and a
* media/CDN stall is undiagnosable. info level so stage beacons show. */
const hostLogFile = join(app.getPath('logs'), 'tm-wechat-host.log')
this.child = spawn(
hostPath,
[
'--port',
String(PORT),
'--manifest',
join(runtimeDir, 'runtime-manifest.json'),
'--log-level',
'info'
],
{
cwd: runtimeDir,
stdio: 'ignore',
detached: false,
env: { ...process.env, TM_WECHAT_LOG_FILE: hostLogFile }
}
)
if (!app.isPackaged) {
execFileSync('/usr/bin/codesign', ['--force', '--sign', '-', '--timestamp=none', hostPath])
}
execFileSync('/usr/bin/codesign', ['--verify', '--strict', hostPath])
} catch (error) {
this.lifecycle = 'stopped'
this.lastError = String(error)
this.lastError =
'无法验证发送 Host 签名:' + (error instanceof Error ? error.message : String(error))
appLogger.write({
level: 'error',
scope: 'mac-wechat-runtime',
message: 'host_signature_invalid',
details: { detail: this.lastError }
})
return this.getSnapshot()
}
this.child.on('exit', (code) => {
const manifestPath = join(runtimeDir, 'runtime-manifest.json')
/* stderr 保持管道以便启动失败时取诊断;运行日志走 hostLogFile。 */
const hostLogFile = join(app.getPath('logs'), 'tm-wechat-host.log')
const candidates = this.candidatePorts()
const failures: Array<{ port: number; detail: string; portConflict: boolean }> = []
for (const port of candidates) {
this.activePort = port
this.lifecycle = 'starting'
this.lastError = null
let child: ChildProcess
try {
child = spawn(
hostPath,
['--port', String(port), '--manifest', manifestPath, '--log-level', 'info'],
{
cwd: runtimeDir,
stdio: ['ignore', 'ignore', 'pipe'],
detached: false,
env: { ...process.env, TM_WECHAT_LOG_FILE: hostLogFile }
}
)
} catch (error) {
this.lifecycle = 'stopped'
this.lastError = String(error)
return this.getSnapshot()
}
this.child = child
let startupDiagnostic = ''
let exitedDuringStartup = false
child.stderr?.setEncoding('utf8')
child.stderr?.on('data', (chunk: string) => {
startupDiagnostic = (startupDiagnostic + chunk).slice(-2_000)
})
child.on('exit', () => {
exitedDuringStartup = true
if (this.child === child) this.child = null
})
child.on('error', (error) => {
exitedDuringStartup = true
startupDiagnostic += `\nspawn error: ${error.message}`
if (this.child === child) this.child = null
})
/* Host 退出就结束等待,不必耗满 healthz 超时。 */
let reachable = false
const deadline = Date.now() + START_TIMEOUT_MS
while (Date.now() < deadline) {
if (await this.ping()) {
reachable = true
break
}
if (exitedDuringStartup) break
await new Promise((resolve) => setTimeout(resolve, 300))
}
if (reachable) {
this.lifecycle = 'online'
this.portFallbackFrom = port === DEFAULT_PORT ? null : DEFAULT_PORT
this.attachChildLifecycleHandlers(child, startupDiagnostic)
if (this.portFallbackFrom !== null) {
appLogger.write({
level: 'warn',
scope: 'mac-wechat-runtime',
message: 'host_port_fallback',
details: { preferredPort: DEFAULT_PORT, activePort: port }
})
}
await this.refreshBinding().catch(() => undefined)
if (
!this.lastBinding ||
!this.manifest ||
!bindingMatchesRuntimeManifest(this.lastBinding, this.manifest)
) {
this.lifecycle = 'crashed_unbound'
this.lastError = '运行中的 host 与 runtime manifest 不一致'
return this.getSnapshot()
}
return this.getSnapshot()
}
const portConflict = isPortConflictDiagnostic(startupDiagnostic)
failures.push({
port,
detail: exitedDuringStartup
? formatMacWechatHostStartupFailure(child.exitCode, startupDiagnostic)
: '发送运行时未在超时内响应 /healthz',
portConflict
})
appLogger.write({
level: 'warn',
scope: 'mac-wechat-runtime',
message: 'host_port_attempt_failed',
details: { port, portConflict }
})
/* 其他启动失败换端口也不会好,直接停。 */
if (!portConflict) break
if (child.exitCode === null && child.signalCode === null) {
try {
child.kill('SIGKILL')
} catch {
/* 进程可能已在状态检查后退出。 */
}
}
}
this.lifecycle = 'crashed_unbound'
this.lastError = await this.formatPortRotationFailure(failures)
return this.getSnapshot()
}
/* Always retry the preferred port first so it is reused once available. */
private candidatePorts(): number[] {
const ports = [DEFAULT_PORT, this.activePort]
for (let offset = 1; offset <= PORT_FALLBACK_SPAN; offset++) ports.push(DEFAULT_PORT + offset)
return ports.filter(
(port, index) =>
Number.isSafeInteger(port) && port > 0 && port < 65_536 && ports.indexOf(port) === index
)
}
/* Reuse an existing Host on any supported port before spawning another one. */
private async adoptRunningHost(): Promise<boolean> {
for (const port of this.candidatePorts()) {
const previous = this.activePort
this.activePort = port
if (await this.ping()) {
this.portFallbackFrom = port === DEFAULT_PORT ? null : DEFAULT_PORT
return true
}
this.activePort = previous
}
return false
}
private attachChildLifecycleHandlers(child: ChildProcess, startupDiagnostic: string): void {
child.on('exit', (code) => {
const wasBound =
this.lastBinding?.bound === true ||
this.lastBinding?.sessionAttached === true ||
this.lastBinding?.bindingState === 'binding'
const orphanPid = this.lastBinding?.boundWechatPid || this.lastBinding?.wechatPid || 0
this.child = null
if (this.child === child) this.child = null
this.lastBinding = null
if (this.lifecycle === 'stopped') return // deliberate shutdown
@@ -446,47 +663,45 @@ class MacWechatRuntimeManager {
message: 'host_died_while_bound',
details: { code: code ?? null, orphanWechatPid: orphanPid }
})
} else {
this.lifecycle = 'crashed_unbound'
appLogger.write({
level: 'warn',
scope: 'mac-wechat-runtime',
message: 'host_died_while_unbound_auto_restart',
details: { code: code ?? null }
})
if (this.restartTimer) clearTimeout(this.restartTimer)
this.restartTimer = setTimeout(() => {
void this.ensureStarted()
}, CRASH_RESTART_DELAY_MS)
return
}
})
// Wait for /healthz
const deadline = Date.now() + START_TIMEOUT_MS
while (Date.now() < deadline) {
if (await this.ping()) {
this.lifecycle = 'online'
await this.refreshBinding().catch(() => undefined)
if (
!this.lastBinding ||
!this.manifest ||
!bindingMatchesRuntimeManifest(this.lastBinding, this.manifest)
) {
this.lifecycle = 'crashed_unbound'
this.lastError = '运行中的 host 与 runtime manifest 不一致'
return this.getSnapshot()
}
return this.getSnapshot()
}
if (this.child === null) break // died during startup
await new Promise((resolve) => setTimeout(resolve, 300))
}
if (this.lifecycle === 'starting') {
this.lifecycle = 'crashed_unbound'
this.lastError = 'host did not answer /healthz in time'
}
return this.getSnapshot()
this.lastError = formatMacWechatHostStartupFailure(code, startupDiagnostic)
appLogger.write({
level: 'warn',
scope: 'mac-wechat-runtime',
message: 'host_died_while_unbound_auto_restart',
details: { code: code ?? null }
})
if (this.restartTimer) clearTimeout(this.restartTimer)
this.restartTimer = setTimeout(() => {
void this.ensureStarted()
}, CRASH_RESTART_DELAY_MS)
})
child.on('error', (error) => {
if (this.lifecycle === 'stopped') return
if (this.child === child) this.child = null
this.lifecycle = 'crashed_unbound'
this.lastError = '无法启动发送 Host:' + error.message
appLogger.write({
level: 'error',
scope: 'mac-wechat-runtime',
message: 'host_spawn_failed',
details: { detail: error.message }
})
})
}
private async formatPortRotationFailure(
failures: Array<{ port: number; detail: string; portConflict: boolean }>
): Promise<string> {
const last = failures[failures.length - 1]
if (!last) return '发送运行时启动失败'
if (!failures.some((failure) => failure.portConflict)) return last.detail
const holder = await describePortHolder(last.port)
const holderText = holder ? `,占用者 ${holder}` : ''
if (failures.length === 1) return `${last.detail}${holderText}`
return `端口 ${failures.map((failure) => failure.port).join('、')} 均被占用${holderText}。请重启系统释放端口,或用 TM_WECHAT_HOST_PORT 指定其他端口。`
}
private request(
@@ -503,7 +718,7 @@ class MacWechatRuntimeManager {
const req = transport(
{
host: HOST,
port: PORT,
port: this.activePort,
path,
method,
timeout: timeoutMs,
@@ -614,6 +829,10 @@ class MacWechatRuntimeManager {
return this.lastBinding
}
async getSendMechanism(): Promise<string | undefined> {
return resolveMacWechatSendMechanism(await this.getBindingStatus(), this.manifest)
}
// GET reads the local snapshot; POST runs one real online check.
// Neither touches the WeChat binding.
@@ -723,7 +942,22 @@ class MacWechatRuntimeManager {
* capability mapping and the send path report the same facts without a
* circular import.
*/
async buildSenderStatus(): Promise<PersonalWechatSenderStatus> {
buildSenderStatus(): Promise<PersonalWechatSenderStatus> {
if (this.senderStatusInFlight) return this.senderStatusInFlight
const statusPromise = this.buildSenderStatusOnce()
this.senderStatusInFlight = statusPromise
void statusPromise.then(
() => {
if (this.senderStatusInFlight === statusPromise) this.senderStatusInFlight = null
},
() => {
if (this.senderStatusInFlight === statusPromise) this.senderStatusInFlight = null
}
)
return statusPromise
}
private async buildSenderStatusOnce(): Promise<PersonalWechatSenderStatus> {
if (isMacNativeRuntimeUnavailable()) {
const message = '当前环境不包含微信发送能力'
return {
@@ -732,7 +966,7 @@ class MacWechatRuntimeManager {
arch: process.arch,
sipDisabled: true,
wechatRunning: false,
endpoint: `http://${HOST}:${PORT}`,
endpoint: `http://${HOST}:${this.activePort}`,
endpointReady: false,
runtimeReady: false,
attachReady: false,
@@ -769,7 +1003,7 @@ class MacWechatRuntimeManager {
try {
const runtimeDir = this.resolveRuntimeDir()
if (!runtimeDir) throw new Error('runtime missing')
this.manifest = readMacWechatRuntimeManifest(runtimeDir)
this.manifest = this.manifestCache.read(runtimeDir)
} catch (error) {
const detail = error instanceof Error ? error.message : String(error)
appLogger.write({
@@ -787,7 +1021,7 @@ class MacWechatRuntimeManager {
arch: process.arch,
sipDisabled: true,
wechatRunning: false,
endpoint: `http://${HOST}:${PORT}`,
endpoint: `http://${HOST}:${this.activePort}`,
endpointReady: false,
runtimeReady: false,
attachReady: false,
+43 -3
View File
@@ -137,14 +137,39 @@ export function extractMentionTargets(source: string | undefined): string[] {
if (!match) return []
const inner = match[1].trim()
const unwrapped = inner.replace(/^<!\[CDATA\[/, '').replace(/\]\]>$/, '').trim()
return unwrapped ? [unwrapped] : []
if (!unwrapped) return []
return unwrapped
.split(',')
.map((item) => item.trim())
.filter(Boolean)
}
/** 把 WCDB 的 `source` 列(zstd 压缩的 Buffer)还原成 XML 文本。 */
/** 把 WCDB 的 `source` 列(明文 XML 字符串或 zstd 压缩的 Buffer)还原成 XML 文本。 */
export function decodeSourcePayload(value: unknown): string | undefined {
if (typeof value === 'string') {
const trimmed = value.trim()
if (!trimmed) return undefined
if (
trimmed.length >= 8 &&
trimmed.length % 2 === 0 &&
/^28b52ffd[0-9a-f]+$/i.test(trimmed)
) {
try {
return Buffer.from(zstdDecompress(Buffer.from(trimmed, 'hex'))).toString('utf8')
} catch {
return undefined
}
}
return trimmed
}
let buffer: Buffer | null = null
if (Buffer.isBuffer(value)) {
buffer = value
} else if (value instanceof Uint8Array) {
buffer = Buffer.from(value)
} else if (Array.isArray(value)) {
buffer = Buffer.from(value)
} else {
const candidate = value as { type?: string; data?: unknown } | null
if (candidate?.type === 'Buffer' && Array.isArray(candidate.data)) {
@@ -193,6 +218,7 @@ export class MessageListenerService {
private readonly pendingSessions = new Set<string>()
private coalesceTimer: ReturnType<typeof setTimeout> | null = null
private readbackInFlight = false
private pendingReadback = false
private disposed = false
private readonly coalesceMs: number
@@ -282,8 +308,13 @@ export class MessageListenerService {
* - **legacy(protocol v1,旧 runtime)**:只能退回「最近活跃会话」`getSessions()[0]`。
*/
private async readback(): Promise<void> {
if (this.disposed || this.readbackInFlight) return
if (this.disposed) return
if (this.readbackInFlight) {
this.pendingReadback = true
return
}
this.readbackInFlight = true
this.pendingReadback = false
const startedAt = Date.now()
const preciseSessions = Array.from(this.pendingSessions)
@@ -321,6 +352,15 @@ export class MessageListenerService {
)
} finally {
this.readbackInFlight = false
if (!this.disposed && (this.pendingReadback || this.pendingSessions.size > 0)) {
this.pendingReadback = false
if (!this.coalesceTimer) {
this.coalesceTimer = setTimeout(() => {
this.coalesceTimer = null
void this.readback()
}, this.coalesceMs)
}
}
}
}
@@ -37,7 +37,9 @@ export class PersonalWechatCapabilityService {
const capabilities = {
text: Boolean(senderStatus.canSendText),
image: Boolean(senderStatus.canSendImage),
voice: Boolean(senderStatus.canSendVoice)
voice: Boolean(senderStatus.canSendVoice),
video: Boolean(senderStatus.canSendVideo),
file: Boolean(senderStatus.canSendFile)
}
const status = this.mapState(senderStatus)
const ready = status === 'ready'
+553 -84
View File
@@ -11,7 +11,7 @@ import {
writeFileSync
} from 'fs'
import { homedir, tmpdir } from 'os'
import { delimiter, dirname, extname, join, sep } from 'path'
import { delimiter, dirname, extname, join, sep, basename } from 'path'
import { resolveBundledFfmpegPath } from '../ffmpeg-path'
import { promisify } from 'util'
import type {
@@ -23,7 +23,10 @@ import type {
import { loadSettings } from './settings-store'
import { SilkAudioDecoder, SilkAudioEncoder } from '../voice-pipeline/audio-decoder'
import { appLogger } from '../app-logger'
import { readLocalAccountIdentity } from './local-account-identity'
import {
accountDirectoryBelongsToIdentity,
readLocalAccountIdentity
} from './local-account-identity'
import { macWechatRuntimeManager } from './mac-wechat-runtime-manager'
const execFileAsync = promisify(execFile)
@@ -31,6 +34,9 @@ const WINDOWS_LOOPBACK_HOST = '127.0.0.1'
const REQUEST_TIMEOUT_MS = 20_000
const MAX_IMAGE_BYTES = 20 * 1024 * 1024
const MAX_VOICE_BYTES = 20 * 1024 * 1024
/** 视频与扩展发送通道的上限保持一致。 */
const MAX_VIDEO_BYTES = 100 * 1024 * 1024
const MAX_FILE_BYTES = 100 * 1024 * 1024
// 语音编码由 native runtime 内的 SILK 实现完成,不再是外部编码器进程。
const VOICE_ENCODER_NAME = 'silk'
const VOICE_ENCODER_VERSION = 'tm-wechat-native'
@@ -69,11 +75,7 @@ export function buildPersonalWechatRuntimePath(): string {
return [dirname(bundledFfmpeg), existing].filter(Boolean).join(delimiter)
}
/**
* Build the environment used by TraceMemo's local voice encoding helpers.
* Keep this in one place so environment checks cannot accidentally inspect a
* different ffmpeg than the sender process.
*/
/** Build the environment used by TraceMemo's local voice encoding helpers.。 */
export function buildPersonalWechatRuntimeEnvironment(): NodeJS.ProcessEnv {
return {
...process.env,
@@ -212,13 +214,15 @@ async function prepareWindowsVoiceFile(filePath: string): Promise<{
)
const pcm = Buffer.isBuffer(result.stdout) ? result.stdout : Buffer.from(result.stdout || '')
if (!pcm.length) throw new Error('语音转换失败:没有得到 PCM 音频数据')
const pcmDurationMs = Math.round((pcm.length / 2 / 24_000) * 1000)
const encoded = await new SilkAudioEncoder().encode(pcm, 24_000)
if (!encoded.data.length) throw new Error('语音转换失败:没有得到 SILK 数据')
const durationMs = encoded.durationMs >= 1000 ? encoded.durationMs : pcmDurationMs
const convertedPath = join(tmpdir(), `tracememo-voice-${randomBytes(8).toString('hex')}.silk`)
writeFileSync(convertedPath, encoded.data)
return {
filePath: convertedPath,
...(encoded.durationMs > 0 ? { durationMs: encoded.durationMs } : {}),
...(durationMs > 0 ? { durationMs } : {}),
temporary: true
}
}
@@ -249,7 +253,11 @@ function windowsImageTempRoot(): string {
throw new Error('无法创建 Windows 图片临时目录')
}
export function prepareWindowsImageFile(filePath: string): {
/** hook 侧用 ANSI API 判文件存在,非 ASCII 路径一律判成不存在,先拷一份 ASCII 副本。 */
export function prepareWindowsMediaFile(
filePath: string,
options: { prefix: string; fallbackExtension: string }
): {
filePath: string
temporary: boolean
} {
@@ -257,12 +265,12 @@ export function prepareWindowsImageFile(filePath: string): {
if (isAsciiPath(normalized)) return { filePath: normalized, temporary: false }
const extension = extname(normalized).toLowerCase()
const safeExtension = /^\.[a-z0-9]{1,8}$/.test(extension) ? extension : '.png'
const safeExtension = /^\.[a-z0-9]{1,8}$/.test(extension) ? extension : options.fallbackExtension
const temporaryPath = join(
windowsImageTempRoot(),
`tm-img-${randomBytes(8).toString('hex')}${safeExtension}`
`${options.prefix}${randomBytes(8).toString('hex')}${safeExtension}`
)
if (!isAsciiPath(temporaryPath)) throw new Error('Windows 图片临时路径必须只包含 ASCII 字符')
if (!isAsciiPath(temporaryPath)) throw new Error('Windows 媒体临时路径必须只包含 ASCII 字符')
try {
copyFileSync(normalized, temporaryPath)
} catch (error) {
@@ -276,14 +284,68 @@ export function prepareWindowsImageFile(filePath: string): {
return { filePath: temporaryPath, temporary: true }
}
function prepareMacWechatImageFile(filePath: string): { filePath: string; md5: string } {
/* Stage the image in WeChat's temporary image directory using the
* filename/hash layout required by the macOS native send path:
* - stage inside the active account's ImageTemp tree selected by
* findWechatImagePath(), not an arbitrary readable sandbox directory;
* - append a per-send salt before calculating MD5, so the staged image and
* the MD5 passed to the CDN task describe the same unique byte stream. */
const temporaryRoot = findWechatImagePath()
export function prepareWindowsImageFile(filePath: string): {
filePath: string
temporary: boolean
} {
return prepareWindowsMediaFile(filePath, { prefix: 'tm-img-', fallbackExtension: '.png' })
}
/** Windows 文件名里不允许出现的字符(控制字符由后面的 ASCII 过滤统一剔除)。 */
const WINDOWS_INVALID_FILE_NAME_CHARS = /[<>:"/\\|?*]/g
/** 单段路径上限 255,给随机后缀与扩展名留出余量。 */
const WINDOWS_TEMP_FILE_STEM_LIMIT = 80
/** 发送组件只认路径 basename 当显示名,改名或非 ASCII 路径都要走副本。 */
export function prepareWindowsFileForSend(
filePath: string,
fileName?: string
): { filePath: string; temporary: boolean } {
const normalized = String(filePath || '').trim()
const sourceName = basename(normalized)
const requestedName = basename(String(fileName || '').trim() || sourceName)
if (isAsciiPath(normalized) && requestedName === sourceName) {
return { filePath: normalized, temporary: false }
}
const extension = extname(requestedName).toLowerCase()
const safeExtension = /^\.[a-z0-9]{1,12}$/.test(extension) ? extension : ''
const asciiStem = basename(requestedName, extname(requestedName))
.replace(WINDOWS_INVALID_FILE_NAME_CHARS, '_')
.replace(/[^\x20-\x7e]/g, '')
.replace(/^[.\s_]+|[.\s_]+$/g, '')
.slice(0, WINDOWS_TEMP_FILE_STEM_LIMIT)
const root = windowsImageTempRoot()
// 同名副本不覆盖:上一笔发送可能还在读文件。
let temporaryPath = join(root, `${asciiStem || 'tm-file'}${safeExtension}`)
if (!asciiStem || existsSync(temporaryPath)) {
temporaryPath = join(
root,
`${asciiStem || 'tm-file'}-${randomBytes(4).toString('hex')}${safeExtension}`
)
}
if (!isAsciiPath(temporaryPath)) throw new Error('Windows 文件临时路径必须只包含 ASCII 字符')
try {
copyFileSync(normalized, temporaryPath)
} catch (error) {
try {
unlinkSync(temporaryPath)
} catch {
// 半拷贝残留只做尽力清理。
}
throw error
}
return { filePath: temporaryPath, temporary: true }
}
function prepareMacWechatImageFile(
filePath: string,
senderWxid: string,
wechatFilesRoot = WECHAT_FILES_ROOT
): { filePath: string; md5: string } {
/** Stage the image in WeChat's temporary image directory using the。 */
const temporaryRoot = findWechatImagePath(wechatFilesRoot, new Date(), senderWxid)
if (!temporaryRoot) throw new Error('无法定位当前微信账号的图片临时目录')
mkdirSync(temporaryRoot, { recursive: true })
const extension = extname(filePath).toLowerCase()
@@ -305,16 +367,158 @@ function prepareMacWechatImageFile(filePath: string): { filePath: string; md5: s
}
}
function stageMacWechatImageForMessageSourceSend(
filePath: string,
senderWxid: string,
wechatFilesRoot = WECHAT_FILES_ROOT
): string {
const temporaryRoot = findWechatImagePath(wechatFilesRoot, new Date(), senderWxid)
if (!temporaryRoot) throw new Error('无法定位当前微信账号的图片临时目录')
mkdirSync(temporaryRoot, { recursive: true })
const extension = extname(filePath).toLowerCase()
const safeExtension = /^\.[a-z0-9]{1,8}$/.test(extension) ? extension : '.png'
const stagedPath = join(
temporaryRoot,
`tm-${randomBytes(8).toString('hex')}-${Math.floor(Date.now() / 1000)}${safeExtension}`
)
copyFileSync(filePath, stagedPath)
return stagedPath
}
const MAC_VIDEO_STAGE_PREFIX = 'tm-video-'
const MAC_VIDEO_STAGE_RETENTION_MS = 10 * 60 * 1000
/** macOS WeChat 运行在 App Sandbox 容器中,注入在微信进程内的 `libtmwechat.dylib`。 */
export function stageMacWechatVideoForSend(
filePath: string,
wechatFilesRoot = WECHAT_FILES_ROOT
): { stagedPath: string; cleanup: () => void } {
const normalized = String(filePath || '').trim()
const containerDataRoot = dirname(dirname(wechatFilesRoot))
if (
containerDataRoot.includes('com.tencent.xinWeChat') &&
normalized.startsWith(`${containerDataRoot}${sep}`)
) {
return { stagedPath: normalized, cleanup: () => {} }
}
const documentsDir = dirname(wechatFilesRoot)
const stageDir = existsSync(documentsDir) ? documentsDir : wechatFilesRoot
mkdirSync(stageDir, { recursive: true })
// 顺手清理超过 10 分钟的历史暂存视频,防止异常退出残留。
const now = Date.now()
try {
for (const entry of readdirSync(stageDir)) {
if (!entry.startsWith(MAC_VIDEO_STAGE_PREFIX)) continue
const candidate = join(stageDir, entry)
try {
if (now - statSync(candidate).mtimeMs > MAC_VIDEO_STAGE_RETENTION_MS) {
unlinkSync(candidate)
}
} catch {
// Best-effort stale file cleanup.
}
}
} catch {
// Ignore directory listing errors.
}
const extension = extname(normalized).toLowerCase()
const safeExtension = /^\.[a-z0-9]{1,8}$/.test(extension) ? extension : '.mp4'
const stagedPath = join(
stageDir,
`${MAC_VIDEO_STAGE_PREFIX}${randomBytes(6).toString('hex')}-${now}${safeExtension}`
)
copyFileSync(normalized, stagedPath)
return {
stagedPath,
cleanup: () => {
const timer = setTimeout(() => {
try {
unlinkSync(stagedPath)
} catch {
// Best-effort delayed cleanup after WeChat finishes asynchronous video upload.
}
}, 120_000)
timer.unref?.()
}
}
}
const MAC_FILE_STAGE_PREFIX = 'tm-file-'
const MAC_FILE_STAGE_RETENTION_MS = 10 * 60 * 1000
export function stageMacWechatFileForSend(
filePath: string,
wechatFilesRoot = WECHAT_FILES_ROOT
): { stagedPath: string; cleanup: () => void } {
const normalized = String(filePath || '').trim()
const containerDataRoot = dirname(dirname(wechatFilesRoot))
if (
containerDataRoot.includes('com.tencent.xinWeChat') &&
normalized.startsWith(`${containerDataRoot}${sep}`)
) {
return { stagedPath: normalized, cleanup: () => {} }
}
const documentsDir = dirname(wechatFilesRoot)
const stageDir = existsSync(documentsDir) ? documentsDir : wechatFilesRoot
mkdirSync(stageDir, { recursive: true })
const now = Date.now()
try {
for (const entry of readdirSync(stageDir)) {
if (!entry.startsWith(MAC_FILE_STAGE_PREFIX)) continue
const candidate = join(stageDir, entry)
try {
if (now - statSync(candidate).mtimeMs > MAC_FILE_STAGE_RETENTION_MS) {
unlinkSync(candidate)
}
} catch {
// Best-effort stale file cleanup.
}
}
} catch {
// Ignore directory listing errors.
}
const extension = extname(normalized).toLowerCase()
const safeExtension = /^\.[a-z0-9]{1,12}$/.test(extension) ? extension : '.bin'
const stagedPath = join(
stageDir,
`${MAC_FILE_STAGE_PREFIX}${randomBytes(6).toString('hex')}-${now}${safeExtension}`
)
copyFileSync(normalized, stagedPath)
return {
stagedPath,
cleanup: () => {
const timer = setTimeout(() => {
try {
unlinkSync(stagedPath)
} catch {
// Best-effort delayed cleanup after WeChat finishes asynchronous upload.
}
}, 300_000)
timer.unref?.()
}
}
}
/** Locate the current account's temporary image directory consumed by the image send path. */
export function findWechatImagePath(
root = WECHAT_FILES_ROOT,
now = new Date()
now = new Date(),
senderWxid?: string
): string | undefined {
try {
const month = `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}`
const candidates: Array<{ path: string; mtime: number }> = []
const fallbacks: Array<{ path: string; mtime: number }> = []
for (const account of readdirSync(root)) {
if (senderWxid && !accountDirectoryBelongsToIdentity(account, senderWxid)) continue
const tempRoot = join(root, account, 'temp')
if (!existsSync(tempRoot)) continue
fallbacks.push({
@@ -419,6 +623,19 @@ export function buildWindowsWechatRequest(
body: { toWxid: target, type: 'image', msg: String(request.filePath || '').trim() }
}
}
if (request.type === 'video') {
return {
endpoint: '/SendMsg',
body: { toWxid: target, type: 'video', msg: String(request.filePath || '').trim() }
}
}
if (request.type === 'file') {
return {
endpoint: '/SendMsg',
body: { toWxid: target, type: 'file', msg: String(request.filePath || '').trim() }
}
}
const fromId = String(request.fromId || '').trim()
const filePath = String(options.filePath || request.filePath || '').trim()
@@ -456,6 +673,8 @@ function windowsStatusBase(host = windowsHookHost() || ''): PersonalWechatSender
canSendText: false,
canSendImage: false,
canSendVoice: false,
canSendVideo: false,
canSendFile: false,
message: '正在检查 Windows 微信消息接口'
}
}
@@ -469,14 +688,11 @@ function safeFileSize(target: string): number {
}
}
/**
* 发送链路诊断日志(排查「hook 报成功、群里却没有消息」时用)。
*
* 只有在设置里打开「调试模式」时才输出,所以正常使用不会刷屏。
*
* **隐私约束**:只允许输出类型、字节数、HTTP 状态码、hook 的 `ret` 这类结构性字段。
* 文件名、完整路径、wxid、群名、消息正文不进日志。
*/
function isDefinitiveImageSourcePreparationFailure(message: string): boolean {
return message.trim() === 'IMAGE_PREPARATION_FAILED:0'
}
/** 发送链路诊断日志(排查「hook 报成功、群里却没有消息」时用)。 */
function logSendDiagnostic(
stage: string,
detail: Record<string, string | number | boolean | null>
@@ -489,18 +705,30 @@ function logSendDiagnostic(
console.log(`[SendDiag] ${stage} ${JSON.stringify(detail)}`)
}
/**
* 发送完成后**保留**图片临时文件的时长(毫秒)。默认 `0` = 立刻删除(现行行为)。
*
* 为什么留这个开关:`finally` 里的删除发生在 **hook 返回之后**,这隐含假设
* 「hook 返回时发送已经完成」。如果 hook 其实是「先回 200、后台再读文件」,
* 文件就可能在它读到之前已经被删掉 —— 现象正好是「hook 报成功、微信里没有消息」。
*
* 置为非 0 时可分辨两类失败:保留期间图片到了 ⇒ 删除时机问题(修法与 hook 约定文件生命周期);
* 仍然没到 ⇒ 与文件生命周期无关。
*/
/** 能力轮询会反复打这些端点,成功时不计入发送诊断,否则日志被探测刷满。 */
const WINDOWS_PROBE_ENDPOINTS = new Set(['/getLoginInfo'])
/** 发送完成后**保留**图片临时文件的时长(毫秒)。默认 `0` = 立刻删除(现行行为)。 */
const WINDOWS_TEMP_IMAGE_GRACE_MS = 0
/** 视频上传在 send_message 返回后才开始,删早了接收端只能拿到空文件。 */
const WINDOWS_TEMP_VIDEO_GRACE_MS = 10 * 60 * 1000
/** 文件副本保留窗口:`/SendMsg` 返回时微信还在读,删早了接收端拿到空文件。 */
const WINDOWS_TEMP_FILE_GRACE_MS = 10 * 60 * 1000
// unref: 不让清理定时器拖住进程退出
function scheduleTempFileCleanup(target: string, delayMs: number): void {
const timer = setTimeout(() => {
try {
unlinkSync(target)
} catch {
// best effort
}
}, delayMs)
timer.unref?.()
}
async function requestWindowsHook(
endpoint: string,
body: Record<string, unknown>,
@@ -515,12 +743,15 @@ async function requestWindowsHook(
headers: { 'Content-Type': 'application/json' }
}
if (method !== 'GET') init.body = JSON.stringify(body)
logSendDiagnostic('hook-request', {
endpoint,
method,
// 只报 payload 里有没有内容,不报内容本身。
hasPayload: method !== 'GET' ? init.body !== undefined : false
})
const isProbe = WINDOWS_PROBE_ENDPOINTS.has(endpoint)
if (!isProbe) {
logSendDiagnostic('hook-request', {
endpoint,
method,
// 只报 payload 里有没有内容,不报内容本身。
hasPayload: method !== 'GET' ? init.body !== undefined : false
})
}
const response = await requestWithTimeout(`http://${host}${endpoint}`, init, timeoutMs)
const responseText = await response.text()
if (!response.ok) {
@@ -535,18 +766,22 @@ async function requestWindowsHook(
throw new WindowsHookHttpError(response.status, responseText)
}
const parsed = parseWindowsHookResponse(responseText, method === 'POST')
logSendDiagnostic('hook-response', {
endpoint,
httpStatus: response.status,
ok: true,
ret: typeof parsed.ret === 'number' ? parsed.ret : null,
retMessageLength: String(parsed.retmsg ?? parsed.msg ?? '').length,
elapsedMs: Date.now() - startedAt
})
if (!isProbe) {
logSendDiagnostic('hook-response', {
endpoint,
httpStatus: response.status,
ok: true,
ret: typeof parsed.ret === 'number' ? parsed.ret : null,
retMessageLength: String(parsed.retmsg ?? parsed.msg ?? '').length,
elapsedMs: Date.now() - startedAt
})
}
return parsed
}
export class PersonalWechatSendService {
constructor(private readonly wechatFilesRoot = WECHAT_FILES_ROOT) {}
async getStatus(): Promise<PersonalWechatSenderStatus> {
// macOS 发送能力完全由 native runtime(tm-wechat-host)提供,
// 这里保持同源,避免出现第二套状态判断。
@@ -579,6 +814,8 @@ export class PersonalWechatSendService {
if (request.type === 'text') return this.sendMacText(request)
if (request.type === 'image') return this.sendMacImage(request)
if (request.type === 'voice') return this.sendMacVoice(request)
if (request.type === 'video') return this.sendMacVideo(request)
if (request.type === 'file') return this.sendMacFile(request)
}
return {
success: false,
@@ -635,6 +872,8 @@ export class PersonalWechatSendService {
canSendText: true,
canSendImage: true,
canSendVoice: true,
canSendVideo: true,
canSendFile: true,
message: 'Windows 微信发送能力已连接,可以发送消息'
}
} catch (error) {
@@ -647,10 +886,7 @@ export class PersonalWechatSendService {
}
}
/*
* macOS native runtime 的文字发送:HTTP POST /sendText 到 tm-wechat-host。
* 绑定状态由 host 侧保证;未绑定/未就绪时返回与旧契约一致的结果结构。
*/
/** macOS native runtime 的文字发送:HTTP POST /sendText 到 tm-wechat-host。 */
private async sendMacText(
request: Extract<PersonalWechatSendRequest, { type: 'text' }>
): Promise<PersonalWechatSendResult> {
@@ -663,6 +899,32 @@ export class PersonalWechatSendService {
error: initialStatus.message || '微信发送能力未就绪'
}
}
const sendMechanism = await macWechatRuntimeManager.getSendMechanism()
if (request.at && sendMechanism !== 'tm-message-source-send') {
return {
success: false,
status: initialStatus,
error: '当前微信发送组件不支持原生群聊 @,请升级微信与发送组件'
}
}
if (sendMechanism === 'tm-message-source-send') {
const result = await this.postMacHost(
'/sendMsg',
{
type: 'text',
to: request.to,
text: request.text,
is_group: Boolean(request.isGroup),
...(request.at ? { at: request.at } : {})
},
50_000
)
const status = await macWechatRuntimeManager.buildSenderStatus()
if (!result?.ok) {
return { success: false, status, error: result?.message || '文字发送失败' }
}
return { success: true, status }
}
const payload = JSON.stringify({
to: request.to,
@@ -693,14 +955,9 @@ export class PersonalWechatSendService {
return { success: true, status: resultStatus }
}
/*
* Resolve the bound account's own wxid from the local WeChat data root.
* The media proto embeds the sender, and the mac runtime does not learn it
* from inbound traffic, so it is read from
* the on-disk account identity instead.
*/
/** Resolve the bound account's own wxid from the local WeChat data root.。 */
private async resolveMacSenderWxid(): Promise<string> {
const identity = readLocalAccountIdentity(WECHAT_FILES_ROOT)
const identity = readLocalAccountIdentity(this.wechatFilesRoot)
return identity?.wxid ?? ''
}
@@ -716,11 +973,118 @@ export class PersonalWechatSendService {
signal: AbortSignal.timeout(timeoutMs)
}).catch(() => null)
if (response === null || !response.ok) return null
return (await response.json().catch(() => null)) as {
code: number
ok: boolean
message: string
} | null
const payload = (await response.json().catch(() => null)) as Record<string, unknown> | null
if (!payload) return null
/** 不同 Host 路由的响应形状不一致:`/sendText` 等返回 `{ok}`。 */
const explicitFailure = payload.ok === false || payload.status === false
const ok =
!explicitFailure &&
(payload.ok === true || payload.status === true || payload.ret === 0 || payload.code === 0)
return {
code: Number(payload.code ?? payload.ret ?? (ok ? 0 : 1)),
ok,
message: String(payload.message ?? payload.msg ?? '')
}
}
/** macOS 视频发送:`POST /SendMsg`,body 为 `{toWxid, type:'video', msg:<绝对路径>}`。 */
private async sendMacVideo(
request: Extract<PersonalWechatSendRequest, { type: 'video' }>
): Promise<PersonalWechatSendResult> {
await macWechatRuntimeManager.ensureStarted()
const status = await macWechatRuntimeManager.buildSenderStatus()
if (!status.canSendVideo) {
return {
success: false,
status,
error: status.message || '当前微信发送组件不支持视频,请升级后重试'
}
}
const filePath = String(request.filePath || '').trim()
if (!filePath || !existsSync(filePath)) {
return { success: false, status, error: '请选择有效的视频文件' }
}
const size = statSync(filePath).size
if (size <= 0 || size > MAX_VIDEO_BYTES) {
return { success: false, status, error: '视频必须小于 100 MB' }
}
let staged: { stagedPath: string; cleanup: () => void } | null = null
try {
staged = stageMacWechatVideoForSend(filePath, this.wechatFilesRoot)
} catch (error) {
const latest = await macWechatRuntimeManager.buildSenderStatus()
return {
success: false,
status: latest,
error: error instanceof Error ? error.message : '无法将视频暂存到微信沙盒目录'
}
}
try {
const result = await this.postMacHost(
'/SendMsg',
{ toWxid: request.to, type: 'video', msg: staged.stagedPath },
180_000
)
const latest = await macWechatRuntimeManager.buildSenderStatus()
if (!result?.ok) {
return { success: false, status: latest, error: result?.message || '视频发送失败' }
}
return { success: true, status: latest }
} finally {
staged.cleanup()
}
}
private async sendMacFile(
request: Extract<PersonalWechatSendRequest, { type: 'file' }>
): Promise<PersonalWechatSendResult> {
await macWechatRuntimeManager.ensureStarted()
const status = await macWechatRuntimeManager.buildSenderStatus()
if (!status.canSendFile) {
return {
success: false,
status,
error: status.message || '当前微信发送组件不支持文件,请升级后重试'
}
}
const filePath = String(request.filePath || '').trim()
if (!filePath || !existsSync(filePath)) {
return { success: false, status, error: '请选择有效的文件' }
}
const size = statSync(filePath).size
if (size <= 0 || size > MAX_FILE_BYTES) {
return { success: false, status, error: '文件必须小于 100 MB' }
}
const fileName = String(request.fileName || '').trim() || basename(filePath)
let staged: { stagedPath: string; cleanup: () => void } | null = null
try {
staged = stageMacWechatFileForSend(filePath, this.wechatFilesRoot)
} catch (error) {
const latest = await macWechatRuntimeManager.buildSenderStatus()
return {
success: false,
status: latest,
error: error instanceof Error ? error.message : '无法将文件暂存到微信沙盒目录'
}
}
try {
const result = await this.postMacHost(
'/sendMsg',
{ to: request.to, type: 'file', path: staged.stagedPath, name: fileName },
180_000
)
const latest = await macWechatRuntimeManager.buildSenderStatus()
if (!result?.ok) {
return { success: false, status: latest, error: result?.message || '文件发送失败' }
}
return { success: true, status: latest }
} finally {
staged.cleanup()
}
}
private async sendMacImage(
@@ -737,13 +1101,42 @@ export class PersonalWechatSendService {
}
const filePath = String(request.filePath || '').trim()
if (!filePath || !existsSync(filePath)) return fail('请选择有效的图片文件')
const sendMechanism = await macWechatRuntimeManager.getSendMechanism()
const sender = await this.resolveMacSenderWxid()
if (!sender) return fail('无法识别当前微信账号 wxid')
if (sendMechanism === 'tm-message-source-send') {
let stagedPath = ''
let sourceError = ''
try {
stagedPath = stageMacWechatImageForMessageSourceSend(filePath, sender, this.wechatFilesRoot)
const sent = await this.postMacHost(
'/sendMsg',
{ type: 'image', to: request.to, path: stagedPath },
55_000
)
const status = await macWechatRuntimeManager.buildSenderStatus()
if (!sent?.ok) {
sourceError = sent?.message || '图片发送失败'
} else {
return { success: true, status }
}
} catch (error) {
sourceError = error instanceof Error ? error.message : String(error)
} finally {
if (stagedPath) {
try {
unlinkSync(stagedPath)
} catch {
// Best-effort cleanup after WeChat has consumed the staged image.
}
}
}
if (!isDefinitiveImageSourcePreparationFailure(sourceError)) return fail(sourceError)
}
let uploadPath = ''
try {
const prepared = prepareMacWechatImageFile(filePath)
const prepared = prepareMacWechatImageFile(filePath, sender, this.wechatFilesRoot)
uploadPath = prepared.filePath
const upload = await this.postMacHost(
'/uploadImage',
@@ -791,12 +1184,14 @@ export class PersonalWechatSendService {
}
const filePath = String(request.filePath || '').trim()
if (!filePath || !existsSync(filePath)) return fail('请选择有效的语音文件')
const sendMechanism = await macWechatRuntimeManager.getSendMechanism()
let sender = ''
if (sendMechanism !== 'tm-message-source-send') {
sender = await this.resolveMacSenderWxid()
if (!sender) return fail('无法识别当前微信账号 wxid')
}
const sender = await this.resolveMacSenderWxid()
if (!sender) return fail('无法识别当前微信账号 wxid')
/* Reuse the Windows SILK preparation: it already normalizes any input to
* SILK and reports the duration. */
/** Reuse the Windows SILK preparation: it already normalizes any input to。 */
let temporaryVoicePath: string | undefined
try {
const prepared = await prepareWindowsVoiceFile(filePath)
@@ -816,6 +1211,25 @@ export class PersonalWechatSendService {
normalized_input_bytes: silkData.length,
silk_duration_ms: durationMs
})
if (sendMechanism === 'tm-message-source-send') {
if (durationMs < 1000) return fail('原生语音发送要求时长至少 1 秒', 'duration')
const sent = await this.postMacHost(
'/sendMsg',
{
type: 'voice',
to: request.to,
voice_hex: silkData.toString('hex'),
duration_ms: durationMs
},
55_000
)
if (!sent?.ok) {
return fail(sent?.message || '语音发送失败', 'send')
}
const status = await macWechatRuntimeManager.buildSenderStatus()
logVoiceAttempt(requestId, 'completed', { send_result: '0' })
return { success: true, status }
}
const upload = await this.postMacHost(
'/uploadVoice',
@@ -867,21 +1281,33 @@ export class PersonalWechatSendService {
request = { ...request, to, text }
} else {
const filePath = String(request.filePath || '').trim()
const label =
request.type === 'voice'
? '语音'
: request.type === 'video'
? '视频'
: request.type === 'file'
? '文件'
: '图片'
const limit =
request.type === 'voice'
? MAX_VOICE_BYTES
: request.type === 'video'
? MAX_VIDEO_BYTES
: request.type === 'file'
? MAX_FILE_BYTES
: MAX_IMAGE_BYTES
if (!filePath || !existsSync(filePath)) {
const status = await this.getWindowsStatus()
return {
success: false,
status,
error: `请选择有效的${request.type === 'voice' ? '语音' : '图片'}文件`
}
return { success: false, status, error: `请选择有效的${label}文件` }
}
const size = statSync(filePath).size
if (size <= 0 || size > (request.type === 'voice' ? MAX_VOICE_BYTES : MAX_IMAGE_BYTES)) {
if (size <= 0 || size > limit) {
const status = await this.getWindowsStatus()
return {
success: false,
status,
error: `${request.type === 'voice' ? '语音' : '图片'}必须小于 20 MB`
error: `${label}必须小于 ${Math.round(limit / (1024 * 1024))} MB`
}
}
request = { ...request, to, filePath }
@@ -891,7 +1317,9 @@ export class PersonalWechatSendService {
if (!status.canSend) return { success: false, status, error: status.error || status.message }
let temporaryImagePath: string | undefined
let temporaryVideoPath: string | undefined
let temporaryVoicePath: string | undefined
let temporaryFilePath: string | undefined
try {
if (request.type === 'text') {
const windowsRequest = buildWindowsWechatRequest(request)
@@ -912,6 +1340,36 @@ export class PersonalWechatSendService {
filePath: preparedImage.filePath
})
await requestWindowsHook(windowsRequest.endpoint, windowsRequest.body, 60_000)
} else if (request.type === 'video') {
const preparedVideo = prepareWindowsMediaFile(request.filePath, {
prefix: 'tm-video-',
fallbackExtension: '.mp4'
})
temporaryVideoPath = preparedVideo.temporary ? preparedVideo.filePath : undefined
logSendDiagnostic('video-prepared', {
sourceBytes: safeFileSize(request.filePath),
usedTempCopy: preparedVideo.temporary,
copiedBytes: safeFileSize(preparedVideo.filePath)
})
const windowsRequest = buildWindowsWechatRequest({
...request,
filePath: preparedVideo.filePath
})
await requestWindowsHook(windowsRequest.endpoint, windowsRequest.body, 180_000)
} else if (request.type === 'file') {
const preparedFile = prepareWindowsFileForSend(request.filePath, request.fileName)
temporaryFilePath = preparedFile.temporary ? preparedFile.filePath : undefined
logSendDiagnostic('file-prepared', {
sourceBytes: safeFileSize(request.filePath),
usedTempCopy: preparedFile.temporary,
copiedBytes: safeFileSize(preparedFile.filePath)
})
const windowsRequest = buildWindowsWechatRequest({
...request,
filePath: preparedFile.filePath
})
// 文件构造 appmsg 后还要走 CDN 上传,超时阈值按视频档给。
await requestWindowsHook(windowsRequest.endpoint, windowsRequest.body, 180_000)
} else if (request.type === 'voice') {
const fromId = String(request.fromId || '').trim()
if (!fromId) throw new Error('无法识别当前微信账号 wxid,无法发送语音')
@@ -937,7 +1395,12 @@ export class PersonalWechatSendService {
}
return { success: true, status: await this.getWindowsStatus() }
} catch (error) {
const message = error instanceof Error ? error.message : String(error)
const raw = error instanceof Error ? error.message : String(error)
// 老版发送组件不认 type=file,只会回校验错误 → 换成可操作的文案。
const message =
request.type === 'file' && /type must be/i.test(raw)
? '当前微信发送组件不支持文件发送,请升级发送组件后重试'
: raw
return {
success: false,
status: { ...(await this.getWindowsStatus()), state: 'error', error: message },
@@ -963,6 +1426,12 @@ export class PersonalWechatSendService {
}
}
}
if (temporaryVideoPath) {
scheduleTempFileCleanup(temporaryVideoPath, WINDOWS_TEMP_VIDEO_GRACE_MS)
}
if (temporaryFilePath) {
scheduleTempFileCleanup(temporaryFilePath, WINDOWS_TEMP_FILE_GRACE_MS)
}
if (temporaryVoicePath) {
try {
unlinkSync(temporaryVoicePath)
@@ -22,6 +22,20 @@ const FISH_AUDIO_PUBLIC_ASSET_URL = 'https://public-platform.r2.fish.audio/'
const DEFAULT_PAGE_SIZE = 24
const MAX_PAGE_SIZE = 100
const GENERATED_AUDIO_MAX_AGE_MS = 24 * 60 * 60 * 1000
const VOICE_META_CACHE_TTL_MS = 10 * 60 * 1000
const voiceMetaCache = new Map<string, { voice: TextToSpeechVoice; cachedAt: number }>()
function cacheVoiceMeta(voice: TextToSpeechVoice): void {
if (!voice?.id) return
voiceMetaCache.set(voice.id, { voice, cachedAt: Date.now() })
}
function getCachedVoiceMeta(id: string): TextToSpeechVoice | null {
const entry = voiceMetaCache.get(id)
if (!entry) return null
if (Date.now() - entry.cachedAt > VOICE_META_CACHE_TTL_MS) return null
return entry.voice
}
interface FishAudioModelEntity {
_id: string
@@ -128,6 +142,7 @@ export class TextToSpeechSettingsService {
let items = payload.items
.filter((model) => model.type === 'tts' && model.state === 'trained')
.map(toVoice)
for (const item of items) cacheVoiceMeta(item)
const selectedVoiceId = normalizeSelectedVoiceId(loadSettings().ttsSelectedVoiceId)
if (
@@ -138,7 +153,10 @@ export class TextToSpeechSettingsService {
) {
if (!items.some((item) => item.id === selectedVoiceId)) {
const selected = await this.getVoice(selectedVoiceId, resolved.key)
if (selected) items = [selected, ...items]
if (selected) {
cacheVoiceMeta(selected)
items = [selected, ...items]
}
}
}
@@ -229,6 +247,37 @@ export class TextToSpeechSettingsService {
}
}
async getVoiceStatus(): Promise<{
configured: boolean
model: TextToSpeechModel
selectedVoiceId: string
selectedVoice: TextToSpeechVoice | null
}> {
const resolved = this.resolveKey()
const settings = loadSettings()
const selectedVoiceId = normalizeSelectedVoiceId(settings.ttsSelectedVoiceId)
const model = normalizeModel(settings.ttsModel)
const configured = Boolean(resolved.key && selectedVoiceId)
if (!selectedVoiceId) {
return { configured: false, model, selectedVoiceId: '', selectedVoice: null }
}
const cached = getCachedVoiceMeta(selectedVoiceId)
if (cached) {
return { configured, model, selectedVoiceId, selectedVoice: cached }
}
if (!resolved.key) {
return { configured: false, model, selectedVoiceId, selectedVoice: null }
}
const fetched = await this.getVoice(selectedVoiceId, resolved.key)
if (fetched) cacheVoiceMeta(fetched)
return {
configured,
model,
selectedVoiceId,
selectedVoice: fetched
}
}
private resolveKey(): {
success: boolean
key?: string
@@ -299,7 +348,7 @@ function toVoice(model: FishAudioModelEntity): TextToSpeechVoice {
languages: Array.isArray(model.languages) ? model.languages : [],
source: 'fish-audio',
coverImage: resolvePublicAssetUrl(model.cover_image || model.author?.avatar),
previewUrl: sample?.audio || undefined,
previewUrl: resolvePublicAssetUrl(sample?.audio),
previewText: sample?.text || model.default_text || undefined,
authorName: model.author?.nickname || undefined,
taskCount: model.task_count,
+136 -11
View File
@@ -39,7 +39,15 @@ const AUTOMATION_PURPOSE_ALLOWLIST = new Set([
// purpose,各自有幂等位 —— 少这一条会被 evaluateWechatActionPolicy 拦下。
'automation_scheduled_report_postfix',
'manual_report_image',
'manual_report_postfix'
'manual_report_postfix',
/*
* 扩展来源的两个用途。
*
* 扩展不能自己决定 purpose:`ExtensionSendGateway` 与自动化 runner 分别填这两个值,
* 且 `evaluateWechatActionPolicy` 要求 `origin === 'extension'`,两边同时成立才放行。
*/
'extension_send',
'extension_action'
])
export interface ReportImageSequenceRequest {
@@ -137,6 +145,46 @@ export class WechatActionGateway {
return this.loadAuditState().records.map((record) => ({ ...record }))
}
/**
* 扩展来源的发送入口。
*
* 与 `execute()` 的区别只有一个:`origin` / `purpose` / `metadata.extensionId`
* 由这里按宿主规则填,扩展侧传不进来。其余检查(能力、审计、幂等、
* 自动化发送节流)与普通发送完全一致。
*/
async executeFromExtension(input: {
extensionId: string
purpose: 'extension_send' | 'extension_action'
recipient: WechatActionRequest['recipient']
content: WechatActionContent
idempotencyKey?: string
executionId?: string
}): Promise<WechatActionResult> {
const extensionId = String(input.extensionId || '').trim()
const startedAt = this.deps.now().toISOString()
if (!extensionId) {
return {
actionId: randomUUID(),
status: 'blocked',
decision: 'block',
errorCode: 'INVALID_REQUEST',
reason: '扩展发送缺少扩展标识',
startedAt,
finishedAt: startedAt
}
}
return this.execute({
...(input.idempotencyKey ? { idempotencyKey: String(input.idempotencyKey) } : {}),
...(input.executionId ? { executionId: String(input.executionId) } : {}),
origin: 'extension',
purpose: input.purpose,
triggerType: 'automation',
recipient: input.recipient,
content: input.content,
metadata: { extensionId }
})
}
async execute(request: WechatActionRequest): Promise<WechatActionResult> {
const normalized = normalizeActionRequest(request)
const idempotencyKey = normalized ? this.idempotencyKey(normalized) : undefined
@@ -256,9 +304,10 @@ export class WechatActionGateway {
const queued = this.automationSendTail.then(async () => {
const now = this.deps.now().getTime()
const remaining = this.lastAutomationSendStartedAt !== undefined
? Math.max(0, AUTOMATION_SEND_INTERVAL_MS - (now - this.lastAutomationSendStartedAt))
: 0
const remaining =
this.lastAutomationSendStartedAt !== undefined
? Math.max(0, AUTOMATION_SEND_INTERVAL_MS - (now - this.lastAutomationSendStartedAt))
: 0
if (remaining > 0) await this.deps.wait(remaining)
this.lastAutomationSendStartedAt = this.deps.now().getTime()
return this.deps.send(sendRequest)
@@ -393,14 +442,21 @@ export class WechatActionGateway {
!request.content ||
(request.content.type !== 'text' &&
request.content.type !== 'image' &&
request.content.type !== 'voice')
request.content.type !== 'video' &&
request.content.type !== 'voice' &&
request.content.type !== 'file')
) {
return
}
const state = this.loadAuditState()
const extensionId =
request.metadata && typeof request.metadata.extensionId === 'string'
? request.metadata.extensionId.trim().slice(0, 128)
: ''
const record: WechatActionAuditRecord = {
actionId: result.actionId,
...(idempotencyKey ? { idempotencyKey } : {}),
...(extensionId ? { extensionId } : {}),
origin: request.origin,
purpose: request.purpose,
triggerType: request.triggerType,
@@ -465,6 +521,18 @@ export function evaluateWechatActionPolicy(request: WechatActionRequest): Policy
reason: `自动化动作不允许执行 purpose=${request.purpose}`
}
}
/*
* 扩展用途必须来自扩展来源。少了这一条,任何能构造 `WechatActionRequest` 的
* 内部调用都可以用 `extension_send` 绕过自动化用途白名单。
*/
if (String(request.purpose).startsWith('extension_') && request.origin !== 'extension') {
return {
decision: 'block',
source: 'deterministic',
reasonCode: 'ACTION_NOT_ALLOWED',
reason: '扩展发送用途只能用于扩展来源的请求'
}
}
return { decision: 'allow', source: 'deterministic' }
}
@@ -493,6 +561,20 @@ export function normalizeActionRequest(value: unknown): WechatActionRequest | nu
if (contentType === 'text') {
const text = String((content as { text?: unknown }).text || '').trim()
if (!text || text.length > 2_000) return null
const rawAt = (content as { at?: unknown }).at
let at: Record<string, string> | undefined
if (rawAt !== undefined) {
if (!rawAt || typeof rawAt !== 'object' || Array.isArray(rawAt)) return null
if (recipientType !== 'group' && !recipientId.endsWith('@chatroom')) return null
const entries = Object.entries(rawAt as Record<string, unknown>)
if (entries.length > 50) return null
at = {}
for (const [rawWxid, rawName] of entries) {
const wxid = rawWxid.trim()
if (!wxid || typeof rawName !== 'string') return null
at[wxid] = rawName.trim()
}
}
return {
...input,
origin,
@@ -509,12 +591,21 @@ export function normalizeActionRequest(value: unknown): WechatActionRequest | nu
? { name: String((recipient as { name?: unknown }).name).trim() }
: {})
},
content: { type: 'text', text }
content: { type: 'text', text, ...(at ? { at } : {}) }
} as WechatActionRequest
}
if (contentType !== 'image' && contentType !== 'voice') return null
if (
contentType !== 'image' &&
contentType !== 'video' &&
contentType !== 'voice' &&
contentType !== 'file'
) {
return null
}
const filePath = String((content as { path?: unknown }).path || '').trim()
if (!filePath) return null
const contentName =
contentType === 'file' ? String((content as { name?: unknown }).name || '').trim() : ''
return {
...input,
origin,
@@ -531,7 +622,10 @@ export function normalizeActionRequest(value: unknown): WechatActionRequest | nu
? { name: String((recipient as { name?: unknown }).name).trim() }
: {})
},
content: { type: contentType, path: filePath }
content:
contentType === 'file'
? { type: 'file', path: filePath, ...(contentName ? { name: contentName } : {}) }
: { type: contentType, path: filePath }
} as WechatActionRequest
}
@@ -560,10 +654,28 @@ function toPersonalWechatSendRequest(request: WechatActionRequest): PersonalWech
to: request.recipient.id,
isGroup: request.recipient.type === 'group'
}
if (request.content.type === 'text') return { ...base, type: 'text', text: request.content.text }
if (request.content.type === 'text') {
return {
...base,
type: 'text',
text: request.content.text,
...(request.content.at ? { at: request.content.at } : {})
}
}
if (request.content.type === 'image') {
return { ...base, type: 'image', filePath: request.content.path }
}
if (request.content.type === 'video') {
return { ...base, type: 'video', filePath: request.content.path }
}
if (request.content.type === 'file') {
return {
...base,
type: 'file',
filePath: request.content.path,
...(request.content.name ? { fileName: request.content.name } : {})
}
}
const metadata = request.metadata && typeof request.metadata === 'object' ? request.metadata : {}
const fromId = typeof metadata.fromId === 'string' ? metadata.fromId.trim() : ''
const durationMs =
@@ -609,7 +721,12 @@ function contentAudit(
content: WechatActionContent
): Pick<WechatActionAuditRecord, 'contentPreview' | 'contentHash'> {
const raw = content.type === 'text' ? content.text : content.path
const preview = content.type === 'text' ? raw : path.basename(raw)
const preview =
content.type === 'text'
? raw
: content.type === 'file' && content.name
? content.name
: path.basename(raw)
return {
contentPreview: preview.slice(0, MAX_CONTENT_PREVIEW_LENGTH),
contentHash: createHash('sha256').update(raw).digest('hex')
@@ -617,7 +734,15 @@ function contentAudit(
}
function contentTypeLabel(type: WechatActionContent['type']): string {
return type === 'text' ? '文字' : type === 'image' ? '图片' : '语音'
return type === 'text'
? '文字'
: type === 'image'
? '图片'
: type === 'video'
? '视频'
: type === 'file'
? '文件'
: '语音'
}
function normalizeAuditRecords(values: unknown[]): WechatActionAuditRecord[] {
+124 -36
View File
@@ -1442,8 +1442,16 @@ export class Wcdb4Client {
// cannot silently stop at a shard boundary.
let tableMessages: Wcdb4Message[] = []
const cursorSatisfiesLimit = maxRows !== undefined && cursorMessages.length >= maxRows
const cursorMissingSource =
cursorMessages.length > 0 &&
cursorMessages.some(
(msg) => !msg.raw || !Object.prototype.hasOwnProperty.call(msg.raw, 'source')
)
let tableScanExecuted = false
if (!cursorSatisfiesLimit && (endTime || cursorMessages.length === 0)) {
if (
(!cursorSatisfiesLimit && (endTime || cursorMessages.length === 0)) ||
(Boolean(endTime) && cursorMissingSource)
) {
tableScanExecuted = true
tableMessages = await this.getMessagesByTableScanAsync(
username,
@@ -1457,7 +1465,14 @@ export class Wcdb4Client {
`[${requestId}] WCDB message source decision cursorSatisfiesLimit=${cursorSatisfiesLimit} tableScanExecuted=${tableScanExecuted} cursorRows=${cursorMessages.length} tableRows=${tableMessages.length}`
)
const mergeStartedAt = Date.now()
const messages = this.mergeMessageRows(cursorMessages, tableMessages, maxRows)
const recoveredMessages = this.recallJournalEnabled
? await this.readRecallJournalAsync(username, startTime, endTime)
: []
const messages = this.mergeMessageRows(
this.mergeMessageRows(cursorMessages, tableMessages),
recoveredMessages,
maxRows
)
wcdbDebugLog(
`[${requestId}] WCDB mergeMessageRows cost=${Date.now() - mergeStartedAt}ms finalRows=${messages.length}`
)
@@ -1906,14 +1921,14 @@ export class Wcdb4Client {
limit?: number,
requestId = 'NO-REQUEST'
): Promise<Wcdb4Message[]> {
if (!this.wcdbExecQuery) return []
if (!this.wcdbExecQuery) throw new Error('当前 WCDB 数据服务不支持消息分片查询')
const startedAt = Date.now()
wcdbDebugLog(`[${requestId}] WCDB table scan start username=${username}`)
let tables: Wcdb4MessageStore[] = []
try {
const statsStartedAt = Date.now()
tables = await this.listMessageStoresAsync(username)
tables = await this.listMessageStoresAsync(username, true)
wcdbDebugLog(
`[${requestId}] WCDB get_message_table_stats end stores=${tables.length} cost=${Date.now() - statsStartedAt}ms`
)
@@ -1935,34 +1950,39 @@ export class Wcdb4Client {
const order = limit ? 'DESC' : 'ASC'
const allRows: Record<string, unknown>[] = []
let successfulTables = 0
for (const table of tables) {
let offset = 0
try {
const sql = `${this.messageTableSelect(table)}${whereSql} ORDER BY "create_time" ${order} LIMIT ${rowLimit}`
const queryStartedAt = Date.now()
const rows = await this.callJsonAsync<Record<string, unknown>[]>(
this.wcdbExecQuery as unknown as KoffiAsyncFunction,
'message',
table.dbPath,
sql
)
wcdbDebugLog(
`[${requestId}] WCDB exec_query table=${table.tableName} db=${table.dbPath} rows=${Array.isArray(rows) ? rows.length : 0} cost=${Date.now() - queryStartedAt}ms`
)
successfulTables += 1
if (Array.isArray(rows)) allRows.push(...rows)
while (true) {
// An omitted limit means the complete range, not the first 5,000 rows.
// Stable ordering also keeps equal-timestamp messages across pages.
const sql = `${this.messageTableSelect(table)}${whereSql} ORDER BY "create_time" ${order}, "local_id" ${order} LIMIT ${rowLimit} OFFSET ${offset}`
const queryStartedAt = Date.now()
const rows = await this.callJsonAsync<Record<string, unknown>[]>(
this.wcdbExecQuery as unknown as KoffiAsyncFunction,
'message',
table.dbPath,
sql
)
if (!Array.isArray(rows)) throw new Error('消息分片返回格式无效')
wcdbDebugLog(
`[${requestId}] WCDB exec_query table=${table.tableName} db=${table.dbPath} rows=${rows.length} offset=${offset} cost=${Date.now() - queryStartedAt}ms`
)
allRows.push(...rows)
if (limit || rows.length < rowLimit) break
offset += rowLimit
}
} catch (error) {
console.warn(
`[WCDB4] async message table scan failed username=${username} db=${table.dbPath} table=${table.tableName}:`,
error
)
// A partial history must not look like a successful complete range: callers
// may persist a cursor after this request and permanently skip unread rows.
throw new Error('历史消息分片读取失败,请检查数据目录或微信数据版本')
}
}
if (tables.length > 0 && successfulTables === 0) {
throw new Error('历史消息分片均读取失败,请检查数据目录或微信数据版本')
}
const result = this.finalizeMessages(username, allRows, startTime, endTime, limit)
wcdbDebugLog(
`[${requestId}] WCDB table scan end rows=${result.length} cost=${Date.now() - startedAt}ms`
@@ -2144,7 +2164,10 @@ export class Wcdb4Client {
return stores.length > 0 ? stores : this.listFallbackMessageStores(username)
}
private async listMessageStoresAsync(username: string): Promise<Wcdb4MessageStore[]> {
private async listMessageStoresAsync(
username: string,
strict = false
): Promise<Wcdb4MessageStore[]> {
let stores: Wcdb4MessageStore[] = []
if (this.wcdbGetMessageTableStats) {
try {
@@ -2152,12 +2175,13 @@ export class Wcdb4Client {
this.wcdbGetMessageTableStats as unknown as KoffiAsyncFunction,
username
)
if (strict && !Array.isArray(rows)) throw new Error('消息分片目录返回格式无效')
stores = this.parseMessageStores(rows)
} catch (error) {
if (!username.startsWith('gh_')) throw error
}
}
return stores.length > 0 ? stores : this.listFallbackMessageStoresAsync(username)
return stores.length > 0 ? stores : this.listFallbackMessageStoresAsync(username, strict)
}
private parseMessageStores(rows: Record<string, unknown>[]): Wcdb4MessageStore[] {
@@ -2169,7 +2193,7 @@ export class Wcdb4Client {
.filter((row) => row.tableName && row.dbPath)
}
private getMessageDatabasePaths(username: string): string[] {
private getMessageDatabasePaths(username: string, strict = false): string[] {
// Native shard discovery can return no stores on Windows even when SQL reads work.
// Enumerate only canonical databases; sync-conflict copies are not message shards.
const messageRoot = path.join(this.dbStoragePath, 'message')
@@ -2182,7 +2206,8 @@ export class Wcdb4Client {
.filter((name) => pattern.test(name))
.sort()
.map((name) => path.join(messageRoot, name))
} catch {
} catch (error) {
if (strict) throw error
return []
}
}
@@ -2218,12 +2243,18 @@ export class Wcdb4Client {
return stores
}
private async listFallbackMessageStoresAsync(username: string): Promise<Wcdb4MessageStore[]> {
if (!this.wcdbExecQuery) return []
private async listFallbackMessageStoresAsync(
username: string,
strict = false
): Promise<Wcdb4MessageStore[]> {
if (!this.wcdbExecQuery) {
if (strict) throw new Error('当前 WCDB 数据服务不支持消息分片查询')
return []
}
const tableName = `Msg_${this.md5(username)}`
const escapedTableName = tableName.replace(/'/g, "''")
const stores: Wcdb4MessageStore[] = []
for (const dbPath of this.getMessageDatabasePaths(username)) {
for (const dbPath of this.getMessageDatabasePaths(username, strict)) {
try {
const rows = await this.callJsonAsync<Record<string, unknown>[]>(
this.wcdbExecQuery as unknown as KoffiAsyncFunction,
@@ -2231,6 +2262,7 @@ export class Wcdb4Client {
dbPath,
`SELECT name FROM sqlite_master WHERE type='table' AND (name='${escapedTableName}' OR name LIKE 'Name2Id%') ORDER BY name DESC`
)
if (strict && !Array.isArray(rows)) throw new Error('消息分片目录返回格式无效')
if (Array.isArray(rows) && rows.some((row) => row.name === tableName)) {
const senderTableName = rows.find((row) => /^Name2Id/i.test(String(row.name)))?.name
stores.push({
@@ -2239,7 +2271,8 @@ export class Wcdb4Client {
...(senderTableName ? { senderTableName: String(senderTableName) } : {})
})
}
} catch {
} catch (error) {
if (strict) throw error
// A shard may use a different key; continue checking the other databases.
}
}
@@ -2341,6 +2374,35 @@ export class Wcdb4Client {
return this.finalizeMessages(username, recoveredRows, startTime, endTime)
}
private async readRecallJournalAsync(
username: string,
startTime?: number,
endTime?: number
): Promise<Wcdb4Message[]> {
const recoveredRows: Record<string, unknown>[] = []
for (const store of await this.listMessageStoresAsync(username)) {
try {
const begin = this.normalizeTimestamp(startTime || 0)
const end = this.normalizeTimestamp(endTime || 0)
const where = [
`"_wxe_source_table" = '${store.tableName.replace(/'/g, "''")}'`,
begin > 0 ? `"create_time" >= ${begin}` : '',
end > 0 ? `"create_time" <= ${end}` : ''
].filter(Boolean)
const rows = await this.callJsonAsync<Record<string, unknown>[]>(
this.wcdbExecQuery as unknown as KoffiAsyncFunction,
'message',
store.dbPath,
`SELECT *, 1 AS "_wxe_recovered" FROM ${this.quoteSqlIdentifier(this.recallJournalTableName(store.tableName))} WHERE ${where.join(' AND ')} ORDER BY "create_time" ASC LIMIT 500`
)
if (Array.isArray(rows)) recoveredRows.push(...rows)
} catch {
// Like the sync path, the optional journal may not exist on every store.
}
}
return this.finalizeMessages(username, recoveredRows, startTime, endTime)
}
private mergeMessageRows(
current: Wcdb4Message[],
recovered: Wcdb4Message[],
@@ -2357,7 +2419,19 @@ export class Wcdb4Client {
? `local:${message.mesLocalID}:${message.msgCreateTime || 0}`
: `${message.msgCreateTime}:${message.msgContent}`
const key = recoveredRow ? `recovered:${identity}` : identity
merged.set(key, message)
const existing = merged.get(key)
if (existing?.raw && message.raw) {
merged.set(key, {
...existing,
...message,
raw: {
...existing.raw,
...message.raw
}
})
} else {
merged.set(key, message)
}
}
const messages = Array.from(merged.values()).sort(
(left, right) =>
@@ -2691,7 +2765,13 @@ export class Wcdb4Client {
limit?: number,
requestId = 'NO-REQUEST'
): Promise<Wcdb4Message[]> {
if (!this.wcdbOpenMessageCursor || !this.wcdbFetchMessageBatch) return []
if (
!this.wcdbOpenMessageCursor ||
!this.wcdbFetchMessageBatch ||
!this.wcdbCloseMessageCursor
) {
throw new Error('当前 WCDB 数据服务不支持消息游标')
}
const handle = this.ensureHandle()
const batchSize = limit ? Math.min(500, limit) : 1000
@@ -2716,7 +2796,9 @@ export class Wcdb4Client {
wcdbDebugLog(
`[${requestId}] WCDB open_message_cursor end code=${openResult} cursor=${cursorOut[0]} cost=${Date.now() - openStartedAt}ms`
)
if (openResult !== 0 || cursorOut[0] <= 0) return []
if (openResult !== 0 || cursorOut[0] <= 0) {
throw new Error(`无法打开消息游标:${openResult}`)
}
const cursor = cursorOut[0]
const allRows: Record<string, unknown>[] = []
@@ -2739,13 +2821,15 @@ export class Wcdb4Client {
wcdbDebugLog(
`[${requestId}] WCDB fetch_message_batch #${fetchIndex} code=${fetchResult} nativeCost=${fetchNativeCost}ms output=${Boolean(outJson[0])}`
)
break
if (outJson[0]) this.wcdbFreeString?.(outJson[0])
throw new Error(`消息游标读取失败:${fetchResult}`)
}
try {
const decodeStartedAt = Date.now()
const json = this.koffi!.decode(outJson[0], 'char', -1)
const batch = JSON.parse(json) as Record<string, unknown>[]
if (Array.isArray(batch)) allRows.push(...batch)
if (!Array.isArray(batch)) throw new Error('消息游标返回格式无效')
allRows.push(...batch)
wcdbDebugLog(
`[${requestId}] WCDB fetch_message_batch #${fetchIndex} code=${fetchResult} nativeCost=${fetchNativeCost}ms jsonCost=${Date.now() - decodeStartedAt}ms batchRows=${Array.isArray(batch) ? batch.length : 0} hasMore=${outHasMore[0]}`
)
@@ -2757,7 +2841,11 @@ export class Wcdb4Client {
} finally {
const closeStartedAt = Date.now()
try {
this.wcdbCloseMessageCursor?.(handle, cursor)
await this.callAsyncCode(
this.wcdbCloseMessageCursor as unknown as KoffiAsyncFunction,
handle,
cursor
)
} catch {
// Best-effort cursor cleanup.
}
+82
View File
@@ -1,5 +1,21 @@
import { ElectronAPI } from '@electron-toolkit/preload'
import { Contact, Message, MessagesAroundResult } from '../shared/types'
import type {
ExtensionChangedEvent,
ExtensionPageRequest
} from '../shared/extensions/ipc'
import type {
ExtensionInstallResult,
ExtensionLogEntry,
ExtensionOperationResult,
ExtensionPageDescriptor,
ExtensionPageResponse,
ExtensionActionInfo,
ExtensionProjectResult,
ExtensionSystemHealth,
InstalledExtension
} from '../shared/extensions/types'
import type { ExtensionTemplateStatus } from '../shared/extensions/templates'
import {
GroupReportExportRequest,
GroupReportExportResult,
@@ -781,6 +797,12 @@ declare global {
sendPersonalWechatMessage: (
request: PersonalWechatSendRequest
) => Promise<PersonalWechatSendResult>
selectPersonalWechatFile: () => Promise<{
canceled: boolean
path?: string
name?: string
size?: number
}>
/** 定时日报:「立即执行」——与 scheduler 走同一条执行链路(manual trigger)。 */
runScheduledReportRule: (
ruleId: string
@@ -817,6 +839,66 @@ declare global {
onAgentHubConversationsCleared: (callback: () => void) => () => void
onAgentHubStatus: (callback: (status: AgentHubStatus) => void) => () => void
onAgentHubLog: (callback: (entry: AgentHubLogEntry) => void) => () => void
/* 扩展中心 */
listExtensions: () => Promise<InstalledExtension[]>
getExtension: (extensionId: string) => Promise<InstalledExtension | null>
pickExtensionDirectory: () => Promise<string | null>
pickExtensionPackage: () => Promise<string | null>
installExtensionFromDirectory: (directory: string) => Promise<ExtensionInstallResult>
installExtensionFromPackage: (packagePath: string) => Promise<ExtensionInstallResult>
setExtensionEnabled: (
extensionId: string,
enabled: boolean
) => Promise<ExtensionOperationResult>
getExtensionHealth: () => Promise<ExtensionSystemHealth>
grantExtensionPermissions: (
extensionId: string,
permissions: string[]
) => Promise<ExtensionOperationResult>
revokeExtensionPermission: (
extensionId: string,
permission: string
) => Promise<ExtensionOperationResult>
resetExtensionStorage: (extensionId: string) => Promise<ExtensionOperationResult>
listExtensionTemplates: () => Promise<ExtensionTemplateStatus[]>
installExtensionTemplate: (templateId: string) => Promise<ExtensionInstallResult>
acknowledgeExtensionRecovery: () => Promise<ExtensionOperationResult>
acknowledgeExtensionStorage: (extensionId: string) => Promise<ExtensionOperationResult>
adoptExtensionCode: (extensionId: string) => Promise<ExtensionOperationResult>
rollbackExtensionUpgrade: (extensionId: string) => Promise<ExtensionOperationResult>
pickExtensionProjectDirectory: () => Promise<string | null>
linkExtensionDevelopment: (directory: string) => Promise<ExtensionInstallResult>
reloadExtensionDevelopment: (extensionId: string) => Promise<ExtensionOperationResult>
unlinkExtensionDevelopment: (
extensionId: string,
keepData?: boolean
) => Promise<ExtensionOperationResult>
convertExtensionDevelopment: (extensionId: string) => Promise<ExtensionOperationResult>
createExtensionProject: (input: {
templateId: string
targetDirectory: string
extensionId: string
name?: string
}) => Promise<ExtensionProjectResult>
listExtensionActions: () => Promise<ExtensionActionInfo[]>
openExtensionDevelopmentSource: (extensionId: string) => Promise<ExtensionOperationResult>
exportExtensionAsProject: (
extensionId: string,
targetDirectory: string
) => Promise<ExtensionProjectResult>
uninstallExtension: (
extensionId: string,
keepData?: boolean
) => Promise<ExtensionOperationResult>
getExtensionLogs: (extensionId: string, limit?: number) => Promise<ExtensionLogEntry[]>
clearExtensionLogs: (extensionId: string) => Promise<{ success: true }>
getExtensionPageUrl: (
extensionId: string,
pageId?: string
) => Promise<ExtensionPageDescriptor>
extensionPageRequest: (request: ExtensionPageRequest) => Promise<ExtensionPageResponse>
openExtensionDataDir: (extensionId: string) => Promise<{ success: boolean; error?: string }>
onExtensionChanged: (callback: (event: ExtensionChangedEvent) => void) => () => void
}
}
}
+108
View File
@@ -131,6 +131,20 @@ import type {
SaveTextToSpeechSettingsRequest,
SynthesizeTextToSpeechRequest
} from '../shared/text-to-speech'
import type { ExtensionChangedEvent } from '../shared/extensions/ipc'
import type {
ExtensionInstallResult,
ExtensionLogEntry,
ExtensionOperationResult,
ExtensionPageDescriptor,
ExtensionPageRequest,
ExtensionPageResponse,
ExtensionActionInfo,
ExtensionProjectResult,
ExtensionSystemHealth,
InstalledExtension
} from '../shared/extensions/types'
import type { ExtensionTemplateStatus } from '../shared/extensions/templates'
// 渲染器的自定义 API
const api = {
@@ -265,6 +279,94 @@ const api = {
enabled: boolean
): Promise<MsgInsertApplyResult> =>
ipcRenderer.invoke('automation:setMsgInsertSwitch', { name, enabled }),
listExtensions: (): Promise<InstalledExtension[]> => ipcRenderer.invoke('extension:list'),
getExtension: (extensionId: string): Promise<InstalledExtension | null> =>
ipcRenderer.invoke('extension:get', extensionId),
pickExtensionDirectory: (): Promise<string | null> =>
ipcRenderer.invoke('extension:pickDirectory'),
pickExtensionPackage: (): Promise<string | null> => ipcRenderer.invoke('extension:pickPackage'),
installExtensionFromDirectory: (directory: string): Promise<ExtensionInstallResult> =>
ipcRenderer.invoke('extension:installDirectory', directory),
installExtensionFromPackage: (packagePath: string): Promise<ExtensionInstallResult> =>
ipcRenderer.invoke('extension:installPackage', packagePath),
setExtensionEnabled: (extensionId: string, enabled: boolean): Promise<ExtensionOperationResult> =>
ipcRenderer.invoke('extension:setEnabled', { id: extensionId, enabled }),
getExtensionHealth: (): Promise<ExtensionSystemHealth> =>
ipcRenderer.invoke('extension:health'),
grantExtensionPermissions: (
extensionId: string,
permissions: string[]
): Promise<ExtensionOperationResult> =>
ipcRenderer.invoke('extension:grantPermissions', { id: extensionId, permissions }),
revokeExtensionPermission: (
extensionId: string,
permission: string
): Promise<ExtensionOperationResult> =>
ipcRenderer.invoke('extension:revokePermission', { id: extensionId, permission }),
resetExtensionStorage: (extensionId: string): Promise<ExtensionOperationResult> =>
ipcRenderer.invoke('extension:resetStorage', extensionId),
listExtensionTemplates: (): Promise<ExtensionTemplateStatus[]> =>
ipcRenderer.invoke('extension:templates'),
installExtensionTemplate: (templateId: string): Promise<ExtensionInstallResult> =>
ipcRenderer.invoke('extension:installTemplate', templateId),
acknowledgeExtensionRecovery: (): Promise<ExtensionOperationResult> =>
ipcRenderer.invoke('extension:acknowledgeRecovery'),
acknowledgeExtensionStorage: (extensionId: string): Promise<ExtensionOperationResult> =>
ipcRenderer.invoke('extension:acknowledgeStorage', extensionId),
adoptExtensionCode: (extensionId: string): Promise<ExtensionOperationResult> =>
ipcRenderer.invoke('extension:adoptInstalledCode', extensionId),
rollbackExtensionUpgrade: (extensionId: string): Promise<ExtensionOperationResult> =>
ipcRenderer.invoke('extension:rollbackUpgrade', extensionId),
pickExtensionProjectDirectory: (): Promise<string | null> =>
ipcRenderer.invoke('extension:pickProjectDirectory'),
linkExtensionDevelopment: (directory: string): Promise<ExtensionInstallResult> =>
ipcRenderer.invoke('extension:linkDevelopment', directory),
reloadExtensionDevelopment: (extensionId: string): Promise<ExtensionOperationResult> =>
ipcRenderer.invoke('extension:reloadDevelopment', extensionId),
unlinkExtensionDevelopment: (
extensionId: string,
keepData = true
): Promise<ExtensionOperationResult> =>
ipcRenderer.invoke('extension:unlinkDevelopment', { id: extensionId, keepData }),
convertExtensionDevelopment: (extensionId: string): Promise<ExtensionOperationResult> =>
ipcRenderer.invoke('extension:convertDevelopment', extensionId),
createExtensionProject: (input: {
templateId: string
targetDirectory: string
extensionId: string
name?: string
}): Promise<ExtensionProjectResult> =>
ipcRenderer.invoke('extension:createProjectFromTemplate', input),
listExtensionActions: (): Promise<ExtensionActionInfo[]> =>
ipcRenderer.invoke('extension:actions'),
openExtensionDevelopmentSource: (extensionId: string): Promise<ExtensionOperationResult> =>
ipcRenderer.invoke('extension:openDevelopmentSource', extensionId),
exportExtensionAsProject: (
extensionId: string,
targetDirectory: string
): Promise<ExtensionProjectResult> =>
ipcRenderer.invoke('extension:exportInstalledAsProject', {
id: extensionId,
targetDirectory
}),
uninstallExtension: (extensionId: string, keepData = true): Promise<ExtensionOperationResult> =>
ipcRenderer.invoke('extension:uninstall', { id: extensionId, keepData }),
getExtensionLogs: (extensionId: string, limit?: number): Promise<ExtensionLogEntry[]> =>
ipcRenderer.invoke('extension:getLogs', { id: extensionId, limit }),
clearExtensionLogs: (extensionId: string): Promise<{ success: true }> =>
ipcRenderer.invoke('extension:clearLogs', extensionId),
getExtensionPageUrl: (extensionId: string, pageId?: string): Promise<ExtensionPageDescriptor> =>
ipcRenderer.invoke('extension:getPageUrl', { id: extensionId, pageId }),
extensionPageRequest: (request: ExtensionPageRequest): Promise<ExtensionPageResponse> =>
ipcRenderer.invoke('extension:pageRequest', request),
openExtensionDataDir: (extensionId: string): Promise<{ success: boolean; error?: string }> =>
ipcRenderer.invoke('extension:openDataDir', extensionId),
onExtensionChanged: (callback: (event: ExtensionChangedEvent) => void) => {
const listener = (_event: Electron.IpcRendererEvent, payload: ExtensionChangedEvent): void =>
callback(payload)
ipcRenderer.on('extension:changed', listener)
return () => ipcRenderer.removeListener('extension:changed', listener)
},
onGroupExitMonitorState: (callback: (state: GroupExitMonitorState) => void) => {
const listener = (_event: Electron.IpcRendererEvent, state: GroupExitMonitorState): void =>
callback(state)
@@ -634,6 +736,12 @@ const api = {
sendPersonalWechatMessage: (
request: PersonalWechatSendRequest
): Promise<PersonalWechatSendResult> => ipcRenderer.invoke('wechat-personal:send', request),
selectPersonalWechatFile: (): Promise<{
canceled: boolean
path?: string
name?: string
size?: number
}> => ipcRenderer.invoke('wechat-personal:selectFile'),
/**
* 定时日报(Automation 的 `scheduled_report` 规则类型)。
*
+1 -1
View File
@@ -7,7 +7,7 @@
<!-- https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP -->
<meta
http-equiv="Content-Security-Policy"
content="default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data: https: wxe-media:; media-src 'self' https: blob: data: wxe-media:;"
content="default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data: https: wxe-media:; media-src 'self' https: blob: data: wxe-media:; frame-src tm-extension:;"
/>
</head>
+34 -50
View File
@@ -44,8 +44,16 @@ import { switchGeneratedReportTemplate } from './utils/report-template-switch'
import { runtimePlatform } from './utils/runtime-environment'
import { Button, useToast } from './components/ui'
import { AppUpdatePrompt } from './features/app-update/AppUpdatePrompt'
import { GroupExitMonitorWorkspace, type GroupExitMonitorOpenViewRequest } from './features/group-exit-monitor/GroupExitMonitorWorkspace'
import { AutomationWorkspace, type AutomationOpenRuleRequest } from './features/automation/AutomationWorkspace'
import {
GroupExitMonitorWorkspace,
type GroupExitMonitorOpenViewRequest
} from './features/group-exit-monitor/GroupExitMonitorWorkspace'
import {
AutomationWorkspace,
type AutomationOpenRuleRequest
} from './features/automation/AutomationWorkspace'
import { ExtensionWorkspace } from './features/extensions/ExtensionWorkspace'
import type { ExtensionDeepLink } from '../../shared/extensions/types'
import { selectContactAvatarRefreshUsernames } from './utils/contact-avatar'
import {
buildContactSearchIndex,
@@ -257,24 +265,15 @@ function App(): React.ReactElement {
const [databaseEnvironment, setDatabaseEnvironment] = useState<DatabaseKeyEnvironment>()
const connectionOperationRef = React.useRef(0)
const [activePage, setActivePage] = useState<AppPage>('archive')
/**
* 「退群监控 ⇄ 自动化」之间的跨页深链。
*
* 项目没有 react-router,一级菜单就是 `activePage` 这一份 state,
* 所以深链同样是 state —— 用一个单调递增的 requestId 表达"又点了一次",
* 子页面据此重新落位(同一个对象引用不会重复触发 effect)。
*/
/** 从其它页面跳到扩展中心时的定位目标;扩展中心消费后清空。 */
const [extensionDeepLink, setExtensionDeepLink] = useState<ExtensionDeepLink | null>(null)
/** 「退群监控 ⇄ 自动化」之间的跨页深链。 */
const [automationOpenRuleRequest, setAutomationOpenRuleRequest] =
React.useState<AutomationOpenRuleRequest | null>(null)
const [exitMonitorOpenViewRequest, setExitMonitorOpenViewRequest] =
React.useState<GroupExitMonitorOpenViewRequest | null>(null)
const [archiveJumpTime, setArchiveJumpTime] = useState<number | null>(null)
/**
* 精确跳转目标(规范化后的消息 id)。
*
* 与 `archiveJumpTime` 并存而不是替代:时间只能定位到"附近",秒级时间戳在群聊里
* 经常对应多条消息。有 messageRef 时用 id 精确定位,没有时才退回按时间找。
*/
/** 精确跳转目标(规范化后的消息 id);与 `archiveJumpTime` 并存而不是替代:时间只能定位到"附近",秒级时间戳在群聊里 经常对应多条消息。 */
const [archiveJumpMessageId, setArchiveJumpMessageId] = useState<string | null>(null)
const [settingsCategory, setSettingsCategory] = useState<SettingsCategoryId>('account-database')
const [reportSourceContact, setReportSourceContact] = useState<Contact | null>(null)
@@ -1328,15 +1327,7 @@ function App(): React.ReactElement {
}
}
/**
* 跳转到证据的原聊天。
*
* 只靠「真实会话 id + 秒级时间戳」定位不可靠:会话 id 若是展示层合成的 key 就选不中任何
* 真实会话,而时间戳在同一秒有多条消息时会挑错。这里从 `messageRef` 还原真实会话 id →
* 选中会话 → 用 `getMessagesAround` 按稳定消息 id 在有界窗口内精确锚定 → 高亮那一条。
*
* 窗口内找不到时**不静默失败**,明确提示"已打开对应会话,但暂时无法定位原消息"。
*/
/** 跳转到证据的原聊天。 */
const handleOpenSearchEvidence = async (evidence: EvidenceItem): Promise<void> => {
const anchor = decodeMessageRef(evidence.messageRef)
if (!anchor) {
@@ -1611,6 +1602,12 @@ function App(): React.ReactElement {
const isGroupContact = (contact: Contact | null): boolean =>
Boolean(contact?.type === 'group' || contact?.m_nsUsrName?.endsWith('@chatroom'))
/** 跳到扩展中心并带上定位目标(模板 / 扩展)。 */
const openExtensionDeepLink = (target: ExtensionDeepLink): void => {
setExtensionDeepLink(target)
handlePageChange('extensions')
}
const handlePageChange = (page: AppPage): void => {
setActivePage(page)
if (page === 'archive' && selectedContact) void handleSelectContact(selectedContact)
@@ -1650,12 +1647,7 @@ function App(): React.ReactElement {
setActivePage('settings')
}
/**
* 跳到「设置 · 本地索引」。
*
* 用在群统计这类场景:结果不完整的原因是索引没追平,用户需要一个**可操作的去处**,
* 而不是只看到一句「结果可能不完整」却不知道去哪解决。
*/
/** 跳到「设置 · 本地索引」。 */
const openLocalIndexSettings = (): void => {
setSettingsCategory('local-index')
setActivePage('settings')
@@ -1665,23 +1657,13 @@ function App(): React.ReactElement {
setActivePage('agent-hub')
}
/**
* 「退群监控 → 退群通知自动化」。
*
* 直接落到「自动化 → 规则 → 退群通知」,不是只跳到自动化首页。
* 这是纯导航:不改退群监控的任何配置,也不触发任何发送。
*/
/** 「退群监控 → 退群通知自动化」;直接落到「自动化 → 规则 → 退群通知」,不是只跳到自动化首页。 */
const openLeaveNotificationAutomation = (): void => {
setAutomationOpenRuleRequest({ ruleType: 'leave_notification', requestId: Date.now() })
setActivePage('automation')
}
/**
* 「定时日报」已正式迁入自动化,日报页只保留「今日日报 | 社区模板市场」两个 Tab。
*
* 这里仍然留一个导航入口:用户是从日报页产生"要定时发日报"这个念头的,
* 不给路会显得功能被删了。它**不是**第三个 Tab,只是一句去处的说明。
*/
/** 「定时日报」已正式迁入自动化,日报页只保留「今日日报 | 社区模板市场」两个 Tab;它**不是**第三个 Tab,只是一句去处的说明。 */
const openScheduledReportAutomation = (): void => {
setAutomationOpenRuleRequest({ ruleType: 'scheduled_report', requestId: Date.now() })
setActivePage('automation')
@@ -1986,14 +1968,7 @@ function App(): React.ReactElement {
社区模板市场
</button>
</div>
{/*
「定时日报已并入自动化」的指引条。
这里以前是裸 `<p>` + 裸 `<button>`,并且挂了 `.report-workspace-hint` /
`.report-workspace-hint-link` 两个**样式表里根本不存在**的类 ——
于是就成了一条没样式的文字 + 一个长得不像系统里任何按钮的按钮。
现在补上真实样式,按钮统一走 UI 组件库。
*/}
{/** 「定时日报已并入自动化」的指引条。 */}
<div className="report-workspace-hint">
<span>需要「定时日报」?它已经并入「自动化」,可以按时间自动生成并发送日报。</span>
<Button variant="link" size="sm" onClick={openScheduledReportAutomation}>
@@ -2135,10 +2110,19 @@ function App(): React.ReactElement {
openRuleRequest={automationOpenRuleRequest}
onOpenModelSettings={openModelSettings}
onOpenAgentHub={openAgentHub}
onOpenExtension={openExtensionDeepLink}
/>
)
case 'agent-hub':
return <AgentHubWorkspace selfInfo={selfInfo} />
case 'extensions':
return (
<ExtensionWorkspace
deepLink={extensionDeepLink}
onConsumeDeepLink={() => setExtensionDeepLink(null)}
onOpenSendSettings={openWechatSendSettings}
/>
)
case 'api':
return (
<ApiWorkspace
+18 -1
View File
@@ -59,6 +59,7 @@ const ChatWindow: React.FC<ChatWindowProps> = ({
const [isAtLatest, setIsAtLatest] = useState(true)
const [isReloadingAvatars, setIsReloadingAvatars] = useState(false)
const [sendDialogOpen, setSendDialogOpen] = useState(false)
const [pendingFile, setPendingFile] = useState<{ path: string; name: string } | null>(null)
const previousScrollTopRef = useRef(0)
const scrollToBottom = useCallback((): void => {
@@ -167,6 +168,17 @@ const ChatWindow: React.FC<ChatWindowProps> = ({
setSendDialogOpen(true)
}, [onOpenPersonalWechatSettings])
const handleSendFile = useCallback(async (): Promise<void> => {
try {
const picked = await window.api.selectPersonalWechatFile()
if (picked.canceled || !picked.path || !picked.name) return
setPendingFile({ path: picked.path, name: picked.name })
setSendDialogOpen(true)
} catch {
// 选择器本身失败(无窗口、无权限)时什么都不做,不要弹出一个空对话框。
}
}, [])
if (!contact) return <EmptyConversationState />
return (
@@ -181,6 +193,7 @@ const ChatWindow: React.FC<ChatWindowProps> = ({
onContentFilterChange={onContentFilterChange || (() => undefined)}
onRefresh={onRefresh}
onTestSend={() => void handleOpenPersonalWechatSend()}
onSendFile={() => void handleSendFile()}
onOpenAiSettings={onCreateGroupReport || (() => undefined)}
onOpenLocalIndexSettings={onOpenLocalIndexSettings}
/>
@@ -215,9 +228,13 @@ const ChatWindow: React.FC<ChatWindowProps> = ({
<PersonalWechatSendDialog
contact={contact}
isGroupChat={isGroupChat}
onClose={() => setSendDialogOpen(false)}
onClose={() => {
setSendDialogOpen(false)
setPendingFile(null)
}}
onOpenTextToSpeechSettings={onOpenTextToSpeechSettings}
onOpenPersonalWechatSettings={onOpenPersonalWechatSettings}
initialFile={pendingFile}
/>
)}
@@ -2,7 +2,7 @@ import React, { useState } from 'react'
import { Contact } from '../../../../shared/types'
import { Button, IconButton, Tooltip, TooltipContent, TooltipTrigger } from '../ui'
import { ConversationContentSearch } from './ConversationContentSearch'
import { AiIcon, RefreshIcon, SearchIcon, SendIcon, StatsIcon } from './icons'
import { AiIcon, ExportIcon, RefreshIcon, SearchIcon, SendIcon, StatsIcon } from './icons'
import { supportsPersonalWechatSend } from '../../utils/runtime-environment'
import { GroupMemberStatsDialog } from '../group-stats/GroupMemberStatsDialog'
@@ -16,6 +16,7 @@ interface ChatHeaderProps {
onContentFilterChange: (value: string) => void
onRefresh?: () => void
onTestSend: () => void
onSendFile?: () => void
onOpenAiSettings: () => void
/** 跳到「设置 · 本地索引」(群统计发现索引没追平时用)。 */
onOpenLocalIndexSettings?: () => void
@@ -31,6 +32,7 @@ export function ChatHeader({
onContentFilterChange,
onRefresh,
onTestSend,
onSendFile,
onOpenAiSettings,
onOpenLocalIndexSettings
}: ChatHeaderProps): React.ReactElement {
@@ -131,6 +133,19 @@ export function ChatHeader({
<TooltipContent>仅支持 macOS 和 Windows</TooltipContent>
</Tooltip>
)}
{supportsPersonalWechatSend && onSendFile ? (
<Button
variant="outline"
size="sm"
className="chat-header-text-action"
aria-label="发送文件"
title="发送文件"
onClick={onSendFile}
>
<ExportIcon />
<span>发送文件</span>
</Button>
) : null}
<Button
variant="default"
size="sm"
@@ -24,6 +24,7 @@ export interface PersonalWechatSendDialogProps {
onOpenPersonalWechatSettings?: () => void
initialMode?: 'text' | 'image' | 'voice'
initialImage?: SelectedLocalFile | null
initialFile?: SelectedLocalFile | null
}
function fallbackStatus(error: unknown): PersonalWechatSenderStatus {
@@ -62,7 +63,8 @@ function PersonalWechatMacSendDialog({
isGroupChat,
onClose,
onOpenTextToSpeechSettings,
initialImage = null
initialImage = null,
initialFile = null
}: PersonalWechatSendDialogProps): React.ReactElement {
const [senderStatus, setSenderStatus] = useState<PersonalWechatSenderStatus | null>(null)
const [detecting, setDetecting] = useState(true)
@@ -81,7 +83,13 @@ function PersonalWechatMacSendDialog({
const displayName = contact.m_nsNickName || contact.m_nsUsrName || '未命名会话'
const targetId = contact.m_nsUsrName
const isBusy = binding || sendBusy
const setupReady = Boolean(initialImage ? senderStatus?.canSendImage : senderStatus?.canSendVoice)
const setupReady = Boolean(
initialFile
? senderStatus?.canSendFile
: initialImage
? senderStatus?.canSendImage
: senderStatus?.canSendVoice
)
const { postfixText, setPostfixText, persistPostfixText } = useReportImagePostfixSetting(
Boolean(initialImage)
)
@@ -237,8 +245,33 @@ function PersonalWechatMacSendDialog({
}
}
const handleOpenVoiceDiagnostic = async (): Promise<void> => {
if (!isMac) return
const handleSendFile = async (): Promise<void> => {
if (!initialFile || !senderStatus?.canSendFile || sendBusy) return
setSendBusy(true)
setSendError(null)
setSendSuccess(null)
try {
const response = await window.api.sendPersonalWechatMessage({
type: 'file',
to: targetId,
isGroup: isGroupChat,
filePath: initialFile.path,
fileName: initialFile.name
} satisfies PersonalWechatSendRequest)
setSenderStatus(response.status)
if (!response.success) {
setSendError(response.error || '文件发送失败')
return
}
setSendSuccess('文件发送成功')
} catch (error) {
setSendError(error instanceof Error ? error.message : String(error))
} finally {
setSendBusy(false)
}
}
const handleOpenVoiceDiagnostic = async (): Promise<void> => { if (!isMac) return
const diagnostic = await window.api.getPersonalWechatVoiceDiagnostic()
setVoiceDiagnostic(diagnostic)
setVoiceDiagnosticOpen(true)
@@ -263,7 +296,9 @@ function PersonalWechatMacSendDialog({
{displayName.slice(0, 1)}
</div>
<div className="personal-wechat-chat-heading">
<DialogTitle>{initialImage ? '发送日报图片' : '文字转语音'}</DialogTitle>
<DialogTitle>
{initialFile ? '发送文件' : initialImage ? '发送日报图片' : '文字转语音'}
</DialogTitle>
<DialogDescription>
发送给 {displayName} · {setupReady ? '微信已连接' : '配置微信发送能力'}
</DialogDescription>
@@ -275,7 +310,7 @@ function PersonalWechatMacSendDialog({
</DialogHeader>
<div className="personal-wechat-chat-body">
{setupReady && !initialImage && (
{setupReady && !initialImage && !initialFile && (
<div className="personal-wechat-message-list" aria-label="消息列表">
{messages.length === 0 ? (
<div className="personal-wechat-empty-message">还没有发送消息。</div>
@@ -324,7 +359,16 @@ function PersonalWechatMacSendDialog({
</section>
)}
{setupReady && !initialImage && (
{setupReady && initialFile && (
<section className="personal-wechat-composer" aria-label="文件发送">
<p>已选择文件:{initialFile.name}</p>
<Button size="sm" onClick={() => void handleSendFile()} disabled={sendBusy}>
{sendBusy ? '发送中…' : '发送文件'}
</Button>
</section>
)}
{setupReady && !initialImage && !initialFile && (
<PersonalWechatChatComposer
status={senderStatus!}
targetId={targetId}
@@ -346,7 +390,7 @@ function PersonalWechatMacSendDialog({
</div>
)}
</div>
{setupReady && isMac && !initialImage && (
{setupReady && isMac && !initialImage && !initialFile && (
<div className="personal-wechat-chat-footer flex items-center justify-end">
<Button variant="link" size="sm" onClick={() => void handleOpenVoiceDiagnostic()}>
语音发送诊断
@@ -63,6 +63,7 @@ export function PersonalWechatSetupGuide({
canBind = true
}: PersonalWechatSetupGuideProps): React.ReactElement {
const runtimeUnavailable = senderStatus?.state === 'runtime_missing'
const runtimeError = senderStatus?.state === 'error' && !senderStatus.endpointReady
const runtimeLabel = '发送运行时'
const runtimeReady = senderStatus?.runtimeReady === true
const connected = sessionBound && (senderStatus ? isWechatBound(senderStatus) : false)
@@ -82,7 +83,11 @@ export function PersonalWechatSetupGuide({
</div>
<ol className="personal-wechat-steps">
<li className={runtimeReady ? 'is-complete' : 'is-current'}>
<li
className={
runtimeReady ? 'is-complete' : runtimeError ? 'is-error' : 'is-current'
}
>
<span className="personal-wechat-step-number">{runtimeReady ? '✓' : '1'}</span>
<div className="personal-wechat-step-content">
<strong>准备 {runtimeLabel}</strong>
@@ -95,6 +100,10 @@ export function PersonalWechatSetupGuide({
<span className="personal-wechat-step-status">✓ {runtimeLabel}已就绪</span>
) : runtimeUnavailable ? (
<span className="personal-wechat-step-error">当前版本暂未提供微信消息发送功能</span>
) : runtimeError ? (
<span className="personal-wechat-step-error" role="alert">
{senderStatus.message || '发送运行时启动失败,请重新启动发送组件。'}
</span>
) : (
<span className="personal-wechat-step-status">正在检查 {runtimeLabel}…</span>
)}
@@ -183,7 +192,7 @@ export function PersonalWechatSetupGuide({
: '正在等待发送运行时完成初始化…'}
</p>
)}
{senderStatus?.state === 'error' && (
{senderStatus?.state === 'error' && !runtimeError && (
<p className="personal-wechat-step-hint" role="status">
{senderStatus.message || '发送能力初始化失败,请重新绑定。'}
</p>
@@ -30,6 +30,7 @@ function fallbackStatus(error: unknown): PersonalWechatSenderStatus {
canSendText: false,
canSendImage: false,
canSendVoice: false,
canSendVideo: false,
message: '无法检测 Windows 微信发送能力',
error: error instanceof Error ? error.message : String(error)
}
@@ -47,7 +48,7 @@ function statusLabel(status: PersonalWechatSenderStatus | null): string {
}
function statusText(value: string): string {
return value.replace(/Hook/gi, '微信发送能力').replace(/个人微信发送组件/g, '微信发送能力')
return value.replace(/个人微信发送组件/g, '微信发送能力')
}
function statusDescription(status: PersonalWechatSenderStatus | null): string {
@@ -61,7 +62,8 @@ export function PersonalWechatWindowsSendDialog({
onClose,
onOpenTextToSpeechSettings,
onOpenPersonalWechatSettings,
initialImage = null
initialImage = null,
initialFile = null
}: PersonalWechatSendDialogProps): React.ReactElement {
const [status, setStatus] = useState<PersonalWechatSenderStatus | null>(null)
const [detecting, setDetecting] = useState(true)
@@ -181,8 +183,43 @@ export function PersonalWechatWindowsSendDialog({
}
}
const statusTone = useMemo(() => {
if (status?.state === 'online' && status.canSend) return 'ready'
const handleSendFile = async (): Promise<void> => {
if (!initialFile || !status?.canSendFile || sendBusy) return
setSendBusy(true)
setSendError(null)
setSendSuccess(null)
try {
const response = await window.api.sendPersonalWechatMessage({
type: 'file',
to: targetId,
isGroup: isGroupChat,
filePath: initialFile.path,
fileName: initialFile.name
} satisfies PersonalWechatSendRequest)
setStatus(response.status)
if (!response.success) {
setSendError(response.error || '文件发送失败')
return
}
setSendSuccess('文件发送成功')
setMessages((current) => [
...current,
{
id: `${Date.now()}-${Math.random()}`,
type: 'system',
text: initialFile.name,
fileName: initialFile.name,
outgoing: true
}
])
} catch (error) {
setSendError(error instanceof Error ? error.message : String(error))
} finally {
setSendBusy(false)
}
}
const statusTone = useMemo(() => { if (status?.state === 'online' && status.canSend) return 'ready'
if (!status || status.state === 'checking' || status.state === 'starting') return 'checking'
return 'blocked'
}, [status])
@@ -204,22 +241,16 @@ export function PersonalWechatWindowsSendDialog({
<div>
<span className="text-[11px] font-bold tracking-normal text-primary">实验性功能</span>
<DialogTitle className="mt-0.5 text-[19px] leading-[26px] tracking-normal">
文字转语音
{initialFile ? '发送文件' : '文字转语音'}
</DialogTitle>
</div>
<DialogDescription className="sr-only">
向当前微信联系人或群聊发送文字转语音。
{initialFile
? '向当前微信联系人或群聊发送本地文件。'
: '向当前微信联系人或群聊发送文字转语音。'}
</DialogDescription>
</DialogHeader>
<div className="personal-wechat-send-device-note" role="note">
<span aria-hidden>i</span>
<p>
<strong>请在其他设备确认发送结果</strong>
语音消息请切换到手机、平板等其他设备确认是否送达。
</p>
</div>
<div className="personal-wechat-send-target">
<span>{isGroupChat ? '发送到群聊' : '发送给联系人'}</span>
<strong>{displayName}</strong>
@@ -266,13 +297,28 @@ export function PersonalWechatWindowsSendDialog({
key={message.id}
className={`personal-wechat-message-bubble ${message.outgoing ? 'is-outgoing' : ''}`}
>
<span className="personal-wechat-message-kind">语音</span>
<span className="personal-wechat-message-kind">
{message.type === 'voice' ? '语音' : '已发送'}
</span>
<span>{message.text || message.fileName}</span>
</div>
))}
</div>
) : null}
{initialImage && status.canSendImage ? (
{initialFile ? (
status.canSendFile ? (
<section className="personal-wechat-composer" aria-label="文件发送">
<p>已选择文件:{initialFile.name}</p>
<Button size="sm" onClick={() => void handleSendFile()} disabled={sendBusy}>
{sendBusy ? '发送中…' : '发送文件'}
</Button>
</section>
) : (
<div className="personal-wechat-global-error" role="alert">
当前微信发送能力不支持文件发送,请升级发送组件后重试
</div>
)
) : initialImage && status.canSendImage ? (
<section className="personal-wechat-composer" aria-label="日报图片发送">
<p>已准备日报图片:{initialImage.name}</p>
<ReportImagePostfixInput
@@ -289,7 +335,7 @@ export function PersonalWechatWindowsSendDialog({
{sendBusy ? '发送中…' : '发送日报图片'}
</Button>
</section>
) : !initialImage ? (
) : !initialImage && !initialFile ? (
<PersonalWechatChatComposer
status={status}
targetId={targetId}
@@ -46,6 +46,15 @@ function NavIcon({ page }: NavIconProps): React.ReactElement {
<path d="m16.5 9 3 3-3 3" />
</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" />
<path d="M8.5 12h7" />
<path d="M8.5 16h4.5" />
</svg>
)
case 'export':
return (
<svg viewBox="0 0 24 24" aria-hidden="true" focusable="false">
@@ -96,11 +105,41 @@ function NavIcon({ page }: NavIconProps): React.ReactElement {
}
}
/** 发送能力探活间隔:轮询只为点亮导航红点,低频足够。 */
const SEND_CAPABILITY_POLL_MS = 30 * 60 * 1000
export function PrimaryNavigation({
activePage,
onPageChange
}: PrimaryNavigationProps): React.ReactElement {
const [unreadExitCount, setUnreadExitCount] = React.useState(0)
const [sendUnavailable, setSendUnavailable] = React.useState(false)
React.useEffect(() => {
const api = typeof window !== 'undefined' ? window.api : undefined
if (!api || typeof api.getPersonalWechatSendCapability !== 'function') return
let disposed = false
const checkSendCapability = (): void => {
void api
.getPersonalWechatSendCapability()
.then((cap) => {
if (!disposed) setSendUnavailable(Boolean(cap && cap.ready === false))
})
.catch(() => undefined)
}
checkSendCapability()
const timer = window.setInterval(checkSendCapability, SEND_CAPABILITY_POLL_MS)
// 半小时才轮一次,红点会过期;窗口重新可见时补查一次,成本可忽略。
const onVisibilityChange = (): void => {
if (!document.hidden) checkSendCapability()
}
document.addEventListener('visibilitychange', onVisibilityChange)
return () => {
disposed = true
window.clearInterval(timer)
document.removeEventListener('visibilitychange', onVisibilityChange)
}
}, [activePage])
React.useEffect(() => {
const api = typeof window !== 'undefined' ? window.api : undefined
@@ -138,13 +177,22 @@ export function PrimaryNavigation({
type="button"
className={`primary-nav-item ${activePage === item.id ? 'active' : ''}`}
onClick={() => onPageChange(item.id)}
title={item.label}
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>
@@ -5,6 +5,7 @@ export type AppPage =
| 'exit-monitor'
| 'automation'
| 'agent-hub'
| 'extensions'
| 'export'
| 'api'
| 'settings'
@@ -20,6 +21,7 @@ export const PRIMARY_NAV_ITEMS: NavigationItem[] = [
{ id: 'report', label: '日报' },
{ id: 'exit-monitor', label: '退群监控' },
{ id: 'automation', label: '自动化' },
{ id: 'extensions', label: '扩展' },
{ id: 'agent-hub', label: 'Agent' },
{ id: 'export', label: '导出' },
{ id: 'api', label: 'API' },
@@ -1,5 +1,6 @@
import * as React from 'react'
import {
AUTOMATION_RULE_TEMPLATES,
BUILTIN_DAILY_REPORT_RULE_ID,
BUILTIN_LEAVE_NOTIFICATION_RULE_ID,
calculateNextRunAt,
@@ -18,12 +19,12 @@ import {
} from '../../components/ui'
import { RuleListPanel } from './RuleListPanel'
import { RuleEditorPanel } from './RuleEditorPanel'
import type { RuleTemplateCardModel } from './RuleListPanel'
import type { ExtensionTemplateStatus } from '../../../../shared/extensions/templates'
import type { ExtensionDeepLink, InstalledExtension } from '../../../../shared/extensions/types'
import { ExecutionLogPanel } from './ExecutionLogPanel'
import { ExecutionDetailDrawer } from './ExecutionDetailDrawer'
import {
AutomationRuleTypeTabs,
type AutomationRuleTabType
} from './AutomationRuleTypeTabs'
import { AutomationRuleTypeTabs, type AutomationRuleTabType } from './AutomationRuleTypeTabs'
import { MessageInsertSwitches } from './MessageInsertSwitches'
import { ScheduledReportEditor } from './ScheduledReportEditor'
import { ScheduledReportRuleList } from './ScheduledReportRuleList'
@@ -36,12 +37,14 @@ import {
resolveGroupDisplayName,
type ScheduledReportDraft
} from './model/scheduled-report-model'
import {
LeaveNotificationEditor,
type LeaveNotificationSaveInput
} from './LeaveNotificationEditor'
import { LeaveNotificationEditor, type LeaveNotificationSaveInput } from './LeaveNotificationEditor'
import type { LeaveNotificationContactOption } from './LeaveNotificationTargetPicker'
import { UNAVAILABLE_STATUS, automationApi, isAutomationApiAvailable, type AutomationGroupOption } from './model/api'
import {
UNAVAILABLE_STATUS,
automationApi,
isAutomationApiAvailable,
type AutomationGroupOption
} from './model/api'
/**
* AutomationWorkspace —— 自动化一级菜单。
@@ -63,6 +66,16 @@ export interface AutomationOpenRuleRequest {
requestId: number
}
/** 可选能力加载:宿主没有该 API 时返回兜底值,不抛错。 */
async function safeLoad<T>(loader: () => Promise<T> | undefined, fallback: T): Promise<T> {
try {
const result = await loader()
return result ?? fallback
} catch {
return fallback
}
}
export interface AutomationWorkspaceProps {
dbReady: boolean
/** 发送能力不可用时,引导用户去设置页。 */
@@ -75,6 +88,8 @@ export interface AutomationWorkspaceProps {
onOpenAgentHub?: () => void
/** 深链请求(来自退群监控页的「退群通知自动化」入口)。 */
openRuleRequest?: AutomationOpenRuleRequest | null
/** 跳到扩展中心并定位模板 / 扩展 / 开发引导(规则模板卡片用)。 */
onOpenExtension?: (target: ExtensionDeepLink) => void
}
interface EditorState {
@@ -90,7 +105,8 @@ export function AutomationWorkspace({
onOpenExitMonitorGroups,
onOpenModelSettings,
onOpenAgentHub,
openRuleRequest
openRuleRequest,
onOpenExtension
}: AutomationWorkspaceProps): React.ReactElement {
const { toast } = useToast()
const apiAvailable = React.useMemo(() => isAutomationApiAvailable(), [])
@@ -100,7 +116,9 @@ export function AutomationWorkspace({
const [rules, setRules] = React.useState<AutomationRule[]>([])
const [groups, setGroups] = React.useState<AutomationGroupOption[]>([])
const [executions, setExecutions] = React.useState<AutomationExecution[]>([])
const [sendableContacts, setSendableContacts] = React.useState<LeaveNotificationContactOption[]>([])
const [sendableContacts, setSendableContacts] = React.useState<LeaveNotificationContactOption[]>(
[]
)
const [monitoredGroupCount, setMonitoredGroupCount] = React.useState(0)
/** 已监控群聊清单(含显示名)—— 退群通知「通知群聊」二次勾选的候选项。 */
const [monitoredGroups, setMonitoredGroups] = React.useState<AutomationGroupOption[]>([])
@@ -109,6 +127,63 @@ export function AutomationWorkspace({
const [saving, setSaving] = React.useState(false)
const [busyRuleId, setBusyRuleId] = React.useState<string | null>(null)
const [editor, setEditor] = React.useState<EditorState | null>(null)
/** 规则模板依赖的本机事实:官方模板目录 + 已安装扩展。 */
const [extensionTemplates, setExtensionTemplates] = React.useState<ExtensionTemplateStatus[]>([])
const [installedExtensions, setInstalledExtensions] = React.useState<InstalledExtension[]>([])
/**
* 规则模板卡片的真实状态。
*
* 只读「官方模板目录 + 已装扩展」,不在自动化页维护第二份安装状态。
*/
const ruleTemplates = React.useMemo<RuleTemplateCardModel[]>(() => {
return AUTOMATION_RULE_TEMPLATES.map((template) => {
const installed = installedExtensions.find((item) => item.id === template.extensionId)
const catalog = extensionTemplates.find(
(item) => item.template.templateId === template.templateId
)
if (!installed) {
const reason =
catalog?.state === 'damaged'
? catalog.message
: catalog?.state === 'conflict'
? catalog.message
: undefined
return { ...template, state: 'not-installed', ...(reason ? { reason } : {}) }
}
if (!installed.compatibility.compatible) {
return {
...template,
state: 'unavailable',
reason: installed.compatibility.reason || '扩展与当前 TraceMemo 版本不兼容'
}
}
if (installed.runtime.state === 'error') {
return {
...template,
state: 'unavailable',
reason: installed.runtime.lastError || '扩展运行异常'
}
}
if (!installed.enabled) {
return { ...template, state: 'installed-disabled', reason: '已安装但未启用' }
}
return { ...template, state: 'ready' }
})
}, [extensionTemplates, installedExtensions])
const useRuleTemplate = (template: RuleTemplateCardModel): void => {
if (!template.actionId) return
// 打开的是「新建」,不复用上一次日报的编辑目标。
setEditor({ mode: 'create', rule: null, ruleType: 'daily_report' })
toast({
title: '已打开新建规则',
description:
`在执行动作里添加「${template.name}」,选择扩展动作 ${template.actionId}。` +
'若机器人当前是主动订阅模式,规则路径会自动跳过,不会双回复。',
variant: 'default'
})
}
const [selectedExecution, setSelectedExecution] = React.useState<AutomationExecution | null>(null)
const [pendingDelete, setPendingDelete] = React.useState<AutomationRule | null>(null)
@@ -131,6 +206,15 @@ export function AutomationWorkspace({
automationApi.getMonitoredGroupCount(),
automationApi.getMonitoredGroups()
])
// 扩展状态是「模板能不能用」的唯一依据:不自己维护第二份。
// 扩展 API 在旧版宿主或测试环境里可能整体缺失,缺失时按空列表处理,
// 卡片会退化成「未安装」,而不是让整个自动化页崩掉。
const [nextTemplates, nextExtensions] = await Promise.all([
safeLoad<ExtensionTemplateStatus[]>(() => window.api?.listExtensionTemplates?.(), []),
safeLoad<InstalledExtension[]>(() => window.api?.listExtensions?.(), [])
])
setExtensionTemplates(nextTemplates)
setInstalledExtensions(nextExtensions)
setStatus(nextStatus)
setRules(nextRules)
setGroups(nextGroups)
@@ -186,7 +270,6 @@ export function AutomationWorkspace({
const leaveNotificationRule =
rules.find((item) => item.id === BUILTIN_LEAVE_NOTIFICATION_RULE_ID) ?? null
/** 「指定好友」目标的显示名(首页卡片用;拿不到时留空,不伪造)。 */
const leaveContactName = React.useMemo((): string => {
const target = leaveNotificationRule?.leaveNotification?.target
@@ -413,9 +496,7 @@ export function AutomationWorkspace({
* 走独立的 singleton upsert 通道:这条规则 id 固定,保存永远不会多出一条。
* 保存成功后清掉迁移遗留的 `targetNeedsReview`(用户已经做过选择)。
*/
const handleLeaveNotificationSave = async (
input: LeaveNotificationSaveInput
): Promise<void> => {
const handleLeaveNotificationSave = async (input: LeaveNotificationSaveInput): Promise<void> => {
// 静默 return 会让"点保存没反应"变成用户眼里的坏掉,必须说出来。
if (!leaveNotificationRule) {
toast({
@@ -522,7 +603,11 @@ export function AutomationWorkspace({
<div className="automation-status-card">
<span className="automation-status-label">发送能力</span>
<span className={`automation-status-value ${capabilityReady ? 'ok' : 'warn'}`}>
{capabilityReady ? '可以发送文字和图片' : capability.ready ? '发送能力不完整' : '尚未就绪'}
{capabilityReady
? '可以发送文字和图片'
: capability.ready
? '发送能力不完整'
: '尚未就绪'}
</span>
<small className="automation-status-note">{capability.message}</small>
{!capabilityReady && onOpenSendSettings ? (
@@ -637,9 +722,7 @@ export function AutomationWorkspace({
{...(onOpenModelSettings ? { onOpenModelSettings } : {})}
{...(scheduledEditor.ruleId
? (() => {
const rule = scheduledRules.find(
(item) => item.id === scheduledEditor.ruleId
)
const rule = scheduledRules.find((item) => item.id === scheduledEditor.ruleId)
const legacy = rule?.scheduledReport?.legacyTarget
return legacy ? { legacyTarget: legacy } : {}
})()
@@ -709,8 +792,8 @@ export function AutomationWorkspace({
<div className="automation-notice warning automation-notice-stack">
<p>没有找到内置的退群通知规则。</p>
<small>
这条规则应由主进程在首次启动时自动创建。如果你刚更新过版本,
请重启 TraceMemo —— 已经跑起来的主进程不会自动换成新代码。
这条规则应由主进程在首次启动时自动创建。如果你刚更新过版本, 请重启 TraceMemo ——
已经跑起来的主进程不会自动换成新代码。
</small>
<Button
variant="outline"
@@ -760,6 +843,9 @@ export function AutomationWorkspace({
onEditLeaveNotification={() =>
setEditor({ mode: 'edit', rule: null, ruleType: 'leave_notification' })
}
ruleTemplates={ruleTemplates}
onOpenExtension={onOpenExtension}
onUseRuleTemplate={useRuleTemplate}
/>
) : (
<ExecutionLogPanel
@@ -777,7 +863,11 @@ export function AutomationWorkspace({
/>
{pendingDelete ? (
<div className="automation-confirm-layer" role="presentation" onClick={() => setPendingDelete(null)}>
<div
className="automation-confirm-layer"
role="presentation"
onClick={() => setPendingDelete(null)}
>
<div
className="automation-confirm"
role="alertdialog"
@@ -0,0 +1,216 @@
import * as React from 'react'
import type { AutomationAction } from '../../../../shared/automation'
import type { ExtensionActionInfo } from '../../../../shared/extensions/types'
import type { ExtensionActionInputSchema } from '../../../../shared/extensions/action-schema'
import { Button, Input, Switch } from '../../components/ui'
interface ExtensionActionListProps {
/** 完整动作数组(含固定动作),本组件只挑 `extensionAction`。 */
actions: AutomationAction[]
available: ExtensionActionInfo[]
onChange: (next: AutomationAction[]) => void
}
/**
* 扩展动作编辑区。
*
* 按**数组索引**定位要改的那一条:同类型动作可以有多个,
* 按 `type` 批量更新会把它们一起改掉。
*/
export function ExtensionActionList({
actions,
available,
onChange
}: ExtensionActionListProps): React.ReactElement {
const [pendingExtension, setPendingExtension] = React.useState('')
const [pendingAction, setPendingAction] = React.useState('')
const extensionActions = actions
.map((action, index) => ({ action, index }))
.filter((item) => item.action.type === 'extensionAction')
const groups = React.useMemo(() => {
const map = new Map<string, { name: string; actions: ExtensionActionInfo[] }>()
for (const item of available) {
const entry = map.get(item.extensionId) ?? { name: item.extensionName, actions: [] }
entry.actions.push(item)
map.set(item.extensionId, entry)
}
return Array.from(map.entries()).sort((left, right) =>
left[1].name.localeCompare(right[1].name)
)
}, [available])
const patchAt = (index: number, patch: Partial<AutomationAction>): void => {
onChange(
actions.map((action, current) => (current === index ? { ...action, ...patch } : action))
)
}
const removeAt = (index: number): void => {
onChange(actions.filter((_action, current) => current !== index))
}
const addAction = (): void => {
const info = available.find(
(item) => item.extensionId === pendingExtension && item.actionId === pendingAction
)
if (!info) return
const input: Record<string, unknown> = {}
if (info.inputSchema) {
for (const [key, field] of Object.entries(info.inputSchema.properties)) {
if (field.default !== undefined) input[key] = field.default
}
}
onChange([
...actions,
{
type: 'extensionAction',
enabled: true,
extensionId: info.extensionId,
actionId: info.actionId,
input
}
])
setPendingAction('')
}
const actionsOfSelectedExtension = pendingExtension
? available.filter((item) => item.extensionId === pendingExtension)
: []
return (
<div className="automation-extension-actions">
{extensionActions.length === 0 ? (
<p className="automation-muted">还没有扩展动作。扩展启用后这里会出现它注册的动作。</p>
) : (
extensionActions.map(({ action, index }) => {
const info = available.find(
(item) => item.extensionId === action.extensionId && item.actionId === action.actionId
)
const schema: ExtensionActionInputSchema | undefined = info?.inputSchema
const input = action.input ?? {}
return (
<div
key={`${action.extensionId}-${action.actionId}-${index}`}
className="automation-action-row"
>
<div className="automation-action-main">
<div className="automation-switch-row compact">
<div>
<span className="automation-field-label">
{info?.title || action.actionId || '未知动作'}
<span className="automation-extension-badge">
{info?.extensionName || action.extensionId}
</span>
</span>
<small>
{info?.available
? info.description || '扩展动作'
: info?.unavailableReason || '依赖的扩展不可用,规则会保留但无法执行'}
</small>
</div>
<Switch
checked={action.enabled}
onCheckedChange={(checked) => patchAt(index, { enabled: checked })}
/>
</div>
{schema && action.enabled && (
<div className="automation-extension-fields">
{Object.entries(schema.properties).map(([key, field]) => {
const required = schema.required?.includes(key) === true
const label = field.title || key
const value = input[key]
return (
<label key={key} className="automation-field">
<span className="automation-field-label">
{label}
{required && <span className="automation-required">*</span>}
</span>
{field.type === 'boolean' ? (
<Switch
checked={value === true}
onCheckedChange={(checked) =>
patchAt(index, { input: { ...input, [key]: checked } })
}
/>
) : (
<Input
type={field.type === 'string' ? 'text' : 'number'}
value={value === undefined || value === null ? '' : String(value)}
placeholder={field.description || ''}
onChange={(event) => {
const raw = event.target.value
const next: unknown =
field.type === 'string'
? raw
: raw === ''
? undefined
: Number(raw)
patchAt(index, { input: { ...input, [key]: next } })
}}
/>
)}
</label>
)
})}
</div>
)}
<div className="automation-extension-row-actions">
<Button size="sm" variant="ghost" onClick={() => removeAt(index)}>
移除
</Button>
</div>
</div>
</div>
)
})
)}
<div className="automation-extension-add">
<select
className="automation-select"
value={pendingExtension}
aria-label="选择扩展"
onChange={(event) => {
setPendingExtension(event.target.value)
setPendingAction('')
}}
>
<option value="">选择扩展…</option>
{groups.map(([extensionId, group]) => (
<option key={extensionId} value={extensionId}>
{group.name}
{group.actions.every((item) => !item.available) ? '(不可用)' : ''}
</option>
))}
</select>
<select
className="automation-select"
value={pendingAction}
aria-label="选择动作"
disabled={!pendingExtension}
onChange={(event) => setPendingAction(event.target.value)}
>
<option value="">选择动作…</option>
{actionsOfSelectedExtension.map((item) => (
<option key={item.actionId} value={item.actionId} disabled={!item.available}>
{item.title}
{item.available ? '' : `(${item.unavailableReason || '不可用'})`}
</option>
))}
</select>
<Button
size="sm"
variant="outline"
disabled={!pendingExtension || !pendingAction}
onClick={addAction}
>
添加扩展动作
</Button>
</div>
</div>
)
}
@@ -13,7 +13,9 @@ import {
} from '../../../../shared/automation'
import { Button, Input, SegmentedControl, SegmentedControlItem, Switch } from '../../components/ui'
import { EffectPreview } from './EffectPreview'
import { ExtensionActionList } from './ExtensionActionList'
import type { AutomationGroupOption } from './model/api'
import type { ExtensionActionInfo } from '../../../../shared/extensions/types'
/**
* RuleEditorPanel —— 规则编辑页(对应 Stitch 设计稿 1)。
@@ -90,19 +92,56 @@ export function RuleEditorPanel({
setValidationError('')
}, [rule])
/** 扩展动作列表:随扩展启用/停用自动刷新,规则里保存的引用不会被清掉。 */
const [extensionActions, setExtensionActions] = React.useState<ExtensionActionInfo[]>([])
React.useEffect(() => {
let active = true
const load = (): void => {
// 旧宿主或测试环境可能没有扩展 API:此时退化成「没有扩展动作」,
// 不能让整个规则编辑器崩掉。
const loader = window.api?.listExtensionActions
if (!loader) {
setExtensionActions([])
return
}
void Promise.resolve(loader.call(window.api))
.then((list) => {
if (active) setExtensionActions(Array.isArray(list) ? list : [])
})
.catch(() => undefined)
}
load()
const subscribe = window.api?.onExtensionChanged
const unsubscribe = subscribe ? subscribe.call(window.api, () => load()) : () => undefined
return () => {
active = false
unsubscribe()
}
}, [])
const patchConditions = (patch: Partial<AutomationRuleDraft['conditions']>): void => {
setDraft((current) => ({ ...current, conditions: { ...current.conditions, ...patch } }))
}
const patchAction = (type: AutomationActionType, patch: { enabled?: boolean; text?: string }): void => {
/**
* 按**索引**更新动作。
*
* 固定动作每类只有一条,但扩展动作可以有多条同类型:
* 按 `type` 批量更新会把它们一起改掉。
*/
const patchActionAt = (index: number, patch: { enabled?: boolean; text?: string }): void => {
if (index < 0) return
setDraft((current) => ({
...current,
actions: current.actions.map((action) =>
action.type === type ? { ...action, ...patch } : action
actions: current.actions.map((action, currentIndex) =>
currentIndex === index ? { ...action, ...patch } : action
)
}))
}
const indexOfType = (type: AutomationActionType): number =>
draft.actions.findIndex((action) => action.type === type)
const actionOf = (type: AutomationActionType): { enabled: boolean; text?: string } =>
draft.actions.find((action) => action.type === type) ?? { enabled: false }
@@ -268,7 +307,11 @@ export function RuleEditorPanel({
key={group.id}
className={`automation-group-option ${checked ? 'selected' : ''}`}
>
<input type="checkbox" checked={checked} onChange={() => toggleGroup(group.id)} />
<input
type="checkbox"
checked={checked}
onChange={() => toggleGroup(group.id)}
/>
<span>{group.name}</span>
</label>
)
@@ -305,9 +348,7 @@ export function RuleEditorPanel({
const next = Number(event.target.value)
setDraft((current) => ({
...current,
replyDelaySeconds: normalizeReplyDelaySeconds(
Number.isFinite(next) ? next : 0
)
replyDelaySeconds: normalizeReplyDelaySeconds(Number.isFinite(next) ? next : 0)
}))
}}
className="automation-number-input"
@@ -326,13 +367,17 @@ export function RuleEditorPanel({
</div>
<Switch
checked={action.enabled}
onCheckedChange={(checked) => patchAction(meta.type, { enabled: checked })}
onCheckedChange={(checked) =>
patchActionAt(indexOfType(meta.type), { enabled: checked })
}
/>
</div>
{meta.type === 'replyText' && action.enabled ? (
<Input
value={action.text ?? ''}
onChange={(event) => patchAction(meta.type, { text: event.target.value })}
onChange={(event) =>
patchActionAt(indexOfType(meta.type), { text: event.target.value })
}
placeholder={DEFAULT_REPLY_TEXT}
aria-label="回复内容"
/>
@@ -341,6 +386,18 @@ export function RuleEditorPanel({
</div>
)
})}
<div className="automation-subsection">
<div className="automation-subsection-heading">
<h4>执行扩展动作</h4>
<small>由扩展注册,参数按扩展声明的 Schema 填写</small>
</div>
<ExtensionActionList
actions={draft.actions}
available={extensionActions}
onChange={(next) => setDraft((current) => ({ ...current, actions: next }))}
/>
</div>
</section>
<section className="automation-section">
@@ -1,6 +1,5 @@
import * as React from 'react'
import {
AUTOMATION_RULE_TEMPLATES,
BUILTIN_LEAVE_NOTIFICATION_RULE_ID,
describeLeaveNotificationNotifyScope,
describeLeaveNotificationTarget,
@@ -8,6 +7,7 @@ import {
describeRuleTrigger,
type AutomationRule
} from '../../../../shared/automation'
import type { ExtensionDeepLink } from '../../../../shared/extensions/types'
import { Button, Spinner, Switch } from '../../components/ui'
/**
@@ -40,6 +40,25 @@ export interface ScheduledReportCardModel {
nextRunLabel: string
}
/**
* 规则模板卡片的本机状态。
*
* 由工作区根据「官方模板目录 + 已安装扩展 + 运行状态」算出,
* 面板只负责渲染,不自己判断可用性。
*/
export interface RuleTemplateCardModel {
id: string
name: string
description: string
templateId: string
extensionId: string
/** 没有动作的模板只能打开配置,不能「用规则触发」。 */
actionId?: string
state: 'not-installed' | 'installed-disabled' | 'ready' | 'unavailable'
/** 不可用/需要处理时的真实原因。 */
reason?: string
}
export interface RuleListPanelProps {
rules: AutomationRule[]
groups: Array<{ id: string; name: string }>
@@ -55,6 +74,12 @@ export interface RuleListPanelProps {
onEditLeaveNotification: () => void
/** 打开「定时日报」规则类型(多条,所以是"管理"而不是"编辑")。 */
onManageScheduledReport: () => void
/** 规则模板卡片(真实状态)。 */
ruleTemplates?: RuleTemplateCardModel[]
/** 跳到扩展中心并定位模板/扩展/开发引导。 */
onOpenExtension?: (target: ExtensionDeepLink) => void
/** 用该模板预填一条引用扩展动作的规则。 */
onUseRuleTemplate?: (template: RuleTemplateCardModel) => void
}
/** 把规则里的 conversationIds 翻成群名;找不到时显示占位而不是裸 id。 */
@@ -92,7 +117,10 @@ export function RuleListPanel({
onDelete,
onCreate,
onEditLeaveNotification,
onManageScheduledReport
onManageScheduledReport,
ruleTemplates,
onOpenExtension,
onUseRuleTemplate
}: RuleListPanelProps): React.ReactElement {
// 退群通知有自己的卡片,别在「已配置的自动化」里重复渲染一遍。
const configuredRules = rules.filter((rule) => rule.id !== BUILTIN_LEAVE_NOTIFICATION_RULE_ID)
@@ -267,16 +295,99 @@ export function RuleListPanel({
<h2>更多模板</h2>
</div>
<div className="automation-template-grid">
{AUTOMATION_RULE_TEMPLATES.map((template) => (
<article key={template.id} className="automation-template-card">
<div className="automation-template-title">
<h3>{template.name}</h3>
<span className="automation-template-flag">即将支持</span>
</div>
<p>{template.description}</p>
{template.unavailableReason ? <small>{template.unavailableReason}</small> : null}
</article>
))}
{(ruleTemplates ?? []).map((template) => {
const badge =
template.state === 'ready'
? '已就绪'
: template.state === 'installed-disabled'
? '已安装 · 未启用'
: template.state === 'not-installed'
? '未安装'
: '不可用'
return (
<article key={template.id} className="automation-template-card">
<div className="automation-template-title">
<h3>{template.name}</h3>
<span
className={
template.state === 'ready'
? 'automation-template-flag is-ready'
: 'automation-template-flag'
}
>
{badge}
</span>
</div>
<p>{template.description}</p>
{template.reason ? <small>{template.reason}</small> : null}
<div className="automation-template-actions">
{template.state === 'not-installed' && (
<Button
variant="outline"
size="sm"
onClick={() => onOpenExtension?.({ templateId: template.templateId })}
>
去扩展中心安装 →
</Button>
)}
{template.state === 'installed-disabled' && (
<Button
variant="outline"
size="sm"
onClick={() => onOpenExtension?.({ extensionId: template.extensionId })}
>
去启用 →
</Button>
)}
{template.state === 'ready' && (
<>
<Button
variant="outline"
size="sm"
onClick={() => onOpenExtension?.({ extensionId: template.extensionId })}
>
打开扩展配置 →
</Button>
{template.actionId ? (
<Button
variant="ghost"
size="sm"
onClick={() => onUseRuleTemplate?.(template)}
>
用规则触发
</Button>
) : (
<small className="automation-template-note">
该扩展没有注册自动化动作,靠消息事件触发
</small>
)}
</>
)}
</div>
</article>
)
})}
{/* 模板之外还要有出口:没有现成模板可用时,用户应该能自己做一个。 */}
<article className="automation-template-card is-guide">
<div className="automation-template-title">
<h3>做自己的扩展</h3>
</div>
<p>
从官方模板克隆一份代码,改完直接在本地调试;官方升级不会覆盖你的改动。 也可以链接已经
clone 到别处的项目。
</p>
<div className="automation-template-actions">
<Button
variant="outline"
size="sm"
onClick={() => onOpenExtension?.({ development: true })}
>
开始二次开发 →
</Button>
</div>
</article>
</div>
</section>
</div>
Loaded 100 of 165 files, more files were not shown because too many files have changed in this diff. Show more