Compare commits

..
8 Commits
Author SHA1 Message Date
电摇小子 e24e5fe6e8 Merge branch 'develop' 2026-09-29 18:18:02 +07:00
电摇小子 194dd0035b chore: 构建 2026-09-29 18:02:09 +07:00
电摇小子 c3629255ea chore: 更新二维码 2026-09-29 16:24:20 +07:00
电摇小子 345a0db49b chore: 提升版本 整理文档
整理档案首页按钮
2026-09-29 16:13:37 +07:00
电摇小子 5276bce060 chore: 打包配置 测试用例 2026-09-29 13:06:00 +07:00
电摇小子 0abbda1160 Merge branch 'develop_0920' into develop 2026-09-29 10:51:15 +07:00
qingmao 8503c92f3a Add files via upload 2026-09-22 09:49:09 +08:00
Wxw-Gu 9b82ca663b fix: 修复Windows语音消息取错 2026-09-21 00:33:02 +08:00
43 changed files with 1446 additions and 469 deletions
+30 -20
View File
@@ -25,16 +25,14 @@
</p>
<p align="center">
<img src="./public/日报.png" alt="TraceMemo 主界面" />
<img src="./public/日报.png" alt="TraceMemo 日报" />
</p>
<p align="center">
<img src="./public/问问微信.png" alt="TraceMemo 问问微信" />
<img src="./public/自动化.png" alt="TraceMemo 自动化" />
</p>
<p align="center">
<img src="./public/退群监控.png" alt="TraceMemo 退群监控" />
</p>
---
## 🎨 社区日报模板
@@ -49,7 +47,7 @@ TraceMemo 日报除了内置版式,也支持从社区模板市场安装更多
在 TraceMemo 中打开:
**日报 → 今日日报 → 日报模板 → 模板市场**
**日报 → 社区模板市场**
即可查看、预览、安装和切换已发布的社区模板。
@@ -67,18 +65,21 @@ TraceMemo(迹忆)原名 **WechatExplorer** 是一款本地优先的微信数
## 核心能力
- 💬 **聊天档案与搜索**:浏览会话,按关键词或身份信息查找。
- 💬 **聊天档案与搜索**:浏览会话,按关键词、备注、昵称或 wxid 查找消息。
- 🔍 **AI Search / 问问微信**:用自然语言找回模糊记忆,并查看来源。
- 🧠 **本地知识库**:建立索引,提升跨会话查询稳定性。
- 📊 **群聊日报**:生成今日、昨日或近 7 天的群聊总结。
- 👀 **群成员变化监控**:记录指定群聊的退群动态。
- 🔊 **文字转语音**:生成语音,试听后发送到选定会话。
- 🤖 **Agent Hub**:在微信里调用本机 TraceMemo。
- 🔌 **外部 Agent / Local HTTP API**:让外部 Agent 查询本机微信历史。
- 🧠 **本地知识库**:在本机建立索引,让跨会话、跨时间的查询更稳定。
- 🖼️ **图片文字索引**:在本机识别微信图片里的文字(截图、公告、报价图),识别结果可以在搜索和「问问微信」里被检索。识别全程不联网,原始图片不会因为本地识别而上传。
- 📊 **群聊日报**:生成今日、昨日或近 7 天的群聊总结,可保存为 HTML 与 PNG。
- 🗣️ **群发言统计**:统计群成员的发言量和沉默成员,看清一个群里谁在说、谁一直没说。
- 👀 **退群监控**:用成员快照对比记录群成员退出事件,支持多群与事件历史。
- ⚙️ **自动化**:把上面几步按规则串起来——定时生成并发送日报、成员退群时发送通知;能发到哪里取决于当前的发送能力。
- 🔊 **文字转语音**:把文字生成语音,试听后发送到当前会话。
- 🤖 **Agent Hub**:在微信里向本机 TraceMemo 提问。
- 🔌 **外部 Agent / Local HTTP API**:让 Codex 等外部 Agent 查询本机微信历史。
## 💻 平台支持
TraceMemo 2.4.0 支持:
TraceMemo 2.5.0 支持:
- **Windows x64**
- **macOS Apple Silicon(M 系列 / arm64)**
@@ -86,6 +87,12 @@ TraceMemo 2.4.0 支持:
Windows 与 macOS 均支持微信本地数据库连接与数据库 Key 获取。
### 关于“发送能力”
浏览、搜索、日报生成、导出、知识库和图片文字索引都不需要额外的发送组件。只有**把内容真正发回微信**这一步——自动发送日报、退群通知、把语音发到会话——依赖本机发送能力:
发送能力未就绪、未绑定或发送失败时,报告本身仍会正常生成并保存在本机,执行记录会显示为“已生成,但未发送”或“已生成,发送失败”,可以稍后重试。
## 项目缘起
<details>
@@ -138,11 +145,14 @@ TraceMemo 最早叫 **WechatExplorer**。
| 想做什么 | 使用入口 |
| ---------------------------------- | ----------------------------- |
| 找记得原文或关键词的消息 | 档案搜索 |
| 找记得大意、但不知道在哪聊过的内容 | AI Search / 问问微信 |
| 找记得大意、但不知道在哪聊过的内容 | 问问微信(AI Search) |
| 找到截图、公告图里写过的文字 | 问问微信 → 图片文字索引 |
| 长期跨群查询历史 | 本地知识库 |
| 了解一个群今天或近 7 天聊了什么 | 群聊日报 |
| 了解一个群今天或近 7 天聊了什么 | 日报 |
| 看群里谁最活跃、谁一直没说话 | 档案 → 群聊 → 群发言统计 |
| 持续关注群成员退出 | 退群监控 |
| 按计划生成并发送群聊日报 | 定时日报 |
| 按计划自动生成并发送群聊日报 | 自动化 |
| 成员退群时自动发一条通知 | 自动化 → 退群通知 |
| 把文字生成微信语音 | 文字转语音 |
| 在微信里向本机 TraceMemo 提问 | Agent Hub |
| 让 Codex 等工具查询微信历史 | Reader Skill / Local HTTP API |
@@ -159,9 +169,9 @@ TraceMemo 最早叫 **WechatExplorer**。
## 文档
- [用户指南](./docs/README.md#用户指南)
- [用户指南](./docs/README.md#档案与搜索)
- [AI / Knowledge](./docs/README.md#ai-与知识库)
- [Monitor / Automation](./docs/README.md#日报与自动化)
- [日报与自动化](./docs/README.md#日报与自动化)
- [Agent / API](./docs/README.md#agent--api)
- [开发文档](./docs/development/overview.md)
- [隐私与安全](./docs/user-guide/privacy.md)
@@ -213,7 +223,7 @@ TraceMemo 在早期适配微信 4.x 时,曾参考 **[WeFlow](https://github.co
这个项目起初只是一个一时兴起的项目,所以它大概也不会有一份特别严肃的产品路线图。
我可能会按照自己的兴趣继续折腾,也可能突然加入一些奇奇怪怪、但觉得有意思的功能—— 比如让AI给某个好友, 某个群发一个语音条(逗逗群友) 或者定时生成群聊日报并做成微信卡片。
我可能会按照自己的兴趣继续折腾,也可能突然加入一些奇奇怪怪、但觉得有意思的功能
也因此,这个项目随时可能继续折腾,也可能因为其他事情暂时搁置。如果你有想要的功能,可以提Issue;如果觉得现有实现不符合你的需求,也欢迎直接 Fork 后自己改。
+7 -7
View File
@@ -6,29 +6,29 @@
- [第一次使用](./user-guide/getting-started.md):安装、连接微信并完成第一次搜索。
- [Intel Mac 获取微信密钥](./user-guide/intel-mac-key.md):按页面检查结果准备环境并获取密钥。
- [聊天档案与搜索](./user-guide/chat-archive.md):浏览联系人和群聊,按关键词、备注、昵称、微信号或 wxid 查找消息;也包含档案中的文字转语音入口。
- [聊天档案与搜索](./user-guide/chat-archive.md):浏览联系人和群聊,按关键词、备注、昵称、微信号或 wxid 查找消息;也包含档案中的文字转语音入口,以及群聊里的「群发言统计」。
## AI 与知识库
- [AI Search / 问问微信](./user-guide/ai-search.md):用自然语言找回记得大意、但不知道在哪个会话里的内容,并查看 Evidence、Citation 和 Search Trace。
- [本地知识库](./user-guide/knowledge.md):主动建立本地索引,提升跨会话、跨时间查询的稳定性。
- [本地知识库](./user-guide/knowledge.md):主动建立本地索引,提升跨会话、跨时间查询的稳定性;也包括在本机识别图片文字、让截图和公告图变得可搜索的「图片文字索引」。
- [如何核对 AI 的回答来源](./concepts/answer-sources.md):从来源回到原始消息,检查上下文和覆盖范围。
- [从微信数据到回答、日报和导出](./concepts/how-it-works.md):了解哪些步骤在本机完成,哪些 AI 功能可能调用 Provider。
## 日报与自动化
- [群聊日报](./user-guide/report.md):手动生成今日、昨日或近 7 天的群聊报告,也可以创建定时日报。
- 定时日报会依次生成报告、保存 Report History,再按当前微信发送能力尝试通知;发送失败时可复用已有 PNG 重试。
- [群聊日报](./user-guide/report.md):手动生成今日、昨日或近 7 天的群聊报告,也可以在「自动化」里创建定时日报。
- 「自动化」按三类规则执行:**@我生成日报**、**定时日报**、**退群通知**。定时日报会依次生成报告、保存 Report History,再按当前微信发送能力尝试通知;发送失败时可复用已有 PNG 重试。
- 自动发送和监控动作通过统一执行边界,并保留执行记录;简要说明见[产品工作方式](./concepts/how-it-works.md#动作执行与审计)。
## Monitor
## 退群监控
退群监控会比较当前成员与上一份有效快照,记录成员退出事件。它支持多群、Last Good Snapshot 和事件历史;监控关闭期间的变化不会在重新开启后补报。工作方式见[产品工作方式](./concepts/how-it-works.md#退群监控)。
退群监控会比较当前成员与上一份有效快照,记录成员退出事件。它支持多群、Last Good Snapshot 和事件历史;监控关闭期间的变化不会在重新开启后补报。成员退出同时是「自动化 → 退群通知」的触发条件。工作方式见[产品工作方式](./concepts/how-it-works.md#退群监控)。
## 语音能力
- [语音转文字](./user-guide/voice.md):在本机转写微信语音,结果可用于搜索、Knowledge 和导出。
- [聊天档案与搜索](./user-guide/chat-archive.md#文字转语音):把文字生成微信语音,试听后发送到当前联系人或群聊。
- [聊天档案与搜索](./user-guide/chat-archive.md#文字转语音):把文字生成微信语音,试听后发送到当前联系人或群聊;实际发送依赖本机发送能力。
## Agent / API
+12 -11
View File
@@ -21,14 +21,15 @@ Agent Hub 是 TraceMemo 内置的微信机器人入口,也是应用一级导
- “帮我看看最近跟某人聊了些什么。”
- “生成产品交流群今天的群聊总结图片。”
当前已实现的实时任务包括:
Hub 把入站文字分成两类处理。
- 查看最近会话(数量限制为 1–20);
- 查询你和某位联系人的近期聊天;
- 用已配置的 AI 总结你和某位联系人近 7 天的聊天;
- 生成今天、昨天或近 7 天的群聊总结图片;
- 总结指定群成员在群里的近期发言;
- 对不需要读取聊天的普通文字请求返回简短 AI 回复。
**确定性的快捷动作**(不经过模型,命中就执行):
- 查看最近会话:数量限制为 1–20;
- 生成群聊总结图片:今天、昨天或近 7 天(需要同时提到“群”和“图片 / 长图 / 日报 / 报告”);
- 分析某个群成员的近期发言:可以指定“今天 / 昨天 / 最近 N 天”。
**其余问题**交给本机的 Query Agent:它和桌面端“问问微信”使用的是同一个实现,可以按需读取联系人、会话和时间范围来回答,必要时调用你在“设置 → AI 模型”里配置的 AI。例如“帮我看看最近跟某人聊了些什么”“上个月讨论过的项目地址在哪里”。
任务完成后,回复会发送回触发这次请求的微信用户。群聊总结会先发送进度提示,完成后发送图片。
@@ -56,12 +57,12 @@ Agent Hub 页面会记录系统、Agent Hub 和微信连接器日志。日志支
## 安全与边界
- Hub 使用本机通信,不把数据库直接暴露到公网;
- Hub 在主进程内运行,不开放本地监听端口;它不会把数据库暴露到公网;
- 机器人账号和个人微信账号是不同的登录边界,请确认你连接的是正确账号;
- 机器人回复会发送给当前发消息的人;开发者 API 另有受保护的测试发送入口,使用前必须确认接收者;
- Hub 生成群聊总结时仍可能调用你配置的 AI Provider;
- 当前实时自然语言入口主要处理文字消息。底层连接器可以接收图片、语音、文件和视频,但 Agent Hub 尚未为这些媒体提供同等的实时意图处理;
- 当前没有实现群发、广播、定时任务或通用自主操作微信;
- Hub 理解请求或生成总结时,会调用你在“设置 → AI 模型”配置的 Provider;
- 当前实时入口只处理文字消息。连接器会归一化收到的消息条目,但 Agent Hub 只把文本条目当作意图处理,尚未为图片、语音、文件和视频提供同等能力;
- 当前没有实现群发、广播、定时任务或通用自主操作微信(定时日报属于「自动化」,不是 Agent Hub);
- 本页面的“Agent Hub 状态”可以通过 Local HTTP API 查询,但不要把它误认为外部 Agent 的实时消息订阅接口或 MCP Server。
## 无法连接时
+5 -2
View File
@@ -4,9 +4,11 @@
TraceMemo 的本地 API 默认监听 `127.0.0.1:6131`。它面向同一台电脑上的 API Center、Reader Skill、CLI 和 Agent,不是公网网关,也不是带用户账户和细粒度权限 Scope 的服务。
它同时包含**写入型**端点:生成报告并渲染 PNG(`/report`)、通过已连接机器人发送微信消息(`/agent/send`)、创建/修改/删除/启停定时日报任务并触发立即执行(`/scheduled-reports*`)。因此这个 Token 相当于本机敏感凭据,而不是一个只读查询键。
## Bearer Token
新 Agent 配置使用 `TRACEMEMO_API_TOKEN`。v2.2.0 仍兼容读取历史变量 `WECHATEXPLORER_API_TOKEN`,优先级为新变量高于旧变量。
新 Agent 配置使用 `TRACEMEMO_API_TOKEN`。历史变量名 `WECHATEXPLORER_API_TOKEN` 仍被兼容读取,优先级为新变量高于旧变量;当前没有设定旧变量名的移除时间,新配置不要再使用它。
- `/api/v1/health` 是公开健康检查;
- 其他所有端点都要求 `Authorization: Bearer <TOKEN>`;
@@ -14,7 +16,8 @@ TraceMemo 的本地 API 默认监听 `127.0.0.1:6131`。它面向同一台电脑
- Token 由 Electron `safeStorage` 加密保存在用户数据目录的 `local-api-token.bin`;
- 文件权限设置为 `0600`;
- 在“API Center”中可以显示、复制和重新生成;
- 重新生成后旧 Token 立即失效。
- 重新生成后旧 Token 立即失效;
- 服务端只认这个 Token,**不接受用环境变量覆盖**——Agent 一侧的环境变量只是把 Token 交给 Agent 自己的方式,不是鉴权来源。
应用不会自动把 Token 写入 Codex、Claude Code、OpenClaw 或其他 Agent 配置。请把它放进 Agent 自己的本地 secret/environment,例如:
+23 -4
View File
@@ -24,12 +24,14 @@ curl -H "Authorization: Bearer $TRACEMEMO_API_TOKEN" \
不要把 Token 放入 URL、Skill 文件、仓库或命令历史可被共享的脚本中。
新配置必须优先使用 `TRACEMEMO_API_TOKEN`。已安装的旧 Reader Skill 可在 v2.2.0 兼容期内继续读取 `WECHATEXPLORER_API_TOKEN`;如果两个变量都存在,以新变量为准。
新配置必须优先使用 `TRACEMEMO_API_TOKEN`。应用生成的安装指令仍会提示:尚未升级的旧配置可以继续读取 `WECHATEXPLORER_API_TOKEN`,但新配置必须使用新变量名;如果两个变量都存在,以新变量为准。当前没有设定旧变量名的移除时间。
Token 由应用生成并保存在本机,**不接受用环境变量覆盖**:Agent 侧的环境变量只是把 Token 传给 Agent 自己的方式,不是服务端的鉴权来源。
## 端点
| 方法 | 路径 | 作用 | 参数/请求体 |
| ---- | ---------------------------- | -------------------------------------- | --------------------------------------------------------------- |
| ------ | --------------------------------------------------------------- | -------------------------------------- | --------------------------------------------------------------- |
| GET | `/api/v1/health` | 服务与数据库健康状态 | 无 |
| GET | `/api/v1/current_time` | 本机时间、时区和 Unix 时间戳 | 无 |
| GET | `/api/v1/contact` | 联系人和群聊列表 | `filter`、`type=user\|group` |
@@ -43,12 +45,27 @@ curl -H "Authorization: Bearer $TRACEMEMO_API_TOKEN" \
| GET | `/api/v1/agent/status` | Agent Hub、连接器和数据库状态 | 无 |
| POST | `/api/v1/agent/group-report` | 读取群聊并生成总结图片 | `{ "group": "群名或标识", "range": "today\|yesterday\|7days" }` |
| POST | `/api/v1/agent/send` | 通过已连接机器人测试发送文字或本地图片 | `{ "to": "接收者", "text": "...", "media_url": "..." }` |
| GET | `/api/v1/wechat-personal/send-capability` | 个人微信发送能力状态 | 无 |
| GET | `/api/v1/scheduled-reports` | 定时日报任务列表 | 无 |
| POST | `/api/v1/scheduled-reports` | 创建定时日报任务 | `ScheduledReportApiCreateRequest` JSON |
| GET | `/api/v1/scheduled-reports/{id}` | 查询单个定时日报任务 | 无 |
| PATCH | `/api/v1/scheduled-reports/{id}` | 修改定时日报任务 | `ScheduledReportApiUpdateRequest` JSON |
| DELETE | `/api/v1/scheduled-reports/{id}` | 删除定时日报任务 | 无 |
| POST | `/api/v1/scheduled-reports/{id}/enable` | 启用定时日报任务 | 无 |
| POST | `/api/v1/scheduled-reports/{id}/disable` | 暂停定时日报任务 | 无 |
| POST | `/api/v1/scheduled-reports/{id}/run` | 立即执行一次并返回 execution | 无 |
| GET | `/api/v1/scheduled-reports/{id}/executions` | 查询某个任务的执行记录 | 无 |
| POST | `/api/v1/scheduled-reports/executions/{executionId}/retry-send` | 复用已有 PNG 重试发送 | 无 |
`/api/v1/query/*` 是一组结构化的 Query 端点,见下方[LLM-friendly Query Tool API](#llm-friendly-query-tool-api)。
### 这些端点与实时机器人有什么关系
- `/api/v1/agent/status` 只用于查询 Agent Hub、微信连接器和数据库状态;
- `/api/v1/agent/group-report` 由外部 Agent 或脚本主动请求生成群聊总结图片;
- `/api/v1/agent/send` 是受 Bearer Token 保护的开发者/测试发送入口,用于通过已经连接的机器人发送文字或本地图片;它不是任意群发能力,也不是实时消息订阅接口;
- `/api/v1/scheduled-reports*` 会**写入**应用状态:创建、修改、删除、启停定时日报任务,以及立刻执行一次。加上 `/report` 和 `/agent/send`,这个 API 并非只读接口——拿到 Token 就能改配置、生成报告并发送微信消息,请按本机敏感凭据对待;
- `POST /api/v1/scheduled-reports/{id}/run` 与定时触发共用同一条链路:读取群聊 → 生成报告 → 保存 Report History → 尝试发送;
- 当前 API 没有对外暴露实时入站 webhook。微信消息由应用内部的 Agent Hub 和微信连接器接收、处理和回复。
## 时间查询
@@ -83,10 +100,12 @@ curl -H "$AUTH" "$BASE/chatlog?talker=技术交流群&time=2026-08-07"
## 响应与错误
- `200`:请求成功;
- `201`:定时日报任务创建成功;
- `401`:缺少、错误或已失效的 Bearer Token;
- `400`:参数或 JSON 请求体无效;
- `422`:媒体标识格式错误,或目标消息不是可读取的图片(`NOT_IMAGE`);
- `403`:浏览器 Origin 不在允许的 loopback 列表;
- `409`:定时日报任务重复(`error === "duplicate"`,响应里会带回已存在的任务),或群聊名称匹配到多个目标(`ambiguous_contact`);
- `404`:端点、会话或群聊不存在;媒体标识未登记、已过期、有歧义,或图片文件不存在(`NOT_FOUND`)。媒体请求遇到此状态时,先重新读取 `/chatlog` 并使用新的 `media.url`;若仍失败,再检查本地图片文件是否存在;
- `503`:数据库或 Agent Hub 尚未就绪;
- `500`:服务端处理或报告渲染失败。
@@ -155,7 +174,7 @@ curl -X POST -H "$AUTH" -H 'Content-Type: application/json' "$BASE/query/convers
`query/messages`、`query/search`、`query/message-context` 和 `query/conversation-overview` 都接受一个可选的 `scope`,用来把检索限制在一个确定的语料边界内:
| scope | 含义 |
| ----- | ---- |
| ----------------------------------------- | -------------------------------------------------------------------- |
| `{"kind":"all"}` | 所有可读会话(默认;省略 `scope` 等价于此) |
| `{"kind":"groups"}` | 只搜群聊语料,**且包含群成员实际发送的消息**(不是群名称或群元数据) |
| `{"kind":"contact","conversationId":"…"}` | 只搜该一对一会话 |
@@ -187,7 +206,7 @@ curl -X POST -H "$AUTH" -H 'Content-Type: application/json' "$BASE/query/convers
`query/search` 依赖本地索引,而本地索引是异步建立的派生数据,可能落后于聊天数据库。因此它的响应会显式给出覆盖口径:
| 字段 | 含义 |
| ---- | ---- |
| ------------------- | ------------------------------------------------------------------- |
| `indexLatestAt` | 索引目前覆盖到的源数据时间(epoch ms),`null` 表示无法判定 |
| `sourceLatestAt` | 聊天数据库里最新的活跃时间(epoch ms),`null` 表示无法判定 |
| `coverage.state` | `complete` 只在索引确实覆盖了所请求的时间范围时出现 |
+6 -1
View File
@@ -8,7 +8,7 @@ Reader Skill 是一份给 Agent 的操作说明。安装后,Codex、Claude Cod
Reader Skill 只负责“外部 Agent 主动查询历史微信数据”。它不负责二维码登录、监听微信实时消息、接收机器人消息或管理 Agent Hub。想让机器人收到微信消息后处理并回复,请阅读[Agent Hub](./agent-hub.md)。
正式 Reader Skill 名称和目录是 `tracememo-reader`,新安装使用 `TRACEMEMO_API_TOKEN`。已安装的旧 `wechatexplorer-reader` 可在 v2.2.0 兼容期内继续使用旧变量。
正式 Reader Skill 名称和目录是 `tracememo-reader`,新安装使用 `TRACEMEMO_API_TOKEN`。已安装的旧 `wechatexplorer-reader` 仍可继续使用旧变量 `WECHATEXPLORER_API_TOKEN`(当前没有设定移除时间),但新安装请使用新名称与新变量名。
## 推荐安装流程
@@ -53,8 +53,13 @@ Reader Skill 可以指导 Agent 使用:
- 指定会话、日期或时间戳范围的聊天记录;
- 群成员快照;
- 结构化日报渲染和按群聊生成总结图片;
- 定时日报任务的查询、创建、修改、启停、删除、立即执行和执行记录;删除不可逆,Skill 要求先列出唯一任务并取得用户明确确认;
- 个人微信发送能力状态查询(`/wechat-personal/send-capability`);
- `query/*` 一组结构化 Query 端点:`messages`、`search`、`message-context`、`conversation-overview`;
- Agent Hub 状态检查与已连接机器人发送测试。这里的发送接口是开发者/测试用途,不是实时机器人入口,也不会让 Reader Skill 自动监听微信消息。
注意这个 API 不只是只读的:`/report`、`/agent/send` 和 `/scheduled-reports*` 会写入状态或真的发出微信消息。
端点、参数、错误码和鉴权细节以[Local HTTP API](./api.md)为准。Skill 文件保持短小,避免在多个文档中复制会变化的完整响应 schema。
## 隐私边界
+50 -28
View File
@@ -4,39 +4,54 @@
```mermaid
flowchart LR
A[本机微信数据] --> B[读取与解析]
B --> C[聊天档案与普通搜索]
B --> D[本地知识索引]
D --> E[筛选相关消息]
E --> F[用户配置的 AI Provider]
F --> G[回答与可核对来源]
B --> H[聊天导出]
B --> I[整理日报输入]
I --> F
F --> J[本地保存 HTML 与 PNG]
B --> K[Local HTTP API]
K --> L[外部 Agent]
M[微信机器人消息] --> N[Agent Hub]
N --> B
N --> F
B --> O[Monitor / Snapshot]
O --> P[Proposed Action]
F --> P
P --> Q[Policy]
Q --> R[Action Gateway]
R --> S[Personal WeChat Send Capability]
S --> T[Action Audit / Logs]
WX["本机微信数据"] --> PARSE["读取与解析"]
PARSE --> ARCHIVE["聊天档案与普通搜索"]
PARSE --> EXPORT["聊天导出"]
PARSE --> IDX["本机索引"]
IDX --> TEXTIDX["聊天记录索引"]
IDX --> IMGIDX["图片文字索引(本机识别)"]
TEXTIDX --> UNDERSTAND["Understand:AI Search / 问问微信"]
IMGIDX --> UNDERSTAND
UNDERSTAND --> PROVIDER["你配置的 AI Provider"]
PROVIDER --> ANSWER["回答与可核对来源"]
PARSE --> REPORTINPUT["整理日报输入"]
REPORTINPUT --> PROVIDER
PROVIDER --> REPORTFILE["本机保存 HTML 与 PNG"]
PARSE --> MONITOR["Monitor:退群监控 / 成员快照"]
MONITOR --> RULE["自动化规则"]
REPORTFILE --> RULE
RULE --> POLICY["Policy"]
POLICY --> GATEWAY["Action Gateway"]
GATEWAY --> CAP["本机发送能力"]
CAP --> AUDIT["执行记录与审计"]
PARSE --> API["Local HTTP API"]
API --> EXTAGENT["外部 Agent / Reader Skill"]
BOT["微信机器人消息"] --> HUB["Agent Hub"]
HUB --> PARSE
HUB --> PROVIDER
```
## Remember → Understand → Monitor → Act
## Remember → 图片文字 → Understand → Monitor → Act
TraceMemo 的工作方式可以概括为:
```text
Remember → Understand → Monitor → Act
Remember → 图片文字 → Understand → Monitor → Act
```
先读取和整理微信信息,再由 AI、Knowledge 或日报帮助理解;Monitor 负责发现成员变化,明确的业务动作再进入执行边界。回答和动作结果都应能回到来源或记录核对。
- **Remember**:读取并解析本机微信数据,建立聊天档案、普通搜索和导出。
- **图片文字**:在本机识别图片里的文字,把截图、公告、报价图也变成可检索的内容。这一步不联网。
- **Understand**:Knowledge、AI Search / 问问微信、群聊日报。需要模型时,只把完成这次任务所需的受控上下文交给 Provider。
- **Monitor**:用成员快照对比发现群成员变化,产出成员退出事件。
- **Act**:自动化规则把前面的步骤串起来(定时日报、退群通知);动作经过统一执行边界,并留下执行记录。
回答和动作结果都应能回到来源或记录核对。
## 退群监控
@@ -46,7 +61,9 @@ Remember → Understand → Monitor → Act
Current Membership → Snapshot Diff → Member Event
```
上一份有效快照(Last Good Snapshot)不会被不完整读取覆盖,因此重启后仍可继续监控通知。
上一份有效快照(Last Good Snapshot)不会被不完整读取覆盖,因此重启后仍可继续监控通知。监控关闭期间发生的变化,不会在重新开启后补报。
成员退出事件同时是「自动化」里「退群通知」规则的触发条件。
## 动作执行与审计
@@ -58,17 +75,20 @@ Feature → Policy → Gateway → Capability → Execution → Audit
Policy blocked 表示策略不允许,Capability unavailable 表示当前发送能力不可用,Send failed 表示已经尝试但执行失败。Action Audit / Logs 会保留执行结果;定时日报即使发送失败,也会保留已生成的报告记录。
这些动作统一由「自动化」管理,当前有三类规则:**@我生成日报**、**定时日报**、**退群通知**。发送目标支持当前群聊、文件传输助手、自己、指定好友,不是任意群发。
## 哪些步骤在本机
- 微信数据库读取与解析;
- 聊天档案浏览和普通搜索;
- Knowledge 索引与增量同步;
- 图片文字索引:识别图片中的文字完全在本机进行,原始图片不会因为本地识别而上传;
- 离线语音转写;
- 聊天导出文件、日报 HTML/PNG 和本地历史记录的保存。
## 哪些步骤可能调用外部服务
当你主动使用 AI Search、群聊日报或图片理解时,应用会把完成任务所需的受控问题和上下文发送给你配置的 Provider。它不会因为打开软件就自动上传完整数据库。
当你主动使用 AI Search、群聊日报或图片理解时,应用会把完成任务所需的受控问题和上下文发送给你配置的 Provider。它不会因为打开软件就自动上传完整数据库,本机 OCR、离线语音转写和普通搜索也不会触发外发。
Agent Hub 收到微信机器人的文字后,也可能为了理解请求或生成总结调用已配置的 Provider。Reader Skill 调用的是本机 API;外部 Agent 是否把读取结果继续交给云端模型,取决于外部 Agent 自己的配置。
@@ -77,11 +97,13 @@ Agent Hub 收到微信机器人的文字后,也可能为了理解请求或生
## 产品名词和用户任务的对应关系
| 用户想做什么 | 产品中可能看到的名称 |
| ------------------------ | ---------------------------- |
| ------------------------------ | ---------------------------- |
| 让 AI 找相关聊天 | AI Search、Retrieval |
| 让答案能回到原消息 | Evidence、Citation |
| 查看 AI 查找过程 | Search Trace |
| 让跨会话查找更稳定 | Knowledge、FTS 索引 |
| 搜到截图、公告图里写过的文字 | 图片文字索引、本机 OCR |
| 让日报、退群通知按规则自动执行 | 自动化、Policy、执行记录 |
| 让外部 Agent 读取聊天 | Reader Skill、Local HTTP API |
| 让微信机器人调用本机能力 | Agent Hub |
+14 -4
View File
@@ -34,24 +34,34 @@ pnpm test:e2e:build
## 代码变更对应文档
| 代码区域 | 需要同步检查的文档 |
| --------------------------------------------------------- | ------------------------------------------------------- |
| ------------------------------------------------------------------------ | ------------------------------------------------------------------------------ |
| `src/shared/ai-search.ts`、AI Search pipeline | `user-guide/ai-search.md`、`concepts/answer-sources.md` |
| `src/shared/knowledge.ts`、`src/main/knowledge/` | `user-guide/knowledge.md`、`concepts/how-it-works.md` |
| `src/shared/voice-recognition.ts` | `user-guide/voice.md` |
| `src/shared/group-report.ts`、报告 UI | `user-guide/report.md`、API/Agent 文档 |
| `src/shared/export.ts`、导出服务/UI | `user-guide/export.md` |
| `src/main/services/recall-archive-service.ts` | `user-guide/privacy.md` |
| `src/main/services/system-ocr-service.ts`、`image-text-index-service.ts` | `user-guide/knowledge.md`、`concepts/how-it-works.md`、`user-guide/privacy.md` |
| `src/main/services/image-insight-service.ts`、AI Provider | `user-guide/report.md`、`user-guide/privacy.md` |
| `src/shared/automation.ts`、自动化服务与执行网关 | `user-guide/report.md`、`concepts/how-it-works.md`、`docs/README.md` |
| `src/shared/local-api-test.ts`、`src/main/http-server.ts` | `agent/api.md`、`api-security.md`、打包 Skill |
| Agent Hub service/UI | `agent/agent-hub.md`、`user-guide/privacy.md` |
| 设置导航、连接页面 | `user-guide/getting-started.md`、`docs/README.md` |
两条容易被写错的边界:
- **防撤回已下线**(`src/main/services/recall-archive-service.ts` 保留但不再启动):设置入口隐藏,`recallProtectionEnabled` 在所有读写路径上被强制收敛为 `false`。不要把它写回用户指南。
- **图片文字索引(本机 OCR)与图片理解(需要 Provider)是两条不同的路径**:前者写入本地索引、能被搜索,且不联网;后者只在日报和设置里的模型检测中使用。改其中一条时不要把另一条的隐私口径带过去。
## 文档检查
提交文档变更前至少执行:
```bash
git diff --check
rg -n "v2\.1\.7|TraceMemo|迹忆|mcpServers|无鉴权" README.md docs --glob '*.md' --glob '!development/overview.md'
# 过时版本号、旧品牌名、旧结构叙述、MCP 误解
rg -n "v2\.1\.7|2\.4\.0|v2\.2\.0 兼容期|无鉴权|mcpServers" README.md docs --glob '*.md' --glob '!development/overview.md'
# 不存在的产品结构(定时日报已并入自动化)
rg -n "日报 → 定时日报|Monitor / Automation" README.md docs --glob '*.md'
```
历史迁移说明可以出现旧版本号;正式使用指南不要把过时版本写成当前版本。负向澄清“6131 不是 MCP Server”可以保留,以防用户照抄错误配置。
历史迁移说明可以出现旧版本号;正式使用指南不要把过时版本写成当前版本。负向澄清“6131 不是 MCP Server”可以保留,以防用户照抄错误配置。发版前额外确认 `README.md` 里的版本号与 `package.json` 的 `version` 一致。
+27 -5
View File
@@ -1,6 +1,6 @@
---
name: tracememo-reader
description: 通过 TraceMemo 本地 HTTP API 按需读取用户有权访问的微信聊天数据和图片媒体。当用户要求查看微信消息、查找联系人或群聊、总结聊天、查看或理解图片、生成群聊总结时使用。此 Skill 由本机 TraceMemo 提供数据,不是 MCP Server。
description: 通过 TraceMemo 本地 HTTP API 按需读取用户有权访问的微信聊天数据和图片媒体,并管理定时日报任务。当用户要求查看微信消息、查找联系人或群聊、总结聊天、查看或理解图片、生成群聊总结、查询或修改定时日报时使用。此 Skill 由本机 TraceMemo 提供数据,不是 MCP Server。
---
# TraceMemo Reader
@@ -28,7 +28,7 @@ description: 通过 TraceMemo 本地 HTTP API 按需读取用户有权访问的
## 端点速查
| 方法 | 路径 | 用途 |
| ------ | ----------------------------------- | ------------------------------------------------- |
| ------ | ------------------------------------------------------- | ------------------------------------------------- |
| GET | `/health` | 健康和数据库状态 |
| GET | `/current_time` | 本机时间与时区 |
| GET | `/contact` | 联系人/群聊列表;可传 `filter`、`type` |
@@ -38,7 +38,12 @@ description: 通过 TraceMemo 本地 HTTP API 按需读取用户有权访问的
| GET | `/media/{mediaId}` | 按消息返回的 `media.url` 获取图片二进制资源 |
| GET | `/group_snapshot` | 群成员快照;必填 `md5` |
| GET | `/resolve` | 昵称、wxid、md5 解析;必填 `q` |
| GET | `/wechat-personal/send-capability` | 个人微信图片发送能力状态 |
| POST | `/query/messages` | 按目标与时间范围取消息(结构化,不调用 AI) |
| POST | `/query/search` | 受限语义关键词检索(依赖本地索引,见 freshness) |
| POST | `/query/message-context` | 用 `messageRef` 取某条消息的前后文 |
| POST | `/query/conversation-overview` | 按会话与时间范围提取可总结的证据 |
| GET | `/query/capabilities` | Query 端点能力目录 |
| GET | `/wechat-personal/send-capability` | 个人微信发送能力状态(文字 / 图片 / 语音) |
| GET | `/scheduled-reports` | 查询全部定时日报任务 |
| GET | `/scheduled-reports/:id` | 查询单个定时日报任务 |
| POST | `/scheduled-reports` | 创建定时日报任务 |
@@ -48,10 +53,13 @@ description: 通过 TraceMemo 本地 HTTP API 按需读取用户有权访问的
| POST | `/scheduled-reports/:id/disable` | 暂停定时日报任务 |
| POST | `/scheduled-reports/:id/run` | 立即执行一次并返回 execution |
| GET | `/scheduled-reports/:id/executions` | 查询执行记录 |
| POST | `/scheduled-reports/executions/:executionId/retry-send` | 复用已有 PNG 重试发送 |
| POST | `/report` | 将已有日报结构渲染为 HTML/PNG |
| GET | `/agent/status` | Agent Hub、连接器和数据库状态 |
| POST | `/agent/group-report` | 按群和 `today`/`yesterday`/`7days` 生成总结图片 |
| POST | `/agent/send` | 已连接机器人发送测试 |
| POST | `/agent/send` | 已连接机器人发送测试(文字或本地图片) |
这个 API **不只是只读的**:`/report` 会渲染并写文件,`/agent/send` 会真的发出微信消息,`/scheduled-reports*` 会创建、修改、删除或立刻执行定时任务。这些调用都要先确认用户意图;`DELETE` 与 `/agent/send` 尤其需要用户明确确认。
## 定时日报管理
@@ -78,7 +86,7 @@ description: 通过 TraceMemo 本地 HTTP API 按需读取用户有权访问的
}
```
如果 API 返回 `409` 且 `error === "duplicate"`,告诉用户相同任务已经存在,不要再次创建。能力状态为 `unsupported`、`unconfigured`、`needs_binding`、`needs_verification` 或 `error` 时,直接说明需要先在 TraceMemo 设置中完成个人微信绑定和消息能力检测。
如果 API 返回 `409` 且 `error === "duplicate"`,告诉用户相同任务已经存在,不要再次创建。能力状态不是 `ready` 时(`unsupported`、`unconfigured`、`needs_binding`、`initializing` 或 `error`),直接说明需要先在 TraceMemo 的“设置 → 发送能力”里完成个人微信绑定和能力检测,不要继续创建任务。
### 查看、修改和执行
@@ -102,6 +110,20 @@ description: 通过 TraceMemo 本地 HTTP API 按需读取用户有权访问的
- 根据多条消息整理出的总结;
- 没有来源支持的推断。
## 结构化查询(query/\*)
需要按目标 + 时间范围稳定取数时,优先使用 `query/*`,而不是自己拼 `chatlog`:
- `query/messages`:按 `target`、`timeRange`、`direction`、`messageTypes` 取消息;
- `query/search`:受限语义关键词检索,依赖本地索引;
- `query/message-context`:用返回的 `messageRef` 取前后文;
- `query/conversation-overview`:按会话与时间范围提取可总结的证据。
两个要点:
- `messageRef` 是服务端生成的不透明引用,**不要**自行构造 wxid、md5 或数据库路径;
- `query/search` 依赖异步建立的本地索引。`coverage.state` 不是 `complete` 且 `evidence` 为空时,只能说“这段范围暂时无法确认”,**不能**下“没有找到”的结论。
## 媒体消息
当 `/chatlog` 返回图片消息时:
+7 -3
View File
@@ -33,7 +33,7 @@ Apple Silicon 和 Intel 均已适配微信 macOS `4.1.13` 系列。首次获取
- 上表中的版本是当前 TraceMemo 已适配或推荐使用的版本,并不代表只有这些版本可以运行。
- TraceMemo 必须取得当前微信账号对应的数据库密钥,才能读取聊天记录。
- 你需要有权访问要读取的微信账号和聊天数据。
- 如果要使用 AI 问答、群聊日报或图片理解,还需要在应用中配置一个 AI 服务。
- 如果要使用 AI 问答、群聊日报或图片理解,还需要在应用中配置一个 AI 服务。「图片文字索引」不在此列——它在本机识别图片里的文字,不需要配置 AI。
当前代码按微信 4.x 数据结构处理。不同微信客户端版本、系统权限和数据迁移状态可能影响自动连接;遇到问题时请查看[常见问题与排查](./troubleshooting.md)。
@@ -134,6 +134,7 @@ Apple Silicon 和 Intel 均已适配微信 macOS `4.1.13` 系列。首次获取
- [生成群聊日报或总结](./report.md)
- [转写微信语音](./voice.md)
- [导出聊天档案](./export.md)
- [让日报、退群通知按规则自动运行](../README.md#日报与自动化)
- [在微信里向 TraceMemo 提问](../agent/agent-hub.md)
- [让外部 Agent 查询微信历史](../agent/overview.md)
@@ -159,14 +160,17 @@ Agent Hub 是普通用户可以直接使用的入口,不需要安装 Reader Sk
## 8. 需要配置 AI 吗?
不一定。浏览聊天、普通关键词搜索、建立本地知识库和导出不要求在线 AI 服务。
不一定。浏览聊天、普通关键词搜索、建立本地知识库、图片文字识别、离线语音转写和导出都不要求在线 AI 服务。
使用“问问微信”、群聊日报或图片理解时,需要在“设置 → AI 模型”中添加并测试 AI 服务。你主动开始并确认远程 AI 功能后,完成任务所需的内容才可能发送给该服务;计费、留存和地区规则由对应服务商决定。
这两种情况容易混淆:**本机识别图片里的文字**(图片文字索引)不联网、不需要 AI 服务;**让模型看图并回答**(图片理解)才需要配置 AI 服务。
## 9. 数据和隐私的最低须知
- 微信数据库、聊天解析和本地索引默认留在本机。
- 微信数据库、聊天解析、本地索引和图片文字识别默认留在本机。
- 离线语音转写使用本地模型;它与在线 AI 请求是两条不同的数据路径。
- 图片文字索引只在本机识别,原始图片不会因为本地识别而上传;识别出的文字会进入本地索引,供搜索和“问问微信”使用。
- 你主动开始并确认 AI 问答或日报后,完成任务所需的受控上下文才可能发送给你选择的 AI 服务;打开应用不会自动上传全部聊天。
- 应用内 Local HTTP API 默认只监听 `127.0.0.1:6131`,受保护接口需要 Token。
+16 -2
View File
@@ -25,7 +25,7 @@ Knowledge 不会在第一次连接后自动悄悄建立。进入“问问微信
### 状态怎么读
| 状态 | 含义 |
| ---- | ---- |
| ------------------- | ------------------------------------------------ |
| 可用 · 已追至最新 | 索引已覆盖到聊天记录的最新位置,可以直接用 |
| 可用 · 正在追新 | 索引可用,正在后台补充最近新增的消息 |
| 可用 · 正在补齐历史 | 索引可用,正在后台补齐较早的历史内容 |
@@ -38,6 +38,21 @@ Knowledge 不会在第一次连接后自动悄悄建立。进入“问问微信
同步过程中可以点击 **取消同步**(点击后显示“正在取消…”)。取消只结束当前这一轮,不会删除已经建立的索引,也不会回滚已完成的部分;下次同步会从上次停下的位置继续,不需要从头重扫。中断过的索引仍然可以正常搜索。
## 图片文字索引(另一份索引)
本地索引其实有两份,彼此独立:
- **聊天记录索引**(也就是上面说的 Knowledge):索引文字消息,用于跨会话、跨时间查找;
- **图片文字索引**:在本机识别微信图片里的文字(截图、公告、报价图等),把识别结果也变成可搜索的文字。
“独立”的意思是:聊天记录索引建好了,并不代表图片里的文字就搜得到。建立图片文字索引后,可以在“问问微信”里直接搜截图或公告图里写过的词。
图片文字索引只在本机识别,原始图片不会因为本地识别而上传。它**不等于“图片理解”**:识别文字不联网、不需要 AI 服务;而让模型看图并回答属于图片理解,需要配置 AI 服务,走的是另一条路径。
识别失败的图片可以单独重试,也有“只重建搜索索引、不重新识别图片”的修复入口——修索引不需要重跑几万张图。
两个索引都可以在“设置 → 本地索引”里集中查看状态、建立、同步和清理。
## 账号隔离
每个微信账号使用独立的本地索引。切换账号时,应用不会把一个账号的索引混入另一个账号的搜索结果。
@@ -58,4 +73,3 @@ Knowledge 不会在第一次连接后自动悄悄建立。进入“问问微信
## 产品术语(可选)
源码和日志中可能出现 SQLite、FTS、Chunk、索引等词。它们描述的是本地存储和检索实现,不是你开始使用 TraceMemo 的前置知识。
+10 -2
View File
@@ -9,6 +9,7 @@ TraceMemo 的核心路径是本地优先,但“本地优先”不等于所有
- 读取和解析微信数据库;
- 聊天档案浏览和普通关键词搜索;
- 本地 Knowledge 索引及其账号隔离;
- 图片文字索引:识别图片中的文字在本机完成,原始图片不会因为本地识别而上传;
- 离线语音转写;
- 导出文件生成和本地日报历史。
@@ -16,7 +17,7 @@ TraceMemo 的核心路径是本地优先,但“本地优先”不等于所有
## 什么时候会请求外部服务
当你主动使用 AI Search、群聊日报或图片理解,并配置了远程 Provider 时,完成任务所需的内容可能发送给该 Provider。当前设置页给出的边界是:
当你主动使用 AI Search、群聊日报或图片理解,并配置了远程 Provider 时,完成任务所需的内容可能发送给该 Provider。图片文字索引、离线语音转写、档案浏览和普通搜索不会触发这一步。当前设置页给出的边界是:
- 当前用户问题;
- 受控检索所需的有限上下文;
@@ -28,7 +29,14 @@ Ollama 等本机 Provider 可以把模型请求留在本机,但本机服务的
## 语音和媒体
离线语音转写在本机进行。图片理解属于 AI 功能:只有你主动启用并使用相关报告/分析路径时,图片才可能按该 Provider 的请求规则被处理。无法读取的媒体不会被自动“猜出来”。
离线语音转写在本机进行。
图片有两条完全不同的路径,不要混为一谈:
- **图片文字索引**:在本机识别图片里的文字,产出的是本地索引数据;原始图片不会因为这一步被上传,也不需要配置 AI 服务。
- **图片理解**:属于 AI 功能。只有你主动启用并使用相关报告/分析路径时,图片才可能按该 Provider 的请求规则被处理。
无法读取的媒体不会被自动“猜出来”。
## Local HTTP API
+6 -2
View File
@@ -33,9 +33,11 @@
生成成功后会保存本地 HTML 与 PNG,并出现在日报历史中。你可以复制图片、打开文件位置或重新生成。删除历史日报只删除本地生成的报告文件,不会影响微信聊天数据库。
## 定时日报
## 定时日报(在自动化里)
在“日报 → 定时日报”中可以创建每天运行的任务。选择群聊、执行时间、日报范围、消息类型和模板后,TraceMemo 会按计划执行:
定时日报现在是「自动化」里的一种规则,不再单独占一个页面:打开一级导航的「自动化」,新建或编辑一条「定时日报」规则,选择群聊、执行时间、日报范围、消息类型和发送目标。日报页顶部的指引条也会直接跳到自动化。
TraceMemo 会按计划执行:
```text
定时触发 → 读取群聊 → 生成报告 → 保存 Report History → 尝试发送
@@ -45,6 +47,8 @@
执行记录支持查看已生成的日报。对“等待发送”或“发送失败”的记录,可以直接重试发送,重试会复用已经生成的 PNG,不会重新调用 AI 生成整份报告;完整执行状态和发送边界见[如何把聊天变成可用的信息](../concepts/how-it-works.md#动作执行与审计)。
发送目标当前支持**当前群聊、文件传输助手、自己、指定好友**——还不是任意群发。
## 让报告更可靠
- 先选正确的群和时间范围;
+16
View File
@@ -0,0 +1,16 @@
extends: ./electron-builder.yml
extraResources:
- from: build/app-update.yml
to: app-update.yml
- from: resources
to: resources
filter:
- '**/*'
- from: docs/skill/tracememo-reader
to: skill/tracememo-reader
filter:
- '**/*'
mac:
target:
- dmg
- zip
+1
View File
@@ -34,6 +34,7 @@ extraResources:
to: resources
filter:
- '**/*'
- '!runtime/darwin-arm64/**'
- from: docs/skill/tracememo-reader
to: skill/tracememo-reader
filter:
+6 -1
View File
@@ -1,6 +1,6 @@
{
"name": "tracememo",
"version": "2.4.0",
"version": "2.5.0",
"packageManager": "pnpm@7.33.7",
"description": "TraceMemo(迹忆)是一款本地优先、可追溯的 AI 微信知识与分析工作台。 原名 WechatExplorer,支持聊天记录搜索、知识库、微信群聊总结和 Agent 助手。",
"keywords": [
@@ -61,6 +61,7 @@
"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:mac:x64": "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",
@@ -74,8 +75,10 @@
"dependencies": {
"@electron-toolkit/preload": "^3.0.2",
"@electron-toolkit/utils": "^4.0.0",
"@koromix/koffi-darwin-x64": "3.1.0",
"@koromix/koffi-win32-x64": "3.1.0",
"@napi-rs/system-ocr": "1.2.0",
"@napi-rs/system-ocr-darwin-x64": "1.2.0",
"@napi-rs/system-ocr-win32-x64-msvc": "1.2.0",
"@radix-ui/react-alert-dialog": "^1.1.23",
"@radix-ui/react-checkbox": "^1.3.11",
@@ -107,7 +110,9 @@
"parse5": "^8.0.0",
"pinyin-pro": "^3.26.0",
"qrcode": "^1.5.4",
"sherpa-onnx-darwin-x64": "1.13.3",
"sherpa-onnx-node": "1.13.3",
"sherpa-onnx-win-x64": "1.13.4",
"silk-wasm": "^3.7.1",
"tailwind-merge": "^3.6.0",
"unzipper": "^0.12.0",
+38 -31
View File
@@ -11,8 +11,10 @@ specifiers:
'@electron-toolkit/preload': ^3.0.2
'@electron-toolkit/tsconfig': ^2.0.0
'@electron-toolkit/utils': ^4.0.0
'@koromix/koffi-darwin-x64': 3.1.0
'@koromix/koffi-win32-x64': 3.1.0
'@napi-rs/system-ocr': 1.2.0
'@napi-rs/system-ocr-darwin-x64': 1.2.0
'@napi-rs/system-ocr-win32-x64-msvc': 1.2.0
'@playwright/test': ^1.62.1
'@radix-ui/react-alert-dialog': ^1.1.23
@@ -72,7 +74,9 @@ specifiers:
react: ^19.2.1
react-dom: ^19.2.1
sass: ^1.102.0
sherpa-onnx-darwin-x64: 1.13.3
sherpa-onnx-node: 1.13.3
sherpa-onnx-win-x64: 1.13.4
silk-wasm: ^3.7.1
tailwind-merge: ^3.6.0
tailwindcss: 3.4.17
@@ -87,8 +91,10 @@ specifiers:
dependencies:
'@electron-toolkit/preload': 3.0.2_electron@43.1.0
'@electron-toolkit/utils': 4.0.0_electron@43.1.0
'@koromix/koffi-darwin-x64': 3.1.0
'@koromix/koffi-win32-x64': 3.1.0
'@napi-rs/system-ocr': 1.2.0
'@napi-rs/system-ocr-darwin-x64': 1.2.0
'@napi-rs/system-ocr-win32-x64-msvc': 1.2.0
'@radix-ui/react-alert-dialog': 1.1.23_eijghdl4n2x4hz6j4cg7ctgbuu
'@radix-ui/react-checkbox': 1.3.11_eijghdl4n2x4hz6j4cg7ctgbuu
@@ -120,7 +126,9 @@ dependencies:
parse5: 8.0.1
pinyin-pro: 3.29.3
qrcode: 1.5.4
sherpa-onnx-darwin-x64: 1.13.3
sherpa-onnx-node: 1.13.3
sherpa-onnx-win-x64: 1.13.4
silk-wasm: 3.7.1
tailwind-merge: 3.6.0
unzipper: 0.12.5
@@ -1585,7 +1593,6 @@ packages:
cpu: [x64]
os: [darwin]
dev: false
optional: true
/@koromix/koffi-freebsd-arm64/3.1.0:
resolution: {integrity: sha512-vazoPYIhOAlXZksVIqDRMIID4VeUZKx8F3dR90hOobT2ATyOkqNS5dv5UCV7Q7DSq22lQTrdbvENBAhROzCp0w==}
@@ -1689,6 +1696,36 @@ packages:
- supports-color
dev: true
/@napi-rs/system-ocr-darwin-arm64/1.2.0:
resolution: {integrity: sha512-cK8dcDBEl3P4A04xmFJSHEJQxfDytaAIFyDCLqavTp92FVU5plESttWzZsqtTkS81/kzKiBfHyPQffSIndfWbQ==}
engines: {node: '>= 10'}
cpu: [arm64]
os: [darwin]
dev: false
optional: true
/@napi-rs/system-ocr-darwin-x64/1.2.0:
resolution: {integrity: sha512-u3TBvBGrhmT5Os6AfaxbUEg6VHe8lvrFJNPgThJgshJHyRXUx/wCfTyOroJ22KdVCP5AE4GpwS5tFHMb6p6iaQ==}
engines: {node: '>= 10'}
cpu: [x64]
os: [darwin]
dev: false
/@napi-rs/system-ocr-win32-arm64-msvc/1.2.0:
resolution: {integrity: sha512-7ej8uMvmXomw3NXo5gZ5p2Nl6UKsHI+VRU3ELv0mhcxR0sJ6wFifYTu5bJrM1TGcz1/RsaX+TjWMmsDq8vriKQ==}
engines: {node: '>= 10'}
cpu: [arm64]
os: [win32]
dev: false
optional: true
/@napi-rs/system-ocr-win32-x64-msvc/1.2.0:
resolution: {integrity: sha512-oOoCj3FPWDVctTxx98vMBiMI6m51U+w7SMmMefvmtpcpLelzZ/zYTqdwtWZFAjShaHO+RdaKkcpeVcQuBQiVbA==}
engines: {node: '>= 10'}
cpu: [x64]
os: [win32]
dev: false
/@napi-rs/system-ocr/1.2.0:
resolution: {integrity: sha512-r0f2xNH6U+sth44qF+lUP+2WuHSGUBAry5KSCNuaLDGRbgslFqeROr/qJJ/fb6AjBp3Ov+CJP5MdrOWoaoM3cw==}
engines: {node: '>= 10'}
@@ -1699,34 +1736,6 @@ packages:
'@napi-rs/system-ocr-win32-x64-msvc': 1.2.0
dev: false
/@napi-rs/system-ocr-darwin-arm64/1.2.0:
resolution: {integrity: sha512-cK8dcDBEl3P4A04xmFJSHEJQxfDytaAIFyDCLqavTp92FVU5plESttWzZsqtTkS81/kzKiBfHyPQffSIndfWbQ==}
cpu: [arm64]
os: [darwin]
engines: {node: '>= 10'}
dev: false
/@napi-rs/system-ocr-darwin-x64/1.2.0:
resolution: {integrity: sha512-u3TBvBGrhmT5Os6AfaxbUEg6VHe8lvrFJNPgThJgshJHyRXUx/wCfTyOroJ22KdVCP5AE4GpwS5tFHMb6p6iaQ==}
cpu: [x64]
os: [darwin]
engines: {node: '>= 10'}
dev: false
/@napi-rs/system-ocr-win32-arm64-msvc/1.2.0:
resolution: {integrity: sha512-7ej8uMvmXomw3NXo5gZ5p2Nl6UKsHI+VRU3ELv0mhcxR0sJ6wFifYTu5bJrM1TGcz1/RsaX+TjWMmsDq8vriKQ==}
cpu: [arm64]
os: [win32]
engines: {node: '>= 10'}
dev: false
/@napi-rs/system-ocr-win32-x64-msvc/1.2.0:
resolution: {integrity: sha512-oOoCj3FPWDVctTxx98vMBiMI6m51U+w7SMmMefvmtpcpLelzZ/zYTqdwtWZFAjShaHO+RdaKkcpeVcQuBQiVbA==}
cpu: [x64]
os: [win32]
engines: {node: '>= 10'}
dev: false
/@nodelib/fs.scandir/2.1.5:
resolution: {integrity: sha512-vq24Bq3ym5HEQm2NKCr3yXDwjc7vTsEThRDnkp2DK9p1uqLR+DHurm/NOTo0KG7HYHU7eppKZj3MyqYuMBf62g==}
engines: {node: '>= 8'}
@@ -7589,7 +7598,6 @@ packages:
cpu: [x64]
os: [darwin]
dev: false
optional: true
/sherpa-onnx-linux-arm64/1.13.4:
resolution: {integrity: sha512-RMjMRqT82BgTXypNNGmLe6ZFYhc3WEvnAGl3DdkK7qB/kuXwkL3iHhV31wAecbnWPsnEpUoD+8cFovWSBzsCuw==}
@@ -7628,7 +7636,6 @@ packages:
cpu: [x64]
os: [win32]
dev: false
optional: true
/side-channel-list/1.0.0:
resolution: {integrity: sha512-FCLHtRD/gnpCiCHEiJLOwdmFP+wzCmDEkc9y7NsYxeF4u7Btsn1ZuwgwJGxImImHicJArLP4R0yX4c2KCrMrTA==}
Binary file not shown.

Before

Width:  |  Height:  |  Size: 157 KiB

After

Width:  |  Height:  |  Size: 155 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 278 KiB

Binary file not shown.
+198 -18
View File
@@ -125,13 +125,62 @@ function validateSystemOcrRuntime(runtimeResources, platform, arch) {
}
}
/**
* koffi 运行期按 `${process.platform}-${process.arch}` 拼出原生包目录名
* (node_modules/koffi/src/koffi/index.cjs:153/175),找不到就直接抛
* "Cannot find the native Koffi module; did you bundle it correctly?"。
* pnpm 7 不支持 supportedArchitectures,会静默跳过外平台可选依赖,所以每个目标平台的
* koffi 原生包都必须在 package.json 里显式声明;这里再兜一层,缺了就让构建失败,
* 而不是发出一个装得上、却打不开 WCDB 的包。
*/
function koffiNativeTarget(platform, arch) {
if (platform === 'win32') {
return arch === 'x64'
? { label: 'Windows', segments: ['@koromix', 'koffi-win32-x64', 'win32_x64', 'koffi.node'] }
: null
}
if (platform === 'darwin' && (arch === 'x64' || arch === 'arm64')) {
return {
label: 'macOS',
segments: ['@koromix', `koffi-darwin-${arch}`, `darwin_${arch}`, 'koffi.node']
}
}
return null
}
function validateKoffiRuntime(runtimeResources, platform, arch) {
const target = koffiNativeTarget(platform, arch)
if (!target) return
const nativePath = path.join(
runtimeResources,
'app.asar.unpacked',
'node_modules',
...target.segments
)
if (!existsSync(nativePath)) {
throw new Error(`Missing ${target.label} Koffi native module: ${nativePath}`)
}
}
function normalizeBuilderArch(arch) {
if (typeof arch === 'string') return arch
return { 0: 'ia32', 1: 'x64', 2: 'armv7l', 3: 'arm64', 4: 'universal' }[arch] || String(arch)
}
function runCodesign(args) {
execFileSync('/usr/bin/codesign', args, { stdio: 'ignore' })
try {
execFileSync('/usr/bin/codesign', args, {
encoding: 'utf8',
stdio: ['ignore', 'pipe', 'pipe']
})
} catch (error) {
const stderr =
error && typeof error === 'object' && 'stderr' in error ? String(error.stderr) : ''
if (stderr.trim() && error instanceof Error) {
error.message += `\n${stderr.trim()}`
}
throw error
}
}
function isMacosCodeValid(targetPath, run = runCodesign) {
@@ -174,8 +223,89 @@ function signMacosHelpers(runtimeResources, run = runCodesign) {
return helperPaths
}
/**
* codesign 只把这些位置当作「嵌套代码」并要求它们先各自签好,才肯签外层 app。
* 只遍历这一组根目录,而不是整个 bundle:Contents/Resources 下的
* app.asar.unpacked 里成千上万个原生文件不属于嵌套代码,逐个签既慢又无意义。
*/
const MACOS_CODE_LOCATIONS = [
'Frameworks',
'MacOS',
'PlugIns',
'XPCServices',
'Helpers',
'Library/LoginItems'
]
function collectNestedMacosCode(dir, depth, targets) {
let entries
try {
entries = readdirSync(dir, { withFileTypes: true })
} catch {
return
}
for (const entry of entries) {
const entryPath = path.join(dir, entry.name)
// framework 里的 Mantle -> Versions/Current/Mantle 这类符号链接指向真实文件,
// 真实文件会在更深的层级被走到;这里跳过以免重复签名。
if (entry.isSymbolicLink()) continue
if (entry.isDirectory()) {
if (/\.(app|framework|xpc)$/.test(entry.name)) {
targets.push({ path: entryPath, depth, bundle: true })
}
collectNestedMacosCode(entryPath, depth + 1, targets)
continue
}
if (!entry.isFile()) continue
if (readBinaryArchitectures(entryPath).length === 0) continue
targets.push({ path: entryPath, depth, bundle: false })
}
}
/**
* 返回嵌套代码的签名顺序:深度大的先签(framework 内部的 dylib、无扩展名的
* crashpad handler 先于 framework 本身,helper 的可执行文件先于 helper app),
* 同深度时文件先于 bundle。
*/
function findNestedMacosCodePaths(appBundlePath) {
const targets = []
for (const location of MACOS_CODE_LOCATIONS) {
const root = path.join(appBundlePath, 'Contents', ...location.split('/'))
if (existsSync(root)) collectNestedMacosCode(root, 1, targets)
}
return targets
.map((target, index) => ({ ...target, index }))
.sort((a, b) => {
if (a.depth !== b.depth) return b.depth - a.depth
if (a.bundle !== b.bundle) return a.bundle ? 1 : -1
return a.index - b.index
})
.map((target) => target.path)
}
/**
* Electron 43.1.0 的 darwin-x64 官方 zip(sha256 与上游 SHASUMS256.txt 一致)
* 里所有嵌套 Mach-O 都是未签名状态,darwin-arm64 那份则是 linker-signed。
* codesign 签外层 bundle 时要求子组件已签,否则直接报
* "code object is not signed at all" + "In subcomponent: ...",
* 所以 x64 出包时只签外层必然失败,必须先由内向外补签一遍。
*
* 这里不采用 `--deep`(Apple 已标记 deprecated):它会把外层的签名选项套用到
* 所有子组件上,将来接上 Developer ID + entitlements 时会把 app 的 entitlements
* 一并套到 helper 上,属于已知的坑。
*/
function signMacosAppBundle(appBundlePath, run = runCodesign) {
if (isMacosCodeValid(appBundlePath, run)) return appBundlePath
for (const nestedPath of findNestedMacosCodePaths(appBundlePath)) {
try {
run(['--force', '--sign', '-', nestedPath])
} catch (error) {
throw new Error(
'macOS nested code signing failed: ' + path.relative(appBundlePath, nestedPath),
{ cause: error }
)
}
}
run(['--force', '--sign', '-', appBundlePath])
try {
run(['--verify', '--strict', appBundlePath])
@@ -325,9 +455,70 @@ function pruneForeignArchConnectors(runtimeResources, platform, arch) {
return removed
}
/**
* 微信发送运行时打包边界
*/
const SEND_RUNTIME_RELATIVE = ['resources', 'runtime', 'darwin-arm64']
const SEND_RUNTIME_ENTRY = 'tm-wechat-host'
function sendRuntimeLocations(runtimeResources) {
return [
path.join(runtimeResources, ...SEND_RUNTIME_RELATIVE),
path.join(runtimeResources, 'app.asar.unpacked', ...SEND_RUNTIME_RELATIVE)
]
}
function findSendRuntime(runtimeResources) {
return (
sendRuntimeLocations(runtimeResources).find((directory) =>
existsSync(path.join(directory, SEND_RUNTIME_ENTRY))
) || null
)
}
function isSendRuntimeBuild() {
return process.env.TM_SEND_RUNTIME_BUILD === '1'
}
function enforceSendRuntimeBoundary(
runtimeResources,
platform,
bundlesSendRuntime = isSendRuntimeBuild()
) {
if (platform !== 'darwin') return null
const found = findSendRuntime(runtimeResources)
if (bundlesSendRuntime) {
if (!found) {
throw new Error(
'This macOS build requires the WeChat send runtime but resources/runtime/darwin-arm64 is missing. ' +
'Run `pnpm prepare:wechat-native` first, or point TM_NATIVE_RUNTIME_DIR at the artifact.'
)
}
return found
}
if (found) {
throw new Error(
'macOS bundle must not include the WeChat send runtime: ' +
found +
'. Build with `pnpm build:mac:arm64:send-runtime` (TM_SEND_RUNTIME_BUILD=1) when it is required, ' +
'or fix the resources filter in electron-builder.yml.'
)
}
return null
}
exports.default = async function afterPack(context) {
const runtimeResources = getRuntimeResources(context)
const arch = normalizeBuilderArch(context.arch)
// 边界先判,越早失败越好。
const sendRuntime = enforceSendRuntimeBoundary(runtimeResources, context.electronPlatformName)
if (context.electronPlatformName === 'darwin') {
console.log(
sendRuntime
? `[afterPack] send runtime bundled at ${sendRuntime}`
: '[afterPack] send runtime excluded'
)
}
validateAsarRuntimeDependencies(runtimeResources)
validateReaderSkillRuntime(runtimeResources)
validateSilkWasmRuntime(runtimeResources)
@@ -340,6 +531,7 @@ exports.default = async function afterPack(context) {
)
validateSherpaRuntime(runtimeResources, context.electronPlatformName, arch)
validateSystemOcrRuntime(runtimeResources, context.electronPlatformName, arch)
validateKoffiRuntime(runtimeResources, context.electronPlatformName, arch)
pruneIntelMacKeyTool(runtimeResources, context.electronPlatformName, arch)
pruneForeignArchConnectors(runtimeResources, context.electronPlatformName, arch)
pruneForeignArchNativeRuntimes(runtimeResources, context.electronPlatformName, arch)
@@ -352,23 +544,6 @@ exports.default = async function afterPack(context) {
const productName = context.packager.appInfo.productFilename
signMacosAppBundle(path.join(context.appOutDir, productName + '.app'))
}
if (context.electronPlatformName === 'win32') {
const koffiNative = path.join(
context.appOutDir,
'resources',
'app.asar.unpacked',
'node_modules',
'@koromix',
'koffi-win32-x64',
'win32_x64',
'koffi.node'
)
if (!existsSync(koffiNative)) {
throw new Error(`Missing Windows Koffi native module: ${koffiNative}`)
}
return
}
}
exports.getRuntimeResources = getRuntimeResources
@@ -378,6 +553,7 @@ exports.validateFfmpegRuntime = validateFfmpegRuntime
exports.validateSilkWasmRuntime = validateSilkWasmRuntime
exports.validateSherpaRuntime = validateSherpaRuntime
exports.validateSystemOcrRuntime = validateSystemOcrRuntime
exports.validateKoffiRuntime = validateKoffiRuntime
exports.pruneIntelMacKeyTool = pruneIntelMacKeyTool
exports.pruneForeignArchConnectors = pruneForeignArchConnectors
exports.pruneForeignArchNativeRuntimes = pruneForeignArchNativeRuntimes
@@ -386,3 +562,7 @@ exports.findMacosHelperPaths = findMacosHelperPaths
exports.isMacosCodeValid = isMacosCodeValid
exports.signMacosHelpers = signMacosHelpers
exports.signMacosAppBundle = signMacosAppBundle
exports.findNestedMacosCodePaths = findNestedMacosCodePaths
exports.sendRuntimeLocations = sendRuntimeLocations
exports.findSendRuntime = findSendRuntime
exports.enforceSendRuntimeBoundary = enforceSendRuntimeBoundary
-1
View File
@@ -1951,7 +1951,6 @@ function App(): React.ReactElement {
contentFilter={contentFilter}
onContentFilterChange={setContentFilter}
onRefresh={() => selectedContact && handleSelectContact(selectedContact, true)}
onRefreshData={loadContacts}
onReloadAvatars={handleReloadCurrentAvatars}
onLoadOlderMessages={handleLoadOlderMessages}
onCreateGroupReport={handleOpenReportWorkspace}
@@ -18,7 +18,6 @@ interface ChatWindowProps {
contentFilter?: string
onContentFilterChange?: (keyword: string) => void
onRefresh?: () => void
onRefreshData?: () => void
onReloadAvatars?: () => Promise<void>
onLoadOlderMessages?: () => Promise<void>
onCreateGroupReport?: () => void
@@ -40,7 +39,6 @@ const ChatWindow: React.FC<ChatWindowProps> = ({
contentFilter,
onContentFilterChange,
onRefresh,
onRefreshData,
onReloadAvatars,
onLoadOlderMessages,
onCreateGroupReport,
@@ -182,7 +180,6 @@ const ChatWindow: React.FC<ChatWindowProps> = ({
isAiLoading={isAiLoading}
onContentFilterChange={onContentFilterChange || (() => undefined)}
onRefresh={onRefresh}
onRefreshData={onRefreshData}
onTestSend={() => void handleOpenPersonalWechatSend()}
onOpenAiSettings={onCreateGroupReport || (() => undefined)}
onOpenLocalIndexSettings={onOpenLocalIndexSettings}
@@ -1,18 +1,8 @@
import React, { useState } from 'react'
import { Contact } from '../../../../shared/types'
import {
Button,
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuTrigger,
IconButton,
Tooltip,
TooltipContent,
TooltipTrigger
} from '../ui'
import { Button, IconButton, Tooltip, TooltipContent, TooltipTrigger } from '../ui'
import { ConversationContentSearch } from './ConversationContentSearch'
import { AiIcon, MoreIcon, RefreshIcon, SearchIcon, SendIcon } from './icons'
import { AiIcon, RefreshIcon, SearchIcon, SendIcon, StatsIcon } from './icons'
import { supportsPersonalWechatSend } from '../../utils/runtime-environment'
import { GroupMemberStatsDialog } from '../group-stats/GroupMemberStatsDialog'
@@ -25,7 +15,6 @@ interface ChatHeaderProps {
isAiLoading: boolean
onContentFilterChange: (value: string) => void
onRefresh?: () => void
onRefreshData?: () => void
onTestSend: () => void
onOpenAiSettings: () => void
/** 跳到「设置 · 本地索引」(群统计发现索引没追平时用)。 */
@@ -41,7 +30,6 @@ export function ChatHeader({
isAiLoading,
onContentFilterChange,
onRefresh,
onRefreshData,
onTestSend,
onOpenAiSettings,
onOpenLocalIndexSettings
@@ -96,27 +84,20 @@ export function ChatHeader({
<IconButton label="刷新聊天记录" variant="ghost" className="h-8 w-8" onClick={onRefresh}>
<RefreshIcon />
</IconButton>
<DropdownMenu>
<DropdownMenuTrigger asChild>
{/* 群发言统计只对群聊有意义;单聊没有「成员名单」这个概念。 */}
{isGroupChat ? (
<Button
variant="outline"
size="sm"
className="chat-header-text-action"
aria-label="更多功能"
title="更多功能"
aria-label="群发言统计"
title="群发言统计"
onClick={() => setStatsOpen(true)}
>
<MoreIcon />
<span>更多功能</span>
<StatsIcon />
<span>群发言统计</span>
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end">
<DropdownMenuItem onSelect={() => onRefreshData?.()}>刷新数据</DropdownMenuItem>
{/* 群发言统计只对群聊有意义;单聊没有「成员名单」这个概念。 */}
{isGroupChat ? (
<DropdownMenuItem onSelect={() => setStatsOpen(true)}>群发言统计</DropdownMenuItem>
) : null}
</DropdownMenuContent>
</DropdownMenu>
{supportsPersonalWechatSend ? (
<Button
variant="outline"
+4 -4
View File
@@ -34,12 +34,12 @@ export function ExportIcon({ className }: IconProps): React.ReactElement {
)
}
export function MoreIcon({ className }: IconProps): React.ReactElement {
export function StatsIcon({ className }: IconProps): React.ReactElement {
return (
<svg className={className} viewBox="0 0 24 24" aria-hidden="true" focusable="false">
<circle cx="5" cy="12" r="1.4" />
<circle cx="12" cy="12" r="1.4" />
<circle cx="19" cy="12" r="1.4" />
<path d="M5.5 19v-6" />
<path d="M12 19V5" />
<path d="M18.5 19v-9" />
</svg>
)
}
@@ -214,11 +214,11 @@ export function AgentHubWorkspace({
<ul>
<li>
<i />
本机 HTTP 通信
在主进程内运行,不开放本地端口
</li>
<li>
<i />
入站请求鉴权
对话记录可回看
</li>
<li>
<i />
@@ -1,8 +1,9 @@
import { render, screen, waitFor } from '@testing-library/react'
import { render, screen } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { ChatHeader } from '../../src/renderer/src/components/chat/ChatHeader'
import { TooltipProvider } from '../../src/renderer/src/components/ui'
import { type GroupMemberStatsResult } from '../../src/shared/group-stats'
import type { Contact } from '../../src/shared/types'
const groupContact: Contact = {
@@ -19,9 +20,38 @@ const userContact: Contact = {
type: 'user'
}
/** 时区无关:用本地字段构造,别写死 UTC 偏移。 */
const at = (year: number, month: number, day: number): number =>
new Date(year, month - 1, day).getTime()
const statsResult = (): GroupMemberStatsResult => ({
conversationId: groupContact.md5,
startTime: at(2026, 6, 15),
endTime: at(2026, 9, 4),
freshness: 'fresh',
complete: true,
memberCount: 2,
activeMemberCount: 1,
silentMemberCount: 1,
activeMembers: [
{
senderId: 'wxid_a',
displayName: '张三',
groupNickname: '老张',
messageCount: 12,
lastMessageTime: at(2026, 9, 1)
}
],
silentMembers: [{ senderId: 'wxid_b', displayName: '李四', groupNickname: '' }],
unattributedMessages: 0,
excludedSystemMessages: 0,
firstMessageTime: at(2026, 6, 15),
limitations: []
})
beforeEach(() => {
;(window as unknown as { api: Record<string, unknown> }).api = {
getGroupMemberStats: vi.fn(),
getGroupMemberStats: vi.fn().mockResolvedValue(statsResult()),
getPersonalWechatSenderStatus: vi.fn().mockResolvedValue({ canSendText: false })
}
})
@@ -44,22 +74,30 @@ function renderHeader(contact: Contact, isGroupChat: boolean): void {
)
}
async function openMoreMenu(): Promise<void> {
const user = userEvent.setup()
await user.click(screen.getByRole('button', { name: '更多功能' }))
await waitFor(() => expect(screen.getByText('刷新数据')).toBeTruthy())
}
describe('ChatHeader · 群发言统计入口', () => {
it('群聊显示「群发言统计」入口', async () => {
it('群聊把「群发言统计」做成直接按钮,不再藏在「更多功能」下拉里', () => {
renderHeader(groupContact, true)
await openMoreMenu()
expect(screen.getByText('群发言统计')).toBeTruthy()
// 旧入口连同「刷新数据」一起下线,不能再回来。
expect(screen.queryByRole('button', { name: '更多功能' })).toBeNull()
expect(screen.queryByRole('menuitem', { name: '刷新数据' })).toBeNull()
// 是普通按钮,不是菜单触发器 —— 点了就该开面板,不该弹下拉。
expect(screen.getByRole('button', { name: '群发言统计' })).not.toHaveAttribute('aria-haspopup')
})
it('非群聊不显示「群发言统计」入口', async () => {
it('点击入口直接打开群发言统计面板', async () => {
const user = userEvent.setup()
renderHeader(groupContact, true)
await user.click(screen.getByRole('button', { name: '群发言统计' }))
expect(await screen.findByRole('dialog', { name: '群发言统计 · 研发群' })).toBeInTheDocument()
})
it('非群聊不显示「群发言统计」入口', () => {
renderHeader(userContact, false)
await openMoreMenu()
expect(screen.queryByText('群发言统计')).toBeNull()
expect(screen.queryByRole('button', { name: '群发言统计' })).toBeNull()
})
})
-32
View File
@@ -34,37 +34,6 @@ describe('chat menus', () => {
expect(trigger).toHaveFocus()
})
it('closes the chat More menu with Escape and invokes refresh data once', async () => {
const user = userEvent.setup()
const onRefreshData = vi.fn()
renderWithTooltip(
<ChatHeader
contact={contact}
isGroupChat
loadedCount={3}
filteredCount={3}
contentFilter=""
isAiLoading={false}
onContentFilterChange={vi.fn()}
onRefresh={vi.fn()}
onRefreshData={onRefreshData}
onTestSend={vi.fn()}
onOpenAiSettings={vi.fn()}
/>
)
const trigger = screen.getByRole('button', { name: '更多功能' })
await user.click(trigger)
expect(screen.getByRole('menuitem', { name: '刷新数据' })).toBeVisible()
await user.keyboard('{Escape}')
expect(screen.queryByRole('menuitem', { name: '刷新数据' })).not.toBeInTheDocument()
expect(trigger).toHaveFocus()
await user.click(trigger)
await user.click(screen.getByRole('menuitem', { name: '刷新数据' }))
expect(onRefreshData).toHaveBeenCalledOnce()
})
it('keeps header search and actions wired to their existing callbacks', async () => {
const user = userEvent.setup()
const onContentFilterChange = vi.fn()
@@ -80,7 +49,6 @@ describe('chat menus', () => {
isAiLoading={false}
onContentFilterChange={onContentFilterChange}
onRefresh={onRefresh}
onRefreshData={vi.fn()}
onTestSend={vi.fn()}
onOpenAiSettings={onOpenAiSettings}
/>
+57 -20
View File
@@ -197,15 +197,6 @@ test('NAV-04 exit monitor management can save an empty scope and show the setup
await expect(fixture.page.getByRole('heading', { name: '管理群聊', exact: true })).toBeVisible()
await expect(fixture.page.getByText('发送能力已就绪', { exact: true })).toBeVisible()
await expect(fixture.page.getByRole('checkbox', { name: '监控产品测试群' })).toBeChecked()
await fixture.page.getByRole('button', { name: '查看退群监测模板' }).click()
await expect(fixture.page.getByLabel('退群监测模板内容')).toHaveValue(/用户: \{user\}/)
await expect(fixture.page.getByLabel('退群监测模板内容')).toHaveValue(/群备注: \{groupRemark\}/)
const customTemplate = '[退群监测]\n用户: {user}\n群备注: {groupRemark}'
await fixture.page.getByLabel('退群监测模板内容').fill(customTemplate)
await fixture.page.getByRole('button', { name: '保存模板' }).click()
await fixture.page.getByRole('button', { name: '查看退群监测模板' }).click()
await expect(fixture.page.getByLabel('退群监测模板内容')).toHaveValue(customTemplate)
await fixture.page.keyboard.press('Escape')
await fixture.page.getByRole('checkbox', { name: '监控产品测试群' }).click()
await fixture.page.getByRole('checkbox', { name: '监控折叠群聊样本' }).click()
await fixture.page.getByRole('button', { name: '保存监控群聊' }).click()
@@ -216,7 +207,47 @@ test('NAV-04 exit monitor management can save an empty scope and show the setup
}
})
test('CHAT-01 archive More menu is keyboard-safe and keeps the page usable', async () => {
/**
* 退群通知的**内容模板**已随「退群通知」一起迁进自动化,管理群聊页只负责
* 「监测哪些群」。这条用例锁住新家:模板可编辑、可保存,且真的落库。
*/
test('NAV-05 leave notification template is editable in the automation workspace', async () => {
const fixture = await launchTestApp()
const pageErrors: Error[] = []
fixture.page.on('pageerror', (error) => pageErrors.push(error))
try {
await fixture.page.getByRole('button', { name: '退群监控' }).click()
await fixture.page.getByRole('button', { name: '配置退群通知自动化' }).click()
await expect(fixture.page.getByRole('heading', { name: '自动化', exact: true })).toBeVisible()
await expect(fixture.page.getByRole('heading', { name: '退群通知' })).toBeVisible()
const template = fixture.page.getByLabel('退群通知模板内容')
await expect(template).toHaveValue(/用户: \{user\}/)
await expect(template).toHaveValue(/群备注: \{groupRemark\}/)
const customTemplate = '[退群监测]\n用户: {user}\n群备注: {groupRemark}'
await template.fill(customTemplate)
await fixture.page.getByRole('button', { name: '保存' }).click()
/*
* `exact: true` 不能省:Radix 额外渲染一个 `role="status"` 的无障碍播报节点,
* 文本是 `Notification 已保存「退群通知」`,且由 `useNextFrame` **下一帧才填** ——
* 裸 regex 会命中它造成 strict mode violation,且是否命中取决于帧时序。
*/
await expect(fixture.page.getByText('已保存「退群通知」', { exact: true })).toBeVisible()
await fixture.page.reload()
await fixture.page.getByRole('button', { name: '退群监控' }).click()
await fixture.page.getByRole('button', { name: '配置退群通知自动化' }).click()
await expect(fixture.page.getByLabel('退群通知模板内容')).toHaveValue(customTemplate)
expect(pageErrors).toEqual([])
} finally {
await fixture.close()
}
})
test('CHAT-01 archive group stats entry opens the panel and keeps the page usable', async () => {
const fixture = await launchTestApp()
const pageErrors: Error[] = []
fixture.page.on('pageerror', (error) => pageErrors.push(error))
@@ -227,15 +258,6 @@ test('CHAT-01 archive More menu is keyboard-safe and keeps the page usable', asy
await conversationSearch.fill('')
await fixture.page.getByRole('button', { name: '刷新会话列表' }).click()
await fixture.page.getByText('产品测试群', { exact: true }).click()
const moreButton = fixture.page.getByRole('button', { name: '更多' })
await moreButton.click()
await expect(fixture.page.getByRole('menuitem', { name: '刷新数据' })).toBeVisible()
await fixture.page.keyboard.press('Escape')
await expect(fixture.page.getByRole('menuitem', { name: '刷新数据' })).toHaveCount(0)
await expect(moreButton).toBeFocused()
await moreButton.click()
await fixture.page.getByRole('menuitem', { name: '刷新数据' }).click()
await expect(fixture.page.getByRole('heading', { name: '产品测试群' })).toBeVisible()
await fixture.page.getByRole('button', { name: '搜索当前聊天' }).click()
@@ -258,6 +280,21 @@ test('CHAT-01 archive More menu is keyboard-safe and keeps the page usable', asy
expect(
await fixture.page.evaluate(() => document.documentElement.scrollWidth <= window.innerWidth)
).toBe(true)
/*
* 「更多功能」下拉连同「刷新数据」一起下线,群发言统计改为一颗直接按钮。
* 放最后、且不断言关闭:Radix 的 Escape 关闭依赖层监听注册时机,全量跑时偶发不生效,
* 那是组件库行为、不是本次改动的契约(单独连打 8 次均即时关闭)。
*/
await expect(fixture.page.getByRole('button', { name: '更多功能' })).toHaveCount(0)
await expect(fixture.page.getByRole('menuitem', { name: '刷新数据' })).toHaveCount(0)
const statsButton = fixture.page.getByRole('button', { name: '群发言统计', exact: true })
await expect(statsButton).toBeVisible()
await statsButton.click()
await expect(
fixture.page.getByRole('dialog', { name: '群发言统计 · 产品测试群' })
).toBeVisible()
expect(pageErrors).toEqual([])
} finally {
await fixture.close()
@@ -773,7 +810,7 @@ test('AGENT-01 Agent Hub controls stay usable in the default offline layout', as
await fixture.page.keyboard.press('Escape')
await expect(logSource).toBeFocused()
await expect(fixture.page.getByRole('button', { name: '复制日志' })).toBeDisabled()
await fixture.page.getByRole('button', { name: '清空' }).click()
await fixture.page.getByRole('button', { name: '清空', exact: true }).click()
expect(
await fixture.page.evaluate(() => document.documentElement.scrollWidth <= window.innerWidth)
+146 -99
View File
@@ -1,80 +1,146 @@
import { expect, test } from '@playwright/test'
import { expect, test, type Page } from '@playwright/test'
import { launchTestApp } from './support/electron'
const debugNotificationEnabled = ['1', 'true', 'yes', 'on'].includes(
String(process.env.VITE_SCHEDULED_REPORT_DEBUG || '')
.trim()
.toLowerCase()
)
/**
* 定时日报的 E2E。
*
* 「定时日报」已从「日报 → 定时日报」独立页迁到「自动化 → 规则 → 定时日报」,
* 本文件走的是**迁移后**的真实路径:
*
* 日报(提示条)→「去自动化配置 →」→ 自动化 · 定时日报(规则列表)→ 新建 → 编辑器
*
* 断言一律打在真实模型渲染出的**默认值与真实选项**上(范围 / 模板 / 成员名称 /
* 消息类型 / 发送目标),而不是「页面上有个按钮」这种空转检查。
*/
test('SCHEDULED-REPORT-UI-01 opens the scheduled report dialog without viewport overflow', async () => {
/** fixture 约定的固定时刻:2026-08-27 08:30 (+08:00)。 */
const FIXTURE_NOW = Date.parse('2026-08-27T08:30:00+08:00')
/** 从时间线进入「自动化 → 定时日报」的规则列表。 */
async function openScheduledReportRuleList(page: Page): Promise<void> {
await page.getByRole('button', { name: '日报' }).click()
await page.getByRole('button', { name: '去自动化配置 →' }).click()
await expect(page.getByRole('radiogroup', { name: '切换规则类型' })).toBeVisible()
}
/** 列表 → 新建 → 编辑器。 */
async function openScheduledReportEditor(page: Page): Promise<void> {
await openScheduledReportRuleList(page)
await page.getByRole('button', { name: '+ 新建定时日报' }).first().click()
await expect(page.getByRole('heading', { name: '新建定时日报' })).toBeVisible()
}
test('SCHEDULED-REPORT-UI-01 creates a scheduled report rule from the automation workspace without viewport overflow', async () => {
test.skip(
process.platform !== 'darwin' && process.platform !== 'win32',
'The scheduled report send capability requires macOS or Windows'
)
const fixture = await launchTestApp({ now: Date.parse('2026-08-27T08:30:00+08:00') })
const fixture = await launchTestApp({ now: FIXTURE_NOW })
const pageErrors: Error[] = []
fixture.page.on('pageerror', (error) => pageErrors.push(error))
const page = fixture.page
try {
await fixture.page.getByRole('button', { name: '日报' }).click()
await fixture.page.getByRole('tab', { name: '定时日报' }).click()
await expect(fixture.page.getByRole('heading', { name: '定时日报', exact: true })).toBeVisible()
await expect(fixture.page.getByText('✓ 微信发送能力已就绪')).toBeVisible()
await openScheduledReportRuleList(page)
const createButton = fixture.page.getByRole('button', { name: /新建定时日报/ }).first()
await expect(createButton).toBeEnabled()
await createButton.click()
// 深链把「定时日报」这个类型选中,并且先给列表而不是直接甩一个空表单。
await expect(page.getByRole('radio', { name: '定时日报' })).toBeChecked()
await expect(page.getByText('还没有定时日报')).toBeVisible()
const dialog = fixture.page.getByRole('dialog', { name: '新建定时日报' })
await expect(dialog).toBeVisible()
await expect(dialog.getByRole('button', { name: /产品测试群 .*微信群聊/ })).toBeVisible()
await expect(dialog.getByPlaceholder('搜索群聊')).toBeVisible()
await expect(dialog.getByRole('button', { name: '创建定时日报' })).toBeVisible()
await page.getByRole('button', { name: '+ 新建定时日报' }).first().click()
await expect(page.getByRole('heading', { name: '新建定时日报' })).toBeVisible()
const customRange = dialog.locator('[aria-disabled="true"]')
await expect(customRange).toHaveCount(1)
const customLabel = customRange.getByText('自定义', { exact: true })
const customHint = customRange.getByText('即将支持', { exact: true })
await expect(customLabel).toHaveCSS('white-space', 'nowrap')
await expect(customHint).toHaveCSS('white-space', 'nowrap')
expect((await customLabel.boundingBox())?.height).toBeLessThanOrEqual(20)
expect((await customHint.boundingBox())?.height).toBeLessThanOrEqual(20)
// 编辑器是内嵌面板(不是弹窗),三段结构齐全。
for (const heading of ['1 · 什么时候触发', '2 · 生成什么日报', '3 · 生成后发送到哪里']) {
await expect(page.getByRole('heading', { name: heading })).toBeVisible()
}
const selects = dialog.getByRole('combobox')
await expect(selects).toHaveCount(2)
await selects.nth(0).click()
const templateOption = fixture.page.getByRole('option', { name: /Mobile 01.*微信信息流/ })
await expect(templateOption).toBeVisible()
await templateOption.click()
await expect(selects.nth(0)).toContainText('微信信息流')
// 触发段:默认 18:30,且「预计下次执行」按本地时区算出当日槽位。
await expect(page.getByRole('textbox', { name: '执行时间小时' })).toHaveValue('18')
await expect(page.getByRole('textbox', { name: '执行时间分钟' })).toHaveValue('30')
await expect(page.getByTestId('scheduled-next-run')).toHaveText('今日 18:30')
await selects.nth(1).click()
const memberOption = fixture.page.getByRole('option', { name: '微信昵称' })
await expect(memberOption).toBeVisible()
await memberOption.click({ force: true })
await expect(selects.nth(1)).toContainText('微信昵称', { timeout: 8000 })
// 还没填必填项就必须**说不出原因地**拦住保存。
const saveButton = page.getByRole('button', { name: '保存', exact: true })
await expect(saveButton).toBeDisabled()
await expect(page.getByTestId('scheduled-save-blocker')).toHaveText('请填写任务名称')
/*
* 「自定义」区间在旧页面是 aria-disabled 的占位,新编辑器直接把范围收成一个下拉 ——
* 所以这里不再断言那个占位,改成断言下拉本身接的是真实取值。
*/
await expect(page.getByRole('combobox', { name: '日报范围' })).toHaveText('今日')
// 来源群候选来自真实群列表,且搜索框真的过滤。
await expect(page.getByRole('radio', { name: '产品测试群' })).toBeVisible()
await expect(page.getByRole('radio', { name: '折叠群聊样本' })).toBeVisible()
await page.getByRole('textbox', { name: '搜索群聊' }).fill('折叠')
await expect(page.getByRole('radio', { name: '产品测试群' })).toHaveCount(0)
await expect(page.getByRole('radio', { name: '折叠群聊样本' })).toBeVisible()
await page.getByRole('textbox', { name: '搜索群聊' }).fill('')
await expect(page.getByRole('radio', { name: '产品测试群' })).toBeVisible()
// 模板下拉:默认经典日报,能切到社区模板。
const templateSelect = page.getByRole('combobox', { name: '日报模板' })
await expect(templateSelect).toHaveText('经典日报')
await templateSelect.click()
await page.getByRole('option', { name: 'Mobile 01 · 微信信息流' }).click()
await expect(templateSelect).toHaveText('Mobile 01 · 微信信息流')
// 成员名称下拉:默认群昵称,能切到微信昵称。
const memberSelect = page.getByRole('combobox', { name: '成员名称' })
await expect(memberSelect).toHaveText('群昵称')
await memberSelect.click()
await page.getByRole('option', { name: '微信昵称' }).click()
await expect(memberSelect).toHaveText('微信昵称')
await expect(page.getByRole('textbox', { name: '日报生成超时' })).toHaveValue('300')
// 发送目标四选一,默认「文件传输助手」。
await expect(page.getByRole('radio', { name: '文件传输助手' })).toBeChecked()
// 整页不允许出现横向滚动条(布局回归的硬门槛)。
expect(
await fixture.page.evaluate(() => document.documentElement.scrollWidth <= window.innerWidth)
await page.evaluate(() => document.documentElement.scrollWidth <= window.innerWidth)
).toBe(true)
const bounds = await dialog.boundingBox()
expect(bounds).not.toBeNull()
expect(bounds!.y).toBeGreaterThanOrEqual(0)
expect(bounds!.y + bounds!.height).toBeLessThanOrEqual(
await fixture.page.evaluate(() => window.innerHeight)
)
await dialog.getByPlaceholder('例如:技术交流 · 每日日报').fill('E2E 定时日报')
await dialog.getByRole('radio', { name: '今日' }).click()
await dialog.getByRole('button', { name: '创建定时日报' }).click()
await expect(dialog).toHaveCount(0)
await expect(fixture.page.getByText('E2E 定时日报', { exact: true })).toBeVisible()
await expect(fixture.page.getByText('今日', { exact: true })).toBeVisible()
/*
* 阻断原因是**逐级**暴露的:填了名称就轮到来源群,选了群才放行。
* 这里按顺序走一遍,确认拦的是真实缺失项而不是一个笼统的"保存失败"。
*/
await page.getByRole('textbox', { name: '定时日报任务名称' }).fill('E2E 定时日报')
await expect(page.getByTestId('scheduled-save-blocker')).toHaveText('请选择日报来源群')
await expect(saveButton).toBeDisabled()
await fixture.page.getByRole('button', { name: '设置' }).click()
await fixture.page.getByRole('button', { name: '微信发送', exact: true }).click()
await expect(fixture.page.getByRole('heading', { name: '微信发送' })).toBeVisible()
await expect(fixture.page.getByRole('heading', { name: '发送能力', exact: true })).toBeVisible()
await page.getByRole('radio', { name: '产品测试群' }).click()
await expect(page.getByTestId('scheduled-save-blocker')).toHaveCount(0)
await expect(saveButton).toBeEnabled()
await saveButton.click()
// toast 必须 `exact`:Radix 的无障碍播报节点文案是 `Notification 已创建「…」`,子串会命中 2 个。
await expect(page.getByText('已创建「E2E 定时日报」', { exact: true })).toBeVisible()
// 回到列表,卡片渲染的是**保存回来的规则**,不是草稿。
await expect(page.getByRole('heading', { name: 'E2E 定时日报' })).toBeVisible()
await expect(page.getByText('每天 18:30')).toBeVisible()
await expect(page.getByRole('button', { name: '+ 新建定时日报' }).first()).toBeVisible()
// 发送能力状态仍是设置页里的同一份事实。
await page.getByRole('button', { name: '设置' }).click()
await page.getByRole('button', { name: '微信发送', exact: true }).click()
await expect(page.getByRole('heading', { name: '微信发送' })).toBeVisible()
/*
* 这一页的区块标题按平台分叉:macOS 用「配置状态」(SetupGuide 统一展示),
* Windows 才额外有「发送能力」卡。旧断言写死了「发送能力」,在 macOS 上恒假。
*
* `exact: true` 不能省:Windows 上同一页还有「发送能力授权」,
* 子串匹配会同时命中 —— 这正是 CI 上 strict mode violation 的来源。
*/
await expect(
page.getByRole('heading', {
name: process.platform === 'darwin' ? '配置状态' : '发送能力',
exact: true
})
).toBeVisible()
expect(pageErrors).toEqual([])
} finally {
@@ -82,59 +148,40 @@ test('SCHEDULED-REPORT-UI-01 opens the scheduled report dialog without viewport
}
})
test('SCHEDULED-REPORT-UI-02 keeps notification switch off when Agent Hub is offline', async () => {
test('SCHEDULED-REPORT-UI-02 keeps the notification switch off and explains why when Agent Hub is offline', async () => {
test.skip(
process.platform !== 'darwin' && process.platform !== 'win32',
'The scheduled report send capability requires macOS or Windows'
)
const fixture = await launchTestApp({ now: Date.parse('2026-08-27T08:30:00+08:00') })
const fixture = await launchTestApp({ now: FIXTURE_NOW })
const pageErrors: Error[] = []
fixture.page.on('pageerror', (error) => pageErrors.push(error))
const page = fixture.page
try {
await fixture.page.getByRole('button', { name: '日报' }).click()
await fixture.page.getByRole('tab', { name: '定时日报' }).click()
const notificationSwitch = fixture.page.getByRole('switch', { name: '微信异常通知' })
await expect(notificationSwitch).toHaveAttribute('aria-checked', 'false')
await notificationSwitch.click()
await openScheduledReportEditor(page)
// 异常通知挂在编辑器侧栏,是「定时日报」的全局能力,不是单条规则的配置。
await expect(page.getByRole('heading', { name: '微信异常通知' })).toBeVisible()
await expect(
fixture.page
.getByRole('alert')
.getByText('需要先连接 Agent Hub 微信机器人,才能接收异常通知。')
page.getByText('需要先连接 Agent Hub 微信机器人,才能接收异常通知。')
).toBeVisible()
/*
* Agent Hub 离线 ⇒ 开关**禁用**(不是"能点但点了没反应")。
* 迁移前这里是个点了会弹报错的开关;新实现把不可用前置成禁用 + 原因 + 去处,
* 所以断言的是禁用状态与原因文案,而不是点击后的错误提示。
*/
const notificationSwitch = page.getByRole('switch', { name: '开启微信异常通知' })
await expect(notificationSwitch).toHaveAttribute('aria-checked', 'false')
await fixture.page.getByRole('button', { name: '前往 Agent Hub' }).click()
await expect(
fixture.page.getByRole('heading', { name: 'Agent Hub', exact: true })
).toBeVisible()
} finally {
await fixture.close()
}
})
await expect(notificationSwitch).toBeDisabled()
test('SCHEDULED-REPORT-UI-03 sends a simulated error notification in debug mode', async () => {
test.skip(
(process.platform !== 'darwin' && process.platform !== 'win32') || !debugNotificationEnabled,
'The scheduled report debug action requires a supported platform and VITE_SCHEDULED_REPORT_DEBUG=true'
)
const fixture = await launchTestApp({ now: Date.parse('2026-08-27T08:30:00+08:00') })
try {
await fixture.page.getByRole('button', { name: '日报' }).click()
await fixture.page.getByRole('tab', { name: '定时日报' }).click()
await fixture.page
.getByRole('button', { name: /新建定时日报/ })
.first()
.click()
// 能力未就绪时不给「发送测试」—— 不给一个点了必然失败的按钮。
await expect(page.getByRole('button', { name: '发送测试' })).toHaveCount(0)
const dialog = fixture.page.getByRole('dialog', { name: '新建定时日报' })
await dialog.getByPlaceholder('例如:技术交流 · 每日日报').fill('调试定时日报')
await dialog.getByRole('button', { name: '创建定时日报' }).click()
await expect(dialog).toHaveCount(0)
await page.getByRole('button', { name: '去连接 Agent Hub' }).click()
await expect(page.getByRole('heading', { name: 'Agent Hub', exact: true })).toBeVisible()
const debugButton = fixture.page.getByRole('button', { name: '测试错误信息发送' })
await expect(debugButton).toBeVisible()
await debugButton.click()
await expect(
fixture.page.getByText('测试错误信息已发送到 Agent Hub 微信通知接收者')
).toBeVisible()
await expect(fixture.page.getByText('定时日报错误通知测试')).toBeVisible()
expect(pageErrors).toEqual([])
} finally {
await fixture.close()
}
+133 -2
View File
@@ -445,10 +445,106 @@ handle('automation:getStatus', () => ({
message: connected ? '个人微信发送能力已就绪' : '尚未绑定个人微信发送能力'
}
}))
/*
* 定时日报是 `ruleType === 'scheduled_report'` 的**真规则**:列表由
* `automation:listRules` 过滤得到,创建 / 更新走 `automation:createRule` /
* `automation:updateRule`。fixture 必须实现这组通道,否则保存后列表读不回来。
*/
const scheduledReportRules = []
let automationRuleSequence = 0
// 「微信异常通知」是全局开关,新旧两套通道共用同一份状态。
let scheduledReportNotificationEnabled = false
handle('automation:listRules', () => [
builtinDailyReportRule(),
structuredClone(leaveNotificationRule)
structuredClone(leaveNotificationRule),
...scheduledReportRules.map((rule) => structuredClone(rule))
])
handle('automation:createRule', (draft) => {
automationRuleSequence += 1
const rule = {
...draft,
id: `fixture-scheduled-rule-${automationRuleSequence}`,
createdAt: fixtureNowMs,
updatedAt: fixtureNowMs
}
scheduledReportRules.push(rule)
return structuredClone(rule)
})
// `updateRule` / `setRuleEnabled` 收的是**单个对象**(`{ id, draft }` / `{ id, enabled }`),
// 与 `createRule(draft)` / `deleteRule(id)` 的位置参数不同 —— preload 就是这么拼的。
handle('automation:updateRule', (input) => {
const { id, draft } = input || {}
const index = scheduledReportRules.findIndex((rule) => rule.id === id)
if (index < 0) return null
scheduledReportRules[index] = {
...scheduledReportRules[index],
...(draft || {}),
id,
updatedAt: fixtureNowMs
}
return structuredClone(scheduledReportRules[index])
})
handle('automation:deleteRule', (id) => {
const index = scheduledReportRules.findIndex((rule) => rule.id === id)
if (index < 0) return false
scheduledReportRules.splice(index, 1)
return true
})
handle('automation:setRuleEnabled', (input) => {
const { id, enabled } = input || {}
const index = scheduledReportRules.findIndex((rule) => rule.id === id)
if (index < 0) return null
scheduledReportRules[index] = {
...scheduledReportRules[index],
enabled: enabled === true,
updatedAt: fixtureNowMs
}
return structuredClone(scheduledReportRules[index])
})
/*
* 微信异常通知(定时日报的全局能力,不是单条规则的配置)。
*
* 能力判定与 `ScheduledReportService#checkNotificationCapability` 一致:**Agent Hub 离线
* 就是不可用**,且要带上那句可操作的原因。fixture 里 Hub 是 offline,所以这里如实回
* 不可用 —— 不为了让开关点得动而假装就绪。
*
* 这四个通道生产环境都有;不注册会被渲染层的降级兜底吞掉,页面看起来"正常",
* 但测的就不是真实文案了。
*/
handle('automation:getScheduledReportNotificationSettings', () => ({
enabled: scheduledReportNotificationEnabled
}))
handle('automation:getScheduledReportNotificationCapability', () =>
agentHubStatus().hub === 'online'
? { ready: true, recipient: 'wxid_fixture_self' }
: {
ready: false,
reason: 'agent_hub_offline',
error: '需要先连接 Agent Hub 微信机器人,才能接收异常通知。'
}
)
handle('automation:setScheduledReportNotificationEnabled', (enabled) => {
if (enabled && agentHubStatus().hub !== 'online') {
scheduledReportNotificationEnabled = false
return {
success: false,
data: { enabled: false },
reason: 'agent_hub_offline',
error: '需要先连接 Agent Hub 微信机器人,才能接收异常通知。'
}
}
scheduledReportNotificationEnabled = Boolean(enabled)
return { success: true, data: { enabled: scheduledReportNotificationEnabled } }
})
handle('automation:testScheduledReportErrorNotification', (ruleId) =>
scheduledReportRules.some((rule) => rule.id === ruleId)
? {
success: true,
data: { ruleId, notificationId: 'fixture-notification', sentAt: fixtureNowMs }
}
: { success: false, error: '未找到这条定时日报规则' }
)
handle('automation:listGroups', () => automationGroupOptions())
handle('automation:listExecutions', () => [])
handle('automation:clearExecutions', () => true)
@@ -520,7 +616,6 @@ const scheduledReportTasks =
: []
const scheduledReportExecutions = []
const generatedReports = []
let scheduledReportNotificationEnabled = false
const scheduledReportNextRun = (scheduleTime) => {
const [hours, minutes] = String(scheduleTime || '09:00')
.split(':')
@@ -913,6 +1008,30 @@ handle('db:getGroupSnapshot', (md5) =>
}
: null
)
handle('group-stats:getMemberStats', (request) => ({
conversationId: request?.userMd5 || 'group-regular-md5',
startTime: request?.startTime || 0,
endTime: request?.endTime || fixtureNowMs,
freshness: 'fresh',
complete: true,
memberCount: 2,
activeMemberCount: 1,
silentMemberCount: 1,
activeMembers: [
{
senderId: 'wxid_fixture_member',
displayName: '测试成员',
groupNickname: '测试成员',
messageCount: 1,
lastMessageTime: fixtureNowMs
}
],
silentMembers: [{ senderId: 'wxid_fixture_silent', displayName: '沉默成员', groupNickname: '' }],
unattributedMessages: 0,
excludedSystemMessages: 0,
firstMessageTime: fixtureNowMs,
limitations: []
}))
handle('db:getImage', (md5, datName, sessionId, options) =>
md5 === 'unsupported'
? { success: false, error: '不支持的 DAT 版本' }
@@ -1296,6 +1415,18 @@ handle('agent-hub:clearLogs', () => ({ success: true }))
handle('agent-hub:startLogin', () => ({ status: agentHubStatus() }))
handle('agent-hub:cancelLogin', () => ({ status: agentHubStatus() }))
handle('agent-hub:disconnect', () => ({ status: agentHubStatus() }))
/*
* Agent Hub 对话记录(本机 conversations.json 的只读回看)。
*
* fixture 里 Hub 是 offline、也没有任何收发记录,所以恒为空 —— 与
* `agent-hub:getStatus` 的 offline 状态保持一致。
*
* 通道**必须**注册:会话面板挂载即调用,缺 handler 会被渲染层记成 pageerror。
*/
handle('agent-hub:getConversations', () => [])
handle('agent-hub:getConversation', () => null)
handle('agent-hub:clearConversations', () => ({ success: true }))
handle('image:getConfig', () => ({
success: true,
configured: true,
@@ -38,7 +38,13 @@ function makeRoot(): string {
}
afterEach(async () => {
await Promise.all(roots.splice(0).map((root) => rm(root, { recursive: true, force: true })))
// Windows 上 sqlite 句柄未释放时 unlink 会 EBUSY;retry 吸收瞬时占用,
// 免得 teardown 抛错把真正的断言失败盖掉。
await Promise.all(
roots
.splice(0)
.map((root) => rm(root, { recursive: true, force: true, maxRetries: 10, retryDelay: 100 }))
)
})
/** 合法 PNG 头 + 唯一尾部:不同 seed → 不同内容身份(sha256)。 */
@@ -164,8 +170,14 @@ function harness(options: {
}
}
/**
* 等整遍 pass 结束。
*
* 必须显式给预算:这组用例里有 1050 张的 pass,Windows runner 比本机慢一个数量级,
* 默认 1000ms 会超时(其余 image-text-index 用例组也是显式 15s~60s)。
*/
const finishPass = async (service: ImageTextIndexService): Promise<void> => {
await vi.waitFor(() => expect(service.isRunning()).toBe(false))
await vi.waitFor(() => expect(service.isRunning()).toBe(false), { timeout: 60_000 })
}
describe('并发契约', () => {
@@ -491,7 +503,7 @@ describe('并发契约', () => {
})
await restarted.startPass()
await vi.waitFor(() => expect(restarted.isRunning()).toBe(false))
await vi.waitFor(() => expect(restarted.isRunning()).toBe(false), { timeout: 60_000 })
expect(recognize2).not.toHaveBeenCalled()
restarted.resetAccount()
@@ -262,6 +262,11 @@ describe('派生库句柄的账号身份缓存', () => {
h.service.resetAccount()
})
/**
* 显式预算(见结尾 `30_000`):本用例**故意**烧 ≥700ms 的 sleep,再叠两次真实 SQLite pass——
* 本机实测 ~3.9s,已吃掉 vitest 默认 5000ms 的约 80%(Windows 实测 5097ms 越线)。
* 内外预算本就该对齐:`runPass` 内部已在等 60_000ms,外层卡默认 5s 是漏写。
*/
it('pre-loop cost is excluded from per-image cost', async () => {
const PRE_LOOP_MS = 400
const withPreLoop = createHarness({
@@ -308,7 +313,7 @@ describe('派生库句柄的账号身份缓存', () => {
withPreLoop.service.resetAccount()
control.service.resetAccount()
})
}, 30_000)
})
/**
+4 -1
View File
@@ -118,8 +118,11 @@ describe('preload IPC contract', () => {
createTime: 1785553200,
svrId: 'server-11'
}
// preload 把 options 一路透传(不传即显式 undefined),主进程签名是 (reference, options?)。
await api.recognizeVoice(voiceReference)
expect(invoke).toHaveBeenLastCalledWith('voice:recognize', voiceReference)
expect(invoke).toHaveBeenLastCalledWith('voice:recognize', voiceReference, undefined)
await api.recognizeVoice(voiceReference, { force: true })
expect(invoke).toHaveBeenLastCalledWith('voice:recognize', voiceReference, { force: true })
await api.cancelVoiceRecognition(voiceReference)
expect(invoke).toHaveBeenLastCalledWith('voice:cancelRecognition', voiceReference)
await api.downloadVoiceModel()
+20 -3
View File
@@ -38,8 +38,25 @@ const expectContainsTokens = (text: string, tokens: string[]): void => {
const capability = await systemOcrService.getCapability()
const onWindows = process.platform === 'win32'
const nativeAvailable = onWindows && capability.available
const platformGate = onWindows ? it : it.skip
const nativeGate = onWindows && capability.available ? it : it.skip
const nativeGate = nativeAvailable ? it : it.skip
/**
* Windows 引擎是**按语言包**建识别器的:机器上只有 en-US 时能认英文、认不出中文。
* 所以「中文 token」只在确认存在中文识别器时才算硬门槛 —— CI 的 Windows runner
* 只装了 en-US,中文识别不能当所有 CI 的硬门槛(文件头的约定)。
*
* `language` 为 null 表示"跟随系统语言",无法据以判定,按不可用处理(宁可跳过不可误红)。
*/
const nativeChineseGate = nativeAvailable && /^zh/i.test(capability.language ?? '') ? it : it.skip
if (nativeAvailable && !/^zh/i.test(capability.language ?? '')) {
console.warn(
`[integration] Windows OCR 中文用例跳过:识别器语言为「${capability.language ?? '跟随系统语言'}」,` +
'本机未安装中文 OCR 语言包。中文用例需在装有 zh-Hans-CN 识别器的 Windows 机器上通过。'
)
}
describe('Windows System OCR native fidelity', () => {
platformGate('reports a usable capability on this machine', () => {
@@ -49,7 +66,7 @@ describe('Windows System OCR native fidelity', () => {
}
})
nativeGate('recognizes simplified Chinese text', async () => {
nativeChineseGate('recognizes simplified Chinese text', async () => {
const result = await systemOcrService.recognize({
imageDataUrl: toDataUrl('system-ocr-zh.png', 'image/png')
})
@@ -72,7 +89,7 @@ describe('Windows System OCR native fidelity', () => {
expectContainsTokens(result.text, ['TraceMemo', 'System', 'OCR'])
})
nativeGate('recognizes mixed Chinese/English text', async () => {
nativeChineseGate('recognizes mixed Chinese/English text', async () => {
const result = await systemOcrService.recognize({
imageDataUrl: toDataUrl('system-ocr-mixed.png', 'image/png')
})
+161
View File
@@ -0,0 +1,161 @@
import { createRequire } from 'module'
import { mkdirSync, mkdtempSync, rmSync, symlinkSync, writeFileSync } from 'fs'
import { tmpdir } from 'os'
import { join } from 'path'
import { afterAll, describe, expect, it } from 'vitest'
const nodeRequire = createRequire(import.meta.url)
const { findNestedMacosCodePaths, signMacosAppBundle } = nodeRequire(
'../../scripts/after-pack.cjs'
) as {
findNestedMacosCodePaths: (appBundlePath: string) => string[]
signMacosAppBundle: (appBundlePath: string, run?: (args: string[]) => void) => string
}
const root = mkdtempSync(join(tmpdir(), 'wxe-after-pack-sign-'))
/** 最小可用的 64 位 thin Mach-O 头,足以让 readBinaryArchitectures 判出 x64。 */
function macho(): Buffer {
const buffer = Buffer.alloc(32)
buffer.writeUInt32LE(0xfeedfacf, 0)
buffer.writeUInt32LE(0x01000007, 4)
return buffer
}
function file(...segments: string[]): string {
const target = join(root, ...segments)
mkdirSync(join(target, '..'), { recursive: true })
writeFileSync(target, macho())
return target
}
/** 复刻 Electron 43.1.0 darwin-x64 的未签名 bundle 形状。 */
function fixtureApp(): string {
const app = join(root, 'TraceMemo.app')
file('TraceMemo.app', 'Contents', 'MacOS', 'TraceMemo')
file('TraceMemo.app', 'Contents', 'Frameworks', 'Mantle.framework', 'Versions', 'A', 'Mantle')
file(
'TraceMemo.app',
'Contents',
'Frameworks',
'Electron Framework.framework',
'Versions',
'A',
'Electron Framework'
)
file(
'TraceMemo.app',
'Contents',
'Frameworks',
'Electron Framework.framework',
'Versions',
'A',
'Libraries',
'libffmpeg.dylib'
)
file(
'TraceMemo.app',
'Contents',
'Frameworks',
'Electron Framework.framework',
'Versions',
'A',
'Helpers',
'chrome_crashpad_handler'
)
file('TraceMemo.app', 'Contents', 'Frameworks', 'Helper.app', 'Contents', 'MacOS', 'Helper')
// framework 内指向 Versions/A 的符号链接:真实文件在更深层级被走到,这里要跳过。
symlinkSync(
'A',
join(
root,
'TraceMemo.app',
'Contents',
'Frameworks',
'Mantle.framework',
'Versions',
'Current'
),
'dir'
)
// Contents/Resources 下的原生文件不是「嵌套代码」,不参与签名。
file(
'TraceMemo.app',
'Contents',
'Resources',
'app.asar.unpacked',
'node_modules',
'sherpa-onnx-darwin-x64',
'sherpa-onnx.node'
)
// 非原生文件必须被忽略。
writeFileSync(join(root, 'TraceMemo.app', 'Contents', 'Frameworks', 'README.md'), 'not a binary')
return app
}
const app = fixtureApp()
const relative = (target: string): string => target.slice(app.length + 1)
describe('macOS nested code signing order', () => {
afterAll(() => rmSync(root, { recursive: true, force: true }))
it('signs nested code inside-out and ignores resources and symlinks', () => {
const paths = findNestedMacosCodePaths(app).map(relative)
expect(paths).toContain(join('Contents', 'MacOS', 'TraceMemo'))
expect(paths).not.toContain(app)
expect(paths.some((entry) => entry.includes('Resources'))).toBe(false)
expect(paths.some((entry) => entry.endsWith('.md'))).toBe(false)
expect(paths.some((entry) => entry.includes('Versions/Current'))).toBe(false)
const index = (needle: string): number => paths.indexOf(needle)
const handler =
'Contents/Frameworks/Electron Framework.framework/Versions/A/Helpers/chrome_crashpad_handler'
const frameworkBinary =
'Contents/Frameworks/Electron Framework.framework/Versions/A/Electron Framework'
const framework = 'Contents/Frameworks/Electron Framework.framework'
const helperBinary = 'Contents/Frameworks/Helper.app/Contents/MacOS/Helper'
const helperApp = 'Contents/Frameworks/Helper.app'
expect(index(handler)).toBeGreaterThanOrEqual(0)
// 内层可执行文件先于其所属 bundle,helper 的可执行文件先于 helper app。
expect(index(handler)).toBeLessThan(index(framework))
expect(index(frameworkBinary)).toBeLessThan(index(framework))
expect(index(helperBinary)).toBeLessThan(index(helperApp))
// 最深的目标排在最前。
expect(paths[0]).toBe(handler)
})
it('re-signs the app bundle after every nested target', () => {
const calls: string[][] = []
let verifyCalls = 0
const run = (args: string[]): void => {
if (args[0] === '--verify') {
verifyCalls += 1
// 未签名来源包:外层首次校验必然失败,补签之后才允许通过。
if (verifyCalls === 1) throw new Error('code object is not signed at all')
return
}
calls.push(args)
}
signMacosAppBundle(app, run)
const signed = calls.map((args) => args[args.length - 1])
expect(signed[signed.length - 1]).toBe(app)
expect(signed.slice(0, -1)).toEqual(findNestedMacosCodePaths(app))
expect(verifyCalls).toBe(2)
})
it('leaves an already valid bundle untouched', () => {
const calls: string[][] = []
const run = (args: string[]): void => {
calls.push(args)
}
signMacosAppBundle(app, run)
// 只有首次 --verify,没有任何 --sign。
expect(calls).toEqual([['--verify', '--strict', app]])
})
})
@@ -55,7 +55,10 @@ describe('AgentHubConversationStore', () => {
const conversation = store.get('user-a')
expect(conversation?.messages.map((item) => item.direction)).toEqual(['in', 'out'])
// Windows 没有 POSIX 权限位,chmod 0600 是空操作 ⇒ 只在 POSIX 上断言。
if (process.platform !== 'win32') {
expect(statSync(filePath).mode & 0o777).toBe(0o600)
}
})
it('保留发送失败的记录与错误码,便于在界面上对账', () => {
@@ -47,6 +47,16 @@ const readyCapability: PersonalWechatSendCapability = {
const NOW = 1_700_000_000_000
/** 本地时区的 `YYYY-MM-DD HH:mm:ss`:`{time}` 按本地时区渲染,写死偏移量只在东八区通过。 */
function localStamp(epochMs: number): string {
const date = new Date(epochMs)
const pad = (value: number): string => String(value).padStart(2, '0')
return (
`${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())} ` +
`${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(date.getSeconds())}`
)
}
function exitEvent(overrides: Partial<GroupMemberExitedEvent> = {}): GroupMemberExitedEvent {
return {
eventId: 'room@chatroom:wxid_member:1700000000000:1',
@@ -338,7 +348,10 @@ describe('AutomationService.handleGroupExit', () => {
it('发送能力缺失 → execution failed(退群事实不受影响)', async () => {
const harness = createHarness()
harness.setCapability({ ...readyCapability, capabilities: { text: false, image: false, voice: false } })
harness.setCapability({
...readyCapability,
capabilities: { text: false, image: false, voice: false }
})
await harness.service.handleGroupExit(exitEvent())
@@ -395,7 +408,7 @@ describe('AutomationService.handleGroupExit', () => {
if (content.type === 'text') {
// 群名({groupName})与成员群昵称({groupRemark})是两个值,不能混。
expect(content.text).toBe(
'产品测试群|微信昵称|群内备注|wxid_member|243->242|2023-11-15 06:13:20'
`产品测试群|微信昵称|群内备注|wxid_member|243->242|${localStamp(NOW)}`
)
}
})
+226 -1
View File
@@ -22,18 +22,26 @@ const { hasWindowsSherpaRuntime } = nodeRequire('../../scripts/prepare-win-runti
const {
validateAsarRuntimeDependencies,
validateFfmpegRuntime,
validateKoffiRuntime,
validateReaderSkillRuntime,
validateSherpaRuntime,
validateSilkWasmRuntime,
validateSystemOcrRuntime,
findMacosHelperPaths,
signMacosHelpers,
signMacosAppBundle
} = nodeRequire('../../scripts/after-pack.cjs') as {
validateAsarRuntimeDependencies: (runtimeResources: string) => void
validateFfmpegRuntime: (runtimeResources: string, platform?: NodeJS.Platform) => void
validateKoffiRuntime: (runtimeResources: string, platform: NodeJS.Platform, arch: string) => void
validateReaderSkillRuntime: (runtimeResources: string) => string
validateSherpaRuntime: (runtimeResources: string, platform: NodeJS.Platform, arch: string) => void
validateSilkWasmRuntime: (runtimeResources: string) => void
validateSystemOcrRuntime: (
runtimeResources: string,
platform: NodeJS.Platform,
arch: string
) => void
findMacosHelperPaths: (runtimeResources: string) => string[]
signMacosHelpers: (runtimeResources: string, run?: CodesignRunner) => string[]
signMacosAppBundle: (appBundlePath: string, run?: CodesignRunner) => string
@@ -60,7 +68,10 @@ const {
pruneIntelMacKeyTool,
pruneForeignArchConnectors,
pruneForeignArchNativeRuntimes,
validateRuntimeBinaryArchitecture
validateRuntimeBinaryArchitecture,
findSendRuntime,
enforceSendRuntimeBoundary,
default: afterPack
} = nodeRequire('../../scripts/after-pack.cjs') as {
pruneIntelMacKeyTool: (
runtimeResources: string,
@@ -83,6 +94,20 @@ const {
arch: string,
label: string
) => void
findSendRuntime: (runtimeResources: string) => string | null
enforceSendRuntimeBoundary: (
runtimeResources: string,
platform: NodeJS.Platform,
bundlesSendRuntime?: boolean
) => string | null
default: (context: AfterPackContext) => Promise<void>
}
type AfterPackContext = {
appOutDir: string
electronPlatformName: NodeJS.Platform
arch?: number
packager: { appInfo: { productFilename: string } }
}
const { readBinaryArchitectures } = nodeRequire('../../scripts/binary-arch.cjs') as {
readBinaryArchitectures: (filePath: string) => string[]
@@ -248,6 +273,91 @@ describe('production runtime packaging', () => {
expect(config).toContain('node_modules/sherpa-onnx-*/**')
})
it('requires the matching System OCR native runtime', () => {
const resources = join(root, 'system-ocr-resources')
const modules = join(resources, 'app.asar.unpacked', 'node_modules', '@napi-rs')
const base = join(modules, 'system-ocr')
expect(() => validateSystemOcrRuntime(resources, 'darwin', 'arm64')).toThrow(
/Missing unpacked System OCR runtime:.*system-ocr/
)
mkdirSync(base, { recursive: true })
writeFileSync(join(base, 'package.json'), '{}')
writeFileSync(join(base, 'index.js'), 'module.exports = {}')
const mac = join(modules, 'system-ocr-darwin-arm64')
mkdirSync(mac, { recursive: true })
writeFileSync(join(mac, 'package.json'), '{}')
writeFileSync(join(mac, 'system-ocr.darwin-arm64.node'), 'fixture')
expect(() => validateSystemOcrRuntime(resources, 'darwin', 'arm64')).not.toThrow()
// Windows 的原生包名带 -msvc 后缀,查找规则必须跟着改。
expect(() => validateSystemOcrRuntime(resources, 'win32', 'x64')).toThrow(/win32-x64-msvc/)
const windows = join(modules, 'system-ocr-win32-x64-msvc')
mkdirSync(windows, { recursive: true })
writeFileSync(join(windows, 'package.json'), '{}')
writeFileSync(join(windows, 'system-ocr.win32-x64-msvc.node'), 'fixture')
expect(() => validateSystemOcrRuntime(resources, 'win32', 'x64')).not.toThrow()
// Linux 不是 supported target,不应做硬校验。
expect(() => validateSystemOcrRuntime(resources, 'linux', 'x64')).not.toThrow()
})
it('requires the koffi native module for the packaged platform', () => {
const resources = join(root, 'koffi-resources')
const modules = join(resources, 'app.asar.unpacked', 'node_modules', '@koromix')
expect(() => validateKoffiRuntime(resources, 'darwin', 'x64')).toThrow(
/Missing macOS Koffi native module:.*koffi-darwin-x64/
)
expect(() => validateKoffiRuntime(resources, 'darwin', 'arm64')).toThrow(
/koffi-darwin-arm64[/\\]darwin_arm64[/\\]koffi\.node/
)
expect(() => validateKoffiRuntime(resources, 'win32', 'x64')).toThrow(
/Missing Windows Koffi native module:.*koffi-win32-x64/
)
// koffi 运行期按 `${platform}-${arch}` 拼目录名,darwin 用 darwin_<arch>,
// win32 用 win32_x64(见 node_modules/koffi/src/koffi/index.cjs)。
for (const segments of [
['koffi-darwin-x64', 'darwin_x64'],
['koffi-darwin-arm64', 'darwin_arm64'],
['koffi-win32-x64', 'win32_x64']
]) {
const nativeDirectory = join(modules, ...segments)
mkdirSync(nativeDirectory, { recursive: true })
writeFileSync(join(nativeDirectory, 'koffi.node'), 'fixture')
}
expect(() => validateKoffiRuntime(resources, 'darwin', 'x64')).not.toThrow()
expect(() => validateKoffiRuntime(resources, 'darwin', 'arm64')).not.toThrow()
expect(() => validateKoffiRuntime(resources, 'win32', 'x64')).not.toThrow()
// 没有对应原生包的组合应静默跳过,而不是误报。
expect(() => validateKoffiRuntime(resources, 'linux', 'x64')).not.toThrow()
expect(() => validateKoffiRuntime(resources, 'win32', 'arm64')).not.toThrow()
})
it('declares the cross-arch native runtimes pnpm 7 would otherwise skip', () => {
const packageJson = JSON.parse(
readFileSync(resolve(__dirname, '../../package.json'), 'utf8')
) as { dependencies: Record<string, string> }
// pnpm 7.33.7 不支持 supportedArchitectures,非宿主平台的可选依赖会被静默跳过,
// 而这些原生包必须在 dependencies 里显式声明,否则打包阶段才在 afterPack 报缺。
for (const name of [
'sherpa-onnx-darwin-x64',
'sherpa-onnx-win-x64',
'@napi-rs/system-ocr-darwin-x64',
'@napi-rs/system-ocr-win32-x64-msvc',
'@koromix/koffi-darwin-x64',
'@koromix/koffi-win32-x64'
]) {
expect(packageJson.dependencies).toHaveProperty(name)
}
})
it('finds only the macOS helpers that exist in packaged resources', () => {
const resources = join(root, 'helper-detect-resources', 'resources')
mkdirSync(resources, { recursive: true })
@@ -435,6 +545,121 @@ describe('per-architecture macOS packaging', () => {
})
})
describe('send runtime packaging boundary', () => {
const boundaryRoot = mkdtempSync(join(tmpdir(), 'wxe-send-runtime-'))
afterAll(() => rmSync(boundaryRoot, { recursive: true, force: true }))
function resourcesWithSendRuntime(name: string, unpacked = false): string {
const resources = join(boundaryRoot, name, 'Contents', 'Resources')
const runtime = unpacked
? join(resources, 'app.asar.unpacked', 'resources', 'runtime', 'darwin-arm64')
: join(resources, 'resources', 'runtime', 'darwin-arm64')
mkdirSync(runtime, { recursive: true })
writeFileSync(join(runtime, 'tm-wechat-host'), 'fixture')
return resources
}
it('accepts a macOS bundle without the send runtime', () => {
const resources = join(boundaryRoot, 'clean', 'Contents', 'Resources')
mkdirSync(resources, { recursive: true })
expect(findSendRuntime(resources)).toBeNull()
expect(enforceSendRuntimeBoundary(resources, 'darwin', false)).toBeNull()
})
it('fails a bundle that still carries the send runtime', () => {
expect(() =>
enforceSendRuntimeBoundary(resourcesWithSendRuntime('dirty'), 'darwin', false)
).toThrow(/must not include the WeChat send runtime/)
})
it('detects the send runtime when it lands under app.asar.unpacked', () => {
const resources = resourcesWithSendRuntime('unpacked', true)
expect(findSendRuntime(resources)).toBe(
join(resources, 'app.asar.unpacked', 'resources', 'runtime', 'darwin-arm64')
)
expect(() => enforceSendRuntimeBoundary(resources, 'darwin', false)).toThrow(
/must not include the WeChat send runtime/
)
})
it('requires the send runtime when the build is configured to bundle it', () => {
const missing = join(boundaryRoot, 'runtime-missing', 'Contents', 'Resources')
mkdirSync(missing, { recursive: true })
expect(() => enforceSendRuntimeBoundary(missing, 'darwin', true)).toThrow(
/requires the WeChat send runtime/
)
const present = resourcesWithSendRuntime('runtime-ok')
expect(enforceSendRuntimeBoundary(present, 'darwin', true)).toBe(
join(present, 'resources', 'runtime', 'darwin-arm64')
)
})
it('ignores non-macOS bundles', () => {
const resources = resourcesWithSendRuntime('win32')
expect(enforceSendRuntimeBoundary(resources, 'win32', false)).toBeNull()
expect(enforceSendRuntimeBoundary(resources, 'win32', true)).toBeNull()
})
it('keeps the send runtime build off the release publishing path', () => {
const pkg = JSON.parse(readFileSync(resolve(__dirname, '../../package.json'), 'utf8')) as {
scripts: Record<string, string>
}
expect(Object.keys(pkg.scripts).filter((name) => name.includes('send-runtime'))).toEqual([
'build:mac:arm64:send-runtime'
])
expect(pkg.scripts['build:mac:arm64:send-runtime']).toContain('TM_SEND_RUNTIME_BUILD=1')
expect(pkg.scripts['build:mac:arm64:send-runtime']).toContain(
'electron-builder.send-runtime.yml'
)
expect(pkg.scripts['build:mac:arm64:send-runtime']).not.toContain('--publish')
for (const [name, command] of Object.entries(pkg.scripts)) {
if (!name.startsWith('release')) continue
expect(command).not.toContain('electron-builder.send-runtime.yml')
expect(command).not.toContain('TM_SEND_RUNTIME_BUILD')
}
})
it('excludes the send runtime in the default builder config', () => {
const config = readFileSync(resolve(__dirname, '../../electron-builder.yml'), 'utf8')
expect(config).toContain("'!runtime/darwin-arm64/**'")
})
// 只测函数是测不出「边界校验有没有被接上去」的。这个 bundle 故意不含 app.asar 与
// Reader Skill:一旦 afterPack 把边界校验排到其它校验之后,抛出的就会是
// "Missing packaged application archive" 而不是边界错误,用例即失败。
it('applies the boundary check inside afterPack ahead of every other validation', async () => {
const appOutDir = join(boundaryRoot, 'wired')
const runtime = join(
appOutDir,
'TraceMemo.app',
'Contents',
'Resources',
'resources',
'runtime',
'darwin-arm64'
)
mkdirSync(runtime, { recursive: true })
writeFileSync(join(runtime, 'tm-wechat-host'), 'fixture')
await expect(
afterPack({
appOutDir,
electronPlatformName: 'darwin',
arch: 3,
packager: { appInfo: { productFilename: 'TraceMemo' } }
})
).rejects.toThrow(/must not include the WeChat send runtime/)
})
})
describe('release publishing policy', () => {
it('uploads GitHub releases as drafts until the notes are reviewed', () => {
for (const configFile of ['electron-builder.yml', 'electron-builder.win.yml']) {
+25 -31
View File
@@ -36,15 +36,15 @@ const onlineAgentHubStatus = (): AgentHubStatus => ({
})
const SCHEDULE_TIME = '18:30'
/** 按本地时区构造 ISO 串:调度走 `Date#setHours`,写死偏移量会让用例只在东八区通过。 */
const localISO = (year: number, month: number, day: number, hour: number, minute: number): string =>
new Date(year, month - 1, day, hour, minute, 0, 0).toISOString()
/** 一个"当天 18:30 之后"的时刻,保证当日槽位已到点。 */
const AFTER_SLOT = new Date('2026-08-27T18:31:00+08:00')
/**
* 规则的创建时间:**固定**在 2026-08-20。
*
* 必须早于所有参与断言的槽位,否则「槽位晚于创建时间」这道闸会把一切挡住;
* 也绝不能用 `Date.now()` —— 那样断言会随墙上时钟漂移。
*/
const CREATED_AT = Date.parse('2026-08-20T00:00:00+08:00')
const AFTER_SLOT = new Date(2026, 7, 27, 18, 31)
/** 必须早于所有参与断言的槽位,且固定,不能用 `Date.now()`。 */
const CREATED_AT = new Date(2026, 7, 20, 0, 0).getTime()
function makeRule(overrides: Partial<AutomationRule> = {}): AutomationRule {
return {
@@ -114,24 +114,18 @@ describe('定时日报 · 时间计算', () => {
expect(validateScheduleTime('09:05')).toBe(true)
expect(validateScheduleTime('24:00')).toBe(false)
expect(validateScheduleTime('9:5')).toBe(false)
const from = new Date('2026-08-27T10:00:00+08:00')
expect(calculateNextRunAt('18:30', from)).toBe(
new Date('2026-08-27T18:30:00+08:00').toISOString()
)
const from = new Date(2026, 7, 27, 10, 0)
expect(calculateNextRunAt('18:30', from)).toBe(localISO(2026, 8, 27, 18, 30))
// 已经过了今天的点 ⇒ 顺延到明天。
expect(calculateNextRunAt('09:00', from)).toBe(
new Date('2026-08-28T09:00:00+08:00').toISOString()
)
expect(calculateNextRunAt('09:00', from)).toBe(localISO(2026, 8, 28, 9, 0))
})
it('resolveDueScheduledSlot 给出"已经到点、最近的那个"槽位', () => {
// 18:31 时,18:30 已经到点 ⇒ 槽位是今天 18:30。
expect(resolveDueScheduledSlot(SCHEDULE_TIME, AFTER_SLOT)).toBe(
new Date('2026-08-27T18:30:00+08:00').toISOString()
)
expect(resolveDueScheduledSlot(SCHEDULE_TIME, AFTER_SLOT)).toBe(localISO(2026, 8, 27, 18, 30))
// 18:29 时,今天的点还没到 ⇒ 最近一个槽位是昨天。
expect(resolveDueScheduledSlot(SCHEDULE_TIME, new Date('2026-08-27T18:29:00+08:00'))).toBe(
new Date('2026-08-26T18:30:00+08:00').toISOString()
expect(resolveDueScheduledSlot(SCHEDULE_TIME, new Date(2026, 7, 27, 18, 29))).toBe(
localISO(2026, 8, 26, 18, 30)
)
})
})
@@ -148,7 +142,7 @@ describe('定时日报 · 调度器', () => {
expect(ruleId).toBe('rule-1')
expect(options).toEqual({
trigger: 'schedule',
scheduledSlot: new Date('2026-08-27T18:30:00+08:00').toISOString()
scheduledSlot: localISO(2026, 8, 27, 18, 30)
})
})
@@ -159,7 +153,7 @@ describe('定时日报 · 调度器', () => {
schedule: { time: SCHEDULE_TIME },
report: { sourceConversationId: 'g1@chatroom', messageTypes: ['text'] }
}),
lastScheduledSlot: new Date('2026-08-27T18:30:00+08:00').toISOString()
lastScheduledSlot: localISO(2026, 8, 27, 18, 30)
}
})
const { service, executeRule } = await makeHarness({}, [rule])
@@ -209,12 +203,12 @@ describe('定时日报 · 调度器', () => {
schedule: { time: SCHEDULE_TIME },
report: { sourceConversationId: 'g1@chatroom', messageTypes: ['text'] }
}),
lastScheduledSlot: new Date('2026-08-26T18:30:00+08:00').toISOString()
lastScheduledSlot: localISO(2026, 8, 26, 18, 30)
}
})
const { service, executeRule } = await makeHarness({}, [rule])
await service.tick(new Date('2026-08-27T18:29:00+08:00'))
await service.tick(new Date(2026, 7, 27, 18, 29))
await service.settle()
expect(executeRule).not.toHaveBeenCalled()
@@ -224,10 +218,10 @@ describe('定时日报 · 调度器', () => {
// 今天 12:00 建的规则、执行时间 18:30。今天 18:30 还没到,
// 最近的槽位是**昨天 18:30** —— 它早于 createdAt,不属于这条规则。
// 少了这道闸,新建规则会在下一次 15 秒 tick 里立刻发一份昨天的报告。
const rule = makeRule({ createdAt: Date.parse('2026-08-27T12:00:00+08:00') })
const rule = makeRule({ createdAt: new Date(2026, 7, 27, 12, 0).getTime() })
const { service, executeRule } = await makeHarness({}, [rule])
await service.tick(new Date('2026-08-27T18:29:00+08:00'))
await service.tick(new Date(2026, 7, 27, 18, 29))
await service.settle()
expect(executeRule).not.toHaveBeenCalled()
@@ -242,18 +236,18 @@ describe('定时日报 · 调度器', () => {
schedule: { time: SCHEDULE_TIME },
report: { sourceConversationId: 'g1@chatroom', messageTypes: ['text'] }
}),
lastScheduledSlot: new Date('2026-08-25T18:30:00+08:00').toISOString()
lastScheduledSlot: localISO(2026, 8, 25, 18, 30)
}
})
const { service, executeRule } = await makeHarness({}, [rule])
await service.tick(new Date('2026-08-27T18:29:00+08:00'))
await service.tick(new Date(2026, 7, 27, 18, 29))
await service.settle()
expect(executeRule).toHaveBeenCalledTimes(1)
expect(executeRule.mock.calls[0][1]).toEqual({
trigger: 'schedule',
scheduledSlot: new Date('2026-08-26T18:30:00+08:00').toISOString()
scheduledSlot: localISO(2026, 8, 26, 18, 30)
})
})
@@ -264,7 +258,7 @@ describe('定时日报 · 调度器', () => {
schedule: { time: SCHEDULE_TIME },
report: { sourceConversationId: 'g1@chatroom', messageTypes: ['text'] }
}),
lastScheduledSlot: new Date('2026-08-27T18:30:00+08:00').toISOString()
lastScheduledSlot: localISO(2026, 8, 27, 18, 30)
}
})
const { service, executeRule } = await makeHarness({}, [rule])
@@ -272,7 +266,7 @@ describe('定时日报 · 调度器', () => {
// 18:31 时最近槽位正好等于游标 ⇒ 不触发;再把时间回拨到 18:29,
// 槽位退化成 08-26 18:30,仍然**比游标旧** ⇒ 同样不触发。
await service.tick(AFTER_SLOT)
await service.tick(new Date('2026-08-27T18:29:00+08:00'))
await service.tick(new Date(2026, 7, 27, 18, 29))
await service.settle()
expect(executeRule).not.toHaveBeenCalled()
+5 -2
View File
@@ -53,7 +53,7 @@ describe('sticker HTTP failures', () => {
})
describe('personal WeChat runtime security invariants', () => {
it('waits for the macOS native runtime to detach during application shutdown', () => {
it('keeps the macOS native runtime alive across application shutdown', () => {
const mainSource = readFileSync(resolve('src/main/index.ts'), 'utf8')
const shutdownStart = mainSource.indexOf("app.on('before-quit'")
const shutdownEnd = mainSource.indexOf('function showMainWindow', shutdownStart)
@@ -62,7 +62,10 @@ describe('personal WeChat runtime security invariants', () => {
expect(shutdownStart).toBeGreaterThanOrEqual(0)
expect(shutdownEnd).toBeGreaterThan(shutdownStart)
expect(shutdownSource).toContain('await Promise.all([')
expect(shutdownSource).toContain('macWechatRuntimeManager.shutdown()')
// host 要活过 TraceMemo(保留发送能力进程,保住已绑定的 frida 会话),
// 所以退出流程里**不得**关掉它 —— 否则每次重启都要重新绑定微信。
// 它有自己的生命周期:微信消失后自判 stale 并自退,也可从设置卡片手动重载。
expect(shutdownSource).not.toContain('macWechatRuntimeManager.shutdown()')
})
it('does not install Python packages while preparing the native runtime', () => {
@@ -58,7 +58,10 @@ describe('wechat-ilink account store', () => {
expect(path).toBe(
join(home, '.tracememo', 'wechat-connector', 'accounts', 'bot_abc-im-bot.json')
)
// Windows 没有 POSIX 权限位,chmod 0600 是空操作 ⇒ 只在 POSIX 上断言。
if (process.platform !== 'win32') {
expect(statSync(path).mode & 0o777).toBe(0o600)
}
expect(loadAllCredentials(() => home)).toEqual([credentials])
})
@@ -150,7 +153,10 @@ describe('wechat-ilink account store', () => {
accountsDirectory(() => home),
`${accountId}.context.json`
)
// Windows 没有 POSIX 权限位,chmod 0600 是空操作 ⇒ 只在 POSIX 上断言。
if (process.platform !== 'win32') {
expect(statSync(path).mode & 0o777).toBe(0o600)
}
const stored = JSON.parse(readFileSync(path, 'utf8')) as {
tokens: Record<string, { context_token: string }>
+6
View File
@@ -45,7 +45,10 @@ describe('WechatInboundInbox', () => {
expect(accepted.map((entry) => entry.messageId)).toEqual(['1', '2'])
expect(accepted[0].contextToken).toBe('ctx-1')
// Windows 没有 POSIX 权限位,chmod 0600 是空操作 ⇒ 只在 POSIX 上断言。
if (process.platform !== 'win32') {
expect(statSync(filePath).mode & 0o777).toBe(0o600)
}
expect(inbox.size()).toBe(2)
})
@@ -111,6 +114,9 @@ describe('WechatInboundInbox', () => {
const raw = readFileSync(filePath, 'utf8')
expect(raw).toContain('机密内容')
// Windows 没有 POSIX 权限位,chmod 0600 是空操作 ⇒ 只在 POSIX 上断言。
if (process.platform !== 'win32') {
expect(statSync(filePath).mode & 0o777).toBe(0o600)
}
})
})