mirror of
https://wget.la/https://github.com/Wxw-Gu/WechatExplorer
synced 2026-11-30 16:02:58 +08:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c398691792 | ||
|
|
804466aad8 | ||
|
|
d1ee3bbd30 | ||
|
|
7dcda8554e | ||
|
|
6cadcb9a5a | ||
|
|
f47af8024f | ||
|
|
4a4c0eb520 | ||
|
|
05b881d79e | ||
|
|
80e0f43529 | ||
|
|
39753d7784 | ||
|
|
f95e9d491c | ||
|
|
780a19900b | ||
|
|
7e9997cc06 | ||
|
|
8c162969ff | ||
|
|
51c373501a | ||
|
|
9db08dba1a | ||
|
|
49e3fcfb20 | ||
|
|
450668f5e6 | ||
|
|
8804a16ad9 | ||
|
|
d9d0672072 | ||
|
|
a328db687d | ||
|
|
915ee73f95 | ||
|
|
df6388a86d | ||
|
|
695afd7c3e | ||
|
|
049b5a9495 | ||
|
|
43c917a070 | ||
|
|
84737a7407 | ||
|
|
d6d837e6f6 | ||
|
|
443bbc866c | ||
|
|
e17e2d908e | ||
|
|
a0c729374f | ||
|
|
b36311e276 | ||
|
|
9608077b90 | ||
|
|
9ab71bf730 | ||
|
|
52c89bf0c7 | ||
|
|
a799fc1490 | ||
|
|
c366dd1187 | ||
|
|
0d78ad3f54 | ||
|
|
de9f4d311a | ||
|
|
67e4e8f31e | ||
|
|
958dab1ddd | ||
|
|
694d5041bd | ||
|
|
7f3ea4ae6d | ||
|
|
ae0afa65d9 | ||
|
|
72812447fd | ||
|
|
eaa25cd29e | ||
|
|
fd7d5016a8 | ||
|
|
028e8b6553 | ||
|
|
7ce0475b3f | ||
|
|
9564fde04d | ||
|
|
632ec9ee13 | ||
|
|
4d9af4a193 | ||
|
|
e5f0aa59f4 | ||
|
|
ea4d1eabc2 | ||
|
|
108d04f901 | ||
|
|
713232bd62 | ||
|
|
e83e85fe64 | ||
|
|
e5a1656644 | ||
|
|
e24e5fe6e8 | ||
|
|
194dd0035b | ||
|
|
c3629255ea | ||
|
|
345a0db49b | ||
|
|
5276bce060 | ||
|
|
0abbda1160 | ||
|
|
97c74859c0 | ||
|
|
4d5c6459fe | ||
|
|
c835d5c570 | ||
|
|
59872daf52 | ||
|
|
3bd3935042 | ||
|
|
77a6912ade | ||
|
|
4b83aaed61 | ||
|
|
7268188e40 | ||
|
|
069d836dea | ||
|
|
95384a4a92 | ||
|
|
9b82ca663b | ||
|
|
f5633a29cb | ||
|
|
766cd94788 | ||
|
|
b6d287a299 | ||
|
|
4c25236070 | ||
|
|
c1224cb612 | ||
|
|
5036639aa1 | ||
|
|
9593ca0f54 | ||
|
|
b441287d54 | ||
|
|
9b82d29037 | ||
|
|
0f270366aa | ||
|
|
12b8fb34c6 | ||
|
|
774346d503 | ||
|
|
b97e1f4bc6 | ||
|
|
4b2395a8d2 | ||
|
|
1337bcb7de | ||
|
|
b8f08d54c8 | ||
|
|
24399f1d70 |
No files matched your search
@@ -15,6 +15,9 @@ jobs:
|
|||||||
|
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v4
|
- uses: actions/checkout@v4
|
||||||
|
with:
|
||||||
|
# 版本漂移检查需要与基准分支比较 SKILL.md,浅克隆拿不到基准。
|
||||||
|
fetch-depth: 0
|
||||||
|
|
||||||
- uses: pnpm/action-setup@v4
|
- uses: pnpm/action-setup@v4
|
||||||
with:
|
with:
|
||||||
@@ -25,11 +28,6 @@ jobs:
|
|||||||
node-version: 22
|
node-version: 22
|
||||||
cache: pnpm
|
cache: pnpm
|
||||||
|
|
||||||
- uses: actions/setup-go@v5
|
|
||||||
with:
|
|
||||||
go-version-file: services/wechat-connector/go.mod
|
|
||||||
cache-dependency-path: services/wechat-connector/go.sum
|
|
||||||
|
|
||||||
- name: Install dependencies
|
- name: Install dependencies
|
||||||
run: pnpm install
|
run: pnpm install
|
||||||
|
|
||||||
@@ -51,8 +49,8 @@ jobs:
|
|||||||
- name: Skill installation instruction tests
|
- name: Skill installation instruction tests
|
||||||
run: pnpm test:skill-install
|
run: pnpm test:skill-install
|
||||||
|
|
||||||
- name: WeChat connector tests
|
- name: Reader Skill version drift check
|
||||||
run: pnpm test:wechat-connector
|
run: pnpm check:skill-version
|
||||||
|
|
||||||
- name: Build Electron test application
|
- name: Build Electron test application
|
||||||
run: pnpm test:e2e:build
|
run: pnpm test:e2e:build
|
||||||
|
|||||||
+7
-2
@@ -10,8 +10,8 @@ out
|
|||||||
coverage/
|
coverage/
|
||||||
playwright-report/
|
playwright-report/
|
||||||
test-results/
|
test-results/
|
||||||
resources/connectors/wechat/
|
resources/runtime/darwin-arm64
|
||||||
resources/connectors/wechat-personal/
|
.native-runtime-source
|
||||||
.omc
|
.omc
|
||||||
.codex/
|
.codex/
|
||||||
skills-lock.json
|
skills-lock.json
|
||||||
@@ -26,3 +26,8 @@ skills-lock.json
|
|||||||
findings.md
|
findings.md
|
||||||
progress.md
|
progress.md
|
||||||
task_plan.md
|
task_plan.md
|
||||||
|
|
||||||
|
*tm-wcdb-config-helper*
|
||||||
|
*libtmlicense*
|
||||||
|
debug-originals
|
||||||
|
/build/mac-staging/
|
||||||
@@ -25,16 +25,14 @@
|
|||||||
</p>
|
</p>
|
||||||
|
|
||||||
<p align="center">
|
<p align="center">
|
||||||
<img src="./public/日报.png" alt="TraceMemo 主界面" />
|
<img src="./public/日报.png" alt="TraceMemo 日报" />
|
||||||
</p>
|
</p>
|
||||||
|
|
||||||
<p align="center">
|
<p align="center">
|
||||||
<img src="./public/问问微信.png" alt="TraceMemo 问问微信" />
|
<img src="./public/自动化.png" alt="TraceMemo 自动化" />
|
||||||
</p>
|
</p>
|
||||||
|
|
||||||
<p align="center">
|
|
||||||
<img src="./public/退群监控.png" alt="TraceMemo 退群监控" />
|
|
||||||
</p>
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 🎨 社区日报模板
|
## 🎨 社区日报模板
|
||||||
@@ -49,7 +47,7 @@ TraceMemo 日报除了内置版式,也支持从社区模板市场安装更多
|
|||||||
|
|
||||||
在 TraceMemo 中打开:
|
在 TraceMemo 中打开:
|
||||||
|
|
||||||
**日报 → 今日日报 → 日报模板 → 模板市场**
|
**日报 → 社区模板市场**
|
||||||
|
|
||||||
即可查看、预览、安装和切换已发布的社区模板。
|
即可查看、预览、安装和切换已发布的社区模板。
|
||||||
|
|
||||||
@@ -67,18 +65,21 @@ TraceMemo(迹忆)原名 **WechatExplorer** 是一款本地优先的微信数
|
|||||||
|
|
||||||
## 核心能力
|
## 核心能力
|
||||||
|
|
||||||
- 💬 **聊天档案与搜索**:浏览会话,按关键词或身份信息查找。
|
- 💬 **聊天档案与搜索**:浏览会话,按关键词、备注、昵称或 wxid 查找消息。
|
||||||
- 🔍 **AI Search / 问问微信**:用自然语言找回模糊记忆,并查看来源。
|
- 🔍 **AI Search / 问问微信**:用自然语言找回模糊记忆,并查看来源。
|
||||||
- 🧠 **本地知识库**:建立索引,提升跨会话查询稳定性。
|
- 🧠 **本地知识库**:在本机建立索引,让跨会话、跨时间的查询更稳定。
|
||||||
- 📊 **群聊日报**:生成今日、昨日或近 7 天的群聊总结。
|
- 🖼️ **图片文字索引**:在本机识别微信图片里的文字(截图、公告、报价图),识别结果可以在搜索和「问问微信」里被检索。识别全程不联网,原始图片不会因为本地识别而上传。
|
||||||
- 👀 **群成员变化监控**:记录指定群聊的退群动态。
|
- 📊 **群聊日报**:生成今日、昨日或近 7 天的群聊总结,可保存为 HTML 与 PNG。
|
||||||
- 🔊 **文字转语音**:生成语音,试听后发送到选定会话。
|
- 🗣️ **群发言统计**:统计群成员的发言量和沉默成员,看清一个群里谁在说、谁一直没说。
|
||||||
- 🤖 **Agent Hub**:在微信里调用本机 TraceMemo。
|
- 👀 **退群监控**:用成员快照对比记录群成员退出事件,支持多群与事件历史。
|
||||||
- 🔌 **外部 Agent / Local HTTP API**:让外部 Agent 查询本机微信历史。
|
- ⚙️ **自动化**:把上面几步按规则串起来——定时生成并发送日报、成员退群时发送通知;能发到哪里取决于当前的发送能力。
|
||||||
|
- 🔊 **文字转语音**:把文字生成语音,试听后发送到当前会话。
|
||||||
|
- 🤖 **Agent Hub**:在微信里向本机 TraceMemo 提问。
|
||||||
|
- 🔌 **外部 Agent / Local HTTP API**:让 Codex 等外部 Agent 查询本机微信历史。
|
||||||
|
|
||||||
## 💻 平台支持
|
## 💻 平台支持
|
||||||
|
|
||||||
TraceMemo 2.4.0 支持:
|
TraceMemo 2.5.1 支持:
|
||||||
|
|
||||||
- **Windows x64**
|
- **Windows x64**
|
||||||
- **macOS Apple Silicon(M 系列 / arm64)**
|
- **macOS Apple Silicon(M 系列 / arm64)**
|
||||||
@@ -86,6 +87,12 @@ TraceMemo 2.4.0 支持:
|
|||||||
|
|
||||||
Windows 与 macOS 均支持微信本地数据库连接与数据库 Key 获取。
|
Windows 与 macOS 均支持微信本地数据库连接与数据库 Key 获取。
|
||||||
|
|
||||||
|
### 关于“发送能力”
|
||||||
|
|
||||||
|
浏览、搜索、日报生成、导出、知识库和图片文字索引都不需要额外的发送组件。只有**把内容真正发回微信**这一步——自动发送日报、退群通知、把语音发到会话——依赖本机发送能力:
|
||||||
|
|
||||||
|
发送能力未就绪、未绑定或发送失败时,报告本身仍会正常生成并保存在本机,执行记录会显示为“已生成,但未发送”或“已生成,发送失败”,可以稍后重试。
|
||||||
|
|
||||||
## 项目缘起
|
## 项目缘起
|
||||||
|
|
||||||
<details>
|
<details>
|
||||||
@@ -138,11 +145,14 @@ TraceMemo 最早叫 **WechatExplorer**。
|
|||||||
| 想做什么 | 使用入口 |
|
| 想做什么 | 使用入口 |
|
||||||
| ---------------------------------- | ----------------------------- |
|
| ---------------------------------- | ----------------------------- |
|
||||||
| 找记得原文或关键词的消息 | 档案搜索 |
|
| 找记得原文或关键词的消息 | 档案搜索 |
|
||||||
| 找记得大意、但不知道在哪聊过的内容 | AI Search / 问问微信 |
|
| 找记得大意、但不知道在哪聊过的内容 | 问问微信(AI Search) |
|
||||||
|
| 找到截图、公告图里写过的文字 | 问问微信 → 图片文字索引 |
|
||||||
| 长期跨群查询历史 | 本地知识库 |
|
| 长期跨群查询历史 | 本地知识库 |
|
||||||
| 了解一个群今天或近 7 天聊了什么 | 群聊日报 |
|
| 了解一个群今天或近 7 天聊了什么 | 日报 |
|
||||||
|
| 看群里谁最活跃、谁一直没说话 | 档案 → 群聊 → 群发言统计 |
|
||||||
| 持续关注群成员退出 | 退群监控 |
|
| 持续关注群成员退出 | 退群监控 |
|
||||||
| 按计划生成并发送群聊日报 | 定时日报 |
|
| 按计划自动生成并发送群聊日报 | 自动化 |
|
||||||
|
| 成员退群时自动发一条通知 | 自动化 → 退群通知 |
|
||||||
| 把文字生成微信语音 | 文字转语音 |
|
| 把文字生成微信语音 | 文字转语音 |
|
||||||
| 在微信里向本机 TraceMemo 提问 | Agent Hub |
|
| 在微信里向本机 TraceMemo 提问 | Agent Hub |
|
||||||
| 让 Codex 等工具查询微信历史 | Reader Skill / Local HTTP API |
|
| 让 Codex 等工具查询微信历史 | Reader Skill / Local HTTP API |
|
||||||
@@ -159,9 +169,9 @@ TraceMemo 最早叫 **WechatExplorer**。
|
|||||||
|
|
||||||
## 文档
|
## 文档
|
||||||
|
|
||||||
- [用户指南](./docs/README.md#用户指南)
|
- [用户指南](./docs/README.md#档案与搜索)
|
||||||
- [AI / Knowledge](./docs/README.md#ai-与知识库)
|
- [AI / Knowledge](./docs/README.md#ai-与知识库)
|
||||||
- [Monitor / Automation](./docs/README.md#日报与自动化)
|
- [日报与自动化](./docs/README.md#日报与自动化)
|
||||||
- [Agent / API](./docs/README.md#agent--api)
|
- [Agent / API](./docs/README.md#agent--api)
|
||||||
- [开发文档](./docs/development/overview.md)
|
- [开发文档](./docs/development/overview.md)
|
||||||
- [隐私与安全](./docs/user-guide/privacy.md)
|
- [隐私与安全](./docs/user-guide/privacy.md)
|
||||||
@@ -213,7 +223,7 @@ TraceMemo 在早期适配微信 4.x 时,曾参考 **[WeFlow](https://github.co
|
|||||||
|
|
||||||
这个项目起初只是一个一时兴起的项目,所以它大概也不会有一份特别严肃的产品路线图。
|
这个项目起初只是一个一时兴起的项目,所以它大概也不会有一份特别严肃的产品路线图。
|
||||||
|
|
||||||
我可能会按照自己的兴趣继续折腾,也可能突然加入一些奇奇怪怪、但觉得有意思的功能—— 比如让AI给某个好友, 某个群发一个语音条(逗逗群友) 或者定时生成群聊日报并做成微信卡片。
|
我可能会按照自己的兴趣继续折腾,也可能突然加入一些奇奇怪怪、但觉得有意思的功能
|
||||||
|
|
||||||
也因此,这个项目随时可能继续折腾,也可能因为其他事情暂时搁置。如果你有想要的功能,可以提Issue;如果觉得现有实现不符合你的需求,也欢迎直接 Fork 后自己改。
|
也因此,这个项目随时可能继续折腾,也可能因为其他事情暂时搁置。如果你有想要的功能,可以提Issue;如果觉得现有实现不符合你的需求,也欢迎直接 Fork 后自己改。
|
||||||
|
|
||||||
|
|||||||
+10
-8
@@ -6,29 +6,29 @@
|
|||||||
|
|
||||||
- [第一次使用](./user-guide/getting-started.md):安装、连接微信并完成第一次搜索。
|
- [第一次使用](./user-guide/getting-started.md):安装、连接微信并完成第一次搜索。
|
||||||
- [Intel Mac 获取微信密钥](./user-guide/intel-mac-key.md):按页面检查结果准备环境并获取密钥。
|
- [Intel Mac 获取微信密钥](./user-guide/intel-mac-key.md):按页面检查结果准备环境并获取密钥。
|
||||||
- [聊天档案与搜索](./user-guide/chat-archive.md):浏览联系人和群聊,按关键词、备注、昵称、微信号或 wxid 查找消息;也包含档案中的文字转语音入口。
|
- [聊天档案与搜索](./user-guide/chat-archive.md):浏览联系人和群聊,按关键词、备注、昵称、微信号或 wxid 查找消息;也包含档案中的文字转语音入口,以及群聊里的「群发言统计」。
|
||||||
|
|
||||||
## AI 与知识库
|
## AI 与知识库
|
||||||
|
|
||||||
- [AI Search / 问问微信](./user-guide/ai-search.md):用自然语言找回记得大意、但不知道在哪个会话里的内容,并查看 Evidence、Citation 和 Search Trace。
|
- [AI Search / 问问微信](./user-guide/ai-search.md):用自然语言找回记得大意、但不知道在哪个会话里的内容,并查看 Evidence、Citation 和 Search Trace。
|
||||||
- [本地知识库](./user-guide/knowledge.md):主动建立本地索引,提升跨会话、跨时间查询的稳定性。
|
- [本地知识库](./user-guide/knowledge.md):主动建立本地索引,提升跨会话、跨时间查询的稳定性;也包括在本机识别图片文字、让截图和公告图变得可搜索的「图片文字索引」。
|
||||||
- [如何核对 AI 的回答来源](./concepts/answer-sources.md):从来源回到原始消息,检查上下文和覆盖范围。
|
- [如何核对 AI 的回答来源](./concepts/answer-sources.md):从来源回到原始消息,检查上下文和覆盖范围。
|
||||||
- [从微信数据到回答、日报和导出](./concepts/how-it-works.md):了解哪些步骤在本机完成,哪些 AI 功能可能调用 Provider。
|
- [从微信数据到回答、日报和导出](./concepts/how-it-works.md):了解哪些步骤在本机完成,哪些 AI 功能可能调用 Provider。
|
||||||
|
|
||||||
## 日报与自动化
|
## 日报与自动化
|
||||||
|
|
||||||
- [群聊日报](./user-guide/report.md):手动生成今日、昨日或近 7 天的群聊报告,也可以创建定时日报。
|
- [群聊日报](./user-guide/report.md):手动生成今日、昨日或近 7 天的群聊报告,也可以在「自动化」里创建定时日报。
|
||||||
- 定时日报会依次生成报告、保存 Report History,再按当前微信发送能力尝试通知;发送失败时可复用已有 PNG 重试。
|
- 「自动化」按三类规则执行:**@我生成日报**、**定时日报**、**退群通知**。定时日报会依次生成报告、保存 Report History,再按当前微信发送能力尝试通知;发送失败时可复用已有 PNG 重试。
|
||||||
- 自动发送和监控动作通过统一执行边界,并保留执行记录;简要说明见[产品工作方式](./concepts/how-it-works.md#动作执行与审计)。
|
- 自动发送和监控动作通过统一执行边界,并保留执行记录;简要说明见[产品工作方式](./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/voice.md):在本机转写微信语音,结果可用于搜索、Knowledge 和导出。
|
||||||
- [聊天档案与搜索](./user-guide/chat-archive.md#文字转语音):把文字生成微信语音,试听后发送到当前联系人或群聊。
|
- [聊天档案与搜索](./user-guide/chat-archive.md#文字转语音):把文字生成微信语音,试听后发送到当前联系人或群聊;实际发送依赖本机发送能力。
|
||||||
|
|
||||||
## Agent / API
|
## Agent / API
|
||||||
|
|
||||||
@@ -45,10 +45,13 @@ Agent Hub 让微信机器人调用本机 TraceMemo;Reader Skill / Local HTTP A
|
|||||||
- [导出聊天](./user-guide/export.md):导出 HTML、Markdown、CSV 或 JSON 档案。
|
- [导出聊天](./user-guide/export.md):导出 HTML、Markdown、CSV 或 JSON 档案。
|
||||||
- [数据、隐私与安全](./user-guide/privacy.md):本地处理、Provider、媒体和 Token 的数据边界。
|
- [数据、隐私与安全](./user-guide/privacy.md):本地处理、Provider、媒体和 Token 的数据边界。
|
||||||
- [常见问题与排查](./user-guide/troubleshooting.md):按安装、连接、AI、媒体和 Agent 现象排查。
|
- [常见问题与排查](./user-guide/troubleshooting.md):按安装、连接、AI、媒体和 Agent 现象排查。
|
||||||
|
- [macOS 更新27后读不到微信数据](./user-guide/macos27-permission-recovery.md):升级 macOS 或更新应用后失去微信数据访问权限的恢复步骤。
|
||||||
|
|
||||||
## 开发文档
|
## 开发文档
|
||||||
|
|
||||||
- [开发、测试与构建](./development/overview.md)
|
- [开发、测试与构建](./development/overview.md)
|
||||||
|
- [界面开发规范:按钮与主题色](./development/ui-guidelines.md)
|
||||||
|
- [微信系统消息解析与格式兼容](./development/wechat-system-message-parsing.md)
|
||||||
- [Query Agent POC(开发测试入口)](./development/query-agent-poc.md)
|
- [Query Agent POC(开发测试入口)](./development/query-agent-poc.md)
|
||||||
- [本地启动排障](./development/local-startup-troubleshooting.md)
|
- [本地启动排障](./development/local-startup-troubleshooting.md)
|
||||||
- [macOS 数据访问说明](./platform/macos.md)
|
- [macOS 数据访问说明](./platform/macos.md)
|
||||||
@@ -59,7 +62,6 @@ Agent Hub 让微信机器人调用本机 TraceMemo;Reader Skill / Local HTTP A
|
|||||||
- [实验性:自托管微信分享卡片](./deployment/experimental-wechat-share-card.md)
|
- [实验性:自托管微信分享卡片](./deployment/experimental-wechat-share-card.md)
|
||||||
- [微信分享卡片自动部署 Skill](./skill/setup-wechat-share-card/SKILL.md)
|
- [微信分享卡片自动部署 Skill](./skill/setup-wechat-share-card/SKILL.md)
|
||||||
- [TraceMemo Reader Skill 文件](./skill/tracememo-reader/SKILL.md)
|
- [TraceMemo Reader Skill 文件](./skill/tracememo-reader/SKILL.md)
|
||||||
- [第三方组件说明](./third-party/wechat-chatter/NOTICE.md)
|
|
||||||
|
|
||||||
## 版本说明
|
## 版本说明
|
||||||
|
|
||||||
|
|||||||
+12
-11
@@ -21,14 +21,15 @@ Agent Hub 是 TraceMemo 内置的微信机器人入口,也是应用一级导
|
|||||||
- “帮我看看最近跟某人聊了些什么。”
|
- “帮我看看最近跟某人聊了些什么。”
|
||||||
- “生成产品交流群今天的群聊总结图片。”
|
- “生成产品交流群今天的群聊总结图片。”
|
||||||
|
|
||||||
当前已实现的实时任务包括:
|
Hub 把入站文字分成两类处理。
|
||||||
|
|
||||||
- 查看最近会话(数量限制为 1–20);
|
**确定性的快捷动作**(不经过模型,命中就执行):
|
||||||
- 查询你和某位联系人的近期聊天;
|
|
||||||
- 用已配置的 AI 总结你和某位联系人近 7 天的聊天;
|
- 查看最近会话:数量限制为 1–20;
|
||||||
- 生成今天、昨天或近 7 天的群聊总结图片;
|
- 生成群聊总结图片:今天、昨天或近 7 天(需要同时提到“群”和“图片 / 长图 / 日报 / 报告”);
|
||||||
- 总结指定群成员在群里的近期发言;
|
- 分析某个群成员的近期发言:可以指定“今天 / 昨天 / 最近 N 天”。
|
||||||
- 对不需要读取聊天的普通文字请求返回简短 AI 回复。
|
|
||||||
|
**其余问题**交给本机的 Query Agent:它和桌面端“问问微信”使用的是同一个实现,可以按需读取联系人、会话和时间范围来回答,必要时调用你在“设置 → AI 模型”里配置的 AI。例如“帮我看看最近跟某人聊了些什么”“上个月讨论过的项目地址在哪里”。
|
||||||
|
|
||||||
任务完成后,回复会发送回触发这次请求的微信用户。群聊总结会先发送进度提示,完成后发送图片。
|
任务完成后,回复会发送回触发这次请求的微信用户。群聊总结会先发送进度提示,完成后发送图片。
|
||||||
|
|
||||||
@@ -56,12 +57,12 @@ Agent Hub 页面会记录系统、Agent Hub 和微信连接器日志。日志支
|
|||||||
|
|
||||||
## 安全与边界
|
## 安全与边界
|
||||||
|
|
||||||
- Hub 使用本机通信,不把数据库直接暴露到公网;
|
- Hub 在主进程内运行,不开放本地监听端口;它不会把数据库暴露到公网;
|
||||||
- 机器人账号和个人微信账号是不同的登录边界,请确认你连接的是正确账号;
|
- 机器人账号和个人微信账号是不同的登录边界,请确认你连接的是正确账号;
|
||||||
- 机器人回复会发送给当前发消息的人;开发者 API 另有受保护的测试发送入口,使用前必须确认接收者;
|
- 机器人回复会发送给当前发消息的人;开发者 API 另有受保护的测试发送入口,使用前必须确认接收者;
|
||||||
- Hub 生成群聊总结时仍可能调用你配置的 AI Provider;
|
- Hub 理解请求或生成总结时,会调用你在“设置 → AI 模型”配置的 Provider;
|
||||||
- 当前实时自然语言入口主要处理文字消息。底层连接器可以接收图片、语音、文件和视频,但 Agent Hub 尚未为这些媒体提供同等的实时意图处理;
|
- 当前实时入口只处理文字消息。连接器会归一化收到的消息条目,但 Agent Hub 只把文本条目当作意图处理,尚未为图片、语音、文件和视频提供同等能力;
|
||||||
- 当前没有实现群发、广播、定时任务或通用自主操作微信;
|
- 当前没有实现群发、广播、定时任务或通用自主操作微信(定时日报属于「自动化」,不是 Agent Hub);
|
||||||
- 本页面的“Agent Hub 状态”可以通过 Local HTTP API 查询,但不要把它误认为外部 Agent 的实时消息订阅接口或 MCP Server。
|
- 本页面的“Agent Hub 状态”可以通过 Local HTTP API 查询,但不要把它误认为外部 Agent 的实时消息订阅接口或 MCP Server。
|
||||||
|
|
||||||
## 无法连接时
|
## 无法连接时
|
||||||
|
|||||||
@@ -4,9 +4,11 @@
|
|||||||
|
|
||||||
TraceMemo 的本地 API 默认监听 `127.0.0.1:6131`。它面向同一台电脑上的 API Center、Reader Skill、CLI 和 Agent,不是公网网关,也不是带用户账户和细粒度权限 Scope 的服务。
|
TraceMemo 的本地 API 默认监听 `127.0.0.1:6131`。它面向同一台电脑上的 API Center、Reader Skill、CLI 和 Agent,不是公网网关,也不是带用户账户和细粒度权限 Scope 的服务。
|
||||||
|
|
||||||
|
它同时包含**写入型**端点:生成报告并渲染 PNG(`/report`)、通过已连接机器人发送微信消息(`/agent/send`)、创建/修改/删除/启停定时日报任务并触发立即执行(`/scheduled-reports*`)。因此这个 Token 相当于本机敏感凭据,而不是一个只读查询键。
|
||||||
|
|
||||||
## Bearer Token
|
## Bearer Token
|
||||||
|
|
||||||
新 Agent 配置使用 `TRACEMEMO_API_TOKEN`。v2.2.0 仍兼容读取历史变量 `WECHATEXPLORER_API_TOKEN`,优先级为新变量高于旧变量。
|
新 Agent 配置使用 `TRACEMEMO_API_TOKEN`。历史变量名 `WECHATEXPLORER_API_TOKEN` 仍被兼容读取,优先级为新变量高于旧变量;当前没有设定旧变量名的移除时间,新配置不要再使用它。
|
||||||
|
|
||||||
- `/api/v1/health` 是公开健康检查;
|
- `/api/v1/health` 是公开健康检查;
|
||||||
- 其他所有端点都要求 `Authorization: Bearer <TOKEN>`;
|
- 其他所有端点都要求 `Authorization: Bearer <TOKEN>`;
|
||||||
@@ -14,7 +16,8 @@ TraceMemo 的本地 API 默认监听 `127.0.0.1:6131`。它面向同一台电脑
|
|||||||
- Token 由 Electron `safeStorage` 加密保存在用户数据目录的 `local-api-token.bin`;
|
- Token 由 Electron `safeStorage` 加密保存在用户数据目录的 `local-api-token.bin`;
|
||||||
- 文件权限设置为 `0600`;
|
- 文件权限设置为 `0600`;
|
||||||
- 在“API Center”中可以显示、复制和重新生成;
|
- 在“API Center”中可以显示、复制和重新生成;
|
||||||
- 重新生成后旧 Token 立即失效。
|
- 重新生成后旧 Token 立即失效;
|
||||||
|
- 服务端只认这个 Token,**不接受用环境变量覆盖**——Agent 一侧的环境变量只是把 Token 交给 Agent 自己的方式,不是鉴权来源。
|
||||||
|
|
||||||
应用不会自动把 Token 写入 Codex、Claude Code、OpenClaw 或其他 Agent 配置。请把它放进 Agent 自己的本地 secret/environment,例如:
|
应用不会自动把 Token 写入 Codex、Claude Code、OpenClaw 或其他 Agent 配置。请把它放进 Agent 自己的本地 secret/environment,例如:
|
||||||
|
|
||||||
|
|||||||
+350
-28
@@ -8,7 +8,9 @@
|
|||||||
- API 前缀:`/api/v1`
|
- API 前缀:`/api/v1`
|
||||||
- 默认只监听 loopback;不要把它当作公网服务。
|
- 默认只监听 loopback;不要把它当作公网服务。
|
||||||
- `/api/v1/health` 无需 Token;其他端点需要 `Authorization: Bearer <TOKEN>`。
|
- `/api/v1/health` 无需 Token;其他端点需要 `Authorization: Bearer <TOKEN>`。
|
||||||
- 请求体使用 JSON;响应为 JSON。
|
- 请求体使用 JSON,单个请求体最大 `1 MiB`;超限返回 `413`。
|
||||||
|
- 错误响应包含 `requestId`,响应头包含 `X-Request-Id`。客户端可传入 1-128 位的 `[A-Za-z0-9._:-]` 标识,否则服务端会生成 UUID。
|
||||||
|
- 不支持的 HTTP method 返回 `405` 和 `Allow` 响应头。
|
||||||
|
|
||||||
## 最小请求
|
## 最小请求
|
||||||
|
|
||||||
@@ -24,31 +26,250 @@ curl -H "Authorization: Bearer $TRACEMEMO_API_TOKEN" \
|
|||||||
|
|
||||||
不要把 Token 放入 URL、Skill 文件、仓库或命令历史可被共享的脚本中。
|
不要把 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/health` | 服务与数据库健康状态 | 无 |
|
||||||
| GET | `/api/v1/current_time` | 本机时间、时区和 Unix 时间戳 | 无 |
|
| GET | `/api/v1/skill/tracememo-reader` | 当前 Reader Skill 的版本与全文 | 无(需 Token) |
|
||||||
| GET | `/api/v1/contact` | 联系人和群聊列表 | `filter`、`type=user\|group` |
|
| GET | `/api/v1/current_time` | 本机时间、时区和 Unix 时间戳 | 无 |
|
||||||
| GET | `/api/v1/chatroom` | 群聊列表 | `keyword` |
|
| GET | `/api/v1/contact` | 联系人和群聊列表 | `filter`、`type=user\|group` |
|
||||||
| GET | `/api/v1/recent_chat` | 最近会话 | `limit`,默认 50 |
|
| GET | `/api/v1/chatroom` | 群聊列表 | `keyword` |
|
||||||
| GET | `/api/v1/chatlog` | 指定会话的聊天记录 | 必填 `talker`;可选 `time` 或 `startTime`/`endTime` |
|
| GET | `/api/v1/recent_chat` | 最近会话 | `limit`,默认 50 |
|
||||||
| GET | `/api/v1/media/{mediaId}` | 获取图片消息的二进制资源 | 原样使用 `/chatlog` 返回的 `media.url`,不要用消息 `id` 拼接 |
|
| GET | `/api/v1/chatlog` | 指定会话的聊天记录 | 必填 `talker`;可选 `time` 或 `startTime`/`endTime` |
|
||||||
| GET | `/api/v1/group_snapshot` | 群成员快照 | 必填 `md5` |
|
| GET | `/api/v1/media/{mediaId}` | 获取图片消息的二进制资源 | 原样使用 `/chatlog` 返回的 `media.url`,不要用消息 `id` 拼接 |
|
||||||
| GET | `/api/v1/resolve` | 将昵称、wxid 或 md5 解析为会话 | 必填 `q` |
|
| GET | `/api/v1/group_snapshot` | 群成员快照 | 必填 `md5` |
|
||||||
| POST | `/api/v1/report` | 将结构化日报渲染为 HTML 与 PNG | `GroupReportExportRequest` JSON |
|
| GET | `/api/v1/resolve` | 将昵称、wxid 或 md5 解析为会话 | 必填 `q` |
|
||||||
| GET | `/api/v1/agent/status` | Agent Hub、连接器和数据库状态 | 无 |
|
| POST | `/api/v1/report` | 将结构化日报渲染为 HTML 与 PNG | `GroupReportExportRequest` JSON |
|
||||||
| POST | `/api/v1/agent/group-report` | 读取群聊并生成总结图片 | `{ "group": "群名或标识", "range": "today\|yesterday\|7days" }` |
|
| GET | `/api/v1/agent/status` | Agent Hub、连接器和数据库状态 | 无 |
|
||||||
| POST | `/api/v1/agent/send` | 通过已连接机器人测试发送文字或本地图片 | `{ "to": "接收者", "text": "...", "media_url": "..." }` |
|
| POST | `/api/v1/agent/group-report` | 读取群聊并生成总结图片 | `{ "group": "群名或标识", "range": "today\|yesterday\|7days" }` |
|
||||||
|
| POST | `/api/v1/agent/send` | 通过已连接机器人测试发送文字或本地图片 | `{ "to": "接收者", "text": "...", "media_url": "..." }` |
|
||||||
|
| POST | `/api/v1/wechat/send` | 用本机微信账号把消息发给别人 | `{ "to": "wxid 或 filehelper", "type": "text\|image\|voice", "text": "..." }` |
|
||||||
|
| 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` | 兼容占位路由;当前返回 `501 not_supported` | 无 |
|
||||||
|
| GET | `/api/v1/capabilities` | TraceMemo 应用能力和可用状态 | 无 |
|
||||||
|
| GET | `/api/v1/automations` | 自动化规则列表 | 可选 `type`、`enabled` |
|
||||||
|
| POST | `/api/v1/automations` | 创建默认停用的自动化规则 | Automation draft JSON |
|
||||||
|
| POST | `/api/v1/automations/validate` | 校验规则,不保存、不执行 | Automation draft JSON |
|
||||||
|
| GET | `/api/v1/automations/{id}` | 查询单条自动化规则 | 无 |
|
||||||
|
| PATCH | `/api/v1/automations/{id}` | 更新规则配置 | 可变配置字段 JSON |
|
||||||
|
| DELETE | `/api/v1/automations/{id}` | 删除自定义规则 | 系统内置规则受保护 |
|
||||||
|
| POST | `/api/v1/automations/{id}/enable` | 校验并启用规则 | 无 |
|
||||||
|
| POST | `/api/v1/automations/{id}/disable` | 停用规则 | 无 |
|
||||||
|
| GET | `/api/v1/automations/executions` | 查询自动化执行记录 | `ruleId`、`status`、`since`、`until`、`limit` |
|
||||||
|
| GET | `/api/v1/monitors/group-exits` | 查看退群监控状态 | 无 |
|
||||||
|
| PATCH | `/api/v1/monitors/group-exits` | 配置监控群范围或启停 | `enabled`、`monitoredConversationIds` |
|
||||||
|
| GET | `/api/v1/monitors/group-exits/events` | 查询退群事件历史 | `conversationId`、`since`、`until`、`limit` |
|
||||||
|
| GET | `/api/v1/groups/{conversationId}/member-stats` | 查询群成员活跃统计 | 必填 `conversationId`、`start`、`end` |
|
||||||
|
|
||||||
|
`/api/v1/query/*` 是一组结构化的 Query 端点,见下方[LLM-friendly Query Tool API](#llm-friendly-query-tool-api)。
|
||||||
|
|
||||||
|
## 发送消息 API
|
||||||
|
|
||||||
|
两个发送端点走**完全不同的通道**,用途也不同,不要混用。
|
||||||
|
|
||||||
|
| | `POST /api/v1/wechat/send` | `POST /api/v1/agent/send` |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| 通道 | 本机微信(macOS native runtime / Windows hook) | Agent Hub 机器人(iLink) |
|
||||||
|
| 身份 | 你本人当前登录的微信账号 | 已扫码接入的机器人 |
|
||||||
|
| 用途 | **以你的身份把消息发给别人**(好友 / 群 / 文件传输助手) | **机器人给自己发通知**(测试连通性) |
|
||||||
|
| 前置条件 | 本机微信已启动,发送能力为 `ready` | 连接器为 `online` |
|
||||||
|
| 内容类型 | `text` / `image` / `voice`,媒体只接受本地文件 | `text` / `image`(URL 或本地路径) |
|
||||||
|
| 典型失败 | 能力未就绪 `503`、发送失败 `502` | 连接器离线 `503`、凭证过期 `401` |
|
||||||
|
|
||||||
|
### 本地发送:`POST /api/v1/wechat/send`
|
||||||
|
|
||||||
|
用你正在登录的微信账号发消息。**这是唯一能把消息发给别人(而不是发给机器人自己)的端点。**
|
||||||
|
|
||||||
|
```bash
|
||||||
|
: "${TRACEMEMO_API_TOKEN:?Set TRACEMEMO_API_TOKEN from API Center}"
|
||||||
|
curl -X POST http://127.0.0.1:6131/api/v1/wechat/send \
|
||||||
|
-H "Authorization: Bearer $TRACEMEMO_API_TOKEN" \
|
||||||
|
-H "Content-Type: application/json" \
|
||||||
|
-d '{"to":"filehelper","type":"text","text":"来自 Agent 的一条消息"}'
|
||||||
|
```
|
||||||
|
|
||||||
|
请求体:
|
||||||
|
|
||||||
|
| 字段 | 必填 | 说明 |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| `to` | 是 | 接收者:好友 wxid、群 id(以 `@chatroom` 结尾),或 `filehelper`(文件传输助手)。**不做昵称解析**,先调 `/api/v1/resolve?q=张三` 换 wxid |
|
||||||
|
| `type` | 否 | `text`(默认)/ `image` / `voice` |
|
||||||
|
| `text` | `type=text` 时必填 | **最长 2000 字符**,超限返回 `400`,不会截断 |
|
||||||
|
| `filePath` | `type=image\|voice` 时必填 | 本机**绝对路径**,必须已存在。不接受 URL —— 需要发网络图片时先落盘 |
|
||||||
|
| `isGroup` | 否 | 通常可省略;`to` 以 `@chatroom` 结尾时自动判为群 |
|
||||||
|
| `idempotencyKey` | 否 | 幂等键。**重试时请原样带上**,避免 Agent 超时重发导致重复消息 |
|
||||||
|
|
||||||
|
发送前会先校验当前发送能力(等价于 `GET /api/v1/wechat-personal/send-capability`):`ready=false` 时直接返回 `503`,不会进入投递;`capabilities[type]=false` 时返回 `503 SEND_NOT_READY`。
|
||||||
|
|
||||||
|
> **没有 3 秒节流。** 自动化规则(定时日报、退群通知)之间共享 3 秒发送间隔,但本端点属于手动发送,**不受该队列约束**:连续调用会连续投递。Agent 需要自行控制频率,不要用它循环刷消息。
|
||||||
|
|
||||||
|
响应:
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"success": true,
|
||||||
|
"status": "sent",
|
||||||
|
"actionId": "5f0c…",
|
||||||
|
"recipient": { "type": "contact", "id": "filehelper" },
|
||||||
|
"contentType": "text",
|
||||||
|
"durationMs": 842
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
| HTTP | `errorCode` | 含义 |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| `400` | `INVALID_REQUEST` / `INVALID_RECIPIENT` | 字段缺失、`text` 超长、`filePath` 不存在 |
|
||||||
|
| `403` | `POLICY_BLOCKED` / `ACTION_NOT_ALLOWED` / `RECIPIENT_SCOPE_VIOLATION` | 发送策略拒绝 |
|
||||||
|
| `502` | `SEND_FAILED` | 已进入投递,底层发送失败(看 `error`) |
|
||||||
|
| `503` | `SEND_CAPABILITY_UNAVAILABLE` | 微信未启动 / 未绑定 / 未初始化 |
|
||||||
|
| `503` | `SEND_NOT_READY` | 能力在,但不支持该内容类型(例如语音 hook 未就绪) |
|
||||||
|
| `503` | `UNSUPPORTED_PLATFORM` | 非 macOS / Windows |
|
||||||
|
| `500` | `INTERNAL_ERROR` | 网关执行抛出未预期异常 |
|
||||||
|
|
||||||
|
> **`status: "sent"` 只代表投递成功,不等于消息已写入本地数据库。** TraceMemo 读的是微信本地库,自己发出的消息可能延迟落库,也可能根本不会写入。因此不要用 `/api/v1/chatlog` 回查自己刚发的消息来判断是否发送成功 —— 查不到是正常现象;也**不要**因为本地库没有就重发,那会产生真实的重复消息。需要人工确认时,让对方用手机微信或另一个账号查看会话。
|
||||||
|
|
||||||
|
每一次发送都会写入 `actions/wechat-actions.json` 审计记录(`origin` 为 `http_api`),可在 Send Log 中核对。这份记录证明的是「调用过并成功投递」,**不能**证明对方已收到或本地库已落库。
|
||||||
|
|
||||||
|
### 机器人通知:`POST /api/v1/agent/send`
|
||||||
|
|
||||||
|
走已扫码的 Agent Hub 连接器,给**自己**发一条测试消息,用于确认机器人链路是否通畅。它不适合「通知某人」这类场景 —— 那要用上面的 `/api/v1/wechat/send`。
|
||||||
|
|
||||||
|
```bash
|
||||||
|
curl -X POST http://127.0.0.1:6131/api/v1/agent/send \
|
||||||
|
-H "Authorization: Bearer $TRACEMEMO_API_TOKEN" \
|
||||||
|
-H "Content-Type: application/json" \
|
||||||
|
-d '{"to":"<你的 wxid>","text":"connector ok"}'
|
||||||
|
```
|
||||||
|
|
||||||
|
`to` 省略时回落到当前登录账号自己。`media_url` 可传 URL。连接器离线返回 `503`,凭证过期返回 `401`。
|
||||||
|
|
||||||
|
## Application Capabilities
|
||||||
|
|
||||||
|
`GET /api/v1/capabilities` 描述 TraceMemo 应用级能力和当前运行环境;`GET /api/v1/query/capabilities` 只描述结构化 Query primitive,两者不是同一份目录。应用能力使用 `supported` 和 `available` 分开表示“代码支持”与“当前可用”;运行时原因使用稳定的简短 code,不返回 Token、数据库路径、微信密钥或 sender 诊断路径。
|
||||||
|
|
||||||
|
响应包含应用版本、数据库 readiness、Query、Automation、退群监控、群统计,以及个人微信/iLink 的能力状态。`groupExitMonitor.operations` 当前声明 `read_state`、`configure_scope`、`enable`、`disable`、`list_events`;`groupStats.operations` 当前声明 `member_stats`。能力声明不会触发监控扫描或群统计查询。
|
||||||
|
|
||||||
|
```bash
|
||||||
|
: "${TRACEMEMO_API_TOKEN:?Set TRACEMEMO_API_TOKEN from API Center}"
|
||||||
|
BASE="http://127.0.0.1:6131/api/v1"
|
||||||
|
AUTH="Authorization: Bearer $TRACEMEMO_API_TOKEN"
|
||||||
|
curl -H "$AUTH" "$BASE/capabilities"
|
||||||
|
```
|
||||||
|
|
||||||
|
## Group Exit Monitor API
|
||||||
|
|
||||||
|
退群监控只负责“监测哪些群、发现了哪些退群事实”。退群后是否通知、通知到哪里以及通知模板,仍由 `leave_notification` Automation singleton 负责;修改监控范围不会隐式修改该 Automation。
|
||||||
|
|
||||||
|
### 查看和配置监控
|
||||||
|
|
||||||
|
```bash
|
||||||
|
curl -H "$AUTH" "$BASE/monitors/group-exits"
|
||||||
|
|
||||||
|
curl -X PATCH -H "$AUTH" -H 'Content-Type: application/json' \
|
||||||
|
"$BASE/monitors/group-exits" \
|
||||||
|
-d '{"enabled":true,"monitoredConversationIds":["123@chatroom"]}'
|
||||||
|
```
|
||||||
|
|
||||||
|
`monitoredConversationIds` 只接受当前联系人列表中精确存在的群 `roomId`(例如 `xxx@chatroom`),不接受群名、md5、个人联系人、重复或空 ID。请求至少提供 `enabled` 或 `monitoredConversationIds` 其中一个;传空数组表示清空监控范围。服务会先校验全部群,再执行一次原子配置。PATCH 返回最终完整状态。
|
||||||
|
|
||||||
|
状态中的 `eventCount` 是持久化退群事件总数,`lastCheckedAt`/`lastReadAt` 为空时返回 `null`。GET 不会调用 `checkNow()`,也不会触发通知发送。
|
||||||
|
|
||||||
|
### 查询退群事件
|
||||||
|
|
||||||
|
```bash
|
||||||
|
curl -G -H "$AUTH" "$BASE/monitors/group-exits/events" \
|
||||||
|
--data-urlencode 'conversationId=123@chatroom' \
|
||||||
|
--data-urlencode 'since=2026-10-01T00:00:00+07:00' \
|
||||||
|
--data-urlencode 'until=2026-10-02T23:59:59+07:00' \
|
||||||
|
--data-urlencode 'limit=50'
|
||||||
|
```
|
||||||
|
|
||||||
|
时间参数必须是带 offset 的 ISO-8601;默认 `limit=50`,最大 200。事件按 `detectedAt` 升序返回。事件 DTO 使用 `eventId`、稳定的 `conversationId` 和 `memberId`,并把时间输出为 ISO-8601;当前整体已读状态不会伪造成 event-level `read` 字段。当前未开放 clear events、markRead 或 checkNow HTTP 路由。
|
||||||
|
|
||||||
|
一个典型 Agent 工作流是:先通过 `/resolve` 或 `/contact` 找到稳定群 ID,再 PATCH monitor scope;如需通知,再单独 PATCH `leave_notification` Automation,调用 `/automations/validate`,最后启用规则。
|
||||||
|
|
||||||
|
## Group Member Stats API
|
||||||
|
|
||||||
|
```bash
|
||||||
|
curl -G -H "$AUTH" "$BASE/groups/123%40chatroom/member-stats" \
|
||||||
|
--data-urlencode 'start=2026-09-01T00:00:00+07:00' \
|
||||||
|
--data-urlencode 'end=2026-10-01T00:00:00+07:00'
|
||||||
|
```
|
||||||
|
|
||||||
|
`conversationId` 必须是当前联系人列表中精确存在的群 `roomId`;不存在返回 `NOT_FOUND`,个人联系人返回 `NOT_GROUP_CONVERSATION`。`start` 和 `end` 必须同时提供,且使用带 offset 的 ISO-8601,`start` 不能晚于 `end`。HTTP adapter 只负责把稳定群 ID 解析为内部 md5 并调用现有 `GroupStatsService`,不会在 HTTP 层重新统计消息。
|
||||||
|
|
||||||
|
响应中的 `activeMembers` 和 `silentMembers` 都只描述当前成员名单;成员使用 `memberId`,活跃成员的 `lastMessageAt` 和 `range` 时间均为 ISO-8601。`freshness`、`complete`、`limitations` 必须原样保留,`unattributedMessages` 与 `excludedSystemMessages` 用于诊断,`firstMessageAt` 没有消息时为 `null`。当前成员统计不等于完整历史成员统计,`limitations` 表达的退群成员或未归档时段不能从文本中推导成额外的 `formerMembers`,也不会伪造 `totalMessageCount`。
|
||||||
|
|
||||||
|
## Automation API
|
||||||
|
|
||||||
|
`/api/v1/automations*` 是 Automation 的 canonical HTTP API,读写唯一的 `AutomationRuleStore`。它支持当前真实规则类型:`daily_report`、`scheduled_report`、`leave_notification`。本 API 不提供立即执行、重试或清理执行记录。
|
||||||
|
|
||||||
|
旧 `/api/v1/scheduled-reports*` 保持兼容,不设移除日期;它是面向旧 DTO 的受限 compatibility API,不是第二份存储,也不能表示所有新的定时日报目标和配置。新的 Agent 集成应使用 `/automations`。
|
||||||
|
|
||||||
|
创建和校验规则时 `enabled` 只能缺省或为 `false`。创建成功后必须调用 `/automations/{id}/enable` 才会启用。启用会重新校验当前规则;数据库未就绪、目标无法解析或配置无效时不会启用。`PATCH` 只接受规则配置字段,不可改 `ruleType`、`id`、创建/更新时间或 `enabled`;启停必须使用独立 endpoint。未知字段和未知枚举会被拒绝。
|
||||||
|
|
||||||
|
会话范围优先传 `wxid`、`roomId`(如 `xxx@chatroom`)或 canonical conversation ID。唯一匹配的联系人名可被解析为稳定 ID;重名会返回 `ambiguous_contact`,不会猜测。`daily_report.conditions.conversationIds` 在对外 API 中使用稳定 ID,Store 内部仍沿用既有 md5 口径。
|
||||||
|
|
||||||
|
校验请求不落盘、不发消息,也不执行规则。`valid: false` 时查看 `issues`;有效时 `normalized` 是经 ID 解析后的草稿,`effects` 描述启用后的动作,定时日报另外返回按本机时区计算的 `nextRunAt`。
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"name": "产品群每日日报",
|
||||||
|
"ruleType": "scheduled_report",
|
||||||
|
"scheduledReport": {
|
||||||
|
"schedule": { "time": "20:00" },
|
||||||
|
"report": {
|
||||||
|
"sourceConversationId": "wxid_product@chatroom",
|
||||||
|
"range": "today",
|
||||||
|
"messageTypes": ["text", "image"],
|
||||||
|
"templateId": "v1",
|
||||||
|
"memberNameMode": "groupNickname",
|
||||||
|
"timeoutSeconds": 300
|
||||||
|
},
|
||||||
|
"target": { "type": "file_transfer" },
|
||||||
|
"postfixText": ""
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
执行历史只读,默认最多返回 50 条,`limit` 范围是 1-200。`since` 和 `until` 接受带时区的 ISO-8601 时间;execution 本身最多留存 200 条。`running` 记录的 `finishedAt` 为 `null`。
|
||||||
|
|
||||||
|
新 Agent API 的错误格式:
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"error": {
|
||||||
|
"code": "VALIDATION_FAILED",
|
||||||
|
"message": "自动化规则校验失败",
|
||||||
|
"details": []
|
||||||
|
},
|
||||||
|
"requestId": "..."
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
常见错误码包括 `UNAUTHORIZED`、`METHOD_NOT_ALLOWED`、`PAYLOAD_TOO_LARGE`、`INVALID_ARGUMENT`、`NOT_FOUND`、`NOT_GROUP_CONVERSATION`、`DATABASE_NOT_READY`、`VALIDATION_FAILED`、`SINGLETON_RULE`、`PROTECTED_RULE` 和 `PERSISTENCE_FAILED`。`leave_notification` 是固定单例:可读取、修改和启停,但不能创建第二条或删除。内置 `@我生成日报` 同样不能通过 HTTP 删除。
|
||||||
|
|
||||||
### 这些端点与实时机器人有什么关系
|
### 这些端点与实时机器人有什么关系
|
||||||
|
|
||||||
- `/api/v1/agent/status` 只用于查询 Agent Hub、微信连接器和数据库状态;
|
- `/api/v1/agent/status` 只用于查询 Agent Hub、微信连接器和数据库状态;
|
||||||
- `/api/v1/agent/group-report` 由外部 Agent 或脚本主动请求生成群聊总结图片;
|
- `/api/v1/agent/group-report` 由外部 Agent 或脚本主动请求生成群聊总结图片;
|
||||||
- `/api/v1/agent/send` 是受 Bearer Token 保护的开发者/测试发送入口,用于通过已经连接的机器人发送文字或本地图片;它不是任意群发能力,也不是实时消息订阅接口;
|
- `/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 和微信连接器接收、处理和回复。
|
- 当前 API 没有对外暴露实时入站 webhook。微信消息由应用内部的 Agent Hub 和微信连接器接收、处理和回复。
|
||||||
|
|
||||||
## 时间查询
|
## 时间查询
|
||||||
@@ -83,10 +304,12 @@ curl -H "$AUTH" "$BASE/chatlog?talker=技术交流群&time=2026-08-07"
|
|||||||
## 响应与错误
|
## 响应与错误
|
||||||
|
|
||||||
- `200`:请求成功;
|
- `200`:请求成功;
|
||||||
|
- `201`:定时日报任务创建成功;
|
||||||
- `401`:缺少、错误或已失效的 Bearer Token;
|
- `401`:缺少、错误或已失效的 Bearer Token;
|
||||||
- `400`:参数或 JSON 请求体无效;
|
- `400`:参数或 JSON 请求体无效;
|
||||||
- `422`:媒体标识格式错误,或目标消息不是可读取的图片(`NOT_IMAGE`);
|
- `422`:媒体标识格式错误,或目标消息不是可读取的图片(`NOT_IMAGE`);
|
||||||
- `403`:浏览器 Origin 不在允许的 loopback 列表;
|
- `403`:浏览器 Origin 不在允许的 loopback 列表;
|
||||||
|
- `409`:定时日报任务重复(`error === "duplicate"`,响应里会带回已存在的任务),或群聊名称匹配到多个目标(`ambiguous_contact`);
|
||||||
- `404`:端点、会话或群聊不存在;媒体标识未登记、已过期、有歧义,或图片文件不存在(`NOT_FOUND`)。媒体请求遇到此状态时,先重新读取 `/chatlog` 并使用新的 `media.url`;若仍失败,再检查本地图片文件是否存在;
|
- `404`:端点、会话或群聊不存在;媒体标识未登记、已过期、有歧义,或图片文件不存在(`NOT_FOUND`)。媒体请求遇到此状态时,先重新读取 `/chatlog` 并使用新的 `media.url`;若仍失败,再检查本地图片文件是否存在;
|
||||||
- `503`:数据库或 Agent Hub 尚未就绪;
|
- `503`:数据库或 Agent Hub 尚未就绪;
|
||||||
- `500`:服务端处理或报告渲染失败。
|
- `500`:服务端处理或报告渲染失败。
|
||||||
@@ -154,12 +377,12 @@ curl -X POST -H "$AUTH" -H 'Content-Type: application/json' "$BASE/query/convers
|
|||||||
|
|
||||||
`query/messages`、`query/search`、`query/message-context` 和 `query/conversation-overview` 都接受一个可选的 `scope`,用来把检索限制在一个确定的语料边界内:
|
`query/messages`、`query/search`、`query/message-context` 和 `query/conversation-overview` 都接受一个可选的 `scope`,用来把检索限制在一个确定的语料边界内:
|
||||||
|
|
||||||
| scope | 含义 |
|
| scope | 含义 |
|
||||||
| ----- | ---- |
|
| ----------------------------------------- | -------------------------------------------------------------------- |
|
||||||
| `{"kind":"all"}` | 所有可读会话(默认;省略 `scope` 等价于此) |
|
| `{"kind":"all"}` | 所有可读会话(默认;省略 `scope` 等价于此) |
|
||||||
| `{"kind":"groups"}` | 只搜群聊语料,**且包含群成员实际发送的消息**(不是群名称或群元数据) |
|
| `{"kind":"groups"}` | 只搜群聊语料,**且包含群成员实际发送的消息**(不是群名称或群元数据) |
|
||||||
| `{"kind":"contact","conversationId":"…"}` | 只搜该一对一会话 |
|
| `{"kind":"contact","conversationId":"…"}` | 只搜该一对一会话 |
|
||||||
| `{"kind":"current","conversationId":"…"}` | 只搜指定的那个会话(单聊或群聊) |
|
| `{"kind":"current","conversationId":"…"}` | 只搜指定的那个会话(单聊或群聊) |
|
||||||
|
|
||||||
`conversationId` 是会话标识,可用 `/api/v1/resolve` 或 `/api/v1/contact` 得到。`scope` 一旦给出就是**权威边界**:`target` 落在范围之外会被拒绝(`status: "invalid_tool_arguments"`、`constraint: "target_outside_scope"`),不会静默扩大范围;范围里包含多个会话时,`query/messages` 与 `query/conversation-overview` 必须显式指定 `target`(`constraint: "target_required_for_scope"`)。
|
`conversationId` 是会话标识,可用 `/api/v1/resolve` 或 `/api/v1/contact` 得到。`scope` 一旦给出就是**权威边界**:`target` 落在范围之外会被拒绝(`status: "invalid_tool_arguments"`、`constraint: "target_outside_scope"`),不会静默扩大范围;范围里包含多个会话时,`query/messages` 与 `query/conversation-overview` 必须显式指定 `target`(`constraint: "target_required_for_scope"`)。
|
||||||
|
|
||||||
@@ -186,13 +409,112 @@ curl -X POST -H "$AUTH" -H 'Content-Type: application/json' "$BASE/query/convers
|
|||||||
|
|
||||||
`query/search` 依赖本地索引,而本地索引是异步建立的派生数据,可能落后于聊天数据库。因此它的响应会显式给出覆盖口径:
|
`query/search` 依赖本地索引,而本地索引是异步建立的派生数据,可能落后于聊天数据库。因此它的响应会显式给出覆盖口径:
|
||||||
|
|
||||||
| 字段 | 含义 |
|
| 字段 | 含义 |
|
||||||
| ---- | ---- |
|
| ------------------- | ------------------------------------------------------------------- |
|
||||||
| `indexLatestAt` | 索引目前覆盖到的源数据时间(epoch ms),`null` 表示无法判定 |
|
| `indexLatestAt` | 索引目前覆盖到的源数据时间(epoch ms),`null` 表示无法判定 |
|
||||||
| `sourceLatestAt` | 聊天数据库里最新的活跃时间(epoch ms),`null` 表示无法判定 |
|
| `sourceLatestAt` | 聊天数据库里最新的活跃时间(epoch ms),`null` 表示无法判定 |
|
||||||
| `coverage.state` | `complete` 只在索引确实覆盖了所请求的时间范围时出现 |
|
| `coverage.state` | `complete` 只在索引确实覆盖了所请求的时间范围时出现 |
|
||||||
| `freshness.catchUp` | 本次为追赶索引做了什么:`none` / `reused` / `completed` / `pending` |
|
| `freshness.catchUp` | 本次为追赶索引做了什么:`none` / `reused` / `completed` / `pending` |
|
||||||
|
|
||||||
调用方**必须**把 `coverage` 当真:`coverage.state` 不是 `complete` 且 `evidence` 为空时,只能说明"这段范围暂时无法确认",**不能**下"没有找到"的结论。索引落后时服务端会自动请求一次追赶同步,但不会让请求无限等待;`freshness.catchUp` 为 `pending` 表示追赶仍在后台进行,稍后重试即可拿到更新的覆盖。
|
调用方**必须**把 `coverage` 当真:`coverage.state` 不是 `complete` 且 `evidence` 为空时,只能说明"这段范围暂时无法确认",**不能**下"没有找到"的结论。索引落后时服务端会自动请求一次追赶同步,但不会让请求无限等待;`freshness.catchUp` 为 `pending` 表示追赶仍在后台进行,稍后重试即可拿到更新的覆盖。
|
||||||
|
|
||||||
`query/messages` 与 `query/conversation-overview` 直读聊天数据库,不受索引新鲜度影响。
|
`query/messages` 与 `query/conversation-overview` 直读聊天数据库,不受索引新鲜度影响。
|
||||||
|
|
||||||
|
### 语音转文字(voice-transcribe)
|
||||||
|
|
||||||
|
语音消息的正文固定是 `[语音消息]`。本机已转写过的语音,读取时会直接带上转写结果(只读缓存,不触发识别):
|
||||||
|
|
||||||
|
- `query/messages`、`query/message-context`:`voiceTranscriptState` 与 `voiceTranscript`,`derivedSource` 为 `voice_transcript`;
|
||||||
|
- `/chatlog`:语音消息额外带 `messageRef`、`voiceTranscriptState` 与 `voiceTranscript`。
|
||||||
|
|
||||||
|
`voiceTranscriptState` 为 `pending` 表示**还没转写**,不能当成"语音里没说话"。需要内容时,把这些语音的 `messageRef` 交给 `POST /api/v1/query/voice-transcribe`:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
curl -X POST -H "$AUTH" -H 'Content-Type: application/json' "$BASE/query/voice-transcribe" \
|
||||||
|
-d '{"messageRefs":["<语音消息的 messageRef>"],"waitMs":15000}'
|
||||||
|
```
|
||||||
|
|
||||||
|
| 字段 | 含义 |
|
||||||
|
| ------------- | --------------------------------------------------------------------------------------- |
|
||||||
|
| `messageRefs` | 必填,1~20 条;重复的引用会合并 |
|
||||||
|
| `waitMs` | 可选,最多同步等待的毫秒数,默认 15000,上限 60000;`0` 表示只排队、不等待 |
|
||||||
|
| `force` | 可选,`true` 时忽略已有转写和失败记录、重新识别;只在用户明确要求重试时使用 |
|
||||||
|
|
||||||
|
识别在本机离线进行(需要先在 TraceMemo 设置里下载语音识别模型),和界面共用同一份缓存与同一条串行队列:界面上点开语音会优先处理,API 的任务随后继续。等待超时的条目返回 `pending`,识别会在后台继续;稍后用同样的 `messageRefs` 再调用即可取回结果,不会重复排队。
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"status": "completed",
|
||||||
|
"items": [
|
||||||
|
{ "messageRef": "…", "state": "transcribed", "transcript": "…", "cached": false },
|
||||||
|
{ "messageRef": "…", "state": "pending", "code": "still_processing", "hint": "…" }
|
||||||
|
],
|
||||||
|
"summary": { "transcribed": 1, "pending": 1, "failed": 0 }
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
每个未成功的条目都带 `code` 与 `hint`(下一步该怎么做):
|
||||||
|
|
||||||
|
| `code` | 含义 |
|
||||||
|
| ----------------------- | ------------------------------------------ |
|
||||||
|
| `still_processing` | 仍在后台转写,稍后原样重试 |
|
||||||
|
| `previously_failed` | 之前识别失败,默认不自动重跑 |
|
||||||
|
| `recognition_failed` | 本次识别失败(音频损坏、过短或没有人声) |
|
||||||
|
| `recognition_timeout` | 识别超时 |
|
||||||
|
| `not_voice_message` | 不是语音消息 |
|
||||||
|
| `message_not_found` | 找不到消息(可能已切换账号) |
|
||||||
|
| `invalid_message_ref` | `messageRef` 无法解析 |
|
||||||
|
|
||||||
|
整次请求的状态:`200 completed`;`400 invalid_tool_arguments`(带 `field`、`constraint`、`hint`);`503 voice_model_not_ready`(模型未下载)或 `knowledge_unavailable`(数据库未连接);`429 busy`(队列已满,带 `retryAfterSeconds` 与 `Retry-After` 头)。
|
||||||
|
|
||||||
|
## Reader Skill 的版本与更新
|
||||||
|
|
||||||
|
Reader Skill 是随应用分发的说明文件。它被安装到 Agent 自己的 Skill 目录之后就与 TraceMemo 分离了,不再随应用升级自动变化,所以它必须能自己证明版本:
|
||||||
|
|
||||||
|
- `SKILL.md` frontmatter 的 `version` 是**唯一真源**(形如 `1.4.0`);
|
||||||
|
- `/api/v1/health` 的 `skill.version` 回报当前应用内置的版本;
|
||||||
|
- 两者不一致,就说明 Agent 手里那份已经过期,接口契约可能已经变化。
|
||||||
|
|
||||||
|
### 检查更新
|
||||||
|
|
||||||
|
```bash
|
||||||
|
curl http://127.0.0.1:6131/api/v1/health
|
||||||
|
```
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"ok": true,
|
||||||
|
"ready": true,
|
||||||
|
"service": "TraceMemo Reader",
|
||||||
|
"version": "2.5.1",
|
||||||
|
"skill": { "name": "tracememo-reader", "version": "1.4.0", "available": true },
|
||||||
|
"timestamp": "2026-10-13T08:43:52.863Z"
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
注意区分两个版本号:`version` 是应用版本,`skill.version` 才是 Reader Skill 的版本。Skill 文件读不到时 `available` 为 `false`、`skill.version` 为 `null`,此时 health 仍然返回 `200`——外部 Agent 靠它做自检,这个接口不允许因为 Skill 缺失而失败。
|
||||||
|
|
||||||
|
### 拉取最新 Skill
|
||||||
|
|
||||||
|
```bash
|
||||||
|
curl -H "Authorization: Bearer $TRACEMEMO_API_TOKEN" \
|
||||||
|
"http://127.0.0.1:6131/api/v1/skill/tracememo-reader"
|
||||||
|
```
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"name": "tracememo-reader",
|
||||||
|
"version": "1.4.0",
|
||||||
|
"contentHash": "<sha256 hex>",
|
||||||
|
"modifiedAt": "2026-10-13T08:37:30.000Z",
|
||||||
|
"markdown": "---\nname: tracememo-reader\nversion: 1.4.0\n…"
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
`markdown` 就是可以直接落盘的 SKILL.md 全文,`contentHash` 是它的 SHA-256,可用来核对写入结果。响应**不包含**任何本地文件路径。`503 skill_unavailable` 表示应用侧也没找到 Skill 文件,需要重新安装 TraceMemo。
|
||||||
|
|
||||||
|
### Agent 侧的自检义务
|
||||||
|
|
||||||
|
`docs/skill/tracememo-reader/SKILL.md` 中的「版本自检」要求 Agent 在每次会话开始时比对一次版本:不一致就停止读取数据并提醒用户重新安装;用户同意后,Agent 可以直接调用上面的接口自助覆盖本地文件,不需要用户重新复制安装指令。
|
||||||
|
|
||||||
|
修改 `SKILL.md` 内容时必须同步提升 `version`。CI 中的 `pnpm check:skill-version` 会在"只改文档、不升版本"时失败,避免再次出现"文档改了两轮、版本号纹丝不动"的情况。
|
||||||
@@ -8,7 +8,7 @@ Reader Skill 是一份给 Agent 的操作说明。安装后,Codex、Claude Cod
|
|||||||
|
|
||||||
Reader Skill 只负责“外部 Agent 主动查询历史微信数据”。它不负责二维码登录、监听微信实时消息、接收机器人消息或管理 Agent Hub。想让机器人收到微信消息后处理并回复,请阅读[Agent Hub](./agent-hub.md)。
|
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`(当前没有设定移除时间),但新安装请使用新名称与新变量名。
|
||||||
|
|
||||||
## 推荐安装流程
|
## 推荐安装流程
|
||||||
|
|
||||||
@@ -26,6 +26,21 @@ Reader Skill 只负责“外部 Agent 主动查询历史微信数据”。它不
|
|||||||
|
|
||||||
TraceMemo 不会自动把 Token 写进 Agent 配置。重新生成 Token 后,必须同步更新 Agent 环境。
|
TraceMemo 不会自动把 Token 写进 Agent 配置。重新生成 Token 后,必须同步更新 Agent 环境。
|
||||||
|
|
||||||
|
## 更新已安装的 Skill
|
||||||
|
|
||||||
|
Reader Skill 在 Agent 那边是独立副本,**不会随 TraceMemo 升级自动更新**。判断是否需要更新:
|
||||||
|
|
||||||
|
1. 在 API Center 的「Skill 详情」里看到的是 TraceMemo 内置的版本;
|
||||||
|
2. Agent 调用 `/api/v1/health` 拿到 `skill.version`;
|
||||||
|
3. 再和 Agent 手里 SKILL.md frontmatter 的 `version` 比对——不一致就是过期了。
|
||||||
|
|
||||||
|
更新有两种方式,任选其一:
|
||||||
|
|
||||||
|
- **让 Agent 自己更新**:直接告诉 Agent「你的 Reader Skill 过期了,请从本机 TraceMemo 拉最新版覆盖」。它会调用 `/api/v1/skill/tracememo-reader` 取回最新全文并落盘,不需要你重新复制安装指令。
|
||||||
|
- **手工重新安装**:回到 API Center → 快速接入,重新点一次「复制安装指令」交给 Agent 覆盖安装。
|
||||||
|
|
||||||
|
新版 Skill 里带有「版本自检」条款,要求 Agent 每次会话开始时比对一次版本。**如果它从来没提醒过你版本不一致,很可能你手里那份还是旧版**——旧版没有这条自检。
|
||||||
|
|
||||||
## Agent 的读取顺序
|
## Agent 的读取顺序
|
||||||
|
|
||||||
当用户使用“今天”“昨天”“本周”等相对时间时:
|
当用户使用“今天”“昨天”“本周”等相对时间时:
|
||||||
@@ -53,8 +68,14 @@ Reader Skill 可以指导 Agent 使用:
|
|||||||
- 指定会话、日期或时间戳范围的聊天记录;
|
- 指定会话、日期或时间戳范围的聊天记录;
|
||||||
- 群成员快照;
|
- 群成员快照;
|
||||||
- 结构化日报渲染和按群聊生成总结图片;
|
- 结构化日报渲染和按群聊生成总结图片;
|
||||||
|
- 定时日报任务的查询、创建、修改、启停、删除、立即执行和执行记录;删除不可逆,Skill 要求先列出唯一任务并取得用户明确确认;
|
||||||
|
- 个人微信发送能力状态查询(`/wechat-personal/send-capability`);
|
||||||
|
- `query/*` 一组结构化 Query 端点:`messages`、`search`、`message-context`、`conversation-overview`、`voice-transcribe`;
|
||||||
|
- 自身版本查询(`/skill/tracememo-reader`),用于判断是否需要更新;
|
||||||
- Agent Hub 状态检查与已连接机器人发送测试。这里的发送接口是开发者/测试用途,不是实时机器人入口,也不会让 Reader Skill 自动监听微信消息。
|
- Agent Hub 状态检查与已连接机器人发送测试。这里的发送接口是开发者/测试用途,不是实时机器人入口,也不会让 Reader Skill 自动监听微信消息。
|
||||||
|
|
||||||
|
注意这个 API 不只是只读的:`/report`、`/agent/send` 和 `/scheduled-reports*` 会写入状态或真的发出微信消息。
|
||||||
|
|
||||||
端点、参数、错误码和鉴权细节以[Local HTTP API](./api.md)为准。Skill 文件保持短小,避免在多个文档中复制会变化的完整响应 schema。
|
端点、参数、错误码和鉴权细节以[Local HTTP API](./api.md)为准。Skill 文件保持短小,避免在多个文档中复制会变化的完整响应 schema。
|
||||||
|
|
||||||
## 隐私边界
|
## 隐私边界
|
||||||
|
|||||||
@@ -4,39 +4,54 @@
|
|||||||
|
|
||||||
```mermaid
|
```mermaid
|
||||||
flowchart LR
|
flowchart LR
|
||||||
A[本机微信数据] --> B[读取与解析]
|
WX["本机微信数据"] --> PARSE["读取与解析"]
|
||||||
B --> C[聊天档案与普通搜索]
|
|
||||||
B --> D[本地知识索引]
|
PARSE --> ARCHIVE["聊天档案与普通搜索"]
|
||||||
D --> E[筛选相关消息]
|
PARSE --> EXPORT["聊天导出"]
|
||||||
E --> F[用户配置的 AI Provider]
|
|
||||||
F --> G[回答与可核对来源]
|
PARSE --> IDX["本机索引"]
|
||||||
B --> H[聊天导出]
|
IDX --> TEXTIDX["聊天记录索引"]
|
||||||
B --> I[整理日报输入]
|
IDX --> IMGIDX["图片文字索引(本机识别)"]
|
||||||
I --> F
|
|
||||||
F --> J[本地保存 HTML 与 PNG]
|
TEXTIDX --> UNDERSTAND["Understand:AI Search / 问问微信"]
|
||||||
B --> K[Local HTTP API]
|
IMGIDX --> UNDERSTAND
|
||||||
K --> L[外部 Agent]
|
UNDERSTAND --> PROVIDER["你配置的 AI Provider"]
|
||||||
M[微信机器人消息] --> N[Agent Hub]
|
PROVIDER --> ANSWER["回答与可核对来源"]
|
||||||
N --> B
|
|
||||||
N --> F
|
PARSE --> REPORTINPUT["整理日报输入"]
|
||||||
B --> O[Monitor / Snapshot]
|
REPORTINPUT --> PROVIDER
|
||||||
O --> P[Proposed Action]
|
PROVIDER --> REPORTFILE["本机保存 HTML 与 PNG"]
|
||||||
F --> P
|
|
||||||
P --> Q[Policy]
|
PARSE --> MONITOR["Monitor:退群监控 / 成员快照"]
|
||||||
Q --> R[Action Gateway]
|
MONITOR --> RULE["自动化规则"]
|
||||||
R --> S[Personal WeChat Send Capability]
|
REPORTFILE --> RULE
|
||||||
S --> T[Action Audit / Logs]
|
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 的工作方式可以概括为:
|
TraceMemo 的工作方式可以概括为:
|
||||||
|
|
||||||
```text
|
```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
|
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 会保留执行结果;定时日报即使发送失败,也会保留已生成的报告记录。
|
Policy blocked 表示策略不允许,Capability unavailable 表示当前发送能力不可用,Send failed 表示已经尝试但执行失败。Action Audit / Logs 会保留执行结果;定时日报即使发送失败,也会保留已生成的报告记录。
|
||||||
|
|
||||||
|
这些动作统一由「自动化」管理,当前有三类规则:**@我生成日报**、**定时日报**、**退群通知**。发送目标支持当前群聊、文件传输助手、自己、指定好友,不是任意群发。
|
||||||
|
|
||||||
## 哪些步骤在本机
|
## 哪些步骤在本机
|
||||||
|
|
||||||
- 微信数据库读取与解析;
|
- 微信数据库读取与解析;
|
||||||
- 聊天档案浏览和普通搜索;
|
- 聊天档案浏览和普通搜索;
|
||||||
- Knowledge 索引与增量同步;
|
- Knowledge 索引与增量同步;
|
||||||
|
- 图片文字索引:识别图片中的文字完全在本机进行,原始图片不会因为本地识别而上传;
|
||||||
- 离线语音转写;
|
- 离线语音转写;
|
||||||
- 聊天导出文件、日报 HTML/PNG 和本地历史记录的保存。
|
- 聊天导出文件、日报 HTML/PNG 和本地历史记录的保存。
|
||||||
|
|
||||||
## 哪些步骤可能调用外部服务
|
## 哪些步骤可能调用外部服务
|
||||||
|
|
||||||
当你主动使用 AI Search、群聊日报或图片理解时,应用会把完成任务所需的受控问题和上下文发送给你配置的 Provider。它不会因为打开软件就自动上传完整数据库。
|
当你主动使用 AI Search、群聊日报或图片理解时,应用会把完成任务所需的受控问题和上下文发送给你配置的 Provider。它不会因为打开软件就自动上传完整数据库,本机 OCR、离线语音转写和普通搜索也不会触发外发。
|
||||||
|
|
||||||
Agent Hub 收到微信机器人的文字后,也可能为了理解请求或生成总结调用已配置的 Provider。Reader Skill 调用的是本机 API;外部 Agent 是否把读取结果继续交给云端模型,取决于外部 Agent 自己的配置。
|
Agent Hub 收到微信机器人的文字后,也可能为了理解请求或生成总结调用已配置的 Provider。Reader Skill 调用的是本机 API;外部 Agent 是否把读取结果继续交给云端模型,取决于外部 Agent 自己的配置。
|
||||||
|
|
||||||
@@ -76,13 +96,15 @@ Agent Hub 收到微信机器人的文字后,也可能为了理解请求或生
|
|||||||
|
|
||||||
## 产品名词和用户任务的对应关系
|
## 产品名词和用户任务的对应关系
|
||||||
|
|
||||||
| 用户想做什么 | 产品中可能看到的名称 |
|
| 用户想做什么 | 产品中可能看到的名称 |
|
||||||
| ------------------------ | ---------------------------- |
|
| ------------------------------ | ---------------------------- |
|
||||||
| 让 AI 找相关聊天 | AI Search、Retrieval |
|
| 让 AI 找相关聊天 | AI Search、Retrieval |
|
||||||
| 让答案能回到原消息 | Evidence、Citation |
|
| 让答案能回到原消息 | Evidence、Citation |
|
||||||
| 查看 AI 查找过程 | Search Trace |
|
| 查看 AI 查找过程 | Search Trace |
|
||||||
| 让跨会话查找更稳定 | Knowledge、FTS 索引 |
|
| 让跨会话查找更稳定 | Knowledge、FTS 索引 |
|
||||||
| 让外部 Agent 读取聊天 | Reader Skill、Local HTTP API |
|
| 搜到截图、公告图里写过的文字 | 图片文字索引、本机 OCR |
|
||||||
| 让微信机器人调用本机能力 | Agent Hub |
|
| 让日报、退群通知按规则自动执行 | 自动化、Policy、执行记录 |
|
||||||
|
| 让外部 Agent 读取聊天 | Reader Skill、Local HTTP API |
|
||||||
|
| 让微信机器人调用本机能力 | Agent Hub |
|
||||||
|
|
||||||
先按任务使用,再在需要排查或开发集成时阅读术语。
|
先按任务使用,再在需要排查或开发集成时阅读术语。
|
||||||
@@ -0,0 +1,308 @@
|
|||||||
|
# TraceMemo Local HTTP API / Agent API 能力审计
|
||||||
|
|
||||||
|
本报告基于当前代码、文档、IPC、Renderer 调用和相关测试做静态审计,对应当前发布应用版本 `2.5.0`;不连接真实微信数据库,也不修改生产代码、API Center 或测试。
|
||||||
|
|
||||||
|
主要代码入口:[http-server.ts](../../src/main/http-server.ts)、[automation-rule-store.ts](../../src/main/services/automation-rule-store.ts)、[group-exit-monitor-service.ts](../../src/main/services/group-exit-monitor-service.ts)、[group-stats-service.ts](../../src/main/services/group-stats-service.ts)、[api.md](../agent/api.md)。
|
||||||
|
|
||||||
|
## 1. Executive Summary
|
||||||
|
|
||||||
|
当前 HTTP 层声明了 **30 个 Method + Path 模板**:15 个 GET、12 个 POST、1 个 PATCH、1 个 DELETE、1 个 HEAD。共享 `LOCAL_API_ENDPOINTS` 定义 **14 个测试项**,但 Renderer 的 `API_ENDPOINTS` 实际只展示 **12 项**;个人微信能力和 `GET /scheduled-reports` 虽有共享定义,界面没有展示。界面也没有结构化 Query、媒体读取、定时日报写操作、退群监控、群统计、Automation 通用资源或执行日志查询。
|
||||||
|
|
||||||
|
当前不缺成熟的 Query primitive:结构化读取消息、Knowledge 搜索、消息前后文、会话概览和图片 OCR 搜索已经有 HTTP 契约。真正的能力缺口集中在 **监控配置、自动化规则通用管理、群员统计、执行历史、全局能力发现、发送状态和报告历史**。
|
||||||
|
|
||||||
|
几个影响后续设计的代码事实:
|
||||||
|
|
||||||
|
1. 定时日报已迁入 `AutomationRuleStore`。当前 `/scheduled-reports` 是旧 HTTP 契约的兼容投影,不是第二份活动规则存储;但它只表达“生成后发回来源群”,其他当前合法目标不会出现在该兼容 API 列表中。
|
||||||
|
2. 退群监控只负责监测范围、快照和事件历史;退群后如何通知由唯一的 `leave_notification` Automation 规则负责。二者应分别建资源。
|
||||||
|
3. 群统计 Service 足以提供活跃成员、当前沉默成员、时间范围、新鲜度和限制说明;它没有结构化的 former member 列表,也没有覆盖所有发言者的群总消息数。
|
||||||
|
4. 现有微信 Action Gateway 有策略、审计和幂等骨架,但策略目前主要校验收件人,以及 Automation purpose allowlist;手动用户 purpose 默认可放行。它只发个人微信,现有 `/agent/send` 则走 iLink 的 `WechatSendGateway`。两者不能直接视为统一的 Agent 安全边界。
|
||||||
|
5. HTTP 静态 GET handler 大多没有 method guard;对这些路径发 POST、PATCH 或 DELETE 仍会执行读处理。Automation store 的规则落盘失败会记录日志,但仍将内存中的规则返回为成功。
|
||||||
|
|
||||||
|
建议先做应用级能力发现、退群监控资源、严格校验后的 Automation CRUD/执行查询;发送和“立即执行”放到有 dry-run、明确确认、幂等键和 Action 审计的后续阶段。
|
||||||
|
|
||||||
|
## 2. Current API Inventory
|
||||||
|
|
||||||
|
以下按 `http-server.ts` 的路由分派和动态 route factory 盘点。静态读路由的 `Method` 是当前文档和产品语义的预期方法;实际接受方法的差异见本节末尾。
|
||||||
|
|
||||||
|
| Method | Path | 能力 | Read/Write/Execute | Service | API Center | 文档 | Agent 价值 |
|
||||||
|
|---|---|---|---|---|---|---|---|
|
||||||
|
| GET | `/api/v1/health` | HTTP 与数据库 ready 状态;唯一免 Token 路径 | Read | `isReady()` | 是 | 是 | 高:连通性 |
|
||||||
|
| GET | `/api/v1/current_time` | 本机时间、时区、日期 | Read | JavaScript `Date` | 是 | 是 | 中:相对日期换算 |
|
||||||
|
| GET | `/api/v1/contact` | 联系人和群列表;`filter`、`type`;使用异步 hydration | Read | `chat-service.listContactsAsync` | 是 | 是 | 高:标识发现与 resolve 前置 |
|
||||||
|
| GET | `/api/v1/chatroom` | 群聊列表;`keyword`;使用异步 hydration | Read | `chat-service.listContactsAsync` | 是 | 是 | 高:群标识发现 |
|
||||||
|
| GET | `/api/v1/recent_chat` | 最近会话;`limit` 默认 50 | Read | `chat-service.listRecentChat` | 是 | 是 | 高:导航/摘要 |
|
||||||
|
| GET | `/api/v1/chatlog` | 按 talker 和时间读取原始消息;移除 `contentData.aeskey` | Read | `chat-service.listMessages`、`resolveMd5` | 是 | 是 | 高,但旧式、未做结构化分页 |
|
||||||
|
| GET | `/api/v1/group_snapshot` | 群成员快照;必填 `md5` | Read | `chat-service.getGroupSnapshot` | 是 | 是 | 高:成员身份解析 |
|
||||||
|
| GET | `/api/v1/resolve` | 昵称、wxid、md5 解析为会话 | Read | `chat-service.resolveMd5` | 是 | 是 | 高;新资源宜返回稳定 ID 和歧义候选 |
|
||||||
|
| POST | `/api/v1/report` | 接收完整结构化日报并导出 HTML/PNG;当前拒绝外部 `templateRef` | Write:本地文件 | `group-report-service.exportGroupReport` | 是 | 是 | 低/中:低层渲染契约,Agent 须先拼完整结构 |
|
||||||
|
| POST | `/api/v1/agent/group-report` | 读群消息、调用 AI 生成群总结、导出 HTML/PNG | Execute:AI/本地文件 | `agent-group-report-service.generateAgentGroupReport` | 是 | 是 | 高但有模型费用/数据出站;结果不等同于报告历史记录 |
|
||||||
|
| GET | `/api/v1/agent/status` | Agent Hub、connector、数据 API、数据库状态 | Read | `agentHubService.getStatus` | 是 | 是 | 中:只覆盖 Agent Hub,不是应用总能力 |
|
||||||
|
| POST | `/api/v1/agent/send` | 通过 Agent Hub 连接器发送文字或媒体 | Execute:微信发送 | `agentHubService.testSend` → `WechatSendGateway`/iLink | 是 | 是 | 高但 R2;是测试入口,不含统一 Action policy/幂等确认 |
|
||||||
|
| GET | `/api/v1/wechat-personal/send-capability` | 个人微信 text/image/voice 能力状态 | Read | `PersonalWechatCapabilityService`,由 `ScheduledReportApiService` 包装 | 否(共享定义有,界面未展示) | 是 | 高但只代表 personal,不代表 iLink |
|
||||||
|
| GET | `/api/v1/scheduled-reports` | 列出旧 DTO 可表达的定时日报规则 | Read | `ScheduledReportApiService.list` → 规则投影 | 否(共享定义有,界面未展示) | 是 | 高但不完整:仅 `source_chat` 目标 |
|
||||||
|
| POST | `/api/v1/scheduled-reports` | 创建旧型定时日报,来源群即发送目标 | Write:规则配置 | `ScheduledReportApiService.create` → `AutomationRuleStore` | 否 | 是 | 高;功能受旧 DTO 限制 |
|
||||||
|
| GET | `/api/v1/scheduled-reports/{id}` | 单条旧型日报规则投影 | Read | `ScheduledReportApiService.get` → `AutomationRuleStore` | 否 | 是 | 中/高:只支持兼容投影规则 |
|
||||||
|
| PATCH | `/api/v1/scheduled-reports/{id}` | 修改旧型日报规则 | Write:规则配置 | `ScheduledReportApiService.update` → `AutomationRuleStore` | 否 | 是 | 高但只能改旧字段/目标 |
|
||||||
|
| DELETE | `/api/v1/scheduled-reports/{id}` | 删除旧型日报规则 | Write:删除配置 | `ScheduledReportApiService.delete` → `AutomationRuleStore` | 否 | 是 | 中;新 API 应标 R3 并防护系统规则 |
|
||||||
|
| POST | `/api/v1/scheduled-reports/{id}/enable` | 启用规则 | Write:配置/未来执行 | `ScheduledReportApiService.setEnabled` → `AutomationRuleStore` | 否 | 是 | 高;启用后未来可能发送微信 |
|
||||||
|
| POST | `/api/v1/scheduled-reports/{id}/disable` | 暂停规则 | Write:配置 | `ScheduledReportApiService.setEnabled` → `AutomationRuleStore` | 否 | 是 | 高 |
|
||||||
|
| POST | `/api/v1/scheduled-reports/{id}/run` | 手动触发完整日报规则 | Execute:可能调用 AI、保存历史、发微信 | `ScheduledReportService.runScheduledReportNow` → `AutomationService` | 否 | 是 | 高但 R2;当前无 HTTP 幂等键/确认 |
|
||||||
|
| GET | `/api/v1/scheduled-reports/{id}/executions` | 旧型 execution 历史和新 Automation execution 投影 | Read | `ScheduledReportService.listExecutions` | 否 | 是 | 高但旧响应模型/有限留存 |
|
||||||
|
| POST | `/api/v1/scheduled-reports/executions/{executionId}/retry-send` | 旧文档称复用 PNG 重发 | Execute 路由存在但当前固定 `501 not_supported` | `ScheduledReportApiService.retrySend` | 否 | **路径有,语义已失效** | 无:不能重发 |
|
||||||
|
| GET | `/api/v1/media/{mediaId}` | 读取消息关联的图片二进制 | Read | `http-media-service.readImageMedia` | 否 | 是 | 高:图像证据 |
|
||||||
|
| HEAD | `/api/v1/media/{mediaId}` | 图片资源存在性/响应头 | Read | `http-media-service.readImageMedia` | 否 | 否 | 低/中 |
|
||||||
|
| GET | `/api/v1/query/capabilities` | Query Tool 支持的结构化操作、范围和上限 | Read | `LocalQueryApiService.capabilities` | 否 | 是(独立章节) | 高,但不是 TraceMemo 应用能力清单 |
|
||||||
|
| POST | `/api/v1/query/messages` | 单会话、范围、时间、方向、类型等确定性消息读取 | Read | `LocalQueryApiService.messages` | 否 | 是 | 高:推荐 Query primitive |
|
||||||
|
| POST | `/api/v1/query/search` | Knowledge 关键词检索,返回覆盖、新鲜度和 OCR 命中 | Read | `LocalQueryApiService.search` + `KnowledgeSearchService` | 否 | 是 | 高:必须读取 coverage/freshness |
|
||||||
|
| POST | `/api/v1/query/message-context` | 通过 opaque `messageRef` 读取前后文 | Read | `LocalQueryApiService.context` | 否 | 是 | 高:稳定消息引用 |
|
||||||
|
| POST | `/api/v1/query/conversation-overview` | 单会话范围的概览证据和 source coverage | Read | `LocalQueryApiService.overview` | 否 | 是 | 高:broad summary |
|
||||||
|
|
||||||
|
路由来源:[http-server.ts](../../src/main/http-server.ts#L212)、scheduled/query/media route factory(同文件 L404-L670)。总数是代码中声明的业务方法模板,不代表静态 handler 都正确拒绝其他动词:`/health`、`/current_time`、`/contact`、`/chatroom`、`/recent_chat`、`/chatlog`、`/group_snapshot`、`/resolve`、`/agent/status` 没有检查 `req.method`。这些路径携带错误动词仍会走同一 handler;特别是 `POST /health` 也绕过 Token 检查,因为鉴权例外按 pathname 判断。新/旧路由都应 fail closed 并对不支持的方法返回 405。
|
||||||
|
|
||||||
|
全局 `OPTIONS` 在路由和鉴权前处理;媒体额外支持 HEAD。非 health 路径要求 `Authorization: Bearer …`,但 `readBody` 没有大小上限。路由外层目前没有统一请求 schema、统一错误 envelope 或 request id。
|
||||||
|
|
||||||
|
## 3. Internal Capability Inventory
|
||||||
|
|
||||||
|
这里按产品能力追 Service → IPC/Renderer → HTTP → 外部 Agent,而不是按当前 API 名字扩展。
|
||||||
|
|
||||||
|
| 业务域 | 已有能力及实现 | IPC / Renderer | HTTP 现状 | Agent 结论 |
|
||||||
|
|---|---|---|---|---|
|
||||||
|
| Chat / Contact | 联系人、群聊、最近会话、解析、历史消息、群快照、消息周边上下文、媒体定位;`contact-resolution-service` 可精确匹配别名并返回歧义候选 | `db:getContacts`、`db:getGroupSnapshot`、消息查询/around 等,Chat/Contact/档案 UI | 旧 Reader routes + `/query/*` + 图片 `/media/{id}` | 已有 Read API 基础完整。新配置应使用 `m_nsUsrName` 对应的 wxid/roomId 等稳定 ID,不应把昵称当长期键 |
|
||||||
|
| Query / Knowledge | `messages`、`search`、`message-context`、`conversation-overview`;Knowledge 索引覆盖/新鲜度;Image OCR 可进入 Knowledge 搜索和证据 | `knowledge:search/getStatus/startIndex/cancelIndex`、AI Search UI、`LocalQueryToolExecutor` | 四个 Query 操作均已 HTTP 化;`query/capabilities` 只描述 Query Tool | 没有需要重做的基础 Query primitive。缺的是统一应用 capability/status、更多外层筛选和 API Center 展示 |
|
||||||
|
| Group Analytics | 活跃/沉默当前成员、每人 messageCount/lastMessageTime、窗口时间、memberCount、unattributed/system 消息、firstMessageTime、freshness/complete/limitations;索引未新鲜时最多等待 2 秒并如实降级 | `group-stats:getMemberStats`;聊天页群统计 UI | 无 | P1 候选。当前 query 要求群 `userMd5` + epoch 毫秒。former sender 只以限制文案给出数量,没有 formerMembers 数组/结构化计数;没有覆盖 former sender 的群总消息数字段,需扩 DTO 后再承诺 |
|
||||||
|
| Group Exit Monitor | enabled/running/nativeMonitor 状态、监控 roomId 集合、lastChecked、unread、事件历史;每次回传最多 500 条,但完整事件历史 append-only 长期保存;可立即 check、改范围、启停、筛事件、清历史、mark read | `group-exit-monitor:*`;`GroupExitMonitorWorkspace` | 无 | P0。拆成 monitor state/config、events、check。`checkNow` 可能发现事件并触发自动通知,不是纯读操作;重启监控会重建快照基线,暂停期成员变化不会补报 |
|
||||||
|
| Automation | 实际规则类型:`daily_report`、`scheduled_report`、`leave_notification`。`daily_report` 是现有消息触发条件/动作链,不是任意流程引擎;退群通知为固定 ID singleton。规则 CRUD、enable、执行记录读写均已有 Service/Store | `automation:*`;AutomationWorkspace 有规则、日志、定时执行、启停、删除和状态 UI | 没有通用 Automation API;仅 scheduled-report 兼容映射 | P0。使用 typed rule union;不要把内部任意 draft 原样开放。规则创建当前缺省 enabled=true,未知值会被归一化成默认;需 HTTP 严格校验,先 disabled + validate,再显式 enable |
|
||||||
|
| WeChat Send / Action | `WechatSendGateway` 有 personal/iLink transport resolution、text/image/voice/file 统一类型及 Send Log;`WechatActionGateway` 做 capability preflight、Automation purpose allowlist、Action audit、幂等和 Automation 3 秒间隔 | `wechat-personal:send`、`sendGeneratedTtsVoice`、`wechat-action-log:list`、Agent Hub connector 相关 IPC/UI | `/agent/send` 只走 Agent Hub/iLink 测试发送;个人 capability 有独立 GET;两类日志没有 HTTP | 分 transport 公布 capability;R2 send 通过经审计的业务门面,不直接暴露底层 gateway。现有 Action Gateway 还不是普适安全策略:`triggerType=user` 不按 purpose 限制;普通 `/agent/send` 没传 idempotency key,也没有 Action audit |
|
||||||
|
| Agent Hub | status、connector login/reconnect/disconnect、notification recipient/send、logs、conversation list/detail/clear、入站 inbox retry | `agent-hub:*`;Agent Hub UI | 仅 `/agent/status` 和 `/agent/send`;无 conversation/log HTTP | status 有只读价值。对话记录包含完整收发正文;inbox 包含 context token/raw items。Connector 生命周期、登录 QR/验证码、收件箱和通知 recipient 应保持 internal |
|
||||||
|
| Reports / Templates | 手动 report render/export;AI group report;本地 Report History list/save/update template/delete;内置/已安装模板和市场 catalog/install/uninstall | `report:*`、`report-template:*`、`report-template-market:*`;Reports 与 Template Market UI | `/report` 低层 export,`/agent/group-report` AI 生成;没有 history/template API | P1:只读 Report History 元数据/资产可分离设计。现有 `listGeneratedReports` 会读取每张 PNG 为 base64,并返回结构快照和本机绝对路径,不可原样直出。模板目录可读列入 P2;安装/卸载涉及网络与本地包写入,不宜第一批开放 |
|
||||||
|
| Recall Archive | 后台监听撤回变化,最多按会话存归档消息/撤回记录;chat-service 将 archive merge 到历史读结果 | 没有独立 CRUD IPC;设置开关和消息渲染 | 没有独立 archive API;旧 `/chatlog` 可能随底层消息返回 `recalled` 标记;Query DTO 未声明 recalled 字段 | 不开放原始 archive 管理。后续 Query 应明确返回 `recalled`/来源,避免把已撤回归档当普通消息证据 |
|
||||||
|
| OCR / Image Insight | System OCR 本地识别;image-text-index status/count/start/pause/resume/cancel/clear/repair;Image Insight 读/解密图片并可调用 AI Provider | `system-ocr:*`、`image-text-index:*`、`image:*` IPC;Search/Report UI | OCR 派生文本可通过 `/query/search` 得到;索引管理、单图 AI 分析无 HTTP | 已有搜索能力可用。状态可纳入 capability/status;索引删除、key/decoder 配置、任意图像 AI 分析涉及成本、私密图片和索引破坏,不列第一批 |
|
||||||
|
| 系统 / 数据 / 其他 | account discovery、DB key 管理、数据库 connect/root 重开、设置写入、cache summary/clear、app update、voice/TTS、export/import、Reader Skill 本地安装信息 | 多组 IPC;Settings、Cache、Export、Update、Voice UI | 无相应 HTTP API | 只读脱敏运行状态可按需求列 P2;DB key/root、通用 settings patch、cache 清理、任意文件路径、更新安装、TTS synthesis 等保持 internal |
|
||||||
|
|
||||||
|
### A. Chat / Contact 与 ID 语义
|
||||||
|
|
||||||
|
- `/contact`、`/chatroom` 改用 `listContactsAsync`,因为 macOS Session 可能只有原始 wxid/chatroom id,需要 hydrate 显示名;`ScheduledReportApiService` 却使用同步 `listContacts()` 解析群名。稳定 `talker` 可直接解析,但名称输入在需要 hydration 的运行时可能失败/退化。这是可复用 adapter 应统一异步解析的理由。
|
||||||
|
- ID 现在不是一个口径:旧 Query 的 `scope.conversationId`/`target` 解析为 `Contact.md5`;`group-stats` 传 `userMd5`;监控用 `roomId`(`xxx@chatroom`);新的 scheduled automation 用 `sourceConversationId`(wxid/roomId);老 HTTP 路由混用昵称、wxid、md5。保持已有 Reader 契约不动,新 API facade 应统一对外 canonical `conversationId`(底层当前联系人的稳定 username/wxid 或 roomId),并在 main adapter 转为服务所需 md5。名称只做 resolve,不持久化到规则。
|
||||||
|
- `chatlog` 时间边界是 Unix 秒,Query `absolute` 内部也是秒,而 group stats IPC 是 epoch 毫秒;新 Agent 资源建议用带时区 ISO-8601 输入/输出,并在 facade 单点转换。
|
||||||
|
- `/query/messages` 有 200 上限,`messageRef` 是 opaque 稳定引用;图片 OCR 文字和 Coverage 分开呈现。`/chatlog` 则支持旧 talker/time 风格但读取结果没有同等结构边界;作为兼容 Reader 保留,不作为新 Agent 配置/分析的默认接口。
|
||||||
|
|
||||||
|
### B. Group Exit Monitor 与 Leave Notification
|
||||||
|
|
||||||
|
`GroupExitMonitorService` 的真实 IPC 有 `getState`、`setEnabled`、`setGroups`、`checkNow`、`listEvents`、`clearEvents`、`markRead`。事件是群成员差异事实,包含 roomId、member wxid/name、previous/current count、detectedAt;monitor state 中 `events` 只是最近 500 条快照,`totalEventCount` 对应完整内存历史。
|
||||||
|
|
||||||
|
`AutomationService.handleGroupExit` 只处理 `BUILTIN_LEAVE_NOTIFICATION_RULE_ID` 对应的 singleton 规则。规则另有 `notifyScope` / `notifyRoomIds` 二次范围、target、template。Agent 配“监控 A/B/C”需改 monitor 范围;配置通知目标/通知哪些被监控群则另改这条 leave notification automation。两者不能合并为 `/monitors/{id}/notify`。
|
||||||
|
|
||||||
|
### C. Automation 与 Scheduled Report
|
||||||
|
|
||||||
|
`AutomationRuleStore` 的真实方法有 `listRules/getRule/createRule/updateRule/saveLeaveNotificationRule/deleteRule/setRuleEnabled`;`AutomationExecutionLogService` 提供 `list/record/clear/countSince`。执行日志最多留存 200 条,clear 属于破坏性操作。规则在 `{userData}/automation/rules.json` 中 JSON 持久化。
|
||||||
|
|
||||||
|
`scheduled-report-service.ts` 的调度来源是 `automationRuleStore.listRules()`,执行交给 `AutomationService.executeScheduledRule()`,execution 从 Automation Log 投影。迁移后的旧 `tasks.json`/`executions.json` 是只读历史存档。旧 HTTP API 通过 `ScheduledReportApiService` 转换旧 DTO;创建、修改、删除、启停最终也是读写 `AutomationRuleStore`。所以正确方案是保留兼容 facade,并建立 Automation canonical API,不要继续增加第二个 scheduled-report store。
|
||||||
|
|
||||||
|
旧 facade 的限制:只列/操作可投影为 `target.type === 'wechat_group'`、且目标等于来源群的规则。如今 scheduled automation 支持 source_chat/self/file_transfer/contact,故通过新 UI 创建为文件传输助手或联系人目标的规则,会从旧 `/scheduled-reports` 列表隐藏。旧 API 输入 schema 也不能表示完整 scheduled config(成员名、消息类型、模板、timeout、postfix 等)。
|
||||||
|
|
||||||
|
写 API 前还需处理 `AutomationRuleStore` 的归一化和持久化契约:未知 ruleType 会降成 `daily_report`,大部分错误枚举会静默落安全默认;缺省 enabled 是 true;`persist()` catch 写盘错误后只记 warning,Store 仍返回创建/更新后的对象。HTTP adapter 必须先 strict validate,且 Store 需要可观察的持久化结果,不能把内存态冒充成功。
|
||||||
|
|
||||||
|
### D. Group Analytics 确认项
|
||||||
|
|
||||||
|
`GroupStatsService.getMemberStats` 已有可直接复用的核心计算;接口具体有:
|
||||||
|
|
||||||
|
- 当前群成员:`memberCount`、`activeMembers`、`silentMembers`、各活跃成员 `messageCount`/`lastMessageTime`;
|
||||||
|
- 查询窗口:`startTime`、`endTime`(epoch ms)、`firstMessageTime`;
|
||||||
|
- 数据完整性:`freshness = fresh|stale|unknown`、`complete`、`limitations`;
|
||||||
|
- 诊断:`unattributedMessages`、`excludedSystemMessages`。
|
||||||
|
|
||||||
|
成员名单是当前成员集合;知识库统计的 sender 不在当前集合时被排除,只在 `limitations` 中增加“另有 N 位窗口内发言者已不在当前群成员名单”。Service 不返回其身份/每人消息数,也没有 `totalMessageCount`。若 Agent 需要“前成员榜”或全群消息数,需要先扩展 Service/shared type;不能由 API adapter 从 limitation 文案反解析。
|
||||||
|
|
||||||
|
## 4. API / Docs / API Center Drift
|
||||||
|
|
||||||
|
| 项目 | 代码事实 | 漂移/影响 |
|
||||||
|
|---|---|---|
|
||||||
|
| HTTP、共享定义与界面列表 | HTTP 有 30 个 method/path 模板;`LOCAL_API_ENDPOINTS` 定义 14 项,Renderer `API_ENDPOINTS` 实际展示 12 项 | 16 个 HTTP 操作模板没有共享定义;另有 2 个已定义项(个人微信能力、定时日报列表)没有展示。界面仅呈现 12/30 项,不能作为完整 API catalog |
|
||||||
|
| Scheduled Report 展示 | 共享定义只有 `GET /scheduled-reports`;该项本身也未进入 Renderer 列表 | POST 和 task action 不显示,GET 列表也不显示;Agent 在 API Center 里无法发现这组 API |
|
||||||
|
| WeChat Capability 展示 | 共享定义有 `GET /wechat-personal/send-capability`;Renderer 列表未包含它 | API Center 看不到个人微信发送能力状态,用户可能误把 Agent Hub 状态当成完整发送能力 |
|
||||||
|
| Query 展示 | Query 文档在 `api.md` 的独立 LLM-friendly 章节,Service/HTTP 实现完整 | API Center 看不到;用户可能误认为 Reader API 仍只有旧 chatlog |
|
||||||
|
| Media 方法 | `/media/{mediaId}` 支持 GET、HEAD | 文档仅列 GET;API Center 都未列 |
|
||||||
|
| Retry Send | 文档表称 retry-send“复用已有 PNG 重试发送” | `ScheduledReportApiService.retrySend()` 当前无条件抛 `501 not_supported`;integration/unit tests 也未覆盖 retry 路由的这项现状 |
|
||||||
|
| Scheduled Report 完整性 | 旧 facade 只 project `source_chat` | UI 可保存的其他 scheduled target 会从旧 API list/get 隐藏;不是两份存储,但旧 API 不是 Automation API 的完整别名 |
|
||||||
|
| Health 版本 | `/health` 固定返回 `version: "1.0.0"` | 与当前 package version `2.5.0` 不同,Agent 无法据此判断应用版本 |
|
||||||
|
| HTTP 动词 | 九个静态 GET 语义路由无 method guard | POST/PATCH/DELETE 等也可能调用读取逻辑;`/health` 任意 method 均免 Token。测试目前未锁定统一 405 契约 |
|
||||||
|
| 请求/错误 schema | JSON parsing 和错误形状分散:通用 `sendError`、ScheduledReport 专用 error、Query status body、业务自身 result | Agent 要写多套解析逻辑;共享 API schema 和统一错误 code 不存在 |
|
||||||
|
| 命名 | `/contact`、`/chatroom`、`/recent_chat`、`/group_snapshot` 与 `/scheduled-reports`、`/query/*`、`/agent/*`、`/wechat-personal/*` 并存 | snake_case 旧路径、资源路径和“Agent 为业务 owner”的命名混杂;新接口不能继续沿用此漂移 |
|
||||||
|
|
||||||
|
文档 [api.md](../agent/api.md#L35) 基本列出当前 HTTP 路径,Query 在后续单独说明;除 HEAD 外没有发现漏写的当前业务路径,但 retry-send 的成功语义过期。API Center 的来源是单独的 [local-api-test.ts](../../src/shared/local-api-test.ts) 和 [apiEndpoints.ts](../../src/renderer/src/features/api-center/model/apiEndpoints.ts),没有从 HTTP route/schema 派生。测试现有 `local-api-auth` 覆盖鉴权、媒体、部分 Query 和 Agent send;`scheduled-report-api` 覆盖旧生命周期;`local-api-contact-search` 覆盖 hydrate。它们没有自动比对 HTTP route、文档、Catalog 三者,也没有覆盖全部 method guard 和 retry-send。
|
||||||
|
|
||||||
|
## 5. Candidate API Matrix
|
||||||
|
|
||||||
|
风险按本任务口径:R0 只读;R1 本地配置/应用状态修改;R2 微信发送、AI/provider 调用等外部副作用;R3 删除或清空不可轻易恢复的数据。R1 不代表没有后续行为:enable 一条定时规则会武装未来的 R2 执行。
|
||||||
|
|
||||||
|
| Capability | 当前实现 | 当前 API | 建议 | Agent 用例 | Risk | Priority |
|
||||||
|
|---|---|---|---|---|---|---|
|
||||||
|
| 联系人/群/会话 resolve | Chat Service + Contact Resolution | 有旧 routes;Query 内 resolve | 保留旧路由;新 resource 返回稳定 ID、歧义候选 | 查找群并取得 roomId | R0 | P0(复用) |
|
||||||
|
| 结构化消息/搜索/上下文/概览 | LocalQueryApiService + Knowledge | `/query/*` | 保持契约;加 route schema/catalog,后续可升级稳定 ID | 查聊天、关键词/OCR、补上下文 | R0 | P0(复用) |
|
||||||
|
| 应用 capability discovery | 各 Service 能回答局部状态 | 无;`query/capabilities` 仅 Query Tools | 新 `GET /capabilities`,区分 supported/available/reason/operations | 发现自动化、监控、统计、发送 transport | R0 | P0 |
|
||||||
|
| Group Exit Monitor 状态/范围 | GroupExitMonitorService | 仅 IPC | GET state + PATCH enabled/roomIds | 查看监控、监控/停止一个群 | R0/R1 | P0 |
|
||||||
|
| Group Exit events | Monitor JSONL + listEvents | 仅 IPC | GET 带 stable roomId/time/cursor/limit | 最近 7 天谁退群 | R0 | P0 |
|
||||||
|
| 手动检查退群 | checkNow 会扫描并触发事件 handler | 仅 IPC | 有外部通知时按 R2 操作开放,先 validate effects + confirm | 立即检查一次 | R2 | P1 |
|
||||||
|
| Automation 规则 CRUD | AutomationRuleStore | 通用 IPC;HTTP 仅旧 scheduled facade | typed union CRUD;create disabled;validate 再 enable;保护 singleton/system rules | 创建、列出、修改、暂停自动化 | R1/R3(delete) | P0 |
|
||||||
|
| Automation validation/dry-run | 现有编辑器 preview 分散;无通用 validator API | 无 | `POST /automations/validate`;不落盘、不发送 | 确认群、目标、模板、下次运行和能力 | R0 | P0 |
|
||||||
|
| Automation execution history | AutomationExecutionLogService,最多 200 条 | schedule 专属旧投影 | 规范化 Automation execution 读接口;清日志不开放第一批 | 查看失败、按 rule 过滤 | R0/R3(clear) | P0 |
|
||||||
|
| Group member stats | GroupStatsService | 仅 IPC | 按稳定 group ID + ISO window 读统计;先补 former/total 语义 | 近 30 天活跃榜 | R0 | P1 |
|
||||||
|
| WeChat capability | personal capability service;Agent Hub status | personal GET + Agent status | 新全局 capability 含 personal/iLink 和内容能力;旧路由保留 | 检查发送当前是否可用 | R0 | P0 |
|
||||||
|
| 手动微信发送 | WechatSendGateway + Action Gateway | `/agent/send` iLink test send | 新 send command 经受限 Action facade,强制 stable recipient、confirm、idempotency | 文件助手测试消息 | R2 | P1 |
|
||||||
|
| Send Log / Action audit | Send Log 500 条;Action audit 500 条;IPC action-log | 无 HTTP | 分层只读分页,preview 脱敏;按 executionId/requestId 关联 | 查最近发送失败、审计规则动作 | R0 | P1 |
|
||||||
|
| Agent Hub status | AgentHubService.getStatus | `/agent/status` + IPC | 保留 alias,新资源名归 `/agent-hub/status`,与 app capabilities 分开 | 查 Hub/connector online | R0 | P1(复用) |
|
||||||
|
| Agent Hub 对话内容 | Conversation Store,最多 50 会话×500 条 | 仅 IPC | 默认为 Internal;若产品确认需要,另做显式 opt-in、分页/时间过滤 | 查看机器人与某人的对话 | R0(高隐私) | 不建议第一批 |
|
||||||
|
| AI 群日报 | AgentGroupReportService + export | `/agent/group-report` | 保留兼容;未来先 validate model/range/group/data egress,再异步 job | 生成临时总结图片 | R2(provider/本地文件) | P1 |
|
||||||
|
| 日报历史 | ReportHistory Service,IPC CRUD | 无 | 分页 metadata DTO;图片 asset 单独下载;不返回 base64/路径/完整 snapshot | 昨天生成过哪些日报 | R0 | P1 |
|
||||||
|
| 模板列表 | Template Service + market catalog | 仅 IPC | 仅已安装模板只读列表列 P2 | 有哪些日报模板 | R0 | P2 |
|
||||||
|
| 模板安装/删除/历史改版 | Template Service/Market + Report History | 仅 IPC | 不开放通用 HTML/路径写入;将来单独授权且保留校验 | 安装或修改模板 | R1/R3 | Maybe/P2 |
|
||||||
|
| Recall archive 查询 | 内部 archive merge 到历史消息 | 无独立 API | 不单独开放磁盘 Archive;给 Query 增 `recalled` 来源标记 | 找被撤回消息 | R0(敏感/语义风险) | P2 |
|
||||||
|
| Image OCR index 操作 | image-text-index service | IPC(含 clear/repair) | coverage 状态可汇入 capabilities/status;不让 Agent 操作 clear/reset | 查 OCR 覆盖 | R0/R1/R3 | P2 |
|
||||||
|
| AI image insight | ImageInsightService 读/解密图片并调 vision provider | IPC | 不暴露任意 hash/message AI 分析,除非有成本/隐私授权 | 理解群图片 | R2 | 不建议第一批 |
|
||||||
|
| DB key、根目录、settings、cache | 多个设置/DB/cache Service | IPC/UI | 禁止通用 settings patch / 文件路径 / DB key API;只加白名单状态字段 | 修改本机数据库、安全设置 | R1/R3 | 不建议开放 |
|
||||||
|
| Connector 生命周期/inbox | AgentHubService + WechatInboundInbox | 仅 IPC/内部 | connector 登录、验证码、QR、inbox、context token 不对 Agent 暴露 | 重连或直接拿入站 token | R1/R2 | 不建议开放 |
|
||||||
|
|
||||||
|
## 6. P0 Recommendation
|
||||||
|
|
||||||
|
第一批目标是“让 Agent 能配置和核验 TraceMemo,但不意外发消息”。建议只包括:
|
||||||
|
|
||||||
|
1. `GET /api/v1/capabilities`:应用级 capability,不与现有 `/query/capabilities` 合并。返回版本、DB/readiness、supported vs available、不可用原因和依赖;发送分 personal/iLink 与 text/image/voice 能力。
|
||||||
|
2. Group Exit Monitor:读取状态、显式配置 monitored roomIds、读取历史事件。`PATCH` 只接 canonical 群 ID,拒绝不存在/非群 ID;修改范围响应明确显示后台 baseline/check 状态。`check` 先列 P1,因为它可能启动退群通知发送。
|
||||||
|
3. Automation typed CRUD:列/读规则、创建 disabled 规则、更新、显式启停、执行历史读取。Leave Notification 仍使用固定 singleton id,不允许创建重复规则;拒绝未知字段/未知 enum,而不是靠 `normalizeRuleDraft` 静默修正。
|
||||||
|
4. `POST /automations/validate`:验证目标群、稳定通知 recipient、模板变量、report/template 配置、send capability 和 nextRunAt;只返回 plan,不落盘、不发送。
|
||||||
|
5. 运行状态与错误契约:一致的 405、最大 body、请求 ID、错误 envelope;这是任何新 Agent 写接口前的 foundation,不是大规模权限系统。
|
||||||
|
|
||||||
|
Agent 实现示例(概念流程):
|
||||||
|
|
||||||
|
- “监控 A/B/C 退群”:resolve 三个群为 roomId → validate scope → PATCH monitor group IDs。
|
||||||
|
- “A 群有人退出就通知文件助手”:读取 monitor scope 和 singleton leave rule → validate 类型/notify scope/target → 更新规则但保持 disabled → 用户/Agent 明确 enable。监控与 leave-notification 是两份正交配置。
|
||||||
|
- “每天 20:00 生成产品群日报”:resolve sourceConversationId → validate scheduled rule(包含 target/transport/模板/时区/next run)→ 创建 disabled → 显式 enable。旧 `/scheduled-reports` 无法表达所有当前 config,不承担新 Agent CRUD。
|
||||||
|
- “昨天哪些自动化失败”:读 automation executions,按本机 timezone/UTC offset 和 status 查询,不清理日志。
|
||||||
|
|
||||||
|
## 7. Proposed Resource Model
|
||||||
|
|
||||||
|
采用业务 capability 资源,HTTP server 只负责 transport、auth、body、统一错误;每个 domain route 调用独立的 main-process API facade/Service adapter。Facade 复用当前 Service/Store,不把 UI IPC 当 HTTP RPC 转发层。
|
||||||
|
|
||||||
|
| Resource | 职责 | 现有路径的处理 |
|
||||||
|
|---|---|---|
|
||||||
|
| `system` | health、版本、应用级 capabilities、运行状态 | `/health` 保留;新增 `/capabilities`;`query/capabilities` 不改语义 |
|
||||||
|
| `contacts` / `groups` | 稳定 ID 列表、resolve、群成员快照/统计 | `/contact`、`/chatroom`、`/resolve`、`/group_snapshot` 保留兼容 |
|
||||||
|
| `query` | 消息/搜索/上下文/概览证据 | 现有 `/query/*` 保持;query ID 口径升级需兼容 reader skill |
|
||||||
|
| `monitors` | 退群监控范围、启停、事件、显式 check | 新 `/monitors/group-exits`,与通知规则分离 |
|
||||||
|
| `automations` | 规则 typed CRUD、validate、启停和运行 | 新 `/automations` 是 canonical HTTP resource;底层仍由 `AutomationRuleStore` 存储 |
|
||||||
|
| `executions` | 跨 Automation/Action/Send 的只读运行视图 | 新 `/executions` read model,不合并各自写存储 |
|
||||||
|
| `wechat` | transport capabilities、受控 send command、Send Log/Action audit | `/agent/send` 与 `/wechat-personal/send-capability` 保留兼容 |
|
||||||
|
| `reports` | report history 元数据/asset;installed templates read-only | `/report` 与 `/agent/group-report` 保留为不同兼容操作 |
|
||||||
|
| `agent-hub` | Hub/connector 状态;conversation API 默认 internal | `/agent/status` 保留 alias,不复用 app capability |
|
||||||
|
| `developer` | 高级 raw request tester 与诊断 | API Center 的 tester;不作为 Agent 业务 API |
|
||||||
|
|
||||||
|
共享资源原则:新 API 输入以 stable id 为主、名字只用于 resolve;所有写请求 strict validate;时间对新资源用 offset ISO-8601;分页使用 `limit` + `cursor`;成功/失败使用一个 typed envelope;不直接返回 app userData path、token、context token、AES key 或原始 transport payload。
|
||||||
|
|
||||||
|
## 8. Safety Model
|
||||||
|
|
||||||
|
### 当前边界
|
||||||
|
|
||||||
|
- 默认监听 `127.0.0.1:6131`,但 host/port 由设置和 `api:start` 调用传入,API Center 会警告非 loopback。CORS 只允许 loopback Origin,但不带 Origin 的 curl/Agent 请求仍可用 Token;CORS 不是本地进程授权边界。
|
||||||
|
- `/health` 公开,其余 endpoint 共用单一 Bearer Token。Token 为 32 random bytes、safeStorage 加密存储并设 `0600`,没有 read/config/send scope。拿到 token 即可读取聊天,也能建/删/启停规则、立即发送。
|
||||||
|
- HTTP `/agent/send` 的消息进入 `WechatSendGateway`,因此有低层 Send Log;但没有 `WechatActionGateway` 的业务 Action audit/策略决策,也没有调用方 Idempotency-Key。Personal capability 路由只报告个人微信状态。
|
||||||
|
- `WechatActionGateway` 的请求包含 `purpose`、`triggerType`、recipient、content、`idempotencyKey`、`executionId`;Automation trigger 有 purpose allowlist,sender capability 会先检查,审计记录会保存 content preview/hash。当前 `evaluateWechatActionPolicy` 对 `triggerType=user` 不做 purpose allowlist,`shouldUseAiPolicy` 固定 false;幂等只对显式 key 或历史特定 scheduled request 生效。它目前只发个人微信,不能直接替换 iLink send。
|
||||||
|
- Action Audit 和 Send Log 各自上限 500;Automation Execution Log 上限 200。三类日志粒度不同,不是重复的同一事实。
|
||||||
|
|
||||||
|
### 分级建议
|
||||||
|
|
||||||
|
| 风险 | 操作 | 建议控制 |
|
||||||
|
|---|---|---|
|
||||||
|
| R0 | 查询聊天/成员/事件/状态/统计/日志/报告元数据 | 保留本地 Token;响应明确 scope、coverage、freshness、隐私字段 |
|
||||||
|
| R1 | 修改监控群、Automation 配置、启停、模板设置 | typed validation、dry-run plan、显示持久化成功;enable 需确认它武装未来发送 |
|
||||||
|
| R2 | 微信发送、立即执行日报/退群通知 check、调用 AI Provider 生成报告 | 明确 recipient 和内容/规则;`Idempotency-Key` 必填;统一 Action policy + Action audit + Send Log;重复请求回放原结果;返回发送状态 |
|
||||||
|
| R3 | 清理退群事件、删除 report、清空执行/发送/Action 日志、清 cache/index、删规则 | 初始不开放;如以后开放,独立权限、预览计数、可恢复备份/本地确认,不接受批量 wildcard |
|
||||||
|
|
||||||
|
现有 Bearer Token 不足以支撑“查询、配置、发送、清理”都对一个不受信 Agent 开放。近期不必造完整账户系统,但应先修路由 method/body/validation,提供默认只读或 disabled 配置工作流;后续可加入多个 named token + scope(`read`, `configure`, `send`, `destructive`),R2 请求确认和 durable idempotency。风险分类也需承认本地 artifact write(如 `/report` 导出)不是配置本身,可先按 R1 local-write 处理。
|
||||||
|
|
||||||
|
## 9. Compatibility Plan
|
||||||
|
|
||||||
|
1. 不 rename/remove 任何现有 route。Reader Skill 依赖旧 contacts/chatlog/media 路径;新 structured query 已经是更合适的 Agent query,但两者并行。
|
||||||
|
2. 新 `/automations` 读写同一 `AutomationRuleStore`。旧 `/scheduled-reports*` 改为明确标注 Deprecated 的 compatibility adapter;维持现有 request/response shape 和 source_chat 子集,不维护第二个任务存储。响应可加 `Deprecation` header/文档说明,未定 sunset 前不返回 breaking error。
|
||||||
|
3. `/scheduled-reports` 的投影不能假装覆盖所有 scheduled automation。旧 list/get 只反映 source_chat;新 clients 必须迁到 `/automations?type=scheduled_report`。旧 `retry-send` 保留返回 501,文档明确废弃;不能伪造已发送成功。
|
||||||
|
4. `/agent/send` 继续表示现有 iLink/Agent Hub 测试发送。新 `/wechat/send` 必须先明确 transport/recipient schema,再通过能统一 personal+iLink 的受控 Action facade;如果不能保留旧发送语义,就将旧路径作为 adapter 而不是简单 alias。
|
||||||
|
5. `/wechat-personal/send-capability` 保持 personal-only 兼容 view;新全局 capability 返回 transport map。应用能力 `/capabilities` 和 Query Tool 的 `/query/capabilities` 各自有清晰不同的契约。
|
||||||
|
6. 同一 shared contract/catalog 应供 HTTP 验证、API Center、文档和 route contract tests 使用;把实际路由、文档和 API Center 三者 drift 变成测试失败,而不是发布后人工发现。
|
||||||
|
|
||||||
|
## 10. Proposed Phase Plan
|
||||||
|
|
||||||
|
### Phase A — HTTP Contract / Facade
|
||||||
|
|
||||||
|
给现有 routes 加明确 method guard、body size limit、严格 shared request schema、统一错误 envelope/request id;补 `AutomationRuleStore` 写盘成功/失败结果;建立稳定 conversation ID adapter 和 route contract tests。保留 raw Node HTTP,不需要为第一阶段换 web framework。
|
||||||
|
|
||||||
|
### Phase B — Read + Validation P0
|
||||||
|
|
||||||
|
增加应用 `/capabilities`、monitor state/events、automation rules/executions 读取、`/automations/validate`、group stats adapter。monitor `check` 因可能触发 notification 暂留 P1 或先加 side-effect confirmation。把新资源路径、schema、风险元数据接进 EndpointCatalog/生成文档。
|
||||||
|
|
||||||
|
### Phase C — Automation Configuration
|
||||||
|
|
||||||
|
开放 disabled create、PATCH、启停和 DELETE 防护;退群通知专用 singleton upsert 接入同一规则资源;scheduled report 使用真实完整 config;旧 scheduled API 只做 compatibility projection。先做 dry-run 再允许 enable。
|
||||||
|
|
||||||
|
### Phase D — Side Effects / Execution Read Model
|
||||||
|
|
||||||
|
扩展一层统一 `Action` facade 支持 iLink + personal transports,并有 per-purpose policy、recipient allowlist/validation、确认语义、强幂等、Action audit 到 Send Log correlation。再开放 send/check/run;按需增加 `/executions` read projection,不合并底层日志存储。
|
||||||
|
|
||||||
|
### Phase E — API Center
|
||||||
|
|
||||||
|
Overview、Query、Monitors、Automations、WeChat Actions、Reports、Developer 分区;按业务任务做 schema-aware 表单/效果预览,Raw Request Tester 留在 Developer。展示 Token scope/host 范围/transport capability,而不只是固定 URL 测试器。
|
||||||
|
|
||||||
|
## 11. Concrete Endpoint Proposal
|
||||||
|
|
||||||
|
下表是下一阶段建议契约,不表示当前已实现。新写 API 应统一错误:`{"error":{"code":"...","message":"...","details":{...}},"requestId":"..."}`。时间使用带 offset 的 ISO-8601;接口只接受 stable IDs。
|
||||||
|
|
||||||
|
| Method | Path | Request → Response | Risk | Underlying Service |
|
||||||
|
|---|---|---|---|---|
|
||||||
|
| GET | `/api/v1/capabilities` | 无 → app version/readiness + `query`,`groups.memberStats`,`groupExitMonitor`,`automations`、每种 `wechat.transport/content` 的 `supported/available/reason` | R0 | 新薄 facade 汇总 LocalQuery、GroupStats、Monitor、AutomationStore、personal capability、AgentHub status |
|
||||||
|
| GET | `/api/v1/monitors/group-exits` | 无 → `{enabled,running,monitoredConversationIds,lastCheckedAt,eventCount}` | R0 | `GroupExitMonitorService.getState` |
|
||||||
|
| PATCH | `/api/v1/monitors/group-exits` | `{enabled?,monitoredConversationIds?}` → 保存后的 state;监控 ID 必须 resolve 到现有群 | R1 | `setEnabled` / `setMonitoredRoomIds` |
|
||||||
|
| GET | `/api/v1/monitors/group-exits/events?conversationId=&since=&until=&limit=&cursor=` | ISO 时间和稳定群 ID → `{events,nextCursor}`,事件显式 `eventId`、group/member、counts、detectedAt | R0 | `GroupExitMonitorService.listEvents`;为无 cursor 的现有 list 加稳定分页 adapter |
|
||||||
|
| POST | `/api/v1/monitors/group-exits/check` | `{confirmSideEffects:true}` + `Idempotency-Key` → checkedAt、新事件数、notification execution refs | R2 | `checkNow`;因检查可发现事件并调用 leave-notification Automation,不应标成纯读 |
|
||||||
|
| GET | `/api/v1/automations?type=&enabled=` | 无 → typed rules page;包括 singleton leave rule | R0 | `AutomationRuleStore.listRules` |
|
||||||
|
| POST | `/api/v1/automations` | typed `AutomationRuleDraft`,create 默认 `enabled:false` → `{rule}` | R1 | `AutomationRuleStore.createRule`(需先强化 strict validation/persist result) |
|
||||||
|
| GET | `/api/v1/automations/{ruleId}` | 无 → `{rule}` | R0 | `AutomationRuleStore.getRule` |
|
||||||
|
| PATCH | `/api/v1/automations/{ruleId}` | typed partial config → `{rule}`;`ruleType` 不可变 | R1 | `AutomationRuleStore.updateRule` |
|
||||||
|
| DELETE | `/api/v1/automations/{ruleId}` | 无 → `{deletedId}`;默认拒绝 builtin/system singleton 删除 | R3 | `AutomationRuleStore.deleteRule` + protected-id policy |
|
||||||
|
| POST | `/api/v1/automations/validate` | typed draft → `{valid,normalizedDraft,issues,effects,resolvedTargets,nextRunAt,capabilities,validationId}`;不保存、不发送 | R0 | 新 validator adapter:contact resolve、template validator、capability services、schedule pure functions |
|
||||||
|
| POST | `/api/v1/automations/{ruleId}/enable` | `{validationId,confirmFutureEffects:true}` → `{rule}`;validation hash 必须匹配当前规则 | R1(武装未来 R2) | `AutomationRuleStore.setRuleEnabled` + validator |
|
||||||
|
| POST | `/api/v1/automations/{ruleId}/disable` | 无 → `{rule}` | R1 | `AutomationRuleStore.setRuleEnabled` |
|
||||||
|
| POST | `/api/v1/automations/{ruleId}/run` | `{confirmSideEffects:true}` + `Idempotency-Key` → `{execution}` | R2 | `AutomationService.executeScheduledRule`;只对具有 `run` 语义的 rule type 开放 |
|
||||||
|
| GET | `/api/v1/automations/executions?ruleId=&status=&trigger=&since=&until=&limit=&cursor=` | 无 → `{executions,nextCursor}` | R0 | `AutomationExecutionLogService.list`;需加 timestamp/filter/cursor adapter |
|
||||||
|
| GET | `/api/v1/groups/{conversationId}/member-stats?start=&end=` | ISO 时间窗口 → active/silent/counts/freshness/complete/limitations;未来要 former members 则先扩 shared result | R0 | `GroupStatsService.getMemberStats`;adapter 把 canonical roomId 转 md5 |
|
||||||
|
| GET | `/api/v1/wechat/capabilities` | 无 → personal/iLink 分 transport 状态与内容能力 | R0 | `PersonalWechatCapabilityService` + `WechatSendGateway.hasIlinkSender`/Agent Hub connector health |
|
||||||
|
| POST | `/api/v1/wechat/send` | `{recipient:{type,id},content:{type:"text",text},confirm:true}` + 必填 `Idempotency-Key` → `{actionId,status,transport,sendLogRef}` | R2 | 扩展后的 `WechatActionGateway`/统一 Action facade;不得裸调 `WechatSendGateway.send` |
|
||||||
|
| GET | `/api/v1/wechat/send-logs?status=&since=&limit=&cursor=` | 无 → 只读、脱敏 Send Log page | R0 | `WechatSendGateway.listSendLog` / `WechatSendLogService.list` |
|
||||||
|
| GET | `/api/v1/wechat/action-logs?executionId=&status=&since=&limit=&cursor=` | 无 → 业务 Action 审计 page;preview 默认截短/可省略 | R0 | `WechatActionLogService.list` / `WechatActionGateway.listAuditRecords` |
|
||||||
|
| GET | `/api/v1/executions?source=&status=&since=&until=&limit=&cursor=` | 无 → 统一只读 projection,每项保留 source/executionId/trigger/action/status/error/times/correlation IDs | R0 | 组合 `AutomationExecutionLogService`、Action audit、Send Log;不合并其存储 |
|
||||||
|
| GET | `/api/v1/reports/history?groupId=&since=&until=&limit=&cursor=` | 无 → 仅元数据分页,不带 `generatedImage`、本地绝对路径或完整 report snapshot | R0 | `listGeneratedReports` 经 summary adapter,最好先让 Service 支持 metadata-only |
|
||||||
|
| GET | `/api/v1/reports/history/{reportId}/image` | 无 → PNG binary | R0 | Report History 的 file resolver;仅按内部 report id 解析,不接收任意路径 |
|
||||||
|
| GET | `/api/v1/report-templates` | 无 → 已安装模板的 stable id/name/version/available 列表 | R0 | `reportTemplateService.list` |
|
||||||
|
| GET | `/api/v1/agent-hub/status` | 无 → hub/connector/dataApi/dbReady 的脱敏状态 | R0 | `AgentHubService.getStatus`;`/api/v1/agent/status` 保留 alias |
|
||||||
|
|
||||||
|
`POST /wechat/send` 建议先只开放 text + 明确目标;image path/url、voice 和 file 类型各自扩大本机文件/外传风险,需独立 validation/permission,不从现有任意 `msg` 输入自动继承。
|
||||||
|
|
||||||
|
## 12. Do Not Expose
|
||||||
|
|
||||||
|
- 任意数据库 key、图片 AES key、微信登录凭据、iLink `context_token`/bot token、inbound inbox raw items;这些是密钥或未处理消息,不是业务 API。
|
||||||
|
- 通用 `settings:set`、任意 `dbRoot`、数据库 disconnect/reopen、cache 全清、Knowledge/OCR 索引 clear/reset;配置或 destructive blast radius 远高于 Agent automation 管理需求。
|
||||||
|
- Agent Hub QR/login/verify-code/reconnect/disconnect/connector lifecycle。它会影响进程状态/账户登录,也会暴露登录材料。
|
||||||
|
- `WechatInboundInbox` pending/clear/complete/recordFailure 等队列控制。它是 at-least-once 消息交付内部机制,外部 ack 会破坏不丢消息语义。
|
||||||
|
- Agent Hub 完整对话正文默认不暴露。若明确产品需要,独立设计用户授权、最小时间窗口、分页、清理和脱敏;现有 Conversation Store 为本机完整收发留档。
|
||||||
|
- 任意本地 file path、path traversal 类导出/报告资产操作;不要把 IPC 的 file chooser、reveal、delete path 形状直接变 HTTP 参数。
|
||||||
|
- 单图 AI insight/任意 Vision analyze、批量 TTS synthesis、AI Provider 配置/测试和 app update download/install;它们具有费用、敏感图片/文本上传或应用安装影响。
|
||||||
|
- 清除退群、Automation、发送/Action、报告历史或批量发送接口作为 P0。清理类不是“管理配置”的必要前提,应使用 R3 独立权限及本地可恢复流程。
|
||||||
|
- 通用“任意 Automation DAG/任意脚本/任意 purpose”的创建。当前实现只有明确的三类规则和固定动作,不是 workflow engine;扩展功能应有显式 ruleType/schema,而不是暴露内存对象。
|
||||||
|
|
||||||
|
## 13. Open Questions
|
||||||
|
|
||||||
|
以下属于产品边界选择,无法只从代码决定:
|
||||||
|
|
||||||
|
1. 新 Agent API 是否允许同时操作个人微信和 Agent Hub/iLink,还是第一版限定一个 transport?现有 capability 与 send endpoint 分属两套连接状态。
|
||||||
|
2. Agent 是否默认只拿只读 scope;配置和 R2 send 是否要求独立 token/用户确认?当前只有单一 Bearer Token。
|
||||||
|
3. 多账号是否属于本阶段?当前 Query/GroupExit 绑定当前活动数据库账号,Agent Hub 有自己的 connector accountId;没有统一 account-scoped API model。
|
||||||
|
4. Agent Hub 完整对话是否要作为 API capability?它含完整消息正文,和从微信数据库按 query 搜历史是不同隐私边界。
|
||||||
|
|
||||||
|
真实微信 runtime 可用性、平台 hydration 和 transport 能力需在后续实现集成测试中验证;静态代码审计无法替代真实数据库/微信连接的运行时验证。
|
||||||
@@ -6,7 +6,6 @@
|
|||||||
|
|
||||||
执行 `pnpm dev` 后,以下状态同时满足,说明本地开发环境已经可用:
|
执行 `pnpm dev` 后,以下状态同时满足,说明本地开发环境已经可用:
|
||||||
|
|
||||||
- 控制台显示连接器已生成,例如 `resources/connectors/wechat/win32-x64/wechat-connector.exe`;
|
|
||||||
- Electron 窗口已打开,或 `http://localhost:5173/` 返回 HTTP `200`;
|
- Electron 窗口已打开,或 `http://localhost:5173/` 返回 HTTP `200`;
|
||||||
- 控制台显示 Local HTTP API 正在监听 `http://127.0.0.1:6131`。
|
- 控制台显示 Local HTTP API 正在监听 `http://127.0.0.1:6131`。
|
||||||
|
|
||||||
@@ -22,18 +21,6 @@ WCDB_DEBUG_LOGS=1 pnpm dev
|
|||||||
|
|
||||||
开启后会输出 `GETMSG-xxx` 请求耗时和 native `WCDB-EXPLAIN` 执行计划,不记录聊天正文。取消该环境变量或设为 `0` 即可关闭。
|
开启后会输出 `GETMSG-xxx` 请求耗时和 native `WCDB-EXPLAIN` 执行计划,不记录聊天正文。取消该环境变量或设为 `0` 即可关闭。
|
||||||
|
|
||||||
## Go 命令找不到
|
|
||||||
|
|
||||||
如果 `pnpm dev` 在构建微信连接器时出现 `spawnSync go ENOENT`,先执行:
|
|
||||||
|
|
||||||
```bash
|
|
||||||
go version
|
|
||||||
```
|
|
||||||
|
|
||||||
命令不可用表示当前终端的 `PATH` 没有找到 Go。Windows 默认安装位置是 `C:\Program Files\Go\bin`。确认 Go 已安装并把该目录加入系统 `PATH` 后,关闭并重新打开终端或 IDE,再重新执行 `go version` 和 `pnpm dev`。
|
|
||||||
|
|
||||||
如果 Go 刚完成安装,已经打开的终端不会自动继承新的环境变量;重开终端是必要步骤。不要绕过连接器构建直接启动 `electron-vite dev`,否则 Agent Hub 的微信连接器不会生成。
|
|
||||||
|
|
||||||
## Electron 二进制缺失或下载失败
|
## Electron 二进制缺失或下载失败
|
||||||
|
|
||||||
`electron-vite dev` 报 `Electron uninstall`,或 Electron 安装器报 `fetch failed`,通常表示 `node_modules/electron/dist` 中的 Electron 二进制缺失或下载未完成。这不是应用业务代码的启动错误。
|
`electron-vite dev` 报 `Electron uninstall`,或 Electron 安装器报 `fetch failed`,通常表示 `node_modules/electron/dist` 中的 Electron 二进制缺失或下载未完成。这不是应用业务代码的启动错误。
|
||||||
@@ -68,4 +55,4 @@ Vite 在某些 Windows 环境中只监听 IPv6 本机回环地址 `::1`。这时
|
|||||||
|
|
||||||
## 仍无法启动时
|
## 仍无法启动时
|
||||||
|
|
||||||
保留首次错误的完整输出,并同时记录操作系统、Node.js、pnpm 和 Go 版本,以及 `pnpm install --frozen-lockfile` 与 `pnpm dev` 的执行结果。不要提交数据库密钥、AI API Key、微信数据路径或聊天内容。
|
保留首次错误的完整输出,并同时记录操作系统、Node.js 与 pnpm 版本,以及 `pnpm install --frozen-lockfile` 与 `pnpm dev` 的执行结果。不要提交数据库密钥、AI API Key、微信数据路径或聊天内容。
|
||||||
@@ -0,0 +1,28 @@
|
|||||||
|
# macOS 版本发送能力二次开发
|
||||||
|
|
||||||
|
如果你已经拥有 TraceMemo 发送能力授权,并希望基于源码进行二次开发,请联系授权人获取开发环境所需的发送能力组件包。
|
||||||
|
|
||||||
|
## 1. 安装发送能力组件
|
||||||
|
|
||||||
|
获取组件包后,将以下文件放到项目对应目录:
|
||||||
|
|
||||||
|
| 组件 | 放入目录 |
|
||||||
|
| ----------------------- | --------------------------------- |
|
||||||
|
| `tm-wechat-host` | `resources/runtime/darwin-arm64/` |
|
||||||
|
| `libtmwechat.dylib` | `resources/runtime/darwin-arm64/` |
|
||||||
|
| `runtime-manifest.json` | `resources/runtime/darwin-arm64/` |
|
||||||
|
| `libwcdb_api.dylib` | `resources/wcdb/macos/arm64/` |
|
||||||
|
| `libWCDB.dylib` | `resources/wcdb/macos/arm64/` |
|
||||||
|
| `tm-wcdb-config-helper` | `resources/wcdb/macos/arm64/` |
|
||||||
|
| `libtmlicense.dylib` | `resources/wcdb/macos/arm64/` |
|
||||||
|
|
||||||
|
完成后,为以下两个文件添加执行权限:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
chmod 755 resources/runtime/darwin-arm64/tm-wechat-host
|
||||||
|
chmod 755 resources/wcdb/macos/arm64/tm-wcdb-config-helper
|
||||||
|
```
|
||||||
|
|
||||||
|
完成配置后,启动 TraceMemo 开发环境,在「设置 → 微信发送」中查看发送能力与授权状态。
|
||||||
|
|
||||||
|
**注意:** 发送能力组件不包含授权。开发环境仍需使用有效的设备授权才能绑定微信和发送消息。
|
||||||
@@ -6,7 +6,6 @@
|
|||||||
|
|
||||||
- Electron + React + TypeScript;
|
- Electron + React + TypeScript;
|
||||||
- pnpm 7+;
|
- pnpm 7+;
|
||||||
- Go(构建微信连接器);
|
|
||||||
- 平台对应的 Electron/native 构建环境。
|
- 平台对应的 Electron/native 构建环境。
|
||||||
|
|
||||||
产品文档的事实来源优先级是:当前源码 → 当前 UI/Renderer → 测试 → package/config → README/docs → 历史资料。功能、API、版本、隐私和兼容性变更时,不要只改 README。
|
产品文档的事实来源优先级是:当前源码 → 当前 UI/Renderer → 测试 → package/config → README/docs → 历史资料。功能、API、版本、隐私和兼容性变更时,不要只改 README。
|
||||||
@@ -18,7 +17,7 @@ pnpm install
|
|||||||
pnpm dev
|
pnpm dev
|
||||||
```
|
```
|
||||||
|
|
||||||
本地依赖安装、Go 环境和 Electron 二进制下载异常,请查看[本地启动排障](./local-startup-troubleshooting.md)。
|
本地依赖安装与 Electron 二进制下载异常,请查看[本地启动排障](./local-startup-troubleshooting.md)。
|
||||||
|
|
||||||
常用检查:
|
常用检查:
|
||||||
|
|
||||||
@@ -30,21 +29,28 @@ pnpm test:integration
|
|||||||
pnpm test:e2e:build
|
pnpm test:e2e:build
|
||||||
```
|
```
|
||||||
|
|
||||||
完整测试入口 `pnpm test` 还会运行 Skill 安装指令、微信连接器、构建和 Playwright 测试;需要对应平台环境。
|
完整测试入口 `pnpm test` 还会运行 Skill 安装指令、构建和 Playwright 测试;需要对应平台环境。
|
||||||
|
|
||||||
## 代码变更对应文档
|
## 代码变更对应文档
|
||||||
|
|
||||||
| 代码区域 | 需要同步检查的文档 |
|
| 代码区域 | 需要同步检查的文档 |
|
||||||
| --------------------------------------------------------- | ------------------------------------------------------- |
|
| ------------------------------------------------------------------------ | ------------------------------------------------------------------------------ |
|
||||||
| `src/shared/ai-search.ts`、AI Search pipeline | `user-guide/ai-search.md`、`concepts/answer-sources.md` |
|
| `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/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/voice-recognition.ts` | `user-guide/voice.md` |
|
||||||
| `src/shared/group-report.ts`、报告 UI | `user-guide/report.md`、API/Agent 文档 |
|
| `src/shared/group-report.ts`、报告 UI | `user-guide/report.md`、API/Agent 文档 |
|
||||||
| `src/shared/export.ts`、导出服务/UI | `user-guide/export.md` |
|
| `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/shared/local-api-test.ts`、`src/main/http-server.ts` | `agent/api.md`、`api-security.md`、打包 Skill |
|
| `src/main/services/image-insight-service.ts`、AI Provider | `user-guide/report.md`、`user-guide/privacy.md` |
|
||||||
| Agent Hub service/UI | `agent/agent-hub.md`、`user-guide/privacy.md` |
|
| `src/shared/automation.ts`、自动化服务与执行网关 | `user-guide/report.md`、`concepts/how-it-works.md`、`docs/README.md` |
|
||||||
| 设置导航、连接页面 | `user-guide/getting-started.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)是两条不同的路径**:前者写入本地索引、能被搜索,且不联网;后者只在日报和设置里的模型检测中使用。改其中一条时不要把另一条的隐私口径带过去。
|
||||||
|
|
||||||
## 文档检查
|
## 文档检查
|
||||||
|
|
||||||
@@ -52,7 +58,10 @@ pnpm test:e2e:build
|
|||||||
|
|
||||||
```bash
|
```bash
|
||||||
git diff --check
|
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` 一致。
|
||||||
@@ -0,0 +1,171 @@
|
|||||||
|
# 界面开发规范:按钮与主题色
|
||||||
|
|
||||||
|
这份规范回答一件事:**为什么同一个产品里,有的按钮是主题色,有的还是浏览器默认的黑白方角。**
|
||||||
|
|
||||||
|
先看一个真实案例 —— 同一屏里的两组按钮:
|
||||||
|
|
||||||
|
```
|
||||||
|
主界面:「更新图片文字索引」 ← 主题色(正确)
|
||||||
|
弹窗里:「取消」「开始索引」 ← 浏览器默认样式(错误)
|
||||||
|
```
|
||||||
|
|
||||||
|
两者渲染出来完全不同,用户会以为是两个不同的产品。根因不是"设计没定颜色",
|
||||||
|
而是**组件在导出时把样式丢了**。下面写清楚怎么避免。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 1. 永远不要写裸 `<button>`
|
||||||
|
|
||||||
|
任何可点的按钮都必须来自 `components/ui/button`:
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
import { Button } from '../ui'
|
||||||
|
|
||||||
|
<Button variant="outline" onClick={handleCancel}>取消</Button>
|
||||||
|
```
|
||||||
|
|
||||||
|
**唯一的例外**:结构性控件(导航项、Tab、列表行、图标热区)——它们有自己
|
||||||
|
成套的布局样式,用原生 `<button>` 是合理的,但**必须**带 `className`,
|
||||||
|
且样式写在对应的 `.scss` 里,不要在 JSX 里临时拼颜色。
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
// 可以:结构性控件,样式来自 .scss
|
||||||
|
<button type="button" role="tab" className={active ? 'active' : ''} onClick={...}>
|
||||||
|
今日日报
|
||||||
|
</button>
|
||||||
|
```
|
||||||
|
|
||||||
|
**判据**:如果这个按钮在别的界面也会以同样形态出现("取消"、"保存"、"删除"),
|
||||||
|
它就该是 `Button`;如果它只在某一个位置有意义(侧栏导航项),才考虑原生。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 2. 三种角色,只有三个默认变体
|
||||||
|
|
||||||
|
`Button` 提供 6 个变体,但**日常只用其中 3 个**:
|
||||||
|
|
||||||
|
| 角色 | `variant` | 长什么样 | 用在哪 |
|
||||||
|
| --- | --- | --- | --- |
|
||||||
|
| 主要 | `default` | 主题色实底 | 这一步用户唯一该做的事 |
|
||||||
|
| 次要 | `outline` / `ghost` | 描边 / 无底色 | 取消、返回、并列的辅助操作 |
|
||||||
|
| 危险 | `destructive` | 红色实底 | 删除、清空、不可恢复的操作 |
|
||||||
|
|
||||||
|
另外两个(`secondary` / `link`)按需用;`link` 只用于正文里的行内跳转。
|
||||||
|
|
||||||
|
**一条硬约束:同一个界面(或同一个弹窗)里,`default` 最多出现一次。**
|
||||||
|
两个主题色实底按钮并排,等于没有主次。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 3. 弹窗按钮:组件已经带样式了,不要再包一层
|
||||||
|
|
||||||
|
`AlertDialogCancel` 和 `AlertDialogAction` **自带**按钮样式(分别是 `outline`
|
||||||
|
和 `default`),直接写文字即可:
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
<AlertDialogFooter>
|
||||||
|
<AlertDialogCancel>取消</AlertDialogCancel>
|
||||||
|
<AlertDialogAction onClick={handleStart}>开始索引</AlertDialogAction>
|
||||||
|
</AlertDialogFooter>
|
||||||
|
```
|
||||||
|
|
||||||
|
**不要**再套一层 `Button`:
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
// 反面写法:外层已经有样式了,再包一层只会产生重复类名
|
||||||
|
<AlertDialogCancel asChild>
|
||||||
|
<Button variant="outline">取消</Button>
|
||||||
|
</AlertDialogCancel>
|
||||||
|
```
|
||||||
|
|
||||||
|
需要危险动作时,用 `className` 覆盖(`cn` 走 tailwind-merge,同族类后者生效):
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
<AlertDialogAction className="bg-destructive text-destructive-foreground">
|
||||||
|
删除
|
||||||
|
</AlertDialogAction>
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 4. 颜色只能用语义 token,禁止硬编码
|
||||||
|
|
||||||
|
颜色全部走 Tailwind 的语义类,它们背后是 `--tm-*` 变量,换主题时自动跟随:
|
||||||
|
|
||||||
|
```
|
||||||
|
背景 bg-primary / bg-surface / bg-accent / bg-destructive
|
||||||
|
文字 text-foreground / text-primary-foreground / text-muted-foreground
|
||||||
|
描边 border-border / border-border-subtle / border-disabled-border
|
||||||
|
```
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
// 对
|
||||||
|
<Button className="bg-primary text-primary-foreground">保存</Button>
|
||||||
|
|
||||||
|
// 错 —— 换主题时这行不会跟着变
|
||||||
|
<Button className="bg-[#247a63] text-white">保存</Button>
|
||||||
|
```
|
||||||
|
|
||||||
|
**判据**:JSX 里出现 `#` 开头的颜色、`rgb(...)`、或 Tailwind 的调色板名
|
||||||
|
(`bg-green-600`、`text-slate-500`)—— 都是漏用 semantic token 的信号。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 5. 「默认样式」的三个常见来源
|
||||||
|
|
||||||
|
排查界面里冒出来的黑白方角按钮时,按这个顺序找:
|
||||||
|
|
||||||
|
**① 组件导出时把样式丢了。** 最常见。把 Radix 的 primitive 原样导出:
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
// 错:渲染出来就是浏览器默认按钮
|
||||||
|
const AlertDialogCancel = AlertDialogPrimitive.Cancel
|
||||||
|
```
|
||||||
|
|
||||||
|
正确做法是 `forwardRef` 包一层,挂上 `buttonVariants`:
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
const AlertDialogCancel = React.forwardRef<...>(({ className, ...props }, ref) => (
|
||||||
|
<AlertDialogPrimitive.Cancel
|
||||||
|
ref={ref}
|
||||||
|
className={cn(buttonVariants({ variant: 'outline' }), className)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
))
|
||||||
|
```
|
||||||
|
|
||||||
|
**判据**:`components/ui/` 里凡是导出 Radix primitive 的地方,都要确认它是
|
||||||
|
"样式化的封装"还是"原样透传"。原样透传只对布局容器(`Root` / `Portal` /
|
||||||
|
`Group`)成立,对**可点元素**(`Close` / `Action` / `Cancel` / `Item`)不成立。
|
||||||
|
|
||||||
|
**② `asChild` 里重复包了一层。** 外层已经带样式、子元素又带一次,虽然因为
|
||||||
|
同族类后生效而不会出错,但会产生冗余类名。**能去掉一层就去掉。**
|
||||||
|
|
||||||
|
**③ 原生 `<button>` 忘写 `className`。** 见第 1 节的例外条款 —— 结构性控件也必须
|
||||||
|
有样式来源。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 6. 提交前检查清单
|
||||||
|
|
||||||
|
- [ ] 新增的可点元素来自 `Button`,不是裸 `<button>`
|
||||||
|
- [ ] 同一界面里 `default` 变体不超过一个
|
||||||
|
- [ ] 危险操作走 `destructive`,不是红色硬编码
|
||||||
|
- [ ] 弹窗按钮没有重复包 `Button`
|
||||||
|
- [ ] JSX 里没有 `#` 开头的颜色、没有 Tailwind 调色板名
|
||||||
|
- [ ] `components/ui/` 里新导出的可点 primitive 已经挂上 `buttonVariants`
|
||||||
|
- [ ] 组件测试覆盖到按钮的可见性与点击行为(testid 用 `xxx-yyy` 连字符命名)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 7. 一个反面案例的复盘
|
||||||
|
|
||||||
|
弹窗里的「取消 / 开始索引」显示成浏览器默认样式,原因就是第 5 节第 ① 条:
|
||||||
|
`alert-dialog.tsx` 把 `Cancel` / `Action` 两个 primitive 原样导出了。
|
||||||
|
|
||||||
|
修复是给它们各加一个 `forwardRef` 封装,挂上 `buttonVariants`。**组件本身没坏**,
|
||||||
|
所有调用方一行不用改,样式自动生效 —— 这正是把样式收在 `components/ui/` 里的价值:
|
||||||
|
**修一处,全产品对齐。**
|
||||||
|
|
||||||
|
如果你发现某个地方的按钮"没跟上主题",先别去改那个界面 ——
|
||||||
|
**先看它用的组件是不是漏了样式。**
|
||||||
@@ -0,0 +1,92 @@
|
|||||||
|
# 微信系统消息(sysmsg)解析与格式兼容
|
||||||
|
|
||||||
|
微信的「系统消息」(入群、撤回、成员变动等)以 XML(`<sysmsg>`)存放在消息内容里,
|
||||||
|
但**同一类提示的 XML 结构会随客户端版本变化**。本文说明 TraceMemo 的解析方式,
|
||||||
|
以及在遇到新格式时应当怎么扩展。
|
||||||
|
|
||||||
|
## 两类格式
|
||||||
|
|
||||||
|
### 旧格式:正文直接放在 `<plain>`
|
||||||
|
|
||||||
|
```xml
|
||||||
|
<sysmsg type="delchatroommember">
|
||||||
|
<delchatroommember>
|
||||||
|
<plain><![CDATA["成员昵称"通过扫描你分享的二维码加入群聊]]></plain>
|
||||||
|
<text><![CDATA["成员昵称"通过扫描你分享的二维码加入群聊]]></text>
|
||||||
|
<link>
|
||||||
|
<scene>qrcode</scene>
|
||||||
|
<text><![CDATA[撤销]]></text>
|
||||||
|
</link>
|
||||||
|
</delchatroommember>
|
||||||
|
</sysmsg>
|
||||||
|
```
|
||||||
|
|
||||||
|
解析:命中 `delchatroommember`,直接取 `<plain>`。
|
||||||
|
|
||||||
|
### 新格式:正文在 `<template>`,用 `$名称$` 引用 link
|
||||||
|
|
||||||
|
```xml
|
||||||
|
<sysmsg type="sysmsgtemplate">
|
||||||
|
<sysmsgtemplate>
|
||||||
|
<content_template type="tmpl_type_profilewithrevokeqrcode">
|
||||||
|
<plain><![CDATA[]]></plain>
|
||||||
|
<template><![CDATA["$adder$"通过扫描你分享的二维码加入群聊 $revoke$]]></template>
|
||||||
|
<link_list>
|
||||||
|
<link name="adder" type="link_profile">
|
||||||
|
<memberlist><member>
|
||||||
|
<username><![CDATA[wxid_xxxxxxxx]]></username>
|
||||||
|
<nickname><![CDATA[成员昵称]]></nickname>
|
||||||
|
</member></memberlist>
|
||||||
|
</link>
|
||||||
|
<link name="revoke" type="link_revoke_qrcode" hidden="1">
|
||||||
|
<title><![CDATA[撤销]]></title>
|
||||||
|
</link>
|
||||||
|
</link_list>
|
||||||
|
</content_template>
|
||||||
|
</sysmsgtemplate>
|
||||||
|
</sysmsg>
|
||||||
|
```
|
||||||
|
|
||||||
|
三个要点:
|
||||||
|
|
||||||
|
- `<plain>` 变成**空 CDATA**,正文挪进 `<template>`;
|
||||||
|
- 正文里的 `$名称$` 是占位符,按 `<link_list>` 中 `link[name]` 回填;
|
||||||
|
- `hidden="1"` 的 link 在微信里是**可点击按钮**,纯文本展示时应省略其文案。
|
||||||
|
|
||||||
|
## 解析流程
|
||||||
|
|
||||||
|
`src/main/message-parser.ts` 的 `parseSystemMessage()` 按以下顺序尝试:
|
||||||
|
|
||||||
|
| 顺序 | 分支 | 处理对象 |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| 1 | `extractRecallMessage` | `<revokemsg>` 撤回通知 |
|
||||||
|
| 2 | `extractSysmsgTemplateText` | `<sysmsgtemplate>` 模板消息 |
|
||||||
|
| 3 | `extractDelChatroomMemberText` | `<delchatroommember>` 成员变动 |
|
||||||
|
| 4 | 通用提取(`plain` → `text` → `title`),再退回 `fallbackSystemText` | 其余未覆盖类型 |
|
||||||
|
|
||||||
|
第 4 步之前会先调用 `stripSysmsgLinkList()` 剥掉 `<link_list>`。
|
||||||
|
|
||||||
|
## 为什么必须显式处理新格式
|
||||||
|
|
||||||
|
通用提取链只在第 1~3 步全部落空时才执行,而新格式恰好让它落空:
|
||||||
|
`<plain>` 是空 CDATA,又没有 `<text>`,于是取到 `<title>` ——
|
||||||
|
那是 `hidden="1"` 按钮的标题。**结果是整条系统消息只剩一个按钮文案**,
|
||||||
|
例如把「某某通过扫描你分享的二维码加入群聊」显示成「撤销」。
|
||||||
|
|
||||||
|
因此三处约束缺一不可:
|
||||||
|
|
||||||
|
1. 模板分支必须排在通用提取之前;
|
||||||
|
2. 占位符回填必须尊重 `hidden="1"`;
|
||||||
|
3. 通用提取前先剥 `<link_list>`,作为未知类型的防护。
|
||||||
|
|
||||||
|
## 新增一类系统消息时
|
||||||
|
|
||||||
|
1. 从真实消息中取出 `content`(`<sysmsg>` 原文),确认 `type` 与承载正文的标签;
|
||||||
|
2. 在 `parseSystemMessage()` 里加一个**早于通用提取**的分支;
|
||||||
|
3. 补 `tests/unit/message-parser.test.ts` 用例,**新旧两版各一条**,防止回归;
|
||||||
|
4. 文档与代码注释只写结构,不粘贴真实会话内容、昵称、wxid 或二维码链接。
|
||||||
|
|
||||||
|
## 相关位置
|
||||||
|
|
||||||
|
- 解析实现:`src/main/message-parser.ts`
|
||||||
|
- 单元测试:`tests/unit/message-parser.test.ts`
|
||||||
+60
-3
@@ -1,5 +1,62 @@
|
|||||||
# macOS 数据访问说明(兼容入口)
|
# macOS 关闭 SIP 教程
|
||||||
|
|
||||||
完整内容已移到[macOS 数据访问与系统权限](./platform/macos.md)。
|
SIP(System Integrity Protection,系统完整性保护)是 macOS 的系统安全机制。关闭 SIP 会降低系统安全性,只建议在确实需要读取或调试本地微信数据时临时关闭;操作完成后,建议重新开启。
|
||||||
|
|
||||||
保留此文件是为了兼容应用内已经发布的帮助链接。请不要把“关闭 SIP”当作默认安装步骤;只有当当前连接页面明确要求时才处理,并在完成后恢复系统安全设置。
|
> 只在连接页面明确提示需要关闭 SIP 时才处理。首次连接失败时,先确认微信版本、账号目录和登录时机,再按本文操作。关闭 SIP 不是 TraceMemo 的常规安装步骤,也不应长期保持关闭。
|
||||||
|
|
||||||
|
## 准备
|
||||||
|
|
||||||
|
- 一台 Mac 电脑,Intel 芯片和 Apple Silicon 芯片均可。
|
||||||
|
- 需要进入 macOS 恢复模式。
|
||||||
|
- 请先保存正在编辑的文件,并预留一次重启时间。
|
||||||
|
|
||||||
|
## 关闭 SIP
|
||||||
|
|
||||||
|
### Intel Mac
|
||||||
|
|
||||||
|
1. 关机。
|
||||||
|
2. 按下开机键后,立刻按住 `Command + R`。
|
||||||
|
3. 保持按住,直到进入 macOS 恢复模式。
|
||||||
|
|
||||||
|
### Apple Silicon Mac(M1/M2/M3/M4/M5)
|
||||||
|
|
||||||
|
1. 关机。
|
||||||
|
2. 长按开机键不放。
|
||||||
|
3. 直到出现启动选项界面后松开。
|
||||||
|
4. 选择"选项",进入 macOS 恢复模式。
|
||||||
|
|
||||||
|
### 在恢复模式中执行命令
|
||||||
|
|
||||||
|
1. 进入恢复模式后,点击顶部菜单栏的 **Utilities(实用工具)**。
|
||||||
|
2. 选择 **Terminal(终端)**。
|
||||||
|
3. 在终端中输入:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
csrutil disable
|
||||||
|
```
|
||||||
|
|
||||||
|
4. 按回车执行。
|
||||||
|
5. 看到关闭成功提示后,重启电脑。
|
||||||
|
|
||||||
|
## 确认是否生效
|
||||||
|
|
||||||
|
重启回到正常桌面后,打开"终端",执行:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
csrutil status
|
||||||
|
```
|
||||||
|
|
||||||
|
看到 `System Integrity Protection status: disabled.` 才算关闭成功。
|
||||||
|
|
||||||
|
若仍显示 `enabled`,说明没有生效。常见原因是没在恢复模式里执行,或系统刚做过大版本更新——
|
||||||
|
macOS 大版本更新会把 SIP 重置回开启状态,此前关过也会失效,需要重新按上面的步骤操作。
|
||||||
|
|
||||||
|
## 重新开启 SIP
|
||||||
|
|
||||||
|
拿到数据库密钥后,建议重新进入恢复模式,在终端中执行:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
csrutil enable
|
||||||
|
```
|
||||||
|
|
||||||
|
然后重启电脑,恢复系统安全设置。
|
||||||
+58
-2
@@ -8,11 +8,44 @@ TraceMemo 需要读取微信本地数据。macOS 会根据系统版本、微信
|
|||||||
|
|
||||||
1. 先启动 TraceMemo,阅读连接页面显示的当前前置条件。
|
1. 先启动 TraceMemo,阅读连接页面显示的当前前置条件。
|
||||||
2. 确认微信数据目录指向当前账号。
|
2. 确认微信数据目录指向当前账号。
|
||||||
3. 只在页面明确要求时处理系统授权或 SIP;按页面提示完成密钥获取后,恢复你平时使用的安全设置。
|
3. 只在页面明确要求时处理系统授权或 SIP;关闭 SIP 的具体步骤见[关闭 SIP 教程](../mac-disable-sip.md),按页面提示完成密钥获取后,恢复你平时使用的安全设置。
|
||||||
4. 返回应用重新检测账号、数据库和图片资源状态。
|
4. 返回应用重新检测账号、数据库和图片资源状态。
|
||||||
|
|
||||||
不要直接复制网上针对其他微信版本的命令。系统授权失败时,记录 macOS 版本、微信版本和页面错误,再按[排障文档](../user-guide/troubleshooting.md#连接微信失败)处理。
|
不要直接复制网上针对其他微信版本的命令。系统授权失败时,记录 macOS 版本、微信版本和页面错误,再按[排障文档](../user-guide/troubleshooting.md#连接微信失败)处理。
|
||||||
|
|
||||||
|
## 提示「无法读取微信数据库」时
|
||||||
|
|
||||||
|
**这是故障恢复步骤,不是安装前置条件。** 能正常连接的用户不需要做任何权限设置。
|
||||||
|
|
||||||
|
如果你在连接页看到「最近验证结果:无法读取微信数据库」(错误码 `DATABASE_PERMISSION_DENIED`),并且已经确认微信数据目录**实际存在**(例如在终端里能列出 `db_storage/session/session.db`),那说明是 **TraceMemo 这个进程**读不到,而不是文件缺失。
|
||||||
|
|
||||||
|
微信数据放在另一个应用的沙盒容器里,macOS 会对这种跨应用访问单独做校验。先看「完全磁盘访问权限」里 TraceMemo 的状态,再按情况处理:
|
||||||
|
|
||||||
|
- **不在列表里,或开关是关的**:按下面的步骤授权。
|
||||||
|
- **开关已经是开的,但仍然读不到**:这不是「没授权」,而是旧授权记录对不上当前版本的应用,需要先清掉旧记录再重新授权。完整步骤见[macOS 更新后读不到微信数据:权限恢复](../user-guide/macos27-permission-recovery.md)。
|
||||||
|
|
||||||
|
首次授权的步骤:
|
||||||
|
|
||||||
|
1. 打开 **系统设置 → 隐私与安全性 → 完全磁盘访问权限**
|
||||||
|
2. 找到 **TraceMemo**,打开开关
|
||||||
|
3. **重新启动 TraceMemo**(该授权只在进程下次启动时生效)
|
||||||
|
4. 回到连接页重试
|
||||||
|
|
||||||
|
### 为什么终端能读、TraceMemo 读不了
|
||||||
|
|
||||||
|
macOS 的隐私权限按**应用进程的身份**判定,而不是按文件系统的用户身份。同一个用户在终端里能读到文件内容,不代表 TraceMemo 进程也有权限 —— 两者走的是不同的授权判定。所以「终端能读」不能用来排除权限问题。
|
||||||
|
|
||||||
|
### 不要做的事
|
||||||
|
|
||||||
|
上面这条路径**只涉及给 TraceMemo 授权**。以下做法都不需要,而且有风险:
|
||||||
|
|
||||||
|
- 关闭 SIP
|
||||||
|
- `chmod` / `chown` 整个微信目录
|
||||||
|
- 用 `sudo` 启动 TraceMemo
|
||||||
|
- 修改微信数据库文件权限
|
||||||
|
|
||||||
|
「无法读取微信数据库」与 SIP 不是同一个问题;改动微信数据目录的权限还可能影响微信自身的正常运行。
|
||||||
|
|
||||||
## SIP 风险
|
## SIP 风险
|
||||||
|
|
||||||
关闭 System Integrity Protection 会降低 macOS 对系统文件和进程的保护。它不是日常使用 TraceMemo 的功能开关,也不应长期保持关闭。只有在你理解风险、确认页面要求且完成必要操作时才处理;完成后按 Apple 官方方式重新启用。
|
关闭 System Integrity Protection 会降低 macOS 对系统文件和进程的保护。它不是日常使用 TraceMemo 的功能开关,也不应长期保持关闭。只有在你理解风险、确认页面要求且完成必要操作时才处理;完成后按 Apple 官方方式重新启用。
|
||||||
@@ -33,6 +66,29 @@ TraceMemo 同时支持两种 Mac 架构:
|
|||||||
- Apple Silicon:`tracememo-<版本号>-arm64.dmg`
|
- Apple Silicon:`tracememo-<版本号>-arm64.dmg`
|
||||||
- Intel:`tracememo-<版本号>-x64.dmg`
|
- Intel:`tracememo-<版本号>-x64.dmg`
|
||||||
|
|
||||||
两种架构都可以通过应用内的连接流程自动获取微信数据库密钥。首次连接时,TraceMemo 会根据当前机器架构进入对应的流程,按连接页面提示操作即可。
|
两种架构都可以通过应用内的连接流程自动获取微信数据库密钥。首次连接时,TraceMemo 会按**当前运行的这个版本**进入对应流程,按连接页面提示操作即可。
|
||||||
|
|
||||||
|
### 提示「Intel Mac 自动获取」,但电脑是 Apple 芯片
|
||||||
|
|
||||||
|
如果在 M 系列 Mac 上看到「Intel Mac 自动获取」,或页面要求准备 Intel 连接环境,多数是**正在运行 Intel(x64)版 TraceMemo**。macOS 允许 Intel 版应用在 Apple 芯片上通过 Rosetta 运行,应用本身不会报错,但会如实把自己识别成 Intel 版本,于是走了 Intel 的密钥获取方式。
|
||||||
|
|
||||||
|
判断当前跑的是哪个版本:
|
||||||
|
|
||||||
|
- 打开「活动监视器」,选中 TraceMemo,看「种类」一列 —— 显示「Apple」是 arm64 版,显示「Intel」是 x64 版;
|
||||||
|
- 或点连接页的「复制脱敏诊断摘要」,看「处理器架构」和「硬件架构」两行。
|
||||||
|
|
||||||
|
**启动方式不会改变架构。** Finder、Dock、桌面文件夹、`open` 命令打开的都是同一个 `.app`。但如果电脑上存在多个 TraceMemo 副本(例如「应用程序」里一个、下载文件夹里一个),不同入口可能打开不同副本,表现出来就像「有时是 Intel、有时不是」。列出所有副本及架构:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
mdfind "kMDItemCFBundleIdentifier == 'com.tracememo.app'" | while read -r p; do
|
||||||
|
[ -f "$p/Contents/MacOS/TraceMemo" ] && printf '%s -> ' "$p" && file -b "$p/Contents/MacOS/TraceMemo"
|
||||||
|
done
|
||||||
|
```
|
||||||
|
|
||||||
|
输出里带 `arm64` 的是 Apple 芯片版,带 `x86_64` 的是 Intel 版。
|
||||||
|
|
||||||
|
解决办法是从 [Releases](https://github.com/Wxw-Gu/TraceMemo/releases) 下载文件名带 `arm64` 的包,替换现有应用后重启。已保存的数据库密钥和连接配置不需要重新设置。
|
||||||
|
|
||||||
|
这与[提示「无法读取微信数据库」](#提示无法读取微信数据库时)不是同一个问题:那边是系统授权失效,这里是装错了版本。两种情况的处理方式不同,都不需要关闭 SIP。
|
||||||
|
|
||||||
Apple Silicon 和 Intel 已适配微信 macOS `4.1.13`。不同架构、微信版本和系统授权状态可能导致连接结果不同;文档不对所有组合做兼容性保证。
|
Apple Silicon 和 Intel 已适配微信 macOS `4.1.13`。不同架构、微信版本和系统授权状态可能导致连接结果不同;文档不对所有组合做兼容性保证。
|
||||||
@@ -1,6 +1,7 @@
|
|||||||
---
|
---
|
||||||
name: tracememo-reader
|
name: tracememo-reader
|
||||||
description: 通过 TraceMemo 本地 HTTP API 按需读取用户有权访问的微信聊天数据和图片媒体。当用户要求查看微信消息、查找联系人或群聊、总结聊天、查看或理解图片、生成群聊总结时使用。此 Skill 由本机 TraceMemo 提供数据,不是 MCP Server。
|
version: 1.4.0
|
||||||
|
description: 通过 TraceMemo 本地 HTTP API 按需读取用户有权访问的微信聊天数据和图片媒体、管理定时日报任务,并用用户本机登录的微信账号发送消息。当用户要求查看微信消息、查找联系人或群聊、总结聊天、查看或理解图片、生成群聊总结、查询或修改定时日报、给好友或群发送微信消息、代发消息、查看发送记录时使用。此 Skill 由本机 TraceMemo 提供数据,不是 MCP Server。
|
||||||
---
|
---
|
||||||
|
|
||||||
# TraceMemo Reader
|
# TraceMemo Reader
|
||||||
@@ -17,6 +18,35 @@ description: 通过 TraceMemo 本地 HTTP API 按需读取用户有权访问的
|
|||||||
- 不要把 Token 放到 URL、回答、日志、Skill 文件或仓库。
|
- 不要把 Token 放到 URL、回答、日志、Skill 文件或仓库。
|
||||||
- 6131 是普通 Local HTTP API,不是 MCP Server;不要生成 `mcpServers` 配置。
|
- 6131 是普通 Local HTTP API,不是 MCP Server;不要生成 `mcpServers` 配置。
|
||||||
|
|
||||||
|
## 版本自检(每次会话开始时执行一次)
|
||||||
|
|
||||||
|
这份 Skill 随 TraceMemo 一起更新,接口会随版本变化。本文件 frontmatter 里的 `version` 是它的唯一版本标识,服务端在 `/health` 回报当前版本。
|
||||||
|
|
||||||
|
1. 读取本文件 frontmatter 的 `version`。
|
||||||
|
2. 调用 `GET /health`,取返回的 `skill.version`。
|
||||||
|
3. 两者一致 → 正常继续。
|
||||||
|
4. 两者不一致(本文件更旧)→ **先停止,不要继续读取数据**,并原样告知用户:
|
||||||
|
|
||||||
|
> 本机 TraceMemo Reader Skill 是 {本地版本},而 TraceMemo 当前是 {服务端版本},接口契约可能已经过期。
|
||||||
|
> 请打开 TraceMemo → API Center → 快速接入 → 选择目标 Agent → 复制安装指令,把新指令发给我重新安装。
|
||||||
|
|
||||||
|
5. `/health` 没有返回 `skill.version`(说明 TraceMemo 版本较旧)→ 无法比对,正常继续,但要在回答中提醒用户升级 TraceMemo。
|
||||||
|
|
||||||
|
自检只做一次,不要每个任务都执行。**不要**因为版本不一致就自行猜测新接口的用法。
|
||||||
|
|
||||||
|
### 自助更新
|
||||||
|
|
||||||
|
用户同意更新时,不必让他手动复制安装指令,Agent 可以自己完成:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
curl -H "Authorization: Bearer $TRACEMEMO_API_TOKEN" \
|
||||||
|
"http://127.0.0.1:6131/api/v1/skill/tracememo-reader"
|
||||||
|
```
|
||||||
|
|
||||||
|
响应的 `markdown` 就是最新 SKILL.md 全文,`version` 是它的版本,`contentHash` 可用于核对写入结果。先取得用户同意,再用它覆盖本机这份 SKILL.md(连同 frontmatter 一起写),然后重新读取本文件,并告知用户已更新到哪个版本。
|
||||||
|
|
||||||
|
覆盖前先确认目标文件路径并留一份备份;**不要**改动本目录里的其他文件,也不要把 `markdown` 内容写进回答或日志。
|
||||||
|
|
||||||
## 每次任务前
|
## 每次任务前
|
||||||
|
|
||||||
1. 调用 `/health`,确认服务和数据库状态。
|
1. 调用 `/health`,确认服务和数据库状态。
|
||||||
@@ -27,31 +57,103 @@ description: 通过 TraceMemo 本地 HTTP API 按需读取用户有权访问的
|
|||||||
|
|
||||||
## 端点速查
|
## 端点速查
|
||||||
|
|
||||||
| 方法 | 路径 | 用途 |
|
| 方法 | 路径 | 用途 |
|
||||||
| ------ | ----------------------------------- | ------------------------------------------------- |
|
| ------ | ------------------------------------------------------- | ------------------------------------------------- |
|
||||||
| GET | `/health` | 健康和数据库状态 |
|
| GET | `/health` | 健康和数据库状态 + 当前 Skill 版本 |
|
||||||
| GET | `/current_time` | 本机时间与时区 |
|
| GET | `/skill/tracememo-reader` | 当前 SKILL.md 全文与版本号(自助更新用) |
|
||||||
| GET | `/contact` | 联系人/群聊列表;可传 `filter`、`type` |
|
| GET | `/current_time` | 本机时间与时区 |
|
||||||
| GET | `/chatroom` | 群聊列表;可传 `keyword` |
|
| GET | `/contact` | 联系人/群聊列表;可传 `filter`、`type` |
|
||||||
| GET | `/recent_chat` | 最近会话;可传 `limit` |
|
| GET | `/chatroom` | 群聊列表;可传 `keyword` |
|
||||||
| GET | `/chatlog` | 会话消息;必填 `talker`,可传 `time` 或时间戳范围 |
|
| GET | `/recent_chat` | 最近会话;可传 `limit` |
|
||||||
| GET | `/media/{mediaId}` | 按消息返回的 `media.url` 获取图片二进制资源 |
|
| GET | `/chatlog` | 会话消息;必填 `talker`,可传 `time` 或时间戳范围 |
|
||||||
| GET | `/group_snapshot` | 群成员快照;必填 `md5` |
|
| GET | `/media/{mediaId}` | 按消息返回的 `media.url` 获取图片二进制资源 |
|
||||||
| GET | `/resolve` | 昵称、wxid、md5 解析;必填 `q` |
|
| GET | `/group_snapshot` | 群成员快照;必填 `md5` |
|
||||||
| GET | `/wechat-personal/send-capability` | 个人微信图片发送能力状态 |
|
| GET | `/resolve` | 昵称、wxid、md5 解析;必填 `q` |
|
||||||
| GET | `/scheduled-reports` | 查询全部定时日报任务 |
|
| POST | `/query/messages` | 按目标与时间范围取消息(结构化,不调用 AI) |
|
||||||
| GET | `/scheduled-reports/:id` | 查询单个定时日报任务 |
|
| POST | `/query/search` | 受限语义关键词检索(依赖本地索引,见 freshness) |
|
||||||
| POST | `/scheduled-reports` | 创建定时日报任务 |
|
| POST | `/query/message-context` | 用 `messageRef` 取某条消息的前后文 |
|
||||||
| PATCH | `/scheduled-reports/:id` | 修改定时日报任务 |
|
| POST | `/query/conversation-overview` | 按会话与时间范围提取可总结的证据 |
|
||||||
| DELETE | `/scheduled-reports/:id` | 删除定时日报任务(执行前必须获得用户确认) |
|
| POST | `/query/voice-transcribe` | 把指定语音消息转成文字(本机离线识别) |
|
||||||
| POST | `/scheduled-reports/:id/enable` | 启用定时日报任务 |
|
| GET | `/query/capabilities` | Query 端点能力目录 |
|
||||||
| POST | `/scheduled-reports/:id/disable` | 暂停定时日报任务 |
|
| GET | `/wechat-personal/send-capability` | 个人微信发送能力状态(文字 / 图片 / 语音) |
|
||||||
| POST | `/scheduled-reports/:id/run` | 立即执行一次并返回 execution |
|
| POST | `/wechat/send` | 用本机微信账号发消息给他人(文字/图片/语音) |
|
||||||
| GET | `/scheduled-reports/:id/executions` | 查询执行记录 |
|
| GET | `/scheduled-reports` | 查询全部定时日报任务 |
|
||||||
| POST | `/report` | 将已有日报结构渲染为 HTML/PNG |
|
| GET | `/scheduled-reports/:id` | 查询单个定时日报任务 |
|
||||||
| GET | `/agent/status` | Agent Hub、连接器和数据库状态 |
|
| POST | `/scheduled-reports` | 创建定时日报任务 |
|
||||||
| POST | `/agent/group-report` | 按群和 `today`/`yesterday`/`7days` 生成总结图片 |
|
| PATCH | `/scheduled-reports/:id` | 修改定时日报任务 |
|
||||||
| POST | `/agent/send` | 已连接机器人发送测试 |
|
| DELETE | `/scheduled-reports/:id` | 删除定时日报任务(执行前必须获得用户确认) |
|
||||||
|
| POST | `/scheduled-reports/:id/enable` | 启用定时日报任务 |
|
||||||
|
| 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` | 已连接机器人发送测试(文字或本地图片) |
|
||||||
|
|
||||||
|
这个 API **不只是只读的**:`/report` 会渲染并写文件,`/wechat/send` 会以用户本人的微信账号把消息真的发给别人,`/agent/send` 会通过机器人发出消息,`/scheduled-reports*` 会创建、修改、删除或立刻执行定时任务。这些调用都要先确认用户意图;`DELETE`、`/wechat/send` 与 `/agent/send` 尤其需要用户明确确认。
|
||||||
|
|
||||||
|
## 发送微信消息
|
||||||
|
|
||||||
|
两个发送端点的**身份和通道完全不同**,不要混用:
|
||||||
|
|
||||||
|
| | `/wechat/send` | `/agent/send` |
|
||||||
|
| -------- | ------------------------------ | -------------------------------- |
|
||||||
|
| 发送身份 | 用户本机正在登录的微信账号 | 已扫码接入的 TraceMemo 机器人 |
|
||||||
|
| 收件人 | 好友 / 群 / 文件传输助手 | 一般是自己,用于测试连接器连通性 |
|
||||||
|
| 前置条件 | 本机微信已启动,发送能力 ready | Agent Hub 连接器 online |
|
||||||
|
|
||||||
|
用户说“发消息给某人 / 某个群 / 文件传输助手”时,**只能用 `/wechat/send`**。`/agent/send` 不是用来通知别人的。
|
||||||
|
|
||||||
|
### 调用前必须做
|
||||||
|
|
||||||
|
1. 调用 `GET /wechat-personal/send-capability`,只有 `capability.ready === true` 且 `capability.capabilities[type] === true` 才继续。否则停下来说明需要先在 TraceMemo「设置 → 发送能力」里完成绑定,**不要**直接调用再解释失败。
|
||||||
|
2. 通过 `/resolve` 把用户说的昵称换成 wxid;`to` 只接受 wxid、`xxx@chatroom` 群 id,或 `filehelper`。**不要猜 wxid,也不要把昵称直接写进 `to`。**
|
||||||
|
3. 把「发给谁 + 发什么」复述给用户并得到确认后再发。这是不可撤回的外部操作。
|
||||||
|
|
||||||
|
### 请求
|
||||||
|
|
||||||
|
```json
|
||||||
|
{ "to": "wxid_xxx", "type": "text", "text": "消息内容", "idempotencyKey": "可选" }
|
||||||
|
```
|
||||||
|
|
||||||
|
| 字段 | 必填 | 说明 |
|
||||||
|
| ---------------- | ------------------ | ------------------------------------------------------------------- |
|
||||||
|
| `to` | 是 | wxid / `xxx@chatroom` / `filehelper`;以 `@chatroom` 结尾自动判为群 |
|
||||||
|
| `type` | 否 | `text`(默认)/ `image` / `voice` |
|
||||||
|
| `text` | `type=text` 时必填 | **最多 2000 字符**,超限返回 `400`,不会自动截断 |
|
||||||
|
| `filePath` | `type=image/voice` | 本机**绝对路径**且文件必须存在;**不接受 URL** |
|
||||||
|
| `idempotencyKey` | 否 | 重试时原样带回,避免超时重发产生重复消息 |
|
||||||
|
|
||||||
|
几个必须遵守的限制:
|
||||||
|
|
||||||
|
- **超过 2000 字符不要硬发**。先告诉用户内容过长,征得同意后再拆成多条依次发送;不要静默截断。
|
||||||
|
- **媒体只收本地文件**。用户给的是聊天里的图片时,先用 `/chatlog` 拿到 `media.url` 下载成临时文件,再把该路径传给 `filePath`;网络图片同样需要先落盘。不要试图传 URL。
|
||||||
|
- **本端点没有节流**。automation 的 3 秒间隔对它不生效,连续调用就会连续投递。单个任务里连续发送超过 3 条前,先和用户确认节奏。
|
||||||
|
|
||||||
|
### 结果
|
||||||
|
|
||||||
|
成功返回 `success: true`、`status: "sent"`、`actionId`。失败时读 `errorCode`:
|
||||||
|
|
||||||
|
- `400 INVALID_REQUEST` / `INVALID_RECIPIENT`:字段不合法,按 `error` 里的说明修正;
|
||||||
|
- `403 POLICY_BLOCKED`:被发送策略拒绝,如实告知用户;
|
||||||
|
- `502 SEND_FAILED`:已进入投递但微信侧失败,不要说成“已发送”;
|
||||||
|
- `503 SEND_CAPABILITY_UNAVAILABLE` / `SEND_NOT_READY`:能力未就绪,引导用户去绑定;
|
||||||
|
- `503 UNSUPPORTED_PLATFORM`:当前系统不支持。
|
||||||
|
|
||||||
|
只有 `status === "sent"` 才能告诉用户发送成功。不要凭 `actionId` 或 HTTP 200 之外的任何信息推断结果。
|
||||||
|
|
||||||
|
### 发送成功后不要用 `/chatlog` 自证
|
||||||
|
|
||||||
|
`status: "sent"` 只表示消息已经交给微信完成投递,**不代表它会出现在本地聊天数据库里**。TraceMemo 读的是微信本地库,自己发出的消息可能延迟落库,也可能根本不写入。
|
||||||
|
|
||||||
|
因此:
|
||||||
|
|
||||||
|
- **不要**用 `/chatlog` 查自己刚发出的那条消息来确认发送成功。查不到是正常现象,不等于发送失败。
|
||||||
|
- **不要**因为本地库没有这条消息就重发 —— 那会产生真实的重复消息。
|
||||||
|
- 需要人工确认时,请用户用**手机微信**或**另一个微信号**查看该会话;这是唯一可靠的确认方式。
|
||||||
|
- Send Log 与 `actions/wechat-actions.json` 记录的是 TraceMemo 自己的发送动作与结果,能证明“调用过并成功投递”,**不能**证明对方收到或本地库已落库。不要把它们混为一谈。
|
||||||
|
|
||||||
## 定时日报管理
|
## 定时日报管理
|
||||||
|
|
||||||
@@ -78,7 +180,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 +204,21 @@ description: 通过 TraceMemo 本地 HTTP API 按需读取用户有权访问的
|
|||||||
- 根据多条消息整理出的总结;
|
- 根据多条消息整理出的总结;
|
||||||
- 没有来源支持的推断。
|
- 没有来源支持的推断。
|
||||||
|
|
||||||
|
## 结构化查询(query/\*)
|
||||||
|
|
||||||
|
需要按目标 + 时间范围稳定取数时,优先使用 `query/*`,而不是自己拼 `chatlog`:
|
||||||
|
|
||||||
|
- `query/messages`:按 `target`、`timeRange`、`direction`、`messageTypes` 取消息;
|
||||||
|
- `query/search`:受限语义关键词检索,依赖本地索引;
|
||||||
|
- `query/message-context`:用返回的 `messageRef` 取前后文;
|
||||||
|
- `query/conversation-overview`:按会话与时间范围提取可总结的证据。
|
||||||
|
- `query/voice-transcribe`:把指定语音消息的 `messageRef` 转成文字。
|
||||||
|
|
||||||
|
两个要点:
|
||||||
|
|
||||||
|
- `messageRef` 是服务端生成的不透明引用,**不要**自行构造 wxid、md5 或数据库路径;
|
||||||
|
- `query/search` 依赖异步建立的本地索引。`coverage.state` 不是 `complete` 且 `evidence` 为空时,只能说“这段范围暂时无法确认”,**不能**下“没有找到”的结论。
|
||||||
|
|
||||||
## 媒体消息
|
## 媒体消息
|
||||||
|
|
||||||
当 `/chatlog` 返回图片消息时:
|
当 `/chatlog` 返回图片消息时:
|
||||||
@@ -125,6 +242,18 @@ description: 通过 TraceMemo 本地 HTTP API 按需读取用户有权访问的
|
|||||||
|
|
||||||
不要只根据 `[图片]` 猜测内容,不要把一次 OCR 当作完整图片理解,也不要直接读取任意本地图片路径。
|
不要只根据 `[图片]` 猜测内容,不要把一次 OCR 当作完整图片理解,也不要直接读取任意本地图片路径。
|
||||||
|
|
||||||
|
### 语音消息
|
||||||
|
|
||||||
|
语音消息的正文固定是 `[语音消息]`,转写结果在 `voiceTranscript`,状态在 `voiceTranscriptState`(`/chatlog` 与 `query/*` 都会返回)。
|
||||||
|
|
||||||
|
1. `transcribed`:直接使用 `voiceTranscript`。
|
||||||
|
2. `pending`:还没转写,**不能**说成“语音里没内容”。回答需要它时,把这些语音的 `messageRef` 批量(每次最多 20 条)交给 `POST /query/voice-transcribe`。
|
||||||
|
3. 返回 `pending`(`still_processing`)时,稍后用同样的 `messageRefs` 再调用一次;不要换参数反复重试。
|
||||||
|
4. 返回 `failed` 时按 `hint` 处理;`previously_failed` 只有用户明确要求才传 `force: true` 重试。
|
||||||
|
5. `503 voice_model_not_ready`:告诉用户先在 TraceMemo 设置中下载语音识别模型,在此之前不要重试。
|
||||||
|
6. `429 busy`:等待 `retryAfterSeconds` 后再调用。
|
||||||
|
7. 只转写回答问题所需的语音,不要一次把整个会话的语音都提交。
|
||||||
|
|
||||||
## 隐私和安全
|
## 隐私和安全
|
||||||
|
|
||||||
只读取用户请求所需的会话和时间范围。不要把完整聊天数据库、密钥或 Token 暴露给用户。Reader API 本身不自动把聊天转发到外部服务器,但当前 Agent 可能会把工具结果交给其配置的模型;如有疑问,提醒用户检查 Agent 的数据策略。
|
只读取用户请求所需的会话和时间范围。不要把完整聊天数据库、密钥或 Token 暴露给用户。Reader API 本身不自动把聊天转发到外部服务器,但当前 Agent 可能会把工具结果交给其配置的模型;如有疑问,提醒用户检查 Agent 的数据策略。
|
||||||
@@ -132,8 +261,8 @@ description: 通过 TraceMemo 本地 HTTP API 按需读取用户有权访问的
|
|||||||
## 常见错误
|
## 常见错误
|
||||||
|
|
||||||
- `401`:Token 缺失、错误或被轮换;请用户回 API Center 复制最新 Token。
|
- `401`:Token 缺失、错误或被轮换;请用户回 API Center 复制最新 Token。
|
||||||
- `403`:浏览器 Origin 不在 loopback 允许列表;CLI/Agent 通常不带 Origin。
|
- `403`:浏览器 Origin 不在 loopback 允许列表;CLI/Agent 通常不带 Origin。注意 `/wechat/send` 的 `403 POLICY_BLOCKED` 是被发送策略拒绝,含义不同。
|
||||||
- `404`:会话查询失败时先用 `/resolve` 确认会话标识;媒体请求表示标识未登记、已过期、有歧义,或图片文件不存在(`NOT_FOUND`)。先重新读取 `/chatlog` 并使用新的 `media.url`;若仍失败,再检查本地图片文件是否存在。
|
- `404`:会话查询失败时先用 `/resolve` 确认会话标识;媒体请求表示标识未登记、已过期、有歧义,或图片文件不存在(`NOT_FOUND`)。先重新读取 `/chatlog` 并使用新的 `media.url`;若仍失败,再检查本地图片文件是否存在。
|
||||||
- `422`:媒体标识格式错误,或消息不是可读取的图片(`NOT_IMAGE`)。
|
- `422`:媒体标识格式错误,或消息不是可读取的图片(`NOT_IMAGE`)。
|
||||||
- `503`:用户还没有完成数据库连接或对应服务未就绪。
|
- `503`:用户还没有完成数据库连接或对应服务未就绪。发送端点返回 `503` 时先查 `/wechat-personal/send-capability`,不要反复重试。
|
||||||
- 空结果:缩小/扩大时间范围,确认账号和会话,再检查媒体或语音是否可读。
|
- 空结果:缩小/扩大时间范围,确认账号和会话,再检查媒体或语音是否可读。
|
||||||
-674
@@ -1,674 +0,0 @@
|
|||||||
GNU GENERAL PUBLIC LICENSE
|
|
||||||
Version 3, 29 June 2007
|
|
||||||
|
|
||||||
Copyright (C) 2026 yincongcyincong
|
|
||||||
Everyone is permitted to copy and distribute verbatim copies
|
|
||||||
of this license document, but changing it is not allowed.
|
|
||||||
|
|
||||||
Preamble
|
|
||||||
|
|
||||||
The GNU General Public License is a free, copyleft license for
|
|
||||||
software and other kinds of works.
|
|
||||||
|
|
||||||
The licenses for most software and other practical works are designed
|
|
||||||
to take away your freedom to share and change the works. By contrast,
|
|
||||||
the GNU General Public License is intended to guarantee your freedom to
|
|
||||||
share and change all versions of a program--to make sure it remains free
|
|
||||||
software for all its users. We, the Free Software Foundation, use the
|
|
||||||
GNU General Public License for most of our software; it applies also to
|
|
||||||
any other work released this way by its authors. You can apply it to
|
|
||||||
your programs, too.
|
|
||||||
|
|
||||||
When we speak of free software, we are referring to freedom, not
|
|
||||||
price. Our General Public Licenses are designed to make sure that you
|
|
||||||
have the freedom to distribute copies of free software (and charge for
|
|
||||||
them if you wish), that you receive source code or can get it if you
|
|
||||||
want it, that you can change the software or use pieces of it in new
|
|
||||||
free programs, and that you know you can do these things.
|
|
||||||
|
|
||||||
To protect your rights, we need to prevent others from denying you
|
|
||||||
these rights or asking you to surrender the rights. Therefore, you have
|
|
||||||
certain responsibilities if you distribute copies of the software, or if
|
|
||||||
you modify it: responsibilities to respect the freedom of others.
|
|
||||||
|
|
||||||
For example, if you distribute copies of such a program, whether
|
|
||||||
gratis or for a fee, you must pass on to the recipients the same
|
|
||||||
freedoms that you received. You must make sure that they, too, receive
|
|
||||||
or can get the source code. And you must show them these terms so they
|
|
||||||
know their rights.
|
|
||||||
|
|
||||||
Developers that use the GNU GPL protect your rights with two steps:
|
|
||||||
(1) assert copyright on the software, and (2) offer you this License
|
|
||||||
giving you legal permission to copy, distribute and/or modify it.
|
|
||||||
|
|
||||||
For the developers' and authors' protection, the GPL clearly explains
|
|
||||||
that there is no warranty for this free software. For both users' and
|
|
||||||
authors' sake, the GPL requires that modified versions be marked as
|
|
||||||
changed, so that their problems will not be attributed erroneously to
|
|
||||||
authors of previous versions.
|
|
||||||
|
|
||||||
Some devices are designed to deny users access to install or run
|
|
||||||
modified versions of the software inside them, although the manufacturer
|
|
||||||
can do so. This is fundamentally incompatible with the aim of
|
|
||||||
protecting users' freedom to change the software. The systematic
|
|
||||||
pattern of such abuse occurs in the area of products for individuals to
|
|
||||||
use, which is precisely where it is most unacceptable. Therefore, we
|
|
||||||
have designed this version of the GPL to prohibit the practice for those
|
|
||||||
products. If such problems arise substantially in other domains, we
|
|
||||||
stand ready to extend this provision to those domains in future versions
|
|
||||||
of the GPL, as needed to protect the freedom of users.
|
|
||||||
|
|
||||||
Finally, every program is threatened constantly by software patents.
|
|
||||||
States should not allow patents to restrict development and use of
|
|
||||||
software on general-purpose computers, but in those that do, we wish to
|
|
||||||
avoid the special danger that patents applied to a free program could
|
|
||||||
make it effectively proprietary. To prevent this, the GPL assures that
|
|
||||||
patents cannot be used to render the program non-free.
|
|
||||||
|
|
||||||
The precise terms and conditions for copying, distribution and
|
|
||||||
modification follow.
|
|
||||||
|
|
||||||
TERMS AND CONDITIONS
|
|
||||||
|
|
||||||
0. Definitions.
|
|
||||||
|
|
||||||
"This License" refers to version 3 of the GNU General Public License.
|
|
||||||
|
|
||||||
"Copyright" also means copyright-like laws that apply to other kinds of
|
|
||||||
works, such as semiconductor masks.
|
|
||||||
|
|
||||||
"The Program" refers to any copyrightable work licensed under this
|
|
||||||
License. Each licensee is addressed as "you". "Licensees" and
|
|
||||||
"recipients" may be individuals or organizations.
|
|
||||||
|
|
||||||
To "modify" a work means to copy from or adapt all or part of the work
|
|
||||||
in a fashion requiring copyright permission, other than the making of an
|
|
||||||
exact copy. The resulting work is called a "modified version" of the
|
|
||||||
earlier work or a work "based on" the earlier work.
|
|
||||||
|
|
||||||
A "covered work" means either the unmodified Program or a work based
|
|
||||||
on the Program.
|
|
||||||
|
|
||||||
To "propagate" a work means to do anything with it that, without
|
|
||||||
permission, would make you directly or secondarily liable for
|
|
||||||
infringement under applicable copyright law, except executing it on a
|
|
||||||
computer or modifying a private copy. Propagation includes copying,
|
|
||||||
distribution (with or without modification), making available to the
|
|
||||||
public, and in some countries other activities as well.
|
|
||||||
|
|
||||||
To "convey" a work means any kind of propagation that enables other
|
|
||||||
parties to make or receive copies. Mere interaction with a user through
|
|
||||||
a computer network, with no transfer of a copy, is not conveying.
|
|
||||||
|
|
||||||
An interactive user interface displays "Appropriate Legal Notices"
|
|
||||||
to the extent that it includes a convenient and prominently visible
|
|
||||||
feature that (1) displays an appropriate copyright notice, and (2)
|
|
||||||
tells the user that there is no warranty for the work (except to the
|
|
||||||
extent that warranties are provided), that licensees may convey the
|
|
||||||
work under this License, and how to view a copy of this License. If
|
|
||||||
the interface presents a list of user commands or options, such as a
|
|
||||||
menu, a prominent item in the list meets this criterion.
|
|
||||||
|
|
||||||
1. Source Code.
|
|
||||||
|
|
||||||
The "source code" for a work means the preferred form of the work
|
|
||||||
for making modifications to it. "Object code" means any non-source
|
|
||||||
form of a work.
|
|
||||||
|
|
||||||
A "Standard Interface" means an interface that either is an official
|
|
||||||
standard defined by a recognized standards body, or, in the case of
|
|
||||||
interfaces specified for a particular programming language, one that
|
|
||||||
is widely used among developers working in that language.
|
|
||||||
|
|
||||||
The "System Libraries" of an executable work include anything, other
|
|
||||||
than the work as a whole, that (a) is included in the normal form of
|
|
||||||
packaging a Major Component, but which is not part of that Major
|
|
||||||
Component, and (b) serves only to enable use of the work with that
|
|
||||||
Major Component, or to implement a Standard Interface for which an
|
|
||||||
implementation is available to the public in source code form. A
|
|
||||||
"Major Component", in this context, means a major essential component
|
|
||||||
(kernel, window system, and so on) of the specific operating system
|
|
||||||
(if any) on which the executable work runs, or a compiler used to
|
|
||||||
produce the work, or an object code interpreter used to run it.
|
|
||||||
|
|
||||||
The "Corresponding Source" for a work in object code form means all
|
|
||||||
the source code needed to generate, install, and (for an executable
|
|
||||||
work) run the object code and to modify the work, including scripts to
|
|
||||||
control those activities. However, it does not include the work's
|
|
||||||
System Libraries, or general-purpose tools or generally available free
|
|
||||||
programs which are used unmodified in performing those activities but
|
|
||||||
which are not part of the work. For example, Corresponding Source
|
|
||||||
includes interface definition files associated with source files for
|
|
||||||
the work, and the source code for shared libraries and dynamically
|
|
||||||
linked subprograms that the work is specifically designed to require,
|
|
||||||
such as by intimate data communication or control flow between those
|
|
||||||
subprograms and other parts of the work.
|
|
||||||
|
|
||||||
The Corresponding Source need not include anything that users
|
|
||||||
can regenerate automatically from other parts of the Corresponding
|
|
||||||
Source.
|
|
||||||
|
|
||||||
The Corresponding Source for a work in source code form is that
|
|
||||||
same work.
|
|
||||||
|
|
||||||
2. Basic Permissions.
|
|
||||||
|
|
||||||
All rights granted under this License are granted for the term of
|
|
||||||
copyright on the Program, and are irrevocable provided the stated
|
|
||||||
conditions are met. This License explicitly affirms your unlimited
|
|
||||||
permission to run the unmodified Program. The output from running a
|
|
||||||
covered work is covered by this License only if the output, given its
|
|
||||||
content, constitutes a covered work. This License acknowledges your
|
|
||||||
rights of fair use or other equivalent, as provided by copyright law.
|
|
||||||
|
|
||||||
You may make, run and propagate covered works that you do not
|
|
||||||
convey, without conditions so long as your license otherwise remains
|
|
||||||
in force. You may convey covered works to others for the sole purpose
|
|
||||||
of having them make modifications exclusively for you, or provide you
|
|
||||||
with facilities for running those works, provided that you comply with
|
|
||||||
the terms of this License in conveying all material for which you do
|
|
||||||
not control copyright. Those thus making or running the covered works
|
|
||||||
for you must do so exclusively on your behalf, under your direction
|
|
||||||
and control, on terms that prohibit them from making any copies of
|
|
||||||
your copyrighted material outside their relationship with you.
|
|
||||||
|
|
||||||
Conveying under any other circumstances is permitted solely under
|
|
||||||
the conditions stated below. Sublicensing is not allowed; section 10
|
|
||||||
makes it unnecessary.
|
|
||||||
|
|
||||||
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
|
|
||||||
|
|
||||||
No covered work shall be deemed part of an effective technological
|
|
||||||
measure under any applicable law fulfilling obligations under article
|
|
||||||
11 of the WIPO copyright treaty adopted on 20 December 1996, or
|
|
||||||
similar laws prohibiting or restricting circumvention of such
|
|
||||||
measures.
|
|
||||||
|
|
||||||
When you convey a covered work, you waive any legal power to forbid
|
|
||||||
circumvention of technological measures to the extent such circumvention
|
|
||||||
is effected by exercising rights under this License with respect to
|
|
||||||
the covered work, and you disclaim any intention to limit operation or
|
|
||||||
modification of the work as a means of enforcing, against the work's
|
|
||||||
users, your or third parties' legal rights to forbid circumvention of
|
|
||||||
technological measures.
|
|
||||||
|
|
||||||
4. Conveying Verbatim Copies.
|
|
||||||
|
|
||||||
You may convey verbatim copies of the Program's source code as you
|
|
||||||
receive it, in any medium, provided that you conspicuously and
|
|
||||||
appropriately publish on each copy an appropriate copyright notice;
|
|
||||||
keep intact all notices stating that this License and any
|
|
||||||
non-permissive terms added in accord with section 7 apply to the code;
|
|
||||||
keep intact all notices of the absence of any warranty; and give all
|
|
||||||
recipients a copy of this License along with the Program.
|
|
||||||
|
|
||||||
You may charge any price or no price for each copy that you convey,
|
|
||||||
and you may offer support or warranty protection for a fee.
|
|
||||||
|
|
||||||
5. Conveying Modified Source Versions.
|
|
||||||
|
|
||||||
You may convey a work based on the Program, or the modifications to
|
|
||||||
produce it from the Program, in the form of source code under the
|
|
||||||
terms of section 4, provided that you also meet all of these conditions:
|
|
||||||
|
|
||||||
a) The work must carry prominent notices stating that you modified
|
|
||||||
it, and giving a relevant date.
|
|
||||||
|
|
||||||
b) The work must carry prominent notices stating that it is
|
|
||||||
released under this License and any conditions added under section
|
|
||||||
7. This requirement modifies the requirement in section 4 to
|
|
||||||
"keep intact all notices".
|
|
||||||
|
|
||||||
c) You must license the entire work, as a whole, under this
|
|
||||||
License to anyone who comes into possession of a copy. This
|
|
||||||
License will therefore apply, along with any applicable section 7
|
|
||||||
additional terms, to the whole of the work, and all its parts,
|
|
||||||
regardless of how they are packaged. This License gives no
|
|
||||||
permission to license the work in any other way, but it does not
|
|
||||||
invalidate such permission if you have separately received it.
|
|
||||||
|
|
||||||
d) If the work has interactive user interfaces, each must display
|
|
||||||
Appropriate Legal Notices; however, if the Program has interactive
|
|
||||||
interfaces that do not display Appropriate Legal Notices, your
|
|
||||||
work need not make them do so.
|
|
||||||
|
|
||||||
A compilation of a covered work with other separate and independent
|
|
||||||
works, which are not by their nature extensions of the covered work,
|
|
||||||
and which are not combined with it such as to form a larger program,
|
|
||||||
in or on a volume of a storage or distribution medium, is called an
|
|
||||||
"aggregate" if the compilation and its resulting copyright are not
|
|
||||||
used to limit the access or legal rights of the compilation's users
|
|
||||||
beyond what the individual works permit. Inclusion of a covered work
|
|
||||||
in an aggregate does not cause this License to apply to the other
|
|
||||||
parts of the aggregate.
|
|
||||||
|
|
||||||
6. Conveying Non-Source Forms.
|
|
||||||
|
|
||||||
You may convey a covered work in object code form under the terms
|
|
||||||
of sections 4 and 5, provided that you also convey the
|
|
||||||
machine-readable Corresponding Source under the terms of this License,
|
|
||||||
in one of these ways:
|
|
||||||
|
|
||||||
a) Convey the object code in, or embodied in, a physical product
|
|
||||||
(including a physical distribution medium), accompanied by the
|
|
||||||
Corresponding Source fixed on a durable physical medium
|
|
||||||
customarily used for software interchange.
|
|
||||||
|
|
||||||
b) Convey the object code in, or embodied in, a physical product
|
|
||||||
(including a physical distribution medium), accompanied by a
|
|
||||||
written offer, valid for at least three years and valid for as
|
|
||||||
long as you offer spare parts or customer support for that product
|
|
||||||
model, to give anyone who possesses the object code either (1) a
|
|
||||||
copy of the Corresponding Source for all the software in the
|
|
||||||
product that is covered by this License, on a durable physical
|
|
||||||
medium customarily used for software interchange, for a price no
|
|
||||||
more than your reasonable cost of physically performing this
|
|
||||||
conveying of source, or (2) access to copy the
|
|
||||||
Corresponding Source from a network server at no charge.
|
|
||||||
|
|
||||||
c) Convey individual copies of the object code with a copy of the
|
|
||||||
written offer to provide the Corresponding Source. This
|
|
||||||
alternative is allowed only occasionally and noncommercially, and
|
|
||||||
only if you received the object code with such an offer, in accord
|
|
||||||
with subsection 6b.
|
|
||||||
|
|
||||||
d) Convey the object code by offering access from a designated
|
|
||||||
place (gratis or for a charge), and offer equivalent access to the
|
|
||||||
Corresponding Source in the same way through the same place at no
|
|
||||||
further charge. You need not require recipients to copy the
|
|
||||||
Corresponding Source along with the object code. If the place to
|
|
||||||
copy the object code is a network server, the Corresponding Source
|
|
||||||
may be on a different server (operated by you or a third party)
|
|
||||||
that supports equivalent copying facilities, provided you maintain
|
|
||||||
clear directions next to the object code saying where to find the
|
|
||||||
Corresponding Source. Regardless of what server hosts the
|
|
||||||
Corresponding Source, you remain obligated to ensure that it is
|
|
||||||
available for as long as needed to satisfy these requirements.
|
|
||||||
|
|
||||||
e) Convey the object code using peer-to-peer transmission, provided
|
|
||||||
you inform other peers where the object code and Corresponding
|
|
||||||
Source of the work are being offered to the general public at no
|
|
||||||
charge under subsection 6d.
|
|
||||||
|
|
||||||
A separable portion of the object code, whose source code is excluded
|
|
||||||
from the Corresponding Source as a System Library, need not be
|
|
||||||
included in conveying the object code work.
|
|
||||||
|
|
||||||
A "User Product" is either (1) a "consumer product", which means any
|
|
||||||
tangible personal property which is normally used for personal, family,
|
|
||||||
or household purposes, or (2) anything designed or sold for incorporation
|
|
||||||
into a dwelling. In determining whether a product is a consumer product,
|
|
||||||
doubtful cases shall be resolved in favor of coverage. For a particular
|
|
||||||
product received by a particular user, "normally used" refers to a
|
|
||||||
typical or common use of that class of product, regardless of the status
|
|
||||||
of the particular user or of the way in which the particular user
|
|
||||||
actually uses, or expects or is expected to use, the product. A product
|
|
||||||
is a consumer product regardless of whether the product has substantial
|
|
||||||
commercial, industrial or non-consumer uses, unless such uses represent
|
|
||||||
the only significant mode of use of the product.
|
|
||||||
|
|
||||||
"Installation Information" for a User Product means any methods,
|
|
||||||
procedures, authorization keys, or other information required to install
|
|
||||||
and execute modified versions of a covered work in that User Product from
|
|
||||||
a modified version of its Corresponding Source. The information must
|
|
||||||
suffice to ensure that the continued functioning of the modified object
|
|
||||||
code is in no case prevented or interfered with solely because
|
|
||||||
modification has been made.
|
|
||||||
|
|
||||||
If you convey an object code work under this section in, or with, or
|
|
||||||
specifically for use in, a User Product, and the conveying occurs as
|
|
||||||
part of a transaction in which the right of possession and use of the
|
|
||||||
User Product is transferred to the recipient in perpetuity or for a
|
|
||||||
fixed term (regardless of how the transaction is characterized), the
|
|
||||||
Corresponding Source conveyed under this section must be accompanied
|
|
||||||
by the Installation Information. But this requirement does not apply
|
|
||||||
if neither you nor any third party retains the ability to install
|
|
||||||
modified object code on the User Product (for example, the work has
|
|
||||||
been installed in ROM).
|
|
||||||
|
|
||||||
The requirement to provide Installation Information does not include a
|
|
||||||
requirement to continue to provide support service, warranty, or updates
|
|
||||||
for a work that has been modified or installed by the recipient, or for
|
|
||||||
the User Product in which it has been modified or installed. Access to a
|
|
||||||
network may be denied when the modification itself materially and
|
|
||||||
adversely affects the operation of the network or violates the rules and
|
|
||||||
protocols for communication across the network.
|
|
||||||
|
|
||||||
Corresponding Source conveyed, and Installation Information provided,
|
|
||||||
in accord with this section must be in a format that is publicly
|
|
||||||
documented (and with an implementation available to the public in
|
|
||||||
source code form), and must require no special password or key for
|
|
||||||
unpacking, reading or copying.
|
|
||||||
|
|
||||||
7. Additional Terms.
|
|
||||||
|
|
||||||
"Additional permissions" are terms that supplement the terms of this
|
|
||||||
License by making exceptions from one or more of its conditions.
|
|
||||||
Additional permissions that are applicable to the entire Program shall
|
|
||||||
be treated as though they were included in this License, to the extent
|
|
||||||
that they are valid under applicable law. If additional permissions
|
|
||||||
apply only to part of the Program, that part may be used separately
|
|
||||||
under those permissions, but the entire Program remains governed by
|
|
||||||
this License without regard to the additional permissions.
|
|
||||||
|
|
||||||
When you convey a copy of a covered work, you may at your option
|
|
||||||
remove any additional permissions from that copy, or from any part of
|
|
||||||
it. (Additional permissions may be written to require their own
|
|
||||||
removal in certain cases when you modify the work.) You may place
|
|
||||||
additional permissions on material, added by you to a covered work,
|
|
||||||
for which you have or can give appropriate copyright permission.
|
|
||||||
|
|
||||||
Notwithstanding any other provision of this License, for material you
|
|
||||||
add to a covered work, you may (if authorized by the copyright holders of
|
|
||||||
that material) supplement the terms of this License with terms:
|
|
||||||
|
|
||||||
a) Disclaiming warranty or limiting liability differently from the
|
|
||||||
terms of sections 15 and 16 of this License; or
|
|
||||||
|
|
||||||
b) Requiring preservation of specified reasonable legal notices or
|
|
||||||
author attributions in that material or in the Appropriate Legal
|
|
||||||
Notices displayed by works containing it; or
|
|
||||||
|
|
||||||
c) Prohibiting misrepresentation of the origin of that material, or
|
|
||||||
requiring that modified versions of such material be marked in
|
|
||||||
reasonable ways as different from the original version; or
|
|
||||||
|
|
||||||
d) Limiting the use for publicity purposes of names of licensors or
|
|
||||||
authors of the material; or
|
|
||||||
|
|
||||||
e) Declining to grant rights under trademark law for use of some
|
|
||||||
trade names, trademarks, or service marks; or
|
|
||||||
|
|
||||||
f) Requiring indemnification of licensors and authors of that
|
|
||||||
material by anyone who conveys the material (or modified versions of
|
|
||||||
it) with contractual assumptions of liability to the recipient, for
|
|
||||||
any liability that these contractual assumptions directly impose on
|
|
||||||
those licensors and authors.
|
|
||||||
|
|
||||||
All other non-permissive additional terms are considered "further
|
|
||||||
restrictions" within the meaning of section 10. If the Program as you
|
|
||||||
received it, or any part of it, contains a notice stating that it is
|
|
||||||
governed by this License along with a term that is a further
|
|
||||||
restriction, you may remove that term. If a license document contains
|
|
||||||
a further restriction but permits relicensing or conveying under this
|
|
||||||
License, you may add to a covered work material governed by the terms
|
|
||||||
of that license document, provided that the further restriction does
|
|
||||||
not survive such relicensing or conveying.
|
|
||||||
|
|
||||||
If you add terms to a covered work in accord with this section, you
|
|
||||||
must place, in the relevant source files, a statement of the
|
|
||||||
additional terms that apply to those files, or a notice indicating
|
|
||||||
where to find the applicable terms.
|
|
||||||
|
|
||||||
Additional terms, permissive or non-permissive, may be stated in the
|
|
||||||
form of a separately written license, or stated as exceptions;
|
|
||||||
the above requirements apply either way.
|
|
||||||
|
|
||||||
8. Termination.
|
|
||||||
|
|
||||||
You may not propagate or modify a covered work except as expressly
|
|
||||||
provided under this License. Any attempt otherwise to propagate or
|
|
||||||
modify it is void, and will automatically terminate your rights under
|
|
||||||
this License (including any patent licenses granted under the third
|
|
||||||
paragraph of section 11).
|
|
||||||
|
|
||||||
However, if you cease all violation of this License, then your
|
|
||||||
license from a particular copyright holder is reinstated (a)
|
|
||||||
provisionally, unless and until the copyright holder explicitly and
|
|
||||||
finally terminates your license, and (b) permanently, if the copyright
|
|
||||||
holder fails to notify you of the violation by some reasonable means
|
|
||||||
prior to 60 days after the cessation.
|
|
||||||
|
|
||||||
Moreover, your license from a particular copyright holder is
|
|
||||||
reinstated permanently if the copyright holder notifies you of the
|
|
||||||
violation by some reasonable means, this is the first time you have
|
|
||||||
received notice of violation of this License (for any work) from that
|
|
||||||
copyright holder, and you cure the violation prior to 30 days after
|
|
||||||
your receipt of the notice.
|
|
||||||
|
|
||||||
Termination of your rights under this section does not terminate the
|
|
||||||
licenses of parties who have received copies or rights from you under
|
|
||||||
this License. If your rights have been terminated and not permanently
|
|
||||||
reinstated, you do not qualify to receive new licenses for the same
|
|
||||||
material under section 10.
|
|
||||||
|
|
||||||
9. Acceptance Not Required for Having Copies.
|
|
||||||
|
|
||||||
You are not required to accept this License in order to receive or
|
|
||||||
run a copy of the Program. Ancillary propagation of a covered work
|
|
||||||
occurring solely as a consequence of using peer-to-peer transmission
|
|
||||||
to receive a copy likewise does not require acceptance. However,
|
|
||||||
nothing other than this License grants you permission to propagate or
|
|
||||||
modify any covered work. These actions infringe copyright if you do
|
|
||||||
not accept this License. Therefore, by modifying or propagating a
|
|
||||||
covered work, you indicate your acceptance of this License to do so.
|
|
||||||
|
|
||||||
10. Automatic Licensing of Downstream Recipients.
|
|
||||||
|
|
||||||
Each time you convey a covered work, the recipient automatically
|
|
||||||
receives a license from the original licensors, to run, modify and
|
|
||||||
propagate that work, subject to this License. You are not responsible
|
|
||||||
for enforcing compliance by third parties with this License.
|
|
||||||
|
|
||||||
An "entity transaction" is a transaction transferring control of an
|
|
||||||
organization, or substantially all assets of one, or subdividing an
|
|
||||||
organization, or merging organizations. If propagation of a covered
|
|
||||||
work results from an entity transaction, each party to that
|
|
||||||
transaction who receives a copy of the work also receives whatever
|
|
||||||
licenses to the work the party's predecessor in interest had or could
|
|
||||||
give under the previous paragraph, plus a right to possession of the
|
|
||||||
Corresponding Source of the work from the predecessor in interest, if
|
|
||||||
the predecessor has it or can get it with reasonable efforts.
|
|
||||||
|
|
||||||
You may not impose any further restrictions on the exercise of the
|
|
||||||
rights granted or affirmed under this License. For example, you may
|
|
||||||
not impose a license fee, royalty, or other charge for exercise of
|
|
||||||
rights granted under this License, and you may not initiate litigation
|
|
||||||
(including a cross-claim or counterclaim in a lawsuit) alleging that
|
|
||||||
any patent claim is infringed by making, using, selling, offering for
|
|
||||||
sale, or importing the Program or any portion of it.
|
|
||||||
|
|
||||||
11. Patents.
|
|
||||||
|
|
||||||
A "contributor" is a copyright holder who authorizes use under this
|
|
||||||
License of the Program or a work on which the Program is based. The
|
|
||||||
work thus licensed is called the contributor's "contributor version".
|
|
||||||
|
|
||||||
A contributor's "essential patent claims" are all patent claims
|
|
||||||
owned or controlled by the contributor, whether already acquired or
|
|
||||||
hereafter acquired, that would be infringed by some manner, permitted
|
|
||||||
by this License, of making, using, or selling its contributor version,
|
|
||||||
but do not include claims that would be infringed only as a
|
|
||||||
consequence of further modification of the contributor version. For
|
|
||||||
purposes of this definition, "control" includes the right to grant
|
|
||||||
patent sublicenses in a manner consistent with the requirements of
|
|
||||||
this License.
|
|
||||||
|
|
||||||
Each contributor grants you a non-exclusive, worldwide, royalty-free
|
|
||||||
patent license under the contributor's essential patent claims, to
|
|
||||||
make, use, sell, offer for sale, import and otherwise run, modify and
|
|
||||||
propagate the contents of its contributor version.
|
|
||||||
|
|
||||||
In the following three paragraphs, a "patent license" is any express
|
|
||||||
agreement or commitment, however denominated, not to enforce a patent
|
|
||||||
(such as an express permission to practice a patent or covenant not to
|
|
||||||
sue for patent infringement). To "grant" such a patent license to a
|
|
||||||
party means to make such an agreement or commitment not to enforce a
|
|
||||||
patent against the party.
|
|
||||||
|
|
||||||
If you convey a covered work, knowingly relying on a patent license,
|
|
||||||
and the Corresponding Source of the work is not available for anyone
|
|
||||||
to copy, free of charge and under the terms of this License, through a
|
|
||||||
publicly available network server or other readily accessible means,
|
|
||||||
then you must either (1) cause the Corresponding Source to be so
|
|
||||||
available, or (2) arrange to deprive yourself of the benefit of the
|
|
||||||
patent license for this particular work, or (3) arrange, in a manner
|
|
||||||
consistent with the requirements of this License, to extend the patent
|
|
||||||
license to downstream recipients. "Knowingly relying" means you have
|
|
||||||
actual knowledge that, but for the patent license, your conveying the
|
|
||||||
covered work in a country, or your recipient's use of the covered work
|
|
||||||
in a country, would infringe one or more identifiable patents in that
|
|
||||||
country that you have reason to believe are valid.
|
|
||||||
|
|
||||||
If, pursuant to or in connection with a single transaction or
|
|
||||||
arrangement, you convey, or propagate by procuring conveyance of, a
|
|
||||||
covered work, and grant a patent license to some of the parties
|
|
||||||
receiving the covered work authorizing them to use, propagate, modify
|
|
||||||
or convey a specific copy of the covered work, then the patent license
|
|
||||||
you grant is automatically extended to all recipients of the covered
|
|
||||||
work and works based on it.
|
|
||||||
|
|
||||||
A patent license is "discriminatory" if it does not include within
|
|
||||||
the scope of its coverage, prohibits the exercise of, or is
|
|
||||||
conditioned on the non-exercise of one or more of the rights that are
|
|
||||||
specifically granted under this License. You may not convey a covered
|
|
||||||
work if you are a party to an arrangement with a third party that is
|
|
||||||
in the business of distributing software, under which you make payment
|
|
||||||
to the third party based on the extent of your activity of conveying
|
|
||||||
the work, and under which the third party grants, to any of the
|
|
||||||
parties who would receive the covered work from you, a discriminatory
|
|
||||||
patent license (a) in connection with copies of the covered work
|
|
||||||
conveyed by you (or copies made from those copies), or (b) primarily
|
|
||||||
for and in connection with specific products or compilations that
|
|
||||||
contain the covered work, unless you entered into that arrangement,
|
|
||||||
or that patent license was granted, prior to 28 March 2007.
|
|
||||||
|
|
||||||
Nothing in this License shall be construed as excluding or limiting
|
|
||||||
any implied license or other defenses to infringement that may
|
|
||||||
otherwise be available to you under applicable patent law.
|
|
||||||
|
|
||||||
12. No Surrender of Others' Freedom.
|
|
||||||
|
|
||||||
If conditions are imposed on you (whether by court order, agreement or
|
|
||||||
otherwise) that contradict the conditions of this License, they do not
|
|
||||||
excuse you from the conditions of this License. If you cannot convey a
|
|
||||||
covered work so as to satisfy simultaneously your obligations under this
|
|
||||||
License and any other pertinent obligations, then as a consequence you may
|
|
||||||
not convey it at all. For example, if you agree to terms that obligate you
|
|
||||||
to collect a royalty for further conveying from those to whom you convey
|
|
||||||
the Program, the only way you could satisfy both those terms and this
|
|
||||||
License would be to refrain entirely from conveying the Program.
|
|
||||||
|
|
||||||
13. Use with the GNU Affero General Public License.
|
|
||||||
|
|
||||||
Notwithstanding any other provision of this License, you have
|
|
||||||
permission to link or combine any covered work with a work licensed
|
|
||||||
under version 3 of the GNU Affero General Public License into a single
|
|
||||||
combined work, and to convey the resulting work. The terms of this
|
|
||||||
License will continue to apply to the part which is the covered work,
|
|
||||||
but the special requirements of the GNU Affero General Public License,
|
|
||||||
section 13, concerning interaction through a network will apply to the
|
|
||||||
combination as such.
|
|
||||||
|
|
||||||
14. Revised Versions of this License.
|
|
||||||
|
|
||||||
The Free Software Foundation may publish revised and/or new versions of
|
|
||||||
the GNU General Public License from time to time. Such new versions will
|
|
||||||
be similar in spirit to the present version, but may differ in detail to
|
|
||||||
address new problems or concerns.
|
|
||||||
|
|
||||||
Each version is given a distinguishing version number. If the
|
|
||||||
Program specifies that a certain numbered version of the GNU General
|
|
||||||
Public License "or any later version" applies to it, you have the
|
|
||||||
option of following the terms and conditions either of that numbered
|
|
||||||
version or of any later version published by the Free Software
|
|
||||||
Foundation. If the Program does not specify a version number of the
|
|
||||||
GNU General Public License, you may choose any version ever published
|
|
||||||
by the Free Software Foundation.
|
|
||||||
|
|
||||||
If the Program specifies that a proxy can decide which future
|
|
||||||
versions of the GNU General Public License can be used, that proxy's
|
|
||||||
public statement of acceptance of a version permanently authorizes you
|
|
||||||
to choose that version for the Program.
|
|
||||||
|
|
||||||
Later license versions may give you additional or different
|
|
||||||
permissions. However, no additional obligations are imposed on any
|
|
||||||
author or copyright holder as a result of your choosing to follow a
|
|
||||||
later version.
|
|
||||||
|
|
||||||
15. Disclaimer of Warranty.
|
|
||||||
|
|
||||||
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
|
|
||||||
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
|
|
||||||
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
|
|
||||||
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
|
|
||||||
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
|
||||||
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
|
|
||||||
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
|
|
||||||
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
|
||||||
|
|
||||||
16. Limitation of Liability.
|
|
||||||
|
|
||||||
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
|
|
||||||
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
|
|
||||||
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
|
|
||||||
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
|
|
||||||
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
|
|
||||||
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
|
|
||||||
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
|
|
||||||
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
|
|
||||||
SUCH DAMAGES.
|
|
||||||
|
|
||||||
17. Interpretation of Sections 15 and 16.
|
|
||||||
|
|
||||||
If the disclaimer of warranty and limitation of liability provided
|
|
||||||
above cannot be given local legal effect according to their terms,
|
|
||||||
reviewing courts shall apply local law that most closely approximates
|
|
||||||
an absolute waiver of all civil liability in connection with the
|
|
||||||
Program, unless a warranty or assumption of liability accompanies a
|
|
||||||
copy of the Program in return for a fee.
|
|
||||||
|
|
||||||
END OF TERMS AND CONDITIONS
|
|
||||||
|
|
||||||
How to Apply These Terms to Your New Programs
|
|
||||||
|
|
||||||
If you develop a new program, and you want it to be of the greatest
|
|
||||||
possible use to the public, the best way to achieve this is to make it
|
|
||||||
free software which everyone can redistribute and change under these terms.
|
|
||||||
|
|
||||||
To do so, attach the following notices to the program. It is safest
|
|
||||||
to attach them to the start of each source file to most effectively
|
|
||||||
state the exclusion of warranty; and each file should have at least
|
|
||||||
the "copyright" line and a pointer to where the full notice is found.
|
|
||||||
|
|
||||||
<one line to give the program's name and a brief idea of what it does.>
|
|
||||||
Copyright (C) <year> <name of author>
|
|
||||||
|
|
||||||
This program is free software: you can redistribute it and/or modify
|
|
||||||
it under the terms of the GNU General Public License as published by
|
|
||||||
the Free Software Foundation, either version 3 of the License, or
|
|
||||||
(at your option) any later version.
|
|
||||||
|
|
||||||
This program is distributed in the hope that it will be useful,
|
|
||||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
|
||||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
|
||||||
GNU General Public License for more details.
|
|
||||||
|
|
||||||
You should have received a copy of the GNU General Public License
|
|
||||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
|
||||||
|
|
||||||
Also add information on how to contact you by electronic and paper mail.
|
|
||||||
|
|
||||||
If the program does terminal interaction, make it output a short
|
|
||||||
notice like this when it starts in an interactive mode:
|
|
||||||
|
|
||||||
<program> Copyright (C) <year> <name of author>
|
|
||||||
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
|
|
||||||
This is free software, and you are welcome to redistribute it
|
|
||||||
under certain conditions; type `show c' for details.
|
|
||||||
|
|
||||||
The hypothetical commands `show w' and `show c' should show the appropriate
|
|
||||||
parts of the General Public License. Of course, your program's commands
|
|
||||||
might be different; for a GUI interface, you would use an "about box".
|
|
||||||
|
|
||||||
You should also get your employer (if you work as a programmer) or school,
|
|
||||||
if any, to sign a "copyright disclaimer" for the program, if necessary.
|
|
||||||
For more information on this, and how to apply and follow the GNU GPL, see
|
|
||||||
<https://www.gnu.org/licenses/>.
|
|
||||||
|
|
||||||
The GNU General Public License does not permit incorporating your program
|
|
||||||
into proprietary programs. If your program is a subroutine library, you
|
|
||||||
may consider it more useful to permit linking proprietary applications with
|
|
||||||
the library. If this is what you want to do, use the GNU Lesser General
|
|
||||||
Public License instead of this License. But first, please read
|
|
||||||
<https://www.gnu.org/licenses/why-not-lgpl.html>.
|
|
||||||
-28
@@ -1,28 +0,0 @@
|
|||||||
# wechat_chatter / OneBot 第三方组件说明
|
|
||||||
|
|
||||||
TraceMemo 的 macOS 个人微信发送功能会按需使用以下第三方组件:
|
|
||||||
|
|
||||||
- 项目:`yincongcyincong/wechat_chatter`
|
|
||||||
- 上游仓库:https://github.com/yincongcyincong/wechat_chatter
|
|
||||||
- 当前运行时版本:`v0.0.18`
|
|
||||||
- 运行时文件:`onebot_mac_arm64.tar.gz`
|
|
||||||
- 许可证:GNU General Public License version 3(GPL-3.0)
|
|
||||||
- 上游版权:Copyright (C) 2026 yincongcyincong
|
|
||||||
- TraceMemo 修改日期:2026-08-17
|
|
||||||
|
|
||||||
## 集成方式
|
|
||||||
|
|
||||||
OneBot 运行时不会随 TraceMemo 安装包一起分发。用户启用该实验性功能时,TraceMemo 会从上述上游项目的 GitHub Release 按需下载运行时,并将其安装到应用的用户数据目录。
|
|
||||||
|
|
||||||
运行时作为独立进程启动,TraceMemo 通过本机 HTTP 接口与其通信。
|
|
||||||
|
|
||||||
## 本地修改
|
|
||||||
|
|
||||||
为适配连续发送、图片上传 Hook 状态检测以及微信核心模块基址定位,TraceMemo 会在用户设备上对上游 `onebot/script.js` 应用兼容性补丁。补丁逻辑位于:
|
|
||||||
|
|
||||||
- `scripts/prepare-wechat-chatter-runtime.cjs`
|
|
||||||
- `src/main/services/personal-wechat-runtime-manager.ts`
|
|
||||||
|
|
||||||
补丁中源自或修改自上游 `script.js` 的部分,以及补丁应用后产生的修改版 `script.js`,继续按照 GPL-3.0 提供。本说明只针对该第三方组件及相关修改,不用于声明 TraceMemo 仓库其他部分的许可证。
|
|
||||||
|
|
||||||
GPL-3.0 的完整文本见本目录下的 `LICENSE`。
|
|
||||||
@@ -24,6 +24,12 @@ ZIP 是 HTML 资源包的压缩选项,不是第五种内容格式。
|
|||||||
5. 设置文件名并开始导出。
|
5. 设置文件名并开始导出。
|
||||||
6. 在导出任务中心查看读取、解析、媒体处理、转写、写入和压缩进度;完成后打开文件位置。
|
6. 在导出任务中心查看读取、解析、媒体处理、转写、写入和压缩进度;完成后打开文件位置。
|
||||||
|
|
||||||
|
## 导出设置会被记住
|
||||||
|
|
||||||
|
TraceMemo 会记住上一次使用的导出设置,下次打开导出页面时自动恢复,减少重复选择。包括格式、时间范围、消息类型、名称显示方式、媒体选项(原图/缩略图、头像)、语音转写、缺失资源处理、ZIP、文件名和输出目录。
|
||||||
|
|
||||||
|
这些偏好保存在本机,不会随账号同步到其他设备。
|
||||||
|
|
||||||
## 多会话和增量导出
|
## 多会话和增量导出
|
||||||
|
|
||||||
HTML 支持把最多五个会话合并到一个档案中;选择多个会话后,其他格式会不可用。再次使用相同名称导出 HTML 时,可以把新消息增量合并到已有档案;这不会删除之前已导出的消息。
|
HTML 支持把最多五个会话合并到一个档案中;选择多个会话后,其他格式会不可用。再次使用相同名称导出 HTML 时,可以把新消息增量合并到已有档案;这不会删除之前已导出的消息。
|
||||||
|
|||||||
@@ -33,7 +33,7 @@ Apple Silicon 和 Intel 均已适配微信 macOS `4.1.13` 系列。首次获取
|
|||||||
- 上表中的版本是当前 TraceMemo 已适配或推荐使用的版本,并不代表只有这些版本可以运行。
|
- 上表中的版本是当前 TraceMemo 已适配或推荐使用的版本,并不代表只有这些版本可以运行。
|
||||||
- TraceMemo 必须取得当前微信账号对应的数据库密钥,才能读取聊天记录。
|
- TraceMemo 必须取得当前微信账号对应的数据库密钥,才能读取聊天记录。
|
||||||
- 你需要有权访问要读取的微信账号和聊天数据。
|
- 你需要有权访问要读取的微信账号和聊天数据。
|
||||||
- 如果要使用 AI 问答、群聊日报或图片理解,还需要在应用中配置一个 AI 服务。
|
- 如果要使用 AI 问答、群聊日报或图片理解,还需要在应用中配置一个 AI 服务。「图片文字索引」不在此列——它在本机识别图片里的文字,不需要配置 AI。
|
||||||
|
|
||||||
当前代码按微信 4.x 数据结构处理。不同微信客户端版本、系统权限和数据迁移状态可能影响自动连接;遇到问题时请查看[常见问题与排查](./troubleshooting.md)。
|
当前代码按微信 4.x 数据结构处理。不同微信客户端版本、系统权限和数据迁移状态可能影响自动连接;遇到问题时请查看[常见问题与排查](./troubleshooting.md)。
|
||||||
|
|
||||||
@@ -134,6 +134,7 @@ Apple Silicon 和 Intel 均已适配微信 macOS `4.1.13` 系列。首次获取
|
|||||||
- [生成群聊日报或总结](./report.md)
|
- [生成群聊日报或总结](./report.md)
|
||||||
- [转写微信语音](./voice.md)
|
- [转写微信语音](./voice.md)
|
||||||
- [导出聊天档案](./export.md)
|
- [导出聊天档案](./export.md)
|
||||||
|
- [让日报、退群通知按规则自动运行](../README.md#日报与自动化)
|
||||||
- [在微信里向 TraceMemo 提问](../agent/agent-hub.md)
|
- [在微信里向 TraceMemo 提问](../agent/agent-hub.md)
|
||||||
- [让外部 Agent 查询微信历史](../agent/overview.md)
|
- [让外部 Agent 查询微信历史](../agent/overview.md)
|
||||||
|
|
||||||
@@ -159,14 +160,17 @@ Agent Hub 是普通用户可以直接使用的入口,不需要安装 Reader Sk
|
|||||||
|
|
||||||
## 8. 需要配置 AI 吗?
|
## 8. 需要配置 AI 吗?
|
||||||
|
|
||||||
不一定。浏览聊天、普通关键词搜索、建立本地知识库和导出不要求在线 AI 服务。
|
不一定。浏览聊天、普通关键词搜索、建立本地知识库、图片文字识别、离线语音转写和导出都不要求在线 AI 服务。
|
||||||
|
|
||||||
使用“问问微信”、群聊日报或图片理解时,需要在“设置 → AI 模型”中添加并测试 AI 服务。你主动开始并确认远程 AI 功能后,完成任务所需的内容才可能发送给该服务;计费、留存和地区规则由对应服务商决定。
|
使用“问问微信”、群聊日报或图片理解时,需要在“设置 → AI 模型”中添加并测试 AI 服务。你主动开始并确认远程 AI 功能后,完成任务所需的内容才可能发送给该服务;计费、留存和地区规则由对应服务商决定。
|
||||||
|
|
||||||
|
这两种情况容易混淆:**本机识别图片里的文字**(图片文字索引)不联网、不需要 AI 服务;**让模型看图并回答**(图片理解)才需要配置 AI 服务。
|
||||||
|
|
||||||
## 9. 数据和隐私的最低须知
|
## 9. 数据和隐私的最低须知
|
||||||
|
|
||||||
- 微信数据库、聊天解析和本地索引默认留在本机。
|
- 微信数据库、聊天解析、本地索引和图片文字识别默认留在本机。
|
||||||
- 离线语音转写使用本地模型;它与在线 AI 请求是两条不同的数据路径。
|
- 离线语音转写使用本地模型;它与在线 AI 请求是两条不同的数据路径。
|
||||||
|
- 图片文字索引只在本机识别,原始图片不会因为本地识别而上传;识别出的文字会进入本地索引,供搜索和“问问微信”使用。
|
||||||
- 你主动开始并确认 AI 问答或日报后,完成任务所需的受控上下文才可能发送给你选择的 AI 服务;打开应用不会自动上传全部聊天。
|
- 你主动开始并确认 AI 问答或日报后,完成任务所需的受控上下文才可能发送给你选择的 AI 服务;打开应用不会自动上传全部聊天。
|
||||||
- 应用内 Local HTTP API 默认只监听 `127.0.0.1:6131`,受保护接口需要 Token。
|
- 应用内 Local HTTP API 默认只监听 `127.0.0.1:6131`,受保护接口需要 Token。
|
||||||
|
|
||||||
|
|||||||
@@ -24,13 +24,13 @@ Knowledge 不会在第一次连接后自动悄悄建立。进入“问问微信
|
|||||||
|
|
||||||
### 状态怎么读
|
### 状态怎么读
|
||||||
|
|
||||||
| 状态 | 含义 |
|
| 状态 | 含义 |
|
||||||
| ---- | ---- |
|
| ------------------- | ------------------------------------------------ |
|
||||||
| 可用 · 已追至最新 | 索引已覆盖到聊天记录的最新位置,可以直接用 |
|
| 可用 · 已追至最新 | 索引已覆盖到聊天记录的最新位置,可以直接用 |
|
||||||
| 可用 · 正在追新 | 索引可用,正在后台补充最近新增的消息 |
|
| 可用 · 正在追新 | 索引可用,正在后台补充最近新增的消息 |
|
||||||
| 可用 · 正在补齐历史 | 索引可用,正在后台补齐较早的历史内容 |
|
| 可用 · 正在补齐历史 | 索引可用,正在后台补齐较早的历史内容 |
|
||||||
| 可用 · 同步已取消 | 索引仍然可用;上一轮同步被取消,已建立的部分保留 |
|
| 可用 · 同步已取消 | 索引仍然可用;上一轮同步被取消,已建立的部分保留 |
|
||||||
| 可用 · 更新失败 | 索引仍然可用;上一轮同步出错,可以稍后重试 |
|
| 可用 · 更新失败 | 索引仍然可用;上一轮同步出错,可以稍后重试 |
|
||||||
|
|
||||||
只有确实追平、且没有待补齐内容时才会出现“已追至最新”。索引不可查询时不会显示“可用”。
|
只有确实追平、且没有待补齐内容时才会出现“已追至最新”。索引不可查询时不会显示“可用”。
|
||||||
|
|
||||||
@@ -38,6 +38,21 @@ Knowledge 不会在第一次连接后自动悄悄建立。进入“问问微信
|
|||||||
|
|
||||||
同步过程中可以点击 **取消同步**(点击后显示“正在取消…”)。取消只结束当前这一轮,不会删除已经建立的索引,也不会回滚已完成的部分;下次同步会从上次停下的位置继续,不需要从头重扫。中断过的索引仍然可以正常搜索。
|
同步过程中可以点击 **取消同步**(点击后显示“正在取消…”)。取消只结束当前这一轮,不会删除已经建立的索引,也不会回滚已完成的部分;下次同步会从上次停下的位置继续,不需要从头重扫。中断过的索引仍然可以正常搜索。
|
||||||
|
|
||||||
|
## 图片文字索引(另一份索引)
|
||||||
|
|
||||||
|
本地索引其实有两份,彼此独立:
|
||||||
|
|
||||||
|
- **聊天记录索引**(也就是上面说的 Knowledge):索引文字消息,用于跨会话、跨时间查找;
|
||||||
|
- **图片文字索引**:在本机识别微信图片里的文字(截图、公告、报价图等),把识别结果也变成可搜索的文字。
|
||||||
|
|
||||||
|
“独立”的意思是:聊天记录索引建好了,并不代表图片里的文字就搜得到。建立图片文字索引后,可以在“问问微信”里直接搜截图或公告图里写过的词。
|
||||||
|
|
||||||
|
图片文字索引只在本机识别,原始图片不会因为本地识别而上传。它**不等于“图片理解”**:识别文字不联网、不需要 AI 服务;而让模型看图并回答属于图片理解,需要配置 AI 服务,走的是另一条路径。
|
||||||
|
|
||||||
|
识别失败的图片可以单独重试,也有“只重建搜索索引、不重新识别图片”的修复入口——修索引不需要重跑几万张图。
|
||||||
|
|
||||||
|
两个索引都可以在“设置 → 本地索引”里集中查看状态、建立、同步和清理。
|
||||||
|
|
||||||
## 账号隔离
|
## 账号隔离
|
||||||
|
|
||||||
每个微信账号使用独立的本地索引。切换账号时,应用不会把一个账号的索引混入另一个账号的搜索结果。
|
每个微信账号使用独立的本地索引。切换账号时,应用不会把一个账号的索引混入另一个账号的搜索结果。
|
||||||
@@ -58,4 +73,3 @@ Knowledge 不会在第一次连接后自动悄悄建立。进入“问问微信
|
|||||||
## 产品术语(可选)
|
## 产品术语(可选)
|
||||||
|
|
||||||
源码和日志中可能出现 SQLite、FTS、Chunk、索引等词。它们描述的是本地存储和检索实现,不是你开始使用 TraceMemo 的前置知识。
|
源码和日志中可能出现 SQLite、FTS、Chunk、索引等词。它们描述的是本地存储和检索实现,不是你开始使用 TraceMemo 的前置知识。
|
||||||
|
|
||||||
@@ -0,0 +1,247 @@
|
|||||||
|
# macOS 更新后读不到微信数据:权限恢复
|
||||||
|
|
||||||
|
本文只处理一种情况:**TraceMemo 之前能连上微信数据库,升级 macOS 或更新 TraceMemo 之后读不到了**。
|
||||||
|
|
||||||
|
正常使用、没有出现权限提示的用户,不需要做任何操作。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 1. 适用版本与典型表现
|
||||||
|
|
||||||
|
### 适用系统
|
||||||
|
|
||||||
|
- macOS 27 及更高版本(本文的主要场景)
|
||||||
|
- 从 macOS 26 或更早版本升级到 macOS 27 之后首次启动 TraceMemo
|
||||||
|
- TraceMemo 2.5.2 及更高版本(更早的版本升到新版时同样可能出现),且此前已经成功连接过一次微信数据库
|
||||||
|
|
||||||
|
如果你从来没有成功连接过,卡在「自动获取密钥」这一步,那不是本文的场景,请看[第一次使用](./getting-started.md)里的密钥获取流程。
|
||||||
|
|
||||||
|
### 典型表现
|
||||||
|
|
||||||
|
出现下面任意一条,且**微信数据目录确实存在**,再按本文处理:
|
||||||
|
|
||||||
|
- 连接页提示「无法读取微信数据库」,错误码 `DATABASE_PERMISSION_DENIED`
|
||||||
|
- 提示「无法打开数据库」,但微信能正常登录、聊天记录能正常查看(权限不足有时会被包装成「打不开」)
|
||||||
|
- 昨天还能用,更新应用后重启就连接失败,期间没有换账号、没有迁移数据目录
|
||||||
|
- 「系统设置 → 隐私与安全性 → 完全磁盘访问权限」里,TraceMemo 的开关是**打开**的,但应用仍然读不到
|
||||||
|
|
||||||
|
如果提示的是「**密钥与当前账号不匹配**」,那不属于本文范围 —— 那是密钥和账号对不上,按[常见问题与排查](./troubleshooting.md#连接微信失败)里的密钥流程处理。
|
||||||
|
|
||||||
|
判断数据目录是否真的存在,可以在终端执行(把路径里的账号目录换成你自己的):
|
||||||
|
|
||||||
|
```bash
|
||||||
|
ls ~/Library/Containers/com.tencent.xinWeChat/Data/Documents/xwechat_files
|
||||||
|
```
|
||||||
|
|
||||||
|
能列出账号目录,说明数据是完整的,问题出在**权限**,不在文件。
|
||||||
|
|
||||||
|
> 终端能读到、TraceMemo 读不到,是完全正常的情况。macOS 的隐私权限按「应用」判定,不按「用户」判定,两者走的是两套不同的检查。所以「终端能读」不能用来排除权限问题。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 2. 为什么更新应用之后会失去访问权限
|
||||||
|
|
||||||
|
一句话:**macOS 认的是应用文件的「指纹」,不是应用的名字。**
|
||||||
|
|
||||||
|
TraceMemo 目前发布的 macOS 版本没有使用 Apple 开发者证书签名,用的是 ad-hoc 签名(相当于临时签名,没有可核验的开发者身份)。这种签名没有稳定的身份标识,系统只能靠应用二进制的指纹来记住「这是哪个应用、你给它授过什么权」。
|
||||||
|
|
||||||
|
每次发布新版本,二进制内容通常会变,指纹随之改变。系统看到的是一个指纹不同的新应用,之前那条授权记录对不上号,于是按「未授权」处理 —— 微信数据在另一个应用的沙盒容器里,读取被拒绝,连接页就报「无法读取微信数据库」。
|
||||||
|
|
||||||
|
几个容易误解的点:
|
||||||
|
|
||||||
|
- **不是数据库损坏**。数据一直好好的,微信自己也能正常读写。
|
||||||
|
- **不是密钥失效**。密钥还在本地,验证也没问题,卡住的是「打开文件」这一步。
|
||||||
|
- **不是 macOS 27 单独引入的缺陷**。指纹变化导致授权失效,在更早的 macOS 上也会发生;macOS 27 上反馈更集中,但没有做过版本对照验证。
|
||||||
|
- **重装应用通常无效**。重装会生成同样的新指纹,旧授权依旧对不上。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 3. 一次性终端修复
|
||||||
|
|
||||||
|
先**完全退出** TraceMemo,不是关窗口,是退出进程:
|
||||||
|
|
||||||
|
- 菜单栏 `TraceMemo → 退出 TraceMemo`,或按 `Command + Q`
|
||||||
|
- 托盘/菜单栏图标里如果有「退出」,也点一次
|
||||||
|
- 确认没有残留:打开「活动监视器」,搜索 `TraceMemo`,有残留就选中并点「退出」
|
||||||
|
|
||||||
|
然后打开「终端」(`应用程序 → 实用工具 → 终端`),执行:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
tccutil reset SystemPolicyAppDataDetailed com.tracememo.app
|
||||||
|
```
|
||||||
|
|
||||||
|
再执行:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
tccutil reset SystemPolicyAllFiles com.tracememo.app
|
||||||
|
```
|
||||||
|
|
||||||
|
两条命令都只影响当前用户,不需要 `sudo`。
|
||||||
|
|
||||||
|
执行后**不会**看到「授权成功」之类的提示。这条命令的作用是**删掉旧记录**,不是**发放权限**。删除之后,需要你在系统设置里重新授权一次(见第 5 节)。
|
||||||
|
|
||||||
|
### 如果提示服务名无效
|
||||||
|
|
||||||
|
终端报下面这类错误:
|
||||||
|
|
||||||
|
```
|
||||||
|
tccutil: Invalid service name
|
||||||
|
```
|
||||||
|
|
||||||
|
说明当前系统不认识 `SystemPolicyAppDataDetailed` 这个服务名。改用 Apple 公开文档里的写法:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
tccutil reset SystemPolicyAppData com.tracememo.app
|
||||||
|
```
|
||||||
|
|
||||||
|
`SystemPolicyAppDataDetailed` 是否在所有 macOS 27 版本上都可用,尚未逐一验证。两种情况的效果一样:都是清掉 TraceMemo 在这类「其他应用数据」权限上的旧记录。无论用哪条,都还是要走第 5 节手动重新授权。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 4. 两条命令分别管什么
|
||||||
|
|
||||||
|
| 命令 | 管的是 | 什么时候需要 |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| `SystemPolicyAppDataDetailed`(或 `SystemPolicyAppData`) | 访问**其他应用沙盒容器内文件**的授权。微信数据正好在这个范围内 | 主要用这条。它清掉的是「读微信容器」这一层的旧记录 |
|
||||||
|
| `SystemPolicyAllFiles` | **完全磁盘访问权限**的授权记录 | 系统设置里 TraceMemo 的开关看起来是开的、但实际不生效时,用它清掉整条记录重来 |
|
||||||
|
|
||||||
|
适用范围:
|
||||||
|
|
||||||
|
- 两条都只针对 `com.tracememo.app` 这一个应用,不影响微信、不影响其他软件
|
||||||
|
- 都只影响当前登录的 Mac 用户
|
||||||
|
- 都只是**删除记录**,不会自动给权限,也不会把权限收得更紧
|
||||||
|
- 不要在命令里用 `All`(例如 `tccutil reset All`)—— 那会清掉这台机器上**所有应用**的所有隐私授权,微信、输入法、录屏、麦克风全要重新授权一遍,代价远大于收益
|
||||||
|
- 不要用 `sudo`。系统级重置需要重启、影响所有用户,和本文的场景无关
|
||||||
|
|
||||||
|
两条命令可以只执行第一条先试。第一条无效、或系统设置里的开关状态明显不对,再执行第二条。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 5. 执行命令后手动重新授权
|
||||||
|
|
||||||
|
1. 打开 **系统设置 → 隐私与安全性 → 完全磁盘访问权限**
|
||||||
|
(不同系统版本的条目名称略有差异,位置都在「隐私与安全性」下)
|
||||||
|
2. 在列表里找到 **TraceMemo**
|
||||||
|
- 如果还在列表里:选中,点列表下方的 `−` 删除
|
||||||
|
- 如果已经不在列表里:跳过这一步
|
||||||
|
3. 点 `+`,在弹出的文件选择器里进入 **应用程序**,选中 **TraceMemo.app**,点「打开」
|
||||||
|
4. 确认 TraceMemo 右侧的开关是**打开**状态
|
||||||
|
5. **完全退出 TraceMemo 再重新打开**。授权只在应用下次启动时生效,当前正在运行的进程拿不到新权限
|
||||||
|
|
||||||
|
如果第 3 步选不到应用,或添加后开关立刻又关掉,先确认应用确实在 `/Applications/TraceMemo.app`,而不是在下载目录、挂载的 dmg 镜像里、或某个临时文件夹里。从 dmg 直接运行的副本每次挂载路径都不同,系统无法稳定记住授权。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 6. 完全不使用终端的做法
|
||||||
|
|
||||||
|
不想碰终端也可以,只是机制上少了一步,成功率没有统计数据。
|
||||||
|
|
||||||
|
### 步骤
|
||||||
|
|
||||||
|
1. 完全退出 TraceMemo(`Command + Q`,再从活动监视器确认没有残留进程)
|
||||||
|
2. 打开 **系统设置 → 隐私与安全性 → 完全磁盘访问权限**
|
||||||
|
3. 在列表里选中 **TraceMemo**,点 `−` 删除
|
||||||
|
4. 完全退出「系统设置」(`Command + Q`)
|
||||||
|
5. 重新打开「系统设置」,回到同一页面,点 `+`,添加 `/Applications/TraceMemo.app`
|
||||||
|
6. 确认开关已打开
|
||||||
|
7. 重新启动 TraceMemo,回到连接页重试
|
||||||
|
|
||||||
|
### 局限性
|
||||||
|
|
||||||
|
- **删掉再添加,不一定能清掉底层旧记录**。系统设置里删的是可见条目,某些情况下底层的授权记录仍然存在且指向旧的应用指纹,界面看起来正常、实际依旧不生效。终端那两条命令做的正是清掉这一层。
|
||||||
|
- **开关是开的,不等于权限生效**。系统偶尔会显示开关已开,但实际判定仍是拒绝。这时只能靠重置记录解决。
|
||||||
|
- **没有「修复」按钮**。系统设置不提供「重新校验应用」这类操作,能做的只有删除和重新添加。
|
||||||
|
|
||||||
|
两步的分工要说清:终端命令负责**清掉旧记录**,本节负责**重新建立记录**。
|
||||||
|
|
||||||
|
- 只做本节:旧记录可能还在,界面看着正常、实际不生效。
|
||||||
|
- 只做终端命令:记录被一起删掉,必须再走本节第 3 到 5 步添加回来,否则权限是空的。
|
||||||
|
- 已收到的恢复反馈里,成功案例都是两步连着做的。
|
||||||
|
|
||||||
|
所以推荐顺序是:第 3 节命令 → 本节删除并重新添加 → 重启应用。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 7. 如何重启并验证
|
||||||
|
|
||||||
|
授权改完必须**重启进程**,不是重新打开窗口。
|
||||||
|
|
||||||
|
### 从 Dock 退出
|
||||||
|
|
||||||
|
1. 在 Dock 里找到 TraceMemo 图标
|
||||||
|
2. 右键(或双指点按)→ **退出**
|
||||||
|
3. 确认图标下方的运行指示点消失
|
||||||
|
4. 重新点图标启动
|
||||||
|
|
||||||
|
### 从 Finder 退出
|
||||||
|
|
||||||
|
1. 打开「活动监视器」(`应用程序 → 实用工具 → 活动监视器`)
|
||||||
|
2. 搜索框输入 `TraceMemo`
|
||||||
|
3. 选中 `TraceMemo` 进程,点左上角的 `×`,选「退出」
|
||||||
|
4. 确认列表里已经没有 TraceMemo
|
||||||
|
5. 打开「访达 → 应用程序」,双击 **TraceMemo**
|
||||||
|
|
||||||
|
### 验证是否恢复
|
||||||
|
|
||||||
|
启动后回到连接页,看这几点:
|
||||||
|
|
||||||
|
- 不再出现「无法读取微信数据库」
|
||||||
|
- 账号、联系人、会话能正常加载
|
||||||
|
- 随便搜一个关键词,能返回结果
|
||||||
|
|
||||||
|
只看到「已连接」但列表是空的,不算恢复,按第 8 节收集信息。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 8. 修复失败要提供什么
|
||||||
|
|
||||||
|
按顺序做一遍,仍然失败,把下面这些信息一起提交:
|
||||||
|
|
||||||
|
1. **系统版本**:苹果菜单 → 关于本机,记录版本号(例如 macOS 27.x)和芯片(Apple Silicon / Intel)
|
||||||
|
2. **TraceMemo 版本**:应用内「设置 → 关于」,或菜单栏 `TraceMemo → 关于 TraceMemo`
|
||||||
|
3. **微信版本**:微信 `设置 → 关于微信`
|
||||||
|
4. **连接页的完整提示原文**,包括错误码。有截图更好
|
||||||
|
5. **脱敏诊断摘要**:连接页上的「复制脱敏诊断摘要」按钮,点一下会复制到剪贴板,直接粘贴到反馈里
|
||||||
|
6. **第 3 节命令的实际输出**,包括报错。如果提示 `Invalid service name`,一定要写出来
|
||||||
|
7. **系统设置里 TraceMemo 那条记录的状态**:在不在列表里、开关是开还是关
|
||||||
|
|
||||||
|
诊断摘要里不包含聊天内容、数据库密钥、完整文件路径,可以放心贴出来。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 9. 不需要重新取密钥,也不要动微信数据
|
||||||
|
|
||||||
|
这一步很重要,能省掉大量无用操作。
|
||||||
|
|
||||||
|
- **不需要重新获取 WCDB 密钥**。密钥保存在本地,本次故障里它一直是正确的。重新走一遍密钥获取流程,只会多一次监听微信登录的动作,不会改变权限结果。
|
||||||
|
- **不要删除微信数据库**。数据完好,删了就是真的没了。
|
||||||
|
- **不要删除 TraceMemo 的配置目录**。里面有账号指向、密钥、索引,删掉要全部重来。
|
||||||
|
- **不要用 `sudo` 运行 TraceMemo**。以 root 运行会换一个进程身份,权限判定更混乱,还会让配置文件属主变成 root,后续正常启动反而出问题。
|
||||||
|
- **不要 `chmod` / `chown` 整个微信目录**。改了会影响微信自身的读写,属于制造新问题。
|
||||||
|
- **不要为了这个问题关闭 SIP**。SIP 管的是系统完整性保护,和「某个应用能不能读另一个应用的容器」不是一回事。关闭 SIP 不解决这个权限判定,还会降低整机安全性。SIP 相关说明见[关闭 SIP 教程](../mac-disable-sip.md),那是密钥获取流程里的独立话题。
|
||||||
|
|
||||||
|
### 顺带区分:这不是 Frida 附加失败
|
||||||
|
|
||||||
|
两类问题长得像,处理方式完全不同:
|
||||||
|
|
||||||
|
| | 数据库访问权限问题(本文) | 密钥获取/进程附加问题 |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| 出现时机 | 已经连过、升级后重新打开 | 首次连接,或重新获取密钥时 |
|
||||||
|
| 界面提示 | 「无法读取微信数据库」`DATABASE_PERMISSION_DENIED` | 监听超时 `CAPTURE_TIMEOUT`、内存扫描失败,或提示无法绑定微信进程 |
|
||||||
|
| 数据目录检测 | 显示已检测到 | 通常在更早的步骤就失败 |
|
||||||
|
| 处理方向 | 系统设置里重新授权 | 检查微信是否停在登录页、是否需要管理员授权、微信版本是否适配 |
|
||||||
|
|
||||||
|
如果你的现象是「点了自动获取密钥,一直等到超时」,那走的是右边一列,不是本文的权限问题。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 10. 这只是当前故障的恢复方案
|
||||||
|
|
||||||
|
说清楚边界:
|
||||||
|
|
||||||
|
- 本文解决的是**已经发生**的授权断裂,不改变应用的签名方式。
|
||||||
|
- 只要发布包仍然是当前这种 ad-hoc 签名,**下一次更新后仍可能再次发生**。
|
||||||
|
- 出现时,重复第 3 到 5 节即可,通常不需要重装、不需要重新取密钥。
|
||||||
|
- 彻底解决需要发布端改用稳定的开发者签名并完成公证,这属于打包流程的改动,不在用户侧。
|
||||||
|
|
||||||
|
正常使用、没有出现问题的用户,不需要提前做任何权限设置。授权不是安装前置条件。
|
||||||
@@ -9,6 +9,7 @@ TraceMemo 的核心路径是本地优先,但“本地优先”不等于所有
|
|||||||
- 读取和解析微信数据库;
|
- 读取和解析微信数据库;
|
||||||
- 聊天档案浏览和普通关键词搜索;
|
- 聊天档案浏览和普通关键词搜索;
|
||||||
- 本地 Knowledge 索引及其账号隔离;
|
- 本地 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
|
## Local HTTP API
|
||||||
|
|
||||||
|
|||||||
@@ -33,9 +33,11 @@
|
|||||||
|
|
||||||
生成成功后会保存本地 HTML 与 PNG,并出现在日报历史中。你可以复制图片、打开文件位置或重新生成。删除历史日报只删除本地生成的报告文件,不会影响微信聊天数据库。
|
生成成功后会保存本地 HTML 与 PNG,并出现在日报历史中。你可以复制图片、打开文件位置或重新生成。删除历史日报只删除本地生成的报告文件,不会影响微信聊天数据库。
|
||||||
|
|
||||||
## 定时日报
|
## 定时日报(在自动化里)
|
||||||
|
|
||||||
在“日报 → 定时日报”中可以创建每天运行的任务。选择群聊、执行时间、日报范围、消息类型和模板后,TraceMemo 会按计划执行:
|
定时日报现在是「自动化」里的一种规则,不再单独占一个页面:打开一级导航的「自动化」,新建或编辑一条「定时日报」规则,选择群聊、执行时间、日报范围、消息类型和发送目标。日报页顶部的指引条也会直接跳到自动化。
|
||||||
|
|
||||||
|
TraceMemo 会按计划执行:
|
||||||
|
|
||||||
```text
|
```text
|
||||||
定时触发 → 读取群聊 → 生成报告 → 保存 Report History → 尝试发送
|
定时触发 → 读取群聊 → 生成报告 → 保存 Report History → 尝试发送
|
||||||
@@ -45,6 +47,8 @@
|
|||||||
|
|
||||||
执行记录支持查看已生成的日报。对“等待发送”或“发送失败”的记录,可以直接重试发送,重试会复用已经生成的 PNG,不会重新调用 AI 生成整份报告;完整执行状态和发送边界见[如何把聊天变成可用的信息](../concepts/how-it-works.md#动作执行与审计)。
|
执行记录支持查看已生成的日报。对“等待发送”或“发送失败”的记录,可以直接重试发送,重试会复用已经生成的 PNG,不会重新调用 AI 生成整份报告;完整执行状态和发送边界见[如何把聊天变成可用的信息](../concepts/how-it-works.md#动作执行与审计)。
|
||||||
|
|
||||||
|
发送目标当前支持**当前群聊、文件传输助手、自己、指定好友**——还不是任意群发。
|
||||||
|
|
||||||
## 让报告更可靠
|
## 让报告更可靠
|
||||||
|
|
||||||
- 先选正确的群和时间范围;
|
- 先选正确的群和时间范围;
|
||||||
|
|||||||
@@ -25,13 +25,25 @@
|
|||||||
1. 数据目录是否指向当前登录账号,而不是旧备份或迁移前目录;
|
1. 数据目录是否指向当前登录账号,而不是旧备份或迁移前目录;
|
||||||
2. 微信版本是否属于当前代码面向的 4.x 数据结构;
|
2. 微信版本是否属于当前代码面向的 4.x 数据结构;
|
||||||
3. 微信是否处于页面要求的登录/退出状态;
|
3. 微信是否处于页面要求的登录/退出状态;
|
||||||
4. macOS 是否完成页面要求的授权;
|
4. macOS 是否完成页面要求的授权;如果是升级 macOS 或更新 TraceMemo 之后才失败的,按[权限恢复文档](./macos27-permission-recovery.md)处理,只打开开关通常不够;
|
||||||
5. 连接页面的诊断项是否明确指出密钥、账号或数据库问题;
|
5. 连接页面的诊断项是否明确指出密钥、账号或数据库问题;
|
||||||
6. macOS 上 Apple Silicon 与 Intel 使用不同的连接流程,按连接页面提示操作;两者都可以自动获取数据库密钥。
|
6. macOS 上 Apple Silicon 与 Intel 使用不同的连接流程,按连接页面提示操作;两者都可以自动获取数据库密钥。
|
||||||
|
7. 页面显示「Intel Mac 自动获取」但电脑是 Apple 芯片时,多半是装了 Intel 版,见[架构不匹配说明](../platform/macos.md#提示intel-mac-自动获取但电脑是-apple-芯片)。
|
||||||
|
|
||||||
重新输入密钥或断开连接不会删除微信原始数据库。macOS 的 SIP 和授权说明见[平台说明](../platform/macos.md)。
|
重新输入密钥或断开连接不会删除微信原始数据库。macOS 的 SIP 和授权说明见[平台说明](../platform/macos.md)。
|
||||||
|
|
||||||
仍然失败时,记录 **macOS 版本、CPU 架构(Apple Silicon / Intel)、微信版本、TraceMemo 版本和页面错误提示**后 扫码 README 文档二维码进群提交消息, 或者提交 Issue。
|
### 提示「无法读取微信数据库」但文件确实存在
|
||||||
|
|
||||||
|
这是**权限问题,不是文件缺失** —— 如果你在终端里能列出 `db_storage/session/session.db`,说明数据目录是完整的,只是 TraceMemo 这个进程读不到。
|
||||||
|
|
||||||
|
注意:**终端能读到文件不代表 TraceMemo 有权限** —— macOS 的隐私权限按应用进程的身份判定,两者走的是不同的授权。
|
||||||
|
|
||||||
|
按出现时机分两种情况:
|
||||||
|
|
||||||
|
- **首次连接就没成功**:给 TraceMemo 授予「完全磁盘访问权限」即可,步骤见 [macOS 数据访问与系统权限 → 提示「无法读取微信数据库」时](../platform/macos.md#提示无法读取微信数据库时)。
|
||||||
|
- **之前能用,升级 macOS 或更新 TraceMemo 之后才失败**:多数是旧授权记录对不上新版本的应用,只打开开关不够,需要先清掉旧记录再重新授权。完整步骤见[macOS 更新后读不到微信数据:权限恢复](./macos27-permission-recovery.md)。
|
||||||
|
|
||||||
|
仍然失败时,记录 **macOS 版本、CPU 架构(Apple Silicon / Intel)、微信版本、TraceMemo 版本和页面错误提示** 后,扫码 README 文档二维码进群反馈,或提交 Issue。连接页的「复制脱敏诊断摘要」可以直接提供这些环境信息。
|
||||||
|
|
||||||
## 连接成功但没有联系人或消息
|
## 连接成功但没有联系人或消息
|
||||||
|
|
||||||
@@ -92,3 +104,15 @@ Agent Hub 和外部 Agent 是两条路径。机器人异常时依次确认:
|
|||||||
5. 需要总结或自然语言理解时,AI Provider 是否可用。
|
5. 需要总结或自然语言理解时,AI Provider 是否可用。
|
||||||
|
|
||||||
当前机器人不支持群发、定时任务或与文字同等的图片、语音、文件和视频理解。详细边界见[Agent Hub](../agent/agent-hub.md)。
|
当前机器人不支持群发、定时任务或与文字同等的图片、语音、文件和视频理解。详细边界见[Agent Hub](../agent/agent-hub.md)。
|
||||||
|
|
||||||
|
## 点击关闭后应用没有退出
|
||||||
|
|
||||||
|
「关闭窗口时」可能被配置为**最小化到托盘** —— 窗口隐藏,应用仍在后台运行。
|
||||||
|
|
||||||
|
到「设置 → 外观与行为 → 关闭窗口时」可以改成:
|
||||||
|
|
||||||
|
- **每次询问**:每次关闭都弹窗确认;
|
||||||
|
- **最小化到托盘**:窗口隐藏,应用继续在后台运行;
|
||||||
|
- **退出应用**:直接结束 TraceMemo 进程。
|
||||||
|
|
||||||
|
选择「每次询问」时,在关闭弹窗里勾选「记住我的选择,下次不再询问」会自动切换到这里对应的项。
|
||||||
@@ -0,0 +1,20 @@
|
|||||||
|
extends: ./electron-builder.yml
|
||||||
|
extraResources:
|
||||||
|
- from: build/app-update.yml
|
||||||
|
to: app-update.yml
|
||||||
|
- from: resources
|
||||||
|
to: resources
|
||||||
|
filter:
|
||||||
|
- '**/*'
|
||||||
|
- from: resources/wcdb/macos/arm64
|
||||||
|
to: resources/wcdb/macos/arm64
|
||||||
|
filter:
|
||||||
|
- 'tm-wcdb-config-helper'
|
||||||
|
- from: docs/skill/tracememo-reader
|
||||||
|
to: skill/tracememo-reader
|
||||||
|
filter:
|
||||||
|
- '**/*'
|
||||||
|
mac:
|
||||||
|
target:
|
||||||
|
- dmg
|
||||||
|
- zip
|
||||||
@@ -19,6 +19,8 @@ asarUnpack:
|
|||||||
- node_modules/silk-wasm/**
|
- node_modules/silk-wasm/**
|
||||||
- node_modules/sherpa-onnx-node/**
|
- node_modules/sherpa-onnx-node/**
|
||||||
- node_modules/sherpa-onnx-*/**
|
- node_modules/sherpa-onnx-*/**
|
||||||
|
- node_modules/@napi-rs/system-ocr/**
|
||||||
|
- node_modules/@napi-rs/system-ocr-*/**
|
||||||
extraResources:
|
extraResources:
|
||||||
# Keep the updater provider in every packaged Windows app. electron-builder also
|
# Keep the updater provider in every packaged Windows app. electron-builder also
|
||||||
# regenerates this file during publish, using the same release configuration.
|
# regenerates this file during publish, using the same release configuration.
|
||||||
@@ -33,10 +35,15 @@ extraResources:
|
|||||||
- mobile_daily_report.html
|
- mobile_daily_report.html
|
||||||
- mobile_daily_report_v1.html
|
- mobile_daily_report_v1.html
|
||||||
- mobile_daily_report_v2.html
|
- mobile_daily_report_v2.html
|
||||||
- connectors/wechat/win32-x64/**
|
|
||||||
- key/win32/x64/**
|
- key/win32/x64/**
|
||||||
- runtime/win32/**
|
- runtime/win32/**
|
||||||
- wcdb/win32/x64/**
|
- wcdb/win32/x64/**
|
||||||
|
- '!wcdb/**/tm-wcdb-config-helper*'
|
||||||
|
# 默认不打包helper
|
||||||
|
# - from: resources/wcdb/win32/x64
|
||||||
|
# to: resources/wcdb/win32/x64
|
||||||
|
# filter:
|
||||||
|
# - 'tm-wcdb-config-helper.exe'
|
||||||
- from: docs/skill/tracememo-reader
|
- from: docs/skill/tracememo-reader
|
||||||
to: skill/tracememo-reader
|
to: skill/tracememo-reader
|
||||||
filter:
|
filter:
|
||||||
|
|||||||
@@ -19,6 +19,11 @@ asarUnpack:
|
|||||||
- node_modules/silk-wasm/**
|
- node_modules/silk-wasm/**
|
||||||
- node_modules/sherpa-onnx-node/**
|
- node_modules/sherpa-onnx-node/**
|
||||||
- node_modules/sherpa-onnx-*/**
|
- node_modules/sherpa-onnx-*/**
|
||||||
|
# System OCR(@napi-rs/system-ocr)的 native binding 必须 unpacked,否则
|
||||||
|
# macOS 的系统 OCR 会在运行时 MODULE_NOT_FOUND。平台本机的 binding 由
|
||||||
|
# scripts/after-pack.cjs 校验,外架构的同级包在 afterPack 里被裁掉。
|
||||||
|
- node_modules/@napi-rs/system-ocr/**
|
||||||
|
- node_modules/@napi-rs/system-ocr-*/**
|
||||||
extraResources:
|
extraResources:
|
||||||
# Keep the updater provider in every packaged macOS app. electron-builder also
|
# Keep the updater provider in every packaged macOS app. electron-builder also
|
||||||
# regenerates this file during publish, using the same release configuration.
|
# regenerates this file during publish, using the same release configuration.
|
||||||
@@ -29,7 +34,8 @@ extraResources:
|
|||||||
to: resources
|
to: resources
|
||||||
filter:
|
filter:
|
||||||
- '**/*'
|
- '**/*'
|
||||||
- '!connectors/wechat-personal/**'
|
- '!runtime/darwin-arm64/**'
|
||||||
|
- '!wcdb/**/tm-wcdb-config-helper*'
|
||||||
- from: docs/skill/tracememo-reader
|
- from: docs/skill/tracememo-reader
|
||||||
to: skill/tracememo-reader
|
to: skill/tracememo-reader
|
||||||
filter:
|
filter:
|
||||||
|
|||||||
@@ -2,9 +2,12 @@ import { resolve } from 'path'
|
|||||||
import { defineConfig } from 'electron-vite'
|
import { defineConfig } from 'electron-vite'
|
||||||
import react from '@vitejs/plugin-react'
|
import react from '@vitejs/plugin-react'
|
||||||
|
|
||||||
|
const editionOutDir = process.env.TRACEMEMO_EDITION_OUT_DIR
|
||||||
|
|
||||||
export default defineConfig({
|
export default defineConfig({
|
||||||
main: {
|
main: {
|
||||||
build: {
|
build: {
|
||||||
|
...(editionOutDir ? { outDir: editionOutDir } : {}),
|
||||||
rollupOptions: {
|
rollupOptions: {
|
||||||
input: {
|
input: {
|
||||||
index: resolve('src/main/index.ts'),
|
index: resolve('src/main/index.ts'),
|
||||||
@@ -16,12 +19,13 @@ export default defineConfig({
|
|||||||
output: {
|
output: {
|
||||||
entryFileNames: '[name].js'
|
entryFileNames: '[name].js'
|
||||||
},
|
},
|
||||||
external: ['koffi', 'sherpa-onnx-node']
|
external: ['koffi', 'sherpa-onnx-node', '@napi-rs/system-ocr']
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
preload: {},
|
preload: editionOutDir ? { build: { outDir: editionOutDir } } : {},
|
||||||
renderer: {
|
renderer: {
|
||||||
|
...(editionOutDir ? { build: { outDir: editionOutDir } } : {}),
|
||||||
resolve: {
|
resolve: {
|
||||||
alias: {
|
alias: {
|
||||||
'@renderer': resolve('src/renderer/src')
|
'@renderer': resolve('src/renderer/src')
|
||||||
|
|||||||
+25
-19
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "tracememo",
|
"name": "tracememo",
|
||||||
"version": "2.4.0",
|
"version": "2.6.0",
|
||||||
"packageManager": "pnpm@7.33.7",
|
"packageManager": "pnpm@7.33.7",
|
||||||
"description": "TraceMemo(迹忆)是一款本地优先、可追溯的 AI 微信知识与分析工作台。 原名 WechatExplorer,支持聊天记录搜索、知识库、微信群聊总结和 Agent 助手。",
|
"description": "TraceMemo(迹忆)是一款本地优先、可追溯的 AI 微信知识与分析工作台。 原名 WechatExplorer,支持聊天记录搜索、知识库、微信群聊总结和 Agent 助手。",
|
||||||
"keywords": [
|
"keywords": [
|
||||||
@@ -25,27 +25,28 @@
|
|||||||
},
|
},
|
||||||
"main": "./out/main/index.js",
|
"main": "./out/main/index.js",
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"test": "pnpm typecheck && pnpm test:unit && pnpm test:component && pnpm test:integration && pnpm test:skill-install && pnpm test:wechat-connector && pnpm test:e2e:build && playwright test",
|
"test": "pnpm typecheck && pnpm test:unit && pnpm test:component && pnpm test:integration && pnpm test:skill-install && pnpm test:e2e:build && playwright test",
|
||||||
"format": "prettier --write .",
|
"format": "prettier --write .",
|
||||||
"lint": "eslint --cache .",
|
"lint": "eslint --cache .",
|
||||||
"typecheck:node": "tsc --noEmit -p tsconfig.node.json --composite false",
|
"typecheck:node": "tsc --noEmit -p tsconfig.node.json --composite false",
|
||||||
"typecheck:web": "tsc --noEmit -p tsconfig.web.json --composite false",
|
"typecheck:web": "tsc --noEmit -p tsconfig.web.json --composite false",
|
||||||
"typecheck": "npm run typecheck:node && npm run typecheck:web",
|
"typecheck": "npm run typecheck:node && npm run typecheck:web && npm run typecheck:test",
|
||||||
|
"typecheck:test": "node scripts/typecheck-tests.cjs",
|
||||||
"test:skill-install": "node scripts/test-skill-install-instruction.cjs",
|
"test:skill-install": "node scripts/test-skill-install-instruction.cjs",
|
||||||
|
"check:skill-version": "node scripts/check-skill-version-drift.cjs",
|
||||||
"cp:env": "node scripts/ensure-env.cjs",
|
"cp:env": "node scripts/ensure-env.cjs",
|
||||||
"prepare:env": "node scripts/ensure-env.cjs",
|
"prepare:env": "node scripts/ensure-env.cjs",
|
||||||
"prepare:ffmpeg:win": "node scripts/prepare-electron-runtime.cjs --platform win32 --arch x64",
|
"prepare:ffmpeg:win": "node scripts/prepare-electron-runtime.cjs --platform win32 --arch x64",
|
||||||
"prepare:ffmpeg:mac:arm64": "node scripts/prepare-electron-runtime.cjs --platform darwin --arch arm64",
|
"prepare:ffmpeg:mac:arm64": "node scripts/prepare-electron-runtime.cjs --platform darwin --arch arm64",
|
||||||
"prepare:ffmpeg:mac:x64": "node scripts/prepare-electron-runtime.cjs --platform darwin --arch x64",
|
"prepare:ffmpeg:mac:x64": "node scripts/prepare-electron-runtime.cjs --platform darwin --arch x64",
|
||||||
"prepare:win-runtime": "node scripts/prepare-win-runtime.cjs && npm run prepare:ffmpeg:win",
|
"prepare:win-runtime": "node scripts/prepare-win-runtime.cjs && npm run prepare:ffmpeg:win",
|
||||||
"prepare:wechat-personal": "node scripts/prepare-wechat-chatter-runtime.cjs",
|
"prepare:wechat-native": "node scripts/prepare-wechat-native-runtime.cjs",
|
||||||
"start": "electron-vite preview",
|
"start": "electron-vite preview",
|
||||||
"predev": "node scripts/ensure-electron-binary.cjs",
|
"predev": "node scripts/ensure-electron-binary.cjs",
|
||||||
"dev": "node scripts/ensure-env.cjs && node scripts/build-wechat-connector.cjs && electron-vite dev",
|
"dev": "node scripts/ensure-env.cjs && electron-vite dev",
|
||||||
"dev:update": "cross-env TRACEMEMO_UPDATE_SIMULATION=true pnpm dev",
|
"dev:update": "cross-env TRACEMEMO_UPDATE_SIMULATION=true pnpm dev",
|
||||||
"poc:query-agent": "electron-vite build && node scripts/run-query-agent-poc.cjs",
|
"poc:query-agent": "electron-vite build && node scripts/run-query-agent-poc.cjs",
|
||||||
"poc:query-agent:run": "node scripts/run-query-agent-poc.cjs",
|
"poc:query-agent:run": "node scripts/run-query-agent-poc.cjs",
|
||||||
"test:wechat-connector": "go -C services/wechat-connector test ./... && go -C services/wechat-connector vet ./...",
|
|
||||||
"test:unit": "vitest run --config vitest.unit.config.ts",
|
"test:unit": "vitest run --config vitest.unit.config.ts",
|
||||||
"test:component": "vitest run --config vitest.component.config.ts",
|
"test:component": "vitest run --config vitest.component.config.ts",
|
||||||
"test:integration": "vitest run --config vitest.integration.config.ts",
|
"test:integration": "vitest run --config vitest.integration.config.ts",
|
||||||
@@ -56,21 +57,20 @@
|
|||||||
"test:e2e": "pnpm test:e2e:build && playwright test --grep-invert @visual",
|
"test:e2e": "pnpm test:e2e:build && playwright test --grep-invert @visual",
|
||||||
"test:visual": "pnpm test:e2e:build && playwright test tests/e2e/visual.spec.ts",
|
"test:visual": "pnpm test:e2e:build && playwright test tests/e2e/visual.spec.ts",
|
||||||
"test:smoke": "node --test tests/smoke/native-environment.test.mjs",
|
"test:smoke": "node --test tests/smoke/native-environment.test.mjs",
|
||||||
"build:wechat-connector": "node scripts/build-wechat-connector.cjs",
|
"build": "npm run typecheck && electron-vite build",
|
||||||
"build:wechat-connector:win": "node scripts/build-wechat-connector.cjs --platform win32 --arch x64",
|
|
||||||
"build:wechat-connector:mac": "node scripts/build-wechat-connector.cjs --platform darwin --arch arm64",
|
|
||||||
"build:native-services": "npm run build:wechat-connector",
|
|
||||||
"build": "npm run typecheck && npm run build:native-services && electron-vite build",
|
|
||||||
"postinstall": "electron-builder install-app-deps && node scripts/prepare-electron-runtime.cjs && node scripts/ensure-electron-binary.cjs",
|
"postinstall": "electron-builder install-app-deps && node scripts/prepare-electron-runtime.cjs && node scripts/ensure-electron-binary.cjs",
|
||||||
"build:unpack": "npm run build && electron-builder --config electron-builder.yml --dir",
|
"build:unpack": "npm run build && electron-builder --config electron-builder.yml --dir",
|
||||||
"build:win": "npm run typecheck && npm run build:wechat-connector:win && npm run prepare:win-runtime && electron-vite build && electron-builder --config electron-builder.win.yml --win --x64",
|
"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 && node scripts/build-wechat-connector.cjs --platform darwin --arch arm64 && npm run prepare:ffmpeg:mac:arm64 && electron-vite build && electron-builder --config electron-builder.yml --mac --arm64",
|
"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:x64": "npm run typecheck && node scripts/build-wechat-connector.cjs --platform darwin --arch x64 && npm run prepare:ffmpeg:mac:x64 && electron-vite build && electron-builder --config electron-builder.yml --mac --x64",
|
"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:public": "node scripts/build-macos-edition.cjs public",
|
||||||
|
"build:mac:native": "node scripts/build-macos-edition.cjs native",
|
||||||
|
"build:mac:x64": "npm run typecheck && npm run prepare:ffmpeg:mac:x64 && electron-vite build && electron-builder --config electron-builder.yml --mac --x64",
|
||||||
"release": "npm run release:mac && npm run release:win",
|
"release": "npm run release:mac && npm run release:win",
|
||||||
"release:mac": "npm run typecheck && node scripts/build-wechat-connector.cjs --platform darwin --arch arm64,x64 && electron-vite build && npm run release:mac:arm64 && npm run release:mac:x64",
|
"release:mac": "npm run typecheck && electron-vite build && npm run release:mac:arm64 && npm run release:mac:x64",
|
||||||
"release:mac:arm64": "npm run prepare:ffmpeg:mac:arm64 && electron-builder --config electron-builder.yml --mac --arm64 --publish always",
|
"release:mac:arm64": "npm run prepare:ffmpeg:mac:arm64 && electron-builder --config electron-builder.yml --mac --arm64 --publish always --config.directories.output=dist/release/mac-arm64",
|
||||||
"release:mac:x64": "npm run prepare:ffmpeg:mac:x64 && electron-builder --config electron-builder.yml --mac --x64 --publish always",
|
"release:mac:x64": "npm run prepare:ffmpeg:mac:x64 && electron-builder --config electron-builder.yml --mac --x64 --publish always --config.directories.output=dist/release/mac-x64",
|
||||||
"release:win": "npm run typecheck && npm run build:wechat-connector:win && npm run prepare:win-runtime && electron-vite build && electron-builder --config electron-builder.win.yml --win --x64 --publish always",
|
"release:win": "npm run typecheck && npm run prepare:win-runtime && electron-vite build && electron-builder --config electron-builder.win.yml --win --x64 --publish always",
|
||||||
"release:beta": "cross-env EP_PRE_RELEASE=true npm run release",
|
"release:beta": "cross-env EP_PRE_RELEASE=true npm run release",
|
||||||
"release:stable": "npm run release",
|
"release:stable": "npm run release",
|
||||||
"build:linux": "electron-vite build && electron-builder --config electron-builder.yml --linux"
|
"build:linux": "electron-vite build && electron-builder --config electron-builder.yml --linux"
|
||||||
@@ -78,7 +78,11 @@
|
|||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@electron-toolkit/preload": "^3.0.2",
|
"@electron-toolkit/preload": "^3.0.2",
|
||||||
"@electron-toolkit/utils": "^4.0.0",
|
"@electron-toolkit/utils": "^4.0.0",
|
||||||
|
"@koromix/koffi-darwin-x64": "3.1.0",
|
||||||
"@koromix/koffi-win32-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-alert-dialog": "^1.1.23",
|
||||||
"@radix-ui/react-checkbox": "^1.3.11",
|
"@radix-ui/react-checkbox": "^1.3.11",
|
||||||
"@radix-ui/react-dialog": "^1.1.23",
|
"@radix-ui/react-dialog": "^1.1.23",
|
||||||
@@ -109,7 +113,9 @@
|
|||||||
"parse5": "^8.0.0",
|
"parse5": "^8.0.0",
|
||||||
"pinyin-pro": "^3.26.0",
|
"pinyin-pro": "^3.26.0",
|
||||||
"qrcode": "^1.5.4",
|
"qrcode": "^1.5.4",
|
||||||
|
"sherpa-onnx-darwin-x64": "1.13.3",
|
||||||
"sherpa-onnx-node": "1.13.3",
|
"sherpa-onnx-node": "1.13.3",
|
||||||
|
"sherpa-onnx-win-x64": "1.13.4",
|
||||||
"silk-wasm": "^3.7.1",
|
"silk-wasm": "^3.7.1",
|
||||||
"tailwind-merge": "^3.6.0",
|
"tailwind-merge": "^3.6.0",
|
||||||
"unzipper": "^0.12.0",
|
"unzipper": "^0.12.0",
|
||||||
@@ -171,4 +177,4 @@
|
|||||||
"ffmpeg-static"
|
"ffmpeg-static"
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
Generated
+52
-3
@@ -11,7 +11,11 @@ specifiers:
|
|||||||
'@electron-toolkit/preload': ^3.0.2
|
'@electron-toolkit/preload': ^3.0.2
|
||||||
'@electron-toolkit/tsconfig': ^2.0.0
|
'@electron-toolkit/tsconfig': ^2.0.0
|
||||||
'@electron-toolkit/utils': ^4.0.0
|
'@electron-toolkit/utils': ^4.0.0
|
||||||
|
'@koromix/koffi-darwin-x64': 3.1.0
|
||||||
'@koromix/koffi-win32-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
|
'@playwright/test': ^1.62.1
|
||||||
'@radix-ui/react-alert-dialog': ^1.1.23
|
'@radix-ui/react-alert-dialog': ^1.1.23
|
||||||
'@radix-ui/react-checkbox': ^1.3.11
|
'@radix-ui/react-checkbox': ^1.3.11
|
||||||
@@ -70,7 +74,9 @@ specifiers:
|
|||||||
react: ^19.2.1
|
react: ^19.2.1
|
||||||
react-dom: ^19.2.1
|
react-dom: ^19.2.1
|
||||||
sass: ^1.102.0
|
sass: ^1.102.0
|
||||||
|
sherpa-onnx-darwin-x64: 1.13.3
|
||||||
sherpa-onnx-node: 1.13.3
|
sherpa-onnx-node: 1.13.3
|
||||||
|
sherpa-onnx-win-x64: 1.13.4
|
||||||
silk-wasm: ^3.7.1
|
silk-wasm: ^3.7.1
|
||||||
tailwind-merge: ^3.6.0
|
tailwind-merge: ^3.6.0
|
||||||
tailwindcss: 3.4.17
|
tailwindcss: 3.4.17
|
||||||
@@ -85,7 +91,11 @@ specifiers:
|
|||||||
dependencies:
|
dependencies:
|
||||||
'@electron-toolkit/preload': 3.0.2_electron@43.1.0
|
'@electron-toolkit/preload': 3.0.2_electron@43.1.0
|
||||||
'@electron-toolkit/utils': 4.0.0_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
|
'@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-alert-dialog': 1.1.23_eijghdl4n2x4hz6j4cg7ctgbuu
|
||||||
'@radix-ui/react-checkbox': 1.3.11_eijghdl4n2x4hz6j4cg7ctgbuu
|
'@radix-ui/react-checkbox': 1.3.11_eijghdl4n2x4hz6j4cg7ctgbuu
|
||||||
'@radix-ui/react-dialog': 1.1.23_eijghdl4n2x4hz6j4cg7ctgbuu
|
'@radix-ui/react-dialog': 1.1.23_eijghdl4n2x4hz6j4cg7ctgbuu
|
||||||
@@ -116,7 +126,9 @@ dependencies:
|
|||||||
parse5: 8.0.1
|
parse5: 8.0.1
|
||||||
pinyin-pro: 3.29.3
|
pinyin-pro: 3.29.3
|
||||||
qrcode: 1.5.4
|
qrcode: 1.5.4
|
||||||
|
sherpa-onnx-darwin-x64: 1.13.3
|
||||||
sherpa-onnx-node: 1.13.3
|
sherpa-onnx-node: 1.13.3
|
||||||
|
sherpa-onnx-win-x64: 1.13.4
|
||||||
silk-wasm: 3.7.1
|
silk-wasm: 3.7.1
|
||||||
tailwind-merge: 3.6.0
|
tailwind-merge: 3.6.0
|
||||||
unzipper: 0.12.5
|
unzipper: 0.12.5
|
||||||
@@ -1581,7 +1593,6 @@ packages:
|
|||||||
cpu: [x64]
|
cpu: [x64]
|
||||||
os: [darwin]
|
os: [darwin]
|
||||||
dev: false
|
dev: false
|
||||||
optional: true
|
|
||||||
|
|
||||||
/@koromix/koffi-freebsd-arm64/3.1.0:
|
/@koromix/koffi-freebsd-arm64/3.1.0:
|
||||||
resolution: {integrity: sha512-vazoPYIhOAlXZksVIqDRMIID4VeUZKx8F3dR90hOobT2ATyOkqNS5dv5UCV7Q7DSq22lQTrdbvENBAhROzCp0w==}
|
resolution: {integrity: sha512-vazoPYIhOAlXZksVIqDRMIID4VeUZKx8F3dR90hOobT2ATyOkqNS5dv5UCV7Q7DSq22lQTrdbvENBAhROzCp0w==}
|
||||||
@@ -1685,6 +1696,46 @@ packages:
|
|||||||
- supports-color
|
- supports-color
|
||||||
dev: true
|
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'}
|
||||||
|
optionalDependencies:
|
||||||
|
'@napi-rs/system-ocr-darwin-arm64': 1.2.0
|
||||||
|
'@napi-rs/system-ocr-darwin-x64': 1.2.0
|
||||||
|
'@napi-rs/system-ocr-win32-arm64-msvc': 1.2.0
|
||||||
|
'@napi-rs/system-ocr-win32-x64-msvc': 1.2.0
|
||||||
|
dev: false
|
||||||
|
|
||||||
/@nodelib/fs.scandir/2.1.5:
|
/@nodelib/fs.scandir/2.1.5:
|
||||||
resolution: {integrity: sha512-vq24Bq3ym5HEQm2NKCr3yXDwjc7vTsEThRDnkp2DK9p1uqLR+DHurm/NOTo0KG7HYHU7eppKZj3MyqYuMBf62g==}
|
resolution: {integrity: sha512-vq24Bq3ym5HEQm2NKCr3yXDwjc7vTsEThRDnkp2DK9p1uqLR+DHurm/NOTo0KG7HYHU7eppKZj3MyqYuMBf62g==}
|
||||||
engines: {node: '>= 8'}
|
engines: {node: '>= 8'}
|
||||||
@@ -7547,7 +7598,6 @@ packages:
|
|||||||
cpu: [x64]
|
cpu: [x64]
|
||||||
os: [darwin]
|
os: [darwin]
|
||||||
dev: false
|
dev: false
|
||||||
optional: true
|
|
||||||
|
|
||||||
/sherpa-onnx-linux-arm64/1.13.4:
|
/sherpa-onnx-linux-arm64/1.13.4:
|
||||||
resolution: {integrity: sha512-RMjMRqT82BgTXypNNGmLe6ZFYhc3WEvnAGl3DdkK7qB/kuXwkL3iHhV31wAecbnWPsnEpUoD+8cFovWSBzsCuw==}
|
resolution: {integrity: sha512-RMjMRqT82BgTXypNNGmLe6ZFYhc3WEvnAGl3DdkK7qB/kuXwkL3iHhV31wAecbnWPsnEpUoD+8cFovWSBzsCuw==}
|
||||||
@@ -7586,7 +7636,6 @@ packages:
|
|||||||
cpu: [x64]
|
cpu: [x64]
|
||||||
os: [win32]
|
os: [win32]
|
||||||
dev: false
|
dev: false
|
||||||
optional: true
|
|
||||||
|
|
||||||
/side-channel-list/1.0.0:
|
/side-channel-list/1.0.0:
|
||||||
resolution: {integrity: sha512-FCLHtRD/gnpCiCHEiJLOwdmFP+wzCmDEkc9y7NsYxeF4u7Btsn1ZuwgwJGxImImHicJArLP4R0yX4c2KCrMrTA==}
|
resolution: {integrity: sha512-FCLHtRD/gnpCiCHEiJLOwdmFP+wzCmDEkc9y7NsYxeF4u7Btsn1ZuwgwJGxImImHicJArLP4R0yX4c2KCrMrTA==}
|
||||||
|
|||||||
Binary file not shown.
|
Before Width: | Height: | Size: 153 KiB After Width: | Height: | Size: 153 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 278 KiB |
@@ -68,21 +68,29 @@
|
|||||||
.overview {
|
.overview {
|
||||||
margin-top: 2px;
|
margin-top: 2px;
|
||||||
}
|
}
|
||||||
|
/*
|
||||||
|
* hero 头像簇的几何必须由 contract 变量驱动,不能再写死容器尺寸。
|
||||||
|
*
|
||||||
|
* 生产导出会额外注入 `report-template-fragment-contract.ts`,其中
|
||||||
|
* `img.tm-avatar.tm-avatar--hero` 用 !important 把头像钉在
|
||||||
|
* clamp(28px, var(--tm-avatar-hero-size, 40px), 56px)。
|
||||||
|
* 旧版这里写死 58x58(单头像 28x28),两个权威打架:头像实际 40px,
|
||||||
|
* 2 列 x 40px + 3px gap = 83px 塞不进 58px 的盒子,于是头像向右向下溢出容器,
|
||||||
|
* 视觉上越过卡片内边距、压到卡片边缘之外。
|
||||||
|
*
|
||||||
|
* 现在容器尺寸由内容决定(列宽/行高都取同一个变量):头像数 1..4 都不会溢出,
|
||||||
|
* 主题调整 --tm-avatar-hero-size 时容器与头像也不会分叉。
|
||||||
|
*/
|
||||||
.avatar-grid {
|
.avatar-grid {
|
||||||
width: 58px;
|
|
||||||
height: 58px;
|
|
||||||
display: grid;
|
display: grid;
|
||||||
grid-template-columns: 1fr 1fr;
|
grid-template-columns: repeat(2, var(--tm-avatar-hero-size, 40px));
|
||||||
|
grid-auto-rows: var(--tm-avatar-hero-size, 40px);
|
||||||
gap: 3px;
|
gap: 3px;
|
||||||
flex: 0 0 auto;
|
flex: 0 0 auto;
|
||||||
}
|
}
|
||||||
|
/* 单头像时不保留空列,簇宽恰好等于一个头像。 */
|
||||||
.avatar-grid.avatar-count-1 {
|
.avatar-grid.avatar-count-1 {
|
||||||
width: 28px;
|
grid-template-columns: var(--tm-avatar-hero-size, 40px);
|
||||||
height: 28px;
|
|
||||||
grid-template-columns: 1fr;
|
|
||||||
}
|
|
||||||
.avatar-grid.avatar-count-2 {
|
|
||||||
height: 28px;
|
|
||||||
}
|
}
|
||||||
.avatar-grid.empty-section {
|
.avatar-grid.empty-section {
|
||||||
display: none;
|
display: none;
|
||||||
|
|||||||
@@ -61,21 +61,29 @@
|
|||||||
font-size: 13px;
|
font-size: 13px;
|
||||||
line-height: 1.55;
|
line-height: 1.55;
|
||||||
}
|
}
|
||||||
|
/*
|
||||||
|
* hero 头像簇的几何必须由 contract 变量驱动,不能再写死容器尺寸。
|
||||||
|
*
|
||||||
|
* 生产导出会额外注入 `report-template-fragment-contract.ts`,其中
|
||||||
|
* `img.tm-avatar.tm-avatar--hero` 用 !important 把头像钉在
|
||||||
|
* clamp(28px, var(--tm-avatar-hero-size, 40px), 56px)。
|
||||||
|
* 旧版这里写死 58x58(单头像 28x28),两个权威打架:头像实际 40px,
|
||||||
|
* 2 列 x 40px + 3px gap = 83px 塞不进 58px 的盒子,于是头像向右向下溢出容器,
|
||||||
|
* 视觉上越过卡片内边距、压到卡片边缘之外。
|
||||||
|
*
|
||||||
|
* 现在容器尺寸由内容决定(列宽/行高都取同一个变量):头像数 1..4 都不会溢出,
|
||||||
|
* 主题调整 --tm-avatar-hero-size 时容器与头像也不会分叉。
|
||||||
|
*/
|
||||||
.avatar-grid {
|
.avatar-grid {
|
||||||
width: 58px;
|
|
||||||
height: 58px;
|
|
||||||
display: grid;
|
display: grid;
|
||||||
grid-template-columns: 1fr 1fr;
|
grid-template-columns: repeat(2, var(--tm-avatar-hero-size, 40px));
|
||||||
|
grid-auto-rows: var(--tm-avatar-hero-size, 40px);
|
||||||
gap: 3px;
|
gap: 3px;
|
||||||
flex: 0 0 auto;
|
flex: 0 0 auto;
|
||||||
}
|
}
|
||||||
|
/* 单头像时不保留空列,簇宽恰好等于一个头像。 */
|
||||||
.avatar-grid.avatar-count-1 {
|
.avatar-grid.avatar-count-1 {
|
||||||
width: 28px;
|
grid-template-columns: var(--tm-avatar-hero-size, 40px);
|
||||||
height: 28px;
|
|
||||||
grid-template-columns: 1fr;
|
|
||||||
}
|
|
||||||
.avatar-grid.avatar-count-2 {
|
|
||||||
height: 28px;
|
|
||||||
}
|
}
|
||||||
.avatar-grid.empty-section {
|
.avatar-grid.empty-section {
|
||||||
display: none;
|
display: none;
|
||||||
|
|||||||
Binary file not shown.
|
After Width: | Height: | Size: 417 B |
@@ -0,0 +1,13 @@
|
|||||||
|
<svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 18 18">
|
||||||
|
<rect
|
||||||
|
x="1.5"
|
||||||
|
y="1.5"
|
||||||
|
width="15"
|
||||||
|
height="15"
|
||||||
|
rx="3.5"
|
||||||
|
fill="none"
|
||||||
|
stroke="#000"
|
||||||
|
stroke-width="1.75"
|
||||||
|
/>
|
||||||
|
<circle cx="9" cy="9" r="2.3" fill="#000" />
|
||||||
|
</svg>
|
||||||
|
After Width: | Height: | Size: 277 B |
Binary file not shown.
|
After Width: | Height: | Size: 702 B |
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -1 +1 @@
|
|||||||
f1bbd88584075c0e6d3487357a06424949de26d7e6dcad803d210aab83b0cbda xkey_helper_4_1_13
|
a35d3fa67387e049cc30bc073f9e65b077aa1db9c5c2b183125dec695fa013b9 xkey_helper_4_1_13
|
||||||
+614
-25
@@ -1,5 +1,6 @@
|
|||||||
/* eslint-disable @typescript-eslint/no-require-imports, @typescript-eslint/explicit-function-return-type */
|
/* eslint-disable @typescript-eslint/no-require-imports, @typescript-eslint/explicit-function-return-type */
|
||||||
const { chmodSync, existsSync, readdirSync, rmSync } = require('node:fs')
|
const { chmodSync, existsSync, readFileSync, readdirSync, rmSync } = require('node:fs')
|
||||||
|
const { createHash } = require('node:crypto')
|
||||||
const { execFileSync } = require('node:child_process')
|
const { execFileSync } = require('node:child_process')
|
||||||
const path = require('node:path')
|
const path = require('node:path')
|
||||||
const asar = require('@electron/asar')
|
const asar = require('@electron/asar')
|
||||||
@@ -16,6 +17,23 @@ const REQUIRED_RUNTIME_PACKAGES = [
|
|||||||
'koffi'
|
'koffi'
|
||||||
]
|
]
|
||||||
|
|
||||||
|
// electron-builder 26 skips macOS signing entirely when no Developer ID
|
||||||
|
// identity is configured, so an unpacked bundle can ship without a usable
|
||||||
|
// signature. macOS kills a helper whose code or signature is missing or
|
||||||
|
// modified even when SIP is disabled, which is what customers hit on newer
|
||||||
|
// macOS releases. Ad-hoc re-sign the runtime helpers and the outer bundle so
|
||||||
|
// every Mach-O verifies strictly; spctl still rejects ad-hoc code, which is
|
||||||
|
// acceptable for the SIP-disabled customer workflow.
|
||||||
|
const MACOS_HELPER_NAMES = ['xkey_helper', 'xkey_helper_4_1_13']
|
||||||
|
const MACOS_EDITION_CODE_PATHS = [
|
||||||
|
['wcdb', 'macos', 'arm64', 'libwcdb_api.dylib'],
|
||||||
|
['wcdb', 'macos', 'arm64', 'libWCDB.dylib'],
|
||||||
|
['wcdb', 'macos', 'arm64', 'tm-wcdb-config-helper'],
|
||||||
|
['wcdb', 'macos', 'arm64', 'libtmlicense.dylib'],
|
||||||
|
['runtime', 'darwin-arm64', 'tm-wechat-host'],
|
||||||
|
['runtime', 'darwin-arm64', 'libtmwechat.dylib']
|
||||||
|
]
|
||||||
|
|
||||||
function getRuntimeResources(context) {
|
function getRuntimeResources(context) {
|
||||||
const productName = context.packager.appInfo.productFilename
|
const productName = context.packager.appInfo.productFilename
|
||||||
return context.electronPlatformName === 'darwin'
|
return context.electronPlatformName === 'darwin'
|
||||||
@@ -36,7 +54,25 @@ function validateSilkWasmRuntime(runtimeResources) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
function validateFfmpegRuntime(runtimeResources, platform = process.platform) {
|
function validateFfmpegRuntime(
|
||||||
|
runtimeResources,
|
||||||
|
platform = process.platform,
|
||||||
|
edition = process.env.TRACEMEMO_EDITION
|
||||||
|
) {
|
||||||
|
if (platform === 'darwin' && edition) {
|
||||||
|
const editionFfmpeg = path.join(runtimeResources, 'resources', 'ffmpeg', 'ffmpeg')
|
||||||
|
if (!existsSync(editionFfmpeg)) throw new Error(`Missing staged macOS ffmpeg: ${editionFfmpeg}`)
|
||||||
|
const sharedBinary = path.join(
|
||||||
|
runtimeResources,
|
||||||
|
'app.asar.unpacked',
|
||||||
|
'node_modules',
|
||||||
|
'ffmpeg-static',
|
||||||
|
'ffmpeg'
|
||||||
|
)
|
||||||
|
rmSync(sharedBinary, { force: true })
|
||||||
|
chmodSync(editionFfmpeg, 0o755)
|
||||||
|
return editionFfmpeg
|
||||||
|
}
|
||||||
const executable = platform === 'win32' ? 'ffmpeg.exe' : 'ffmpeg'
|
const executable = platform === 'win32' ? 'ffmpeg.exe' : 'ffmpeg'
|
||||||
const ffmpegPath = path.join(
|
const ffmpegPath = path.join(
|
||||||
runtimeResources,
|
runtimeResources,
|
||||||
@@ -52,6 +88,202 @@ function validateFfmpegRuntime(runtimeResources, platform = process.platform) {
|
|||||||
return ffmpegPath
|
return ffmpegPath
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function validateMacEditionResources(runtimeResources, edition, platform) {
|
||||||
|
if (platform !== 'darwin') return
|
||||||
|
const resources = path.join(runtimeResources, 'resources')
|
||||||
|
const markerPath = path.join(resources, 'tracememo-build.json')
|
||||||
|
if (!existsSync(markerPath)) throw new Error(`Missing macOS edition marker: ${markerPath}`)
|
||||||
|
const marker = JSON.parse(readFileSync(markerPath, 'utf8'))
|
||||||
|
if (marker.profile !== edition) throw new Error(`Expected ${edition} bundle, found ${String(marker.profile)}`)
|
||||||
|
const wcdb = path.join(resources, 'wcdb', 'macos', 'arm64')
|
||||||
|
const api = path.join(wcdb, 'libwcdb_api.dylib')
|
||||||
|
const companion = path.join(wcdb, 'libWCDB.dylib')
|
||||||
|
const helper = path.join(wcdb, 'tm-wcdb-config-helper')
|
||||||
|
const runtime = path.join(resources, 'runtime', 'darwin-arm64')
|
||||||
|
const host = path.join(runtime, 'tm-wechat-host')
|
||||||
|
const runtimeDylib = path.join(runtime, 'libtmwechat.dylib')
|
||||||
|
const runtimeManifest = path.join(runtime, 'runtime-manifest.json')
|
||||||
|
const nativeArtifacts = [helper, host, runtimeDylib, runtimeManifest]
|
||||||
|
const presentNativeArtifacts = nativeArtifacts.filter(existsSync)
|
||||||
|
if (edition === 'public' && presentNativeArtifacts.length) {
|
||||||
|
throw new Error(`Public bundle contains native artifacts: ${presentNativeArtifacts.join(', ')}`)
|
||||||
|
}
|
||||||
|
if (edition === 'native' && presentNativeArtifacts.length !== nativeArtifacts.length) {
|
||||||
|
throw new Error('Native bundle is missing WCDB helper or WeChat runtime files')
|
||||||
|
}
|
||||||
|
for (const protectedPath of [path.join(resources, '1.txt'), path.join(resources, 'runtime', 'runtime.zip')]) {
|
||||||
|
if (existsSync(protectedPath)) throw new Error(`Protected file leaked into macOS bundle: ${protectedPath}`)
|
||||||
|
}
|
||||||
|
if (!existsSync(api) || !existsSync(companion)) throw new Error('macOS bundle is missing WCDB files')
|
||||||
|
if (!readBinaryArchitectures(api).includes('arm64')) throw new Error('Bundled WCDB API is not arm64')
|
||||||
|
if (!readBinaryArchitectures(companion).includes('arm64')) throw new Error('Bundled WCDB companion is not arm64')
|
||||||
|
const apiDependencies = execFileSync('/usr/bin/otool', ['-L', api], { encoding: 'utf8' })
|
||||||
|
if (!apiDependencies.includes('@loader_path/libWCDB.dylib')) {
|
||||||
|
throw new Error('Bundled WCDB API is missing its @loader_path companion dependency')
|
||||||
|
}
|
||||||
|
const symbols = execFileSync('/usr/bin/nm', ['-gU', api], { encoding: 'utf8' })
|
||||||
|
.split(/\r?\n/)
|
||||||
|
.map((line) => line.trim().split(/\s+/).pop() || '')
|
||||||
|
.map((symbol) => symbol.replace(/^_/, ''))
|
||||||
|
// OSS 合法保留的只读消息插入状态查询符号;其余 wcdb_msg_insert_* 都是写入入口。
|
||||||
|
const PUBLIC_READONLY_MSG_INSERT = new Set([
|
||||||
|
'wcdb_msg_insert_get_switches',
|
||||||
|
'wcdb_msg_insert_inspect_shard',
|
||||||
|
'wcdb_msg_insert_list_shard_catalog',
|
||||||
|
'wcdb_msg_insert_get_rooms_status'
|
||||||
|
])
|
||||||
|
const msgInsertSymbols = symbols.filter((symbol) => symbol.startsWith('wcdb_msg_insert_'))
|
||||||
|
if (edition === 'public') {
|
||||||
|
const leaked = msgInsertSymbols.filter((symbol) => !PUBLIC_READONLY_MSG_INSERT.has(symbol))
|
||||||
|
if (leaked.length) {
|
||||||
|
throw new Error(`Bundled public WCDB API leaks write ABI: ${leaked.join(', ')}`)
|
||||||
|
}
|
||||||
|
} else if (msgInsertSymbols.length === 0) {
|
||||||
|
throw new Error('Bundled native WCDB API is missing message-insert ABI')
|
||||||
|
}
|
||||||
|
const nativeInput = marker.nativeInput || {}
|
||||||
|
if (edition === 'public') {
|
||||||
|
if (nativeInput.libwcdbApiSha256 && createHash('sha256').update(readFileSync(api)).digest('hex') !== nativeInput.libwcdbApiSha256) {
|
||||||
|
throw new Error('Packaged public WCDB API does not match the recorded WCDB input hash')
|
||||||
|
}
|
||||||
|
if (nativeInput.libWCDBSha256 && createHash('sha256').update(readFileSync(companion)).digest('hex') !== nativeInput.libWCDBSha256) {
|
||||||
|
throw new Error('Packaged public WCDB companion does not match the recorded WCDB input hash')
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const requiredSymbols = [
|
||||||
|
'wcdb_get_messages',
|
||||||
|
'wcdb_get_group_members_batch',
|
||||||
|
'wcdb_start_monitor_pipe',
|
||||||
|
...(edition === 'native'
|
||||||
|
? [
|
||||||
|
'wcdb_msg_insert_set_switch',
|
||||||
|
'wcdb_msg_insert_get_switches',
|
||||||
|
'wcdb_msg_insert_list_shard_catalog',
|
||||||
|
'wcdb_msg_insert_ensure_rooms_rules',
|
||||||
|
'wcdb_msg_insert_get_rooms_status',
|
||||||
|
'wcdb_msg_insert_inspect_shard',
|
||||||
|
'wcdb_msg_insert_insert_local_notice',
|
||||||
|
'wcdb_msg_insert_insert_local_notice_ex',
|
||||||
|
'wcdb_msg_insert_sync_display_names'
|
||||||
|
]
|
||||||
|
: [])
|
||||||
|
]
|
||||||
|
const missingSymbols = requiredSymbols.filter((symbol) => !symbols.includes(symbol))
|
||||||
|
if (missingSymbols.length) throw new Error(`${edition} WCDB API is missing exports: ${missingSymbols.join(', ')}`)
|
||||||
|
const ffmpeg = path.join(resources, 'ffmpeg', 'ffmpeg')
|
||||||
|
if (!existsSync(ffmpeg) || !readBinaryArchitectures(ffmpeg).includes('arm64')) {
|
||||||
|
throw new Error(`macOS arm64 FFmpeg is missing or wrong architecture: ${ffmpeg}`)
|
||||||
|
}
|
||||||
|
if (marker.ffmpegSha256 && createHash('sha256').update(readFileSync(ffmpeg)).digest('hex') !== marker.ffmpegSha256) {
|
||||||
|
throw new Error('Packaged FFmpeg does not match its recorded staged hash')
|
||||||
|
}
|
||||||
|
for (const relative of [
|
||||||
|
'licenses/ffmpeg-static/LICENSE',
|
||||||
|
'licenses/ffmpeg-static/FFMPEG-LICENSE.txt',
|
||||||
|
'licenses/ffmpeg-static/FFMPEG-BUILD-INFO.txt'
|
||||||
|
]) {
|
||||||
|
if (!existsSync(path.join(resources, relative))) {
|
||||||
|
throw new Error(`Missing FFmpeg license/build notice: ${relative}`)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const ffmpegLicenseHashes = marker.ffmpegLicenseSha256
|
||||||
|
if (!ffmpegLicenseHashes || typeof ffmpegLicenseHashes !== 'object') {
|
||||||
|
throw new Error('Mac build marker is missing FFmpeg license/source notice hashes')
|
||||||
|
}
|
||||||
|
for (const [relative, expected] of Object.entries(ffmpegLicenseHashes)) {
|
||||||
|
const notice = path.join(resources, relative)
|
||||||
|
if (!/^[a-f0-9]{64}$/.test(expected) || !existsSync(notice) ||
|
||||||
|
createHash('sha256').update(readFileSync(notice)).digest('hex') !== expected) {
|
||||||
|
throw new Error(`Packaged FFmpeg license/source notice hash mismatch: ${relative}`)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (edition === 'native') {
|
||||||
|
if (!readFileSync(host).includes(Buffer.from('/license/status'))) {
|
||||||
|
throw new Error('Native Host does not implement GET /license/status')
|
||||||
|
}
|
||||||
|
for (const binary of [helper, host, runtimeDylib]) {
|
||||||
|
if (!readBinaryArchitectures(binary).includes('arm64')) {
|
||||||
|
throw new Error(`Native binary lacks arm64 architecture: ${binary}`)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const manifest = JSON.parse(readFileSync(runtimeManifest, 'utf8'))
|
||||||
|
if (manifest.runtime !== 'tm-wechat-native') throw new Error('Runtime Manifest runtime name is invalid')
|
||||||
|
if (manifest.platform !== 'darwin-arm64' || manifest.architecture !== 'arm64' || manifest.protocolVersion !== 1) {
|
||||||
|
throw new Error('Runtime Manifest platform, architecture, or protocol is invalid')
|
||||||
|
}
|
||||||
|
for (const capability of ['text', 'image', 'voice']) {
|
||||||
|
if (!Array.isArray(manifest.capabilities) || !manifest.capabilities.includes(capability)) {
|
||||||
|
throw new Error(`Runtime Manifest is missing capability: ${capability}`)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (!Array.isArray(manifest.supportedWechatVersions) || manifest.supportedWechatVersions.length === 0) {
|
||||||
|
throw new Error('Runtime Manifest has no supported WeChat versions')
|
||||||
|
}
|
||||||
|
const dylib = readFileSync(runtimeDylib)
|
||||||
|
for (const key of ['tmSendSourceSha256', 'addressProfileSha256']) {
|
||||||
|
if (!/^[a-f0-9]{64}$/.test(manifest[key] || '') || !dylib.includes(Buffer.from(manifest[key]))) {
|
||||||
|
throw new Error(`Runtime embedded hash mismatch: ${key}`)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (!execFileSync('/usr/bin/otool', ['-L', helper], { encoding: 'utf8' }).includes('@loader_path/libwcdb_api.dylib')) {
|
||||||
|
throw new Error('Native helper is missing its @loader_path WCDB API dependency')
|
||||||
|
}
|
||||||
|
const actualRuntimeManifest = JSON.parse(readFileSync(runtimeManifest, 'utf8'))
|
||||||
|
if (actualRuntimeManifest.runtime !== 'tm-wechat-native' ||
|
||||||
|
actualRuntimeManifest.platform !== 'darwin-arm64' ||
|
||||||
|
actualRuntimeManifest.architecture !== 'arm64' ||
|
||||||
|
actualRuntimeManifest.protocolVersion !== 1 ||
|
||||||
|
!Array.isArray(actualRuntimeManifest.supportedWechatVersions) ||
|
||||||
|
actualRuntimeManifest.supportedWechatVersions.length === 0) {
|
||||||
|
throw new Error('Runtime Manifest failed application compatibility checks')
|
||||||
|
}
|
||||||
|
for (const key of ['tmSendSourceSha256', 'addressProfileSha256']) {
|
||||||
|
if (!/^[a-f0-9]{64}$/.test(actualRuntimeManifest[key] || '')) {
|
||||||
|
throw new Error(`Runtime Manifest has invalid ${key}`)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const stagedFiles = marker.nativeInput?.files
|
||||||
|
if (!Array.isArray(stagedFiles) || stagedFiles.length !== 7) {
|
||||||
|
throw new Error('Native build marker is missing its source Bundle file hashes')
|
||||||
|
}
|
||||||
|
for (const entry of stagedFiles) {
|
||||||
|
const remainder = entry.path.replace(/^tracememo\//, '')
|
||||||
|
let relative
|
||||||
|
if (remainder === 'runtime/libtmlicense.dylib') {
|
||||||
|
relative = path.join('wcdb', 'macos', 'arm64', 'libtmlicense.dylib')
|
||||||
|
} else if (remainder.startsWith('runtime/')) {
|
||||||
|
relative = remainder.replace(/^runtime\//, 'runtime/darwin-arm64/')
|
||||||
|
} else {
|
||||||
|
relative = path.join('wcdb', 'macos', 'arm64', remainder.replace(/^wcdb\//, ''))
|
||||||
|
}
|
||||||
|
const binary = path.join(resources, relative)
|
||||||
|
if (!existsSync(binary) || readFileSync(binary).length !== entry.bytes) {
|
||||||
|
throw new Error(`Native packaged artifact size mismatch: ${entry.path}`)
|
||||||
|
}
|
||||||
|
const digest = createHash('sha256').update(readFileSync(binary)).digest('hex')
|
||||||
|
if (digest !== entry.sha256) throw new Error(`Native packaged artifact SHA-256 mismatch: ${entry.path}`)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function validateMacEditionProtectedFiles(runtimeResources) {
|
||||||
|
const asarPath = path.join(runtimeResources, 'app.asar')
|
||||||
|
if (!existsSync(asarPath)) throw new Error(`Missing packaged application archive: ${asarPath}`)
|
||||||
|
const entries = asar.listPackage(asarPath).map((entry) => entry.replaceAll('\\', '/'))
|
||||||
|
const leaked = entries.filter((entry) =>
|
||||||
|
/(^|\/)1\.txt$/i.test(entry) ||
|
||||||
|
/(^|\/)runtime\.zip$/i.test(entry) ||
|
||||||
|
/(^|\/)\.env(?:\.|$)/i.test(entry) ||
|
||||||
|
/\.(?:db|sqlite)(?:3)?$/i.test(entry) ||
|
||||||
|
/\.log$/i.test(entry)
|
||||||
|
)
|
||||||
|
if (leaked.length) throw new Error(`Sensitive file(s) leaked into app.asar: ${leaked.join(', ')}`)
|
||||||
|
for (const relative of ['1.txt', 'runtime/runtime.zip']) {
|
||||||
|
const candidate = path.join(runtimeResources, 'resources', relative)
|
||||||
|
if (existsSync(candidate)) throw new Error(`Protected file leaked into packaged resources: ${candidate}`)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
function validateSherpaRuntime(runtimeResources, platform, arch) {
|
function validateSherpaRuntime(runtimeResources, platform, arch) {
|
||||||
const platformName = platform === 'win32' ? 'win' : platform
|
const platformName = platform === 'win32' ? 'win' : platform
|
||||||
const basePath = path.join(
|
const basePath = path.join(
|
||||||
@@ -78,11 +310,245 @@ function validateSherpaRuntime(runtimeResources, platform, arch) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* System OCR 用 native package(@napi-rs/system-ocr)。它是 external + asarUnpack,
|
||||||
|
* 打包后必须以 unpacked 形式存在,否则运行时会 MODULE_NOT_FOUND / native binding missing。
|
||||||
|
* Windows 与 macOS 都是 supported target,都要做硬校验(Linux 不是)。
|
||||||
|
*/
|
||||||
|
function systemOcrTarget(platform, arch) {
|
||||||
|
return platform === 'win32' ? `${platform}-${arch}-msvc` : `${platform}-${arch}`
|
||||||
|
}
|
||||||
|
|
||||||
|
function validateSystemOcrRuntime(runtimeResources, platform, arch) {
|
||||||
|
if (platform !== 'win32' && platform !== 'darwin') return
|
||||||
|
const target = systemOcrTarget(platform, arch)
|
||||||
|
const basePath = path.join(
|
||||||
|
runtimeResources,
|
||||||
|
'app.asar.unpacked',
|
||||||
|
'node_modules',
|
||||||
|
'@napi-rs',
|
||||||
|
'system-ocr'
|
||||||
|
)
|
||||||
|
const nativePath = path.join(
|
||||||
|
runtimeResources,
|
||||||
|
'app.asar.unpacked',
|
||||||
|
'node_modules',
|
||||||
|
'@napi-rs',
|
||||||
|
`system-ocr-${target}`
|
||||||
|
)
|
||||||
|
const requiredFiles = [
|
||||||
|
path.join(basePath, 'package.json'),
|
||||||
|
path.join(basePath, 'index.js'),
|
||||||
|
path.join(nativePath, 'package.json'),
|
||||||
|
path.join(nativePath, `system-ocr.${target}.node`)
|
||||||
|
]
|
||||||
|
const missingFiles = requiredFiles.filter((filePath) => !existsSync(filePath))
|
||||||
|
if (missingFiles.length > 0) {
|
||||||
|
throw new Error(`Missing unpacked System OCR runtime: ${missingFiles.join(', ')}`)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 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) {
|
function normalizeBuilderArch(arch) {
|
||||||
if (typeof arch === 'string') return arch
|
if (typeof arch === 'string') return arch
|
||||||
return { 0: 'ia32', 1: 'x64', 2: 'armv7l', 3: 'arm64', 4: 'universal' }[arch] || String(arch)
|
return { 0: 'ia32', 1: 'x64', 2: 'armv7l', 3: 'arm64', 4: 'universal' }[arch] || String(arch)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function runCodesign(args) {
|
||||||
|
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) {
|
||||||
|
try {
|
||||||
|
run(['--verify', '--strict', targetPath])
|
||||||
|
return true
|
||||||
|
} catch {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function findMacosHelperPaths(runtimeResources) {
|
||||||
|
const paths = MACOS_HELPER_NAMES.map((name) => path.join(runtimeResources, 'resources', name))
|
||||||
|
if (process.env.TRACEMEMO_EDITION) {
|
||||||
|
paths.push(...MACOS_EDITION_CODE_PATHS.map((segments) => path.join(runtimeResources, 'resources', ...segments)))
|
||||||
|
}
|
||||||
|
return paths.filter((helperPath) => existsSync(helperPath))
|
||||||
|
}
|
||||||
|
|
||||||
|
function signMacosHelpers(runtimeResources, run = runCodesign) {
|
||||||
|
const helperPaths = findMacosHelperPaths(runtimeResources)
|
||||||
|
for (const helperPath of helperPaths) {
|
||||||
|
if (!helperPath.endsWith('.dylib')) chmodSync(helperPath, 0o755)
|
||||||
|
if (!isMacosCodeValid(helperPath, run)) {
|
||||||
|
run(['--force', '--sign', '-', helperPath])
|
||||||
|
}
|
||||||
|
const architectures = readBinaryArchitectures(helperPath)
|
||||||
|
if (architectures.length === 0 && process.env.TRACEMEMO_EDITION) {
|
||||||
|
throw new Error(`macOS edition helper is not a supported Mach-O: ${helperPath}`)
|
||||||
|
}
|
||||||
|
const verificationArchitectures = architectures.length
|
||||||
|
? architectures.map((arch) => (arch === 'x64' ? 'x86_64' : arch))
|
||||||
|
: ['arm64', 'x86_64']
|
||||||
|
for (const arch of verificationArchitectures) {
|
||||||
|
try {
|
||||||
|
run(['--verify', '--strict', '--arch', arch, helperPath])
|
||||||
|
} catch (error) {
|
||||||
|
throw new Error(
|
||||||
|
'macOS helper signature verification failed: ' +
|
||||||
|
path.basename(helperPath) +
|
||||||
|
' (' +
|
||||||
|
arch +
|
||||||
|
')',
|
||||||
|
{ cause: error }
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
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])
|
||||||
|
} catch (error) {
|
||||||
|
throw new Error('macOS app bundle signature verification failed: ' + appBundlePath, {
|
||||||
|
cause: error
|
||||||
|
})
|
||||||
|
}
|
||||||
|
return appBundlePath
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* A foreign-architecture binary only fails once the user touches the feature
|
* A foreign-architecture binary only fails once the user touches the feature
|
||||||
* that needs it, so verify the ones whose filename is shared across
|
* that needs it, so verify the ones whose filename is shared across
|
||||||
@@ -99,6 +565,28 @@ function validateRuntimeBinaryArchitecture(filePath, platform, arch, label) {
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 打包目标架构必须与 Electron 主程序一致。
|
||||||
|
*
|
||||||
|
* Electron 缓存残留另一架构时会静默产出「arm64 包 + x64 主程序」:这种包靠 Rosetta
|
||||||
|
* 仍能启动,于是被当成 Intel 机器、走错密钥流程。这里让它在打包阶段直接失败。
|
||||||
|
*/
|
||||||
|
function validateElectronMainBinary(appOutDir, productName, platform, arch) {
|
||||||
|
if (platform !== 'darwin') return
|
||||||
|
const binaryPath = path.join(appOutDir, `${productName}.app`, 'Contents', 'MacOS', productName)
|
||||||
|
if (!existsSync(binaryPath)) {
|
||||||
|
throw new Error(`Missing Electron main binary: ${binaryPath}`)
|
||||||
|
}
|
||||||
|
const architectures = readBinaryArchitectures(binaryPath)
|
||||||
|
if (!architectures.length) {
|
||||||
|
throw new Error(`Electron main binary is not a Mach-O executable: ${binaryPath}`)
|
||||||
|
}
|
||||||
|
if (arch === 'universal' || architectures.includes(arch)) return
|
||||||
|
throw new Error(
|
||||||
|
`Electron main binary is ${architectures.join('/')} but this bundle targets ${arch}: ${binaryPath}`
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* The Intel Mac key helper is an x86_64 executable that only the x64 (or
|
* The Intel Mac key helper is an x86_64 executable that only the x64 (or
|
||||||
* universal) macOS bundle can run. Every other target — Apple Silicon macOS,
|
* universal) macOS bundle can run. Every other target — Apple Silicon macOS,
|
||||||
@@ -152,16 +640,24 @@ function validateReaderSkillRuntime(runtimeResources) {
|
|||||||
* The loaders pick their package from process.platform/arch, so the siblings
|
* The loaders pick their package from process.platform/arch, so the siblings
|
||||||
* are dead weight — drop them.
|
* are dead weight — drop them.
|
||||||
*/
|
*/
|
||||||
|
// 每个条目返回 platform package 的**完整后缀**(不含 package 前缀与连字符)。
|
||||||
const NATIVE_RUNTIME_PACKAGES = [
|
const NATIVE_RUNTIME_PACKAGES = [
|
||||||
{
|
{
|
||||||
modules: [],
|
modules: [],
|
||||||
prefix: 'sherpa-onnx',
|
prefix: 'sherpa-onnx',
|
||||||
platformName: (platform) => (platform === 'win32' ? 'win' : platform)
|
platformName: (platform, arch) => `${platform === 'win32' ? 'win' : platform}-${arch}`
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
modules: ['@koromix'],
|
modules: ['@koromix'],
|
||||||
prefix: 'koffi',
|
prefix: 'koffi',
|
||||||
platformName: (platform) => platform
|
platformName: (platform, arch) => `${platform}-${arch}`
|
||||||
|
},
|
||||||
|
{
|
||||||
|
// @napi-rs 的 platform package 目录名带 -msvc 后缀(win32-x64-msvc)。
|
||||||
|
modules: ['@napi-rs'],
|
||||||
|
prefix: 'system-ocr',
|
||||||
|
platformName: (platform, arch) => systemOcrTarget(platform, arch),
|
||||||
|
foreignPattern: /^system-ocr-[a-z0-9]+-(arm64|x64|ia32|loong64|riscv64)(-msvc)?$/
|
||||||
}
|
}
|
||||||
]
|
]
|
||||||
|
|
||||||
@@ -173,12 +669,16 @@ function pruneForeignArchNativeRuntimes(runtimeResources, platform, arch) {
|
|||||||
for (const runtime of NATIVE_RUNTIME_PACKAGES) {
|
for (const runtime of NATIVE_RUNTIME_PACKAGES) {
|
||||||
const modulesRoot = path.join(unpackedRoot, ...runtime.modules)
|
const modulesRoot = path.join(unpackedRoot, ...runtime.modules)
|
||||||
if (!existsSync(modulesRoot)) continue
|
if (!existsSync(modulesRoot)) continue
|
||||||
const expected = `${runtime.prefix}-${runtime.platformName(platform)}-${arch}`
|
const expected = `${runtime.prefix}-${runtime.platformName(platform, arch)}`
|
||||||
const foreign = new RegExp(`^${runtime.prefix}-[a-z0-9]+-(arm64|x64|ia32|loong64|riscv64)$`)
|
const foreign =
|
||||||
|
runtime.foreignPattern ||
|
||||||
|
new RegExp(`^${runtime.prefix}-[a-z0-9]+-(arm64|x64|ia32|loong64|riscv64)$`)
|
||||||
for (const entry of readdirSync(modulesRoot, { withFileTypes: true })) {
|
for (const entry of readdirSync(modulesRoot, { withFileTypes: true })) {
|
||||||
if (!entry.isDirectory() || entry.name === expected || !foreign.test(entry.name)) continue
|
if (!entry.isDirectory() || entry.name === expected || !foreign.test(entry.name)) continue
|
||||||
rmSync(path.join(modulesRoot, entry.name), { recursive: true, force: true })
|
rmSync(path.join(modulesRoot, entry.name), { recursive: true, force: true })
|
||||||
removed.push(runtime.modules.length ? `${runtime.modules.join('/')}/${entry.name}` : entry.name)
|
removed.push(
|
||||||
|
runtime.modules.length ? `${runtime.modules.join('/')}/${entry.name}` : entry.name
|
||||||
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return removed
|
return removed
|
||||||
@@ -209,13 +709,85 @@ function pruneForeignArchConnectors(runtimeResources, platform, arch) {
|
|||||||
return removed
|
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 =
|
||||||
|
process.env.TRACEMEMO_EDITION === 'native'
|
||||||
|
? true
|
||||||
|
: process.env.TRACEMEMO_EDITION === 'public'
|
||||||
|
? false
|
||||||
|
: 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) {
|
exports.default = async function afterPack(context) {
|
||||||
const runtimeResources = getRuntimeResources(context)
|
const runtimeResources = getRuntimeResources(context)
|
||||||
const arch = normalizeBuilderArch(context.arch)
|
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)
|
validateAsarRuntimeDependencies(runtimeResources)
|
||||||
validateReaderSkillRuntime(runtimeResources)
|
validateReaderSkillRuntime(runtimeResources)
|
||||||
validateSilkWasmRuntime(runtimeResources)
|
validateSilkWasmRuntime(runtimeResources)
|
||||||
const ffmpegPath = validateFfmpegRuntime(runtimeResources, context.electronPlatformName)
|
const ffmpegPath = validateFfmpegRuntime(runtimeResources, context.electronPlatformName)
|
||||||
|
validateElectronMainBinary(
|
||||||
|
context.appOutDir,
|
||||||
|
context.packager.appInfo.productFilename,
|
||||||
|
context.electronPlatformName,
|
||||||
|
arch
|
||||||
|
)
|
||||||
validateRuntimeBinaryArchitecture(
|
validateRuntimeBinaryArchitecture(
|
||||||
ffmpegPath,
|
ffmpegPath,
|
||||||
context.electronPlatformName,
|
context.electronPlatformName,
|
||||||
@@ -223,6 +795,25 @@ exports.default = async function afterPack(context) {
|
|||||||
'Bundled ffmpeg'
|
'Bundled ffmpeg'
|
||||||
)
|
)
|
||||||
validateSherpaRuntime(runtimeResources, context.electronPlatformName, arch)
|
validateSherpaRuntime(runtimeResources, context.electronPlatformName, arch)
|
||||||
|
validateSystemOcrRuntime(runtimeResources, context.electronPlatformName, arch)
|
||||||
|
validateKoffiRuntime(runtimeResources, context.electronPlatformName, arch)
|
||||||
|
if (context.electronPlatformName === 'darwin' && process.env.TRACEMEMO_EDITION) {
|
||||||
|
validateMacEditionResources(runtimeResources, process.env.TRACEMEMO_EDITION, context.electronPlatformName)
|
||||||
|
validateMacEditionProtectedFiles(runtimeResources)
|
||||||
|
if (process.env.TRACEMEMO_EDITION === 'public' && sendRuntime) {
|
||||||
|
throw new Error('Public edition unexpectedly includes a WeChat Runtime')
|
||||||
|
}
|
||||||
|
if (process.env.TRACEMEMO_EDITION === 'native' && !sendRuntime) {
|
||||||
|
throw new Error('Native edition is missing its WeChat Runtime')
|
||||||
|
}
|
||||||
|
if (sendRuntime) {
|
||||||
|
for (const runtimeFile of ['tm-wechat-host', 'libtmwechat.dylib', 'runtime-manifest.json']) {
|
||||||
|
if (!existsSync(path.join(sendRuntime, runtimeFile))) {
|
||||||
|
throw new Error(`Runtime file missing after packaging: ${runtimeFile}`)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
pruneIntelMacKeyTool(runtimeResources, context.electronPlatformName, arch)
|
pruneIntelMacKeyTool(runtimeResources, context.electronPlatformName, arch)
|
||||||
pruneForeignArchConnectors(runtimeResources, context.electronPlatformName, arch)
|
pruneForeignArchConnectors(runtimeResources, context.electronPlatformName, arch)
|
||||||
pruneForeignArchNativeRuntimes(runtimeResources, context.electronPlatformName, arch)
|
pruneForeignArchNativeRuntimes(runtimeResources, context.electronPlatformName, arch)
|
||||||
@@ -231,25 +822,10 @@ exports.default = async function afterPack(context) {
|
|||||||
execFileSync('/usr/bin/codesign', ['--force', '--sign', '-', ffmpegPath], {
|
execFileSync('/usr/bin/codesign', ['--force', '--sign', '-', ffmpegPath], {
|
||||||
stdio: 'ignore'
|
stdio: 'ignore'
|
||||||
})
|
})
|
||||||
|
signMacosHelpers(runtimeResources)
|
||||||
|
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
|
exports.getRuntimeResources = getRuntimeResources
|
||||||
@@ -258,7 +834,20 @@ exports.validateReaderSkillRuntime = validateReaderSkillRuntime
|
|||||||
exports.validateFfmpegRuntime = validateFfmpegRuntime
|
exports.validateFfmpegRuntime = validateFfmpegRuntime
|
||||||
exports.validateSilkWasmRuntime = validateSilkWasmRuntime
|
exports.validateSilkWasmRuntime = validateSilkWasmRuntime
|
||||||
exports.validateSherpaRuntime = validateSherpaRuntime
|
exports.validateSherpaRuntime = validateSherpaRuntime
|
||||||
|
exports.validateSystemOcrRuntime = validateSystemOcrRuntime
|
||||||
|
exports.validateKoffiRuntime = validateKoffiRuntime
|
||||||
|
exports.validateMacEditionResources = validateMacEditionResources
|
||||||
|
exports.validateMacEditionProtectedFiles = validateMacEditionProtectedFiles
|
||||||
exports.pruneIntelMacKeyTool = pruneIntelMacKeyTool
|
exports.pruneIntelMacKeyTool = pruneIntelMacKeyTool
|
||||||
exports.pruneForeignArchConnectors = pruneForeignArchConnectors
|
exports.pruneForeignArchConnectors = pruneForeignArchConnectors
|
||||||
exports.pruneForeignArchNativeRuntimes = pruneForeignArchNativeRuntimes
|
exports.pruneForeignArchNativeRuntimes = pruneForeignArchNativeRuntimes
|
||||||
exports.validateRuntimeBinaryArchitecture = validateRuntimeBinaryArchitecture
|
exports.validateRuntimeBinaryArchitecture = validateRuntimeBinaryArchitecture
|
||||||
|
exports.validateElectronMainBinary = validateElectronMainBinary
|
||||||
|
exports.findMacosHelperPaths = findMacosHelperPaths
|
||||||
|
exports.isMacosCodeValid = isMacosCodeValid
|
||||||
|
exports.signMacosHelpers = signMacosHelpers
|
||||||
|
exports.signMacosAppBundle = signMacosAppBundle
|
||||||
|
exports.findNestedMacosCodePaths = findNestedMacosCodePaths
|
||||||
|
exports.sendRuntimeLocations = sendRuntimeLocations
|
||||||
|
exports.findSendRuntime = findSendRuntime
|
||||||
|
exports.enforceSendRuntimeBoundary = enforceSendRuntimeBoundary
|
||||||
@@ -0,0 +1,174 @@
|
|||||||
|
const fs = require('node:fs')
|
||||||
|
const path = require('node:path')
|
||||||
|
const { spawnSync } = require('node:child_process')
|
||||||
|
const {
|
||||||
|
assertStagingTargetDoesNotExist,
|
||||||
|
prepareEdition,
|
||||||
|
resolveEditionRoots,
|
||||||
|
validateStagedEdition
|
||||||
|
} = require('./prepare-macos-edition.cjs')
|
||||||
|
|
||||||
|
const ROOT = path.resolve(__dirname, '..')
|
||||||
|
const EDITIONS = ['public', 'native']
|
||||||
|
const YAML = require('yaml')
|
||||||
|
|
||||||
|
function run(args, env) {
|
||||||
|
const result = spawnSync(process.execPath, args, { cwd: ROOT, stdio: 'inherit', env })
|
||||||
|
if (result.error) throw result.error
|
||||||
|
if (result.status !== 0) throw new Error(`Command failed (${result.status}): ${args.join(' ')}`)
|
||||||
|
}
|
||||||
|
|
||||||
|
function createBuilderConfig({ edition, stageRoot, buildOutput, outputRoot, appVersion }) {
|
||||||
|
return {
|
||||||
|
appId: 'com.tracememo.app',
|
||||||
|
productName: 'TraceMemo',
|
||||||
|
afterPack: path.join(ROOT, 'scripts/after-pack.cjs'),
|
||||||
|
directories: {
|
||||||
|
buildResources: path.join(ROOT, 'build'),
|
||||||
|
output: outputRoot
|
||||||
|
},
|
||||||
|
files: [
|
||||||
|
{ from: buildOutput, to: 'out', filter: ['**/*'] },
|
||||||
|
'package.json',
|
||||||
|
'!resources/**',
|
||||||
|
'!1.txt',
|
||||||
|
'!**/1.txt',
|
||||||
|
'!**/*.db',
|
||||||
|
'!**/*.sqlite*',
|
||||||
|
'!**/*.log',
|
||||||
|
'!**/runtime.zip',
|
||||||
|
'!.' + 'ai-local/**',
|
||||||
|
'!.' + 'workbuddy/**',
|
||||||
|
'!tests/**',
|
||||||
|
'!AGENTS.md',
|
||||||
|
'!**/.vscode/*',
|
||||||
|
'!src/*',
|
||||||
|
'!electron.vite.config.{js,ts,mjs,cjs}',
|
||||||
|
'!{.eslintcache,eslint.config.mjs,.prettierignore,.prettierrc.yaml,dev-app-update.yml,CHANGELOG.md,README.md}',
|
||||||
|
'!{.env,.env.*,.npmrc,pnpm-lock.yaml}',
|
||||||
|
'!{tsconfig.json,tsconfig.node.json,tsconfig.web.json}'
|
||||||
|
],
|
||||||
|
extraMetadata: { main: 'out/main/index.js' },
|
||||||
|
asarUnpack: [
|
||||||
|
'resources/**',
|
||||||
|
'node_modules/ffmpeg-static/**',
|
||||||
|
'node_modules/silk-wasm/**',
|
||||||
|
'node_modules/sherpa-onnx-node/**',
|
||||||
|
'node_modules/sherpa-onnx-*/**',
|
||||||
|
'node_modules/@napi-rs/system-ocr/**',
|
||||||
|
'node_modules/@napi-rs/system-ocr-*/**'
|
||||||
|
],
|
||||||
|
extraResources: [
|
||||||
|
{ from: path.join(stageRoot, 'resources'), to: 'resources', filter: ['**/*'] },
|
||||||
|
{ from: path.join(ROOT, 'build/app-update.yml'), to: 'app-update.yml' },
|
||||||
|
{
|
||||||
|
from: path.join(ROOT, 'docs/skill/tracememo-reader'),
|
||||||
|
to: 'skill/tracememo-reader',
|
||||||
|
filter: ['**/*']
|
||||||
|
}
|
||||||
|
],
|
||||||
|
mac: {
|
||||||
|
icon: path.join(ROOT, 'build/icon.icns'),
|
||||||
|
target: ['dmg'],
|
||||||
|
entitlementsInherit: path.join(ROOT, 'build/entitlements.mac.plist'),
|
||||||
|
extendInfo: {
|
||||||
|
CFBundleDisplayName: 'TraceMemo',
|
||||||
|
NSCameraUsageDescription: 'Application requests access to the device camera.',
|
||||||
|
NSMicrophoneUsageDescription: 'Application requests access to the device microphone.',
|
||||||
|
NSDocumentsFolderUsageDescription: 'Application requests access to the user documents folder.',
|
||||||
|
NSDownloadsFolderUsageDescription: 'Application requests access to the user downloads folder.'
|
||||||
|
},
|
||||||
|
notarize: false
|
||||||
|
},
|
||||||
|
dmg: {
|
||||||
|
artifactName:
|
||||||
|
edition === 'native'
|
||||||
|
? `TraceMemo-${appVersion}-mac-arm64-native.dmg`
|
||||||
|
: `TraceMemo-${appVersion}-mac-arm64-oss.dmg`
|
||||||
|
},
|
||||||
|
npmRebuild: false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function buildEdition(edition, options = {}) {
|
||||||
|
if (!EDITIONS.includes(edition)) throw new Error('Usage: build-macos-edition.cjs <public|native>')
|
||||||
|
const roots = resolveEditionRoots()
|
||||||
|
const stageRoot = path.join(roots.stageRoot, edition)
|
||||||
|
const outputRoot = path.join(roots.outputRoot, edition)
|
||||||
|
const configRoot = path.join(roots.stageRoot, 'configs')
|
||||||
|
if (fs.existsSync(stageRoot) && !options.reuseStaging) {
|
||||||
|
throw new Error(`Refusing to overwrite existing build staging: ${stageRoot}`)
|
||||||
|
}
|
||||||
|
if (fs.existsSync(outputRoot)) throw new Error(`Refusing to overwrite existing build output: ${outputRoot}`)
|
||||||
|
if (fs.existsSync(configRoot)) throw new Error(`Refusing to overwrite existing build config directory: ${configRoot}`)
|
||||||
|
const preparation = fs.existsSync(stageRoot)
|
||||||
|
? Promise.resolve(validateStagedEdition(edition))
|
||||||
|
: prepareEdition(edition)
|
||||||
|
if (!preparation || typeof preparation.then !== 'function') throw new Error('Edition staging preparation did not return a Promise')
|
||||||
|
return preparation.then(() => {
|
||||||
|
const buildOutput = path.join(stageRoot, 'out')
|
||||||
|
const configPath = path.join(configRoot, `electron-builder-${edition}.yml`)
|
||||||
|
let ownsConfigRoot = false
|
||||||
|
let buildSucceeded = false
|
||||||
|
try {
|
||||||
|
const markerPath = path.join(stageRoot, 'resources', 'tracememo-build.json')
|
||||||
|
const marker = JSON.parse(fs.readFileSync(markerPath, 'utf8'))
|
||||||
|
const packageJson = JSON.parse(fs.readFileSync(path.join(ROOT, 'package.json'), 'utf8'))
|
||||||
|
if (marker.profile !== edition || marker.appVersion !== packageJson.version) {
|
||||||
|
throw new Error('Staged edition marker does not match the current package metadata')
|
||||||
|
}
|
||||||
|
validateStagedEdition(edition)
|
||||||
|
const env = { ...process.env, TRACEMEMO_EDITION: edition, TRACEMEMO_RUNTIME_PROFILE: edition }
|
||||||
|
env.TRACEMEMO_EDITION_OUT_DIR = path.relative(ROOT, buildOutput)
|
||||||
|
run(
|
||||||
|
[
|
||||||
|
path.join(ROOT, 'node_modules/electron-vite/bin/electron-vite.js'),
|
||||||
|
'build',
|
||||||
|
'--outDir',
|
||||||
|
path.relative(ROOT, buildOutput)
|
||||||
|
],
|
||||||
|
env
|
||||||
|
)
|
||||||
|
fs.mkdirSync(configRoot, { recursive: true })
|
||||||
|
ownsConfigRoot = true
|
||||||
|
const config = createBuilderConfig({
|
||||||
|
edition,
|
||||||
|
stageRoot,
|
||||||
|
buildOutput,
|
||||||
|
outputRoot,
|
||||||
|
appVersion: packageJson.version
|
||||||
|
})
|
||||||
|
fs.writeFileSync(configPath, YAML.stringify(config), { flag: 'wx' })
|
||||||
|
run(
|
||||||
|
[
|
||||||
|
path.join(ROOT, 'node_modules/electron-builder/cli.js'),
|
||||||
|
'--config',
|
||||||
|
path.relative(ROOT, configPath),
|
||||||
|
'--mac',
|
||||||
|
'--arm64'
|
||||||
|
],
|
||||||
|
env
|
||||||
|
)
|
||||||
|
buildSucceeded = true
|
||||||
|
} finally {
|
||||||
|
if (ownsConfigRoot) fs.rmSync(configRoot, { recursive: true, force: true })
|
||||||
|
if (!buildSucceeded && fs.existsSync(outputRoot)) {
|
||||||
|
fs.rmSync(outputRoot, { recursive: true, force: true })
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
if (require.main === module) {
|
||||||
|
try {
|
||||||
|
Promise.resolve(buildEdition(process.argv[2], { reuseStaging: process.argv[3] === '--reuse-staging' })).catch((error) => {
|
||||||
|
console.error(error instanceof Error ? error.message : String(error))
|
||||||
|
process.exitCode = 1
|
||||||
|
})
|
||||||
|
} catch (error) {
|
||||||
|
console.error(error instanceof Error ? error.message : String(error))
|
||||||
|
process.exitCode = 1
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = { buildEdition, createBuilderConfig }
|
||||||
@@ -1,65 +0,0 @@
|
|||||||
/* eslint-disable @typescript-eslint/no-require-imports, @typescript-eslint/explicit-function-return-type */
|
|
||||||
const { execFileSync } = require('node:child_process')
|
|
||||||
const fs = require('node:fs')
|
|
||||||
const path = require('node:path')
|
|
||||||
|
|
||||||
const projectRoot = path.resolve(__dirname, '..')
|
|
||||||
const sourceDir = path.join(projectRoot, 'services', 'wechat-connector')
|
|
||||||
const outputRoot = path.join(projectRoot, 'resources', 'connectors', 'wechat')
|
|
||||||
|
|
||||||
function normalizePlatform(value) {
|
|
||||||
if (value === 'win32' || value === 'windows') return 'windows'
|
|
||||||
if (value === 'darwin' || value === 'macos') return 'darwin'
|
|
||||||
if (value === 'linux') return 'linux'
|
|
||||||
throw new Error(`Unsupported connector platform: ${value}`)
|
|
||||||
}
|
|
||||||
|
|
||||||
function normalizeArch(value) {
|
|
||||||
if (value === 'x64' || value === 'amd64') return 'amd64'
|
|
||||||
if (value === 'arm64') return 'arm64'
|
|
||||||
throw new Error(`Unsupported connector architecture: ${value}`)
|
|
||||||
}
|
|
||||||
|
|
||||||
function detectHostArch() {
|
|
||||||
if (process.platform !== 'darwin') return process.arch
|
|
||||||
try {
|
|
||||||
const arm64Supported = execFileSync('sysctl', ['-n', 'hw.optional.arm64'], {
|
|
||||||
encoding: 'utf8'
|
|
||||||
}).trim()
|
|
||||||
return arm64Supported === '1' ? 'arm64' : process.arch
|
|
||||||
} catch {
|
|
||||||
return process.arch
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function parseTargets() {
|
|
||||||
const platformArg = process.argv.indexOf('--platform')
|
|
||||||
const archArg = process.argv.indexOf('--arch')
|
|
||||||
const platforms = platformArg >= 0 ? process.argv[platformArg + 1].split(',') : [process.platform]
|
|
||||||
const arches = archArg >= 0 ? process.argv[archArg + 1].split(',') : [detectHostArch()]
|
|
||||||
return platforms.flatMap((platform) =>
|
|
||||||
arches.map((arch) => ({ goos: normalizePlatform(platform), goarch: normalizeArch(arch) }))
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!fs.existsSync(path.join(sourceDir, 'go.mod'))) {
|
|
||||||
throw new Error(`Repository-local WeChat connector source is missing: ${sourceDir}`)
|
|
||||||
}
|
|
||||||
|
|
||||||
for (const target of parseTargets()) {
|
|
||||||
const directoryName = `${target.goos === 'windows' ? 'win32' : target.goos}-${target.goarch === 'amd64' ? 'x64' : target.goarch}`
|
|
||||||
const outputDir = path.join(outputRoot, directoryName)
|
|
||||||
const outputPath = path.join(
|
|
||||||
outputDir,
|
|
||||||
target.goos === 'windows' ? 'wechat-connector.exe' : 'wechat-connector'
|
|
||||||
)
|
|
||||||
fs.rmSync(outputDir, { recursive: true, force: true })
|
|
||||||
fs.mkdirSync(outputDir, { recursive: true })
|
|
||||||
execFileSync('go', ['build', '-trimpath', '-o', outputPath, '.'], {
|
|
||||||
cwd: sourceDir,
|
|
||||||
env: { ...process.env, GOOS: target.goos, GOARCH: target.goarch, CGO_ENABLED: '0' },
|
|
||||||
stdio: 'inherit'
|
|
||||||
})
|
|
||||||
if (target.goos !== 'windows') fs.chmodSync(outputPath, 0o755)
|
|
||||||
console.log(`[build-wechat-connector] built ${directoryName}: ${outputPath}`)
|
|
||||||
}
|
|
||||||
@@ -0,0 +1,121 @@
|
|||||||
|
#!/usr/bin/env node
|
||||||
|
/**
|
||||||
|
* 防漂移检查:Reader Skill 的版本号只有一个真源 —— SKILL.md frontmatter 的 `version`。
|
||||||
|
*
|
||||||
|
* 只要本次变更动了 SKILL.md 的内容,就必须同时提升 version,否则外部 Agent
|
||||||
|
* 无法通过 /health 上的 skill.version 发现自己手里的 Skill 已经过期,
|
||||||
|
* 会继续按旧契约调用接口(历史上真实发生过:文档改了两轮,版本号没动)。
|
||||||
|
*
|
||||||
|
* 比较基准依次尝试 SKILL_VERSION_BASE / origin/main / origin/develop / HEAD~1;
|
||||||
|
* 找不到基准(例如浅克隆)时只提示并跳过,不阻塞构建。
|
||||||
|
*/
|
||||||
|
const { execFileSync } = require('node:child_process')
|
||||||
|
const { readFileSync, existsSync } = require('node:fs')
|
||||||
|
const path = require('node:path')
|
||||||
|
|
||||||
|
const REQUESTED_BASE = 'SKILL_VERSION_BASE'
|
||||||
|
const SKILL_PATH = 'docs/skill/tracememo-reader/SKILL.md'
|
||||||
|
const SEMVER = /^\d+\.\d+\.\d+$/
|
||||||
|
|
||||||
|
function git(args) {
|
||||||
|
return execFileSync('git', args, {
|
||||||
|
cwd: process.cwd(),
|
||||||
|
encoding: 'utf8',
|
||||||
|
stdio: ['ignore', 'pipe', 'pipe']
|
||||||
|
}).trim()
|
||||||
|
}
|
||||||
|
|
||||||
|
function resolveBase() {
|
||||||
|
const candidates = []
|
||||||
|
if (process.env[REQUESTED_BASE]) candidates.push(process.env[REQUESTED_BASE])
|
||||||
|
candidates.push('origin/main', 'origin/develop', 'HEAD~1')
|
||||||
|
|
||||||
|
for (const candidate of candidates) {
|
||||||
|
try {
|
||||||
|
git(['rev-parse', '--verify', '--quiet', `${candidate}^{commit}`])
|
||||||
|
return candidate
|
||||||
|
} catch {
|
||||||
|
// 该基准不存在,继续尝试下一个
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
|
||||||
|
function versionOf(markdown) {
|
||||||
|
if (!markdown) return null
|
||||||
|
const match = /^version:[ \t]*(\S+)[ \t]*$/m.exec(markdown)
|
||||||
|
return match ? match[1] : null
|
||||||
|
}
|
||||||
|
|
||||||
|
function skip(reason) {
|
||||||
|
console.log(`[skill-version] 跳过版本漂移检查:${reason}`)
|
||||||
|
process.exit(0)
|
||||||
|
}
|
||||||
|
|
||||||
|
function fail(message) {
|
||||||
|
console.error(`[skill-version] FAIL:${message}`)
|
||||||
|
process.exit(1)
|
||||||
|
}
|
||||||
|
|
||||||
|
const root = process.cwd()
|
||||||
|
const skillFile = path.join(root, SKILL_PATH)
|
||||||
|
|
||||||
|
if (!existsSync(skillFile)) fail(`找不到 ${SKILL_PATH}。`)
|
||||||
|
|
||||||
|
const current = readFileSync(skillFile, 'utf8')
|
||||||
|
const currentVersion = versionOf(current)
|
||||||
|
|
||||||
|
if (!currentVersion) {
|
||||||
|
fail(`${SKILL_PATH} 的 frontmatter 缺少 version 字段。外部 Agent 依赖它做版本自检。`)
|
||||||
|
}
|
||||||
|
if (!SEMVER.test(currentVersion)) {
|
||||||
|
fail(`${SKILL_PATH} 的 version "${currentVersion}" 不是 x.y.z 形式。`)
|
||||||
|
}
|
||||||
|
|
||||||
|
const base = resolveBase()
|
||||||
|
if (!base) skip('找不到可用的 git 比较基准(可能是浅克隆)。')
|
||||||
|
|
||||||
|
// 已提交的改动 + 工作区未提交的改动都要看,否则本地预检会漏掉。
|
||||||
|
let changedFiles = new Set()
|
||||||
|
try {
|
||||||
|
for (const args of [
|
||||||
|
['diff', '--name-only', `${base}...HEAD`],
|
||||||
|
['diff', '--name-only', 'HEAD']
|
||||||
|
]) {
|
||||||
|
for (const file of git(args).split('\n')) if (file) changedFiles.add(file)
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
skip(`无法计算与 ${base} 的差异(${error.message.split('\n')[0]})。`)
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!changedFiles.has(SKILL_PATH)) {
|
||||||
|
console.log(`[skill-version] OK:与 ${base} 相比 ${SKILL_PATH} 未变更,无需提升版本。`)
|
||||||
|
process.exit(0)
|
||||||
|
}
|
||||||
|
|
||||||
|
let previous = null
|
||||||
|
try {
|
||||||
|
previous = git(['show', `${base}:${SKILL_PATH}`])
|
||||||
|
} catch {
|
||||||
|
previous = null
|
||||||
|
}
|
||||||
|
|
||||||
|
const previousVersion = versionOf(previous)
|
||||||
|
|
||||||
|
if (previousVersion === null) {
|
||||||
|
console.log(
|
||||||
|
`[skill-version] OK:${base} 上没有可比较的 version,当前为 ${currentVersion}。`
|
||||||
|
)
|
||||||
|
process.exit(0)
|
||||||
|
}
|
||||||
|
|
||||||
|
if (previousVersion === currentVersion) {
|
||||||
|
fail(
|
||||||
|
`${SKILL_PATH} 内容已变更,但 version 仍是 ${currentVersion}(基准 ${base})。\n` +
|
||||||
|
' 外部 Agent 只能通过 version 判断自己是否过期,请提升该版本号(例如 1.3.0 → 1.4.0)。'
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
console.log(
|
||||||
|
`[skill-version] OK:版本随文档一起提升 ${previousVersion} → ${currentVersion}(基准 ${base})。`
|
||||||
|
)
|
||||||
@@ -0,0 +1,660 @@
|
|||||||
|
const fs = require('node:fs')
|
||||||
|
const path = require('node:path')
|
||||||
|
const { createHash } = require('node:crypto')
|
||||||
|
const { execFileSync } = require('node:child_process')
|
||||||
|
const { createGunzip } = require('node:zlib')
|
||||||
|
const https = require('node:https')
|
||||||
|
const { pipeline } = require('node:stream/promises')
|
||||||
|
const { readBinaryArchitectures } = require('./binary-arch.cjs')
|
||||||
|
|
||||||
|
const ROOT = path.resolve(__dirname, '..')
|
||||||
|
function resolveEditionRoots(projectRoot = ROOT, env = process.env) {
|
||||||
|
return {
|
||||||
|
stageRoot: path.resolve(env.TRACEMEMO_MAC_STAGE_ROOT || path.join(projectRoot, 'build', 'mac-staging')),
|
||||||
|
outputRoot: path.resolve(env.TRACEMEMO_MAC_OUTPUT_ROOT || path.join(projectRoot, 'dist', 'mac'))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const WCDB_DIST_ROOT = resolveWcdbDistRoot()
|
||||||
|
const NATIVE_DIST_ROOT =
|
||||||
|
process.env.TRACEMEMO_NATIVE_DIST_ROOT || path.resolve(ROOT, '..', 'native-runtime-dist')
|
||||||
|
const NATIVE_BUNDLE_ROOT = findNativeBundleRoot(NATIVE_DIST_ROOT)
|
||||||
|
const PUBLIC_FILES = [
|
||||||
|
'icon.png',
|
||||||
|
'trayTemplate.png',
|
||||||
|
'trayTemplate@2x.png',
|
||||||
|
'daily_report_templates.html',
|
||||||
|
'mobile_daily_report.html',
|
||||||
|
'mobile_daily_report_v1.html',
|
||||||
|
'mobile_daily_report_v2.html',
|
||||||
|
'xkey_helper',
|
||||||
|
'xkey_helper_4_1_13'
|
||||||
|
]
|
||||||
|
const FFMPEG_LICENSE_FILES = [
|
||||||
|
['LICENSE', 'licenses/ffmpeg-static/LICENSE'],
|
||||||
|
['ffmpeg.LICENSE', 'licenses/ffmpeg-static/FFMPEG-LICENSE.txt'],
|
||||||
|
['ffmpeg.README', 'licenses/ffmpeg-static/FFMPEG-BUILD-INFO.txt']
|
||||||
|
]
|
||||||
|
const REQUIRED_NATIVE_SYMBOLS = [
|
||||||
|
'wcdb_msg_insert_set_switch',
|
||||||
|
'wcdb_msg_insert_get_switches',
|
||||||
|
'wcdb_msg_insert_list_shard_catalog',
|
||||||
|
'wcdb_msg_insert_ensure_rooms_rules',
|
||||||
|
'wcdb_msg_insert_get_rooms_status',
|
||||||
|
'wcdb_msg_insert_inspect_shard',
|
||||||
|
'wcdb_msg_insert_insert_local_notice',
|
||||||
|
'wcdb_msg_insert_insert_local_notice_ex',
|
||||||
|
'wcdb_msg_insert_sync_display_names'
|
||||||
|
]
|
||||||
|
const REQUIRED_PUBLIC_SYMBOLS = [
|
||||||
|
'wcdb_get_messages',
|
||||||
|
'wcdb_get_group_members_batch',
|
||||||
|
'wcdb_start_monitor_pipe',
|
||||||
|
'wcdb_msg_insert_get_switches',
|
||||||
|
'wcdb_msg_insert_inspect_shard',
|
||||||
|
'wcdb_msg_insert_list_shard_catalog',
|
||||||
|
'wcdb_msg_insert_get_rooms_status'
|
||||||
|
]
|
||||||
|
const PUBLIC_ALLOWED_MSG_INSERT = new Set([
|
||||||
|
'wcdb_msg_insert_get_switches',
|
||||||
|
'wcdb_msg_insert_inspect_shard',
|
||||||
|
'wcdb_msg_insert_list_shard_catalog',
|
||||||
|
'wcdb_msg_insert_get_rooms_status'
|
||||||
|
])
|
||||||
|
const PROTECTED_RESOURCE_PATHS = ['runtime/runtime.zip']
|
||||||
|
|
||||||
|
function sha256(filePath) {
|
||||||
|
return createHash('sha256').update(fs.readFileSync(filePath)).digest('hex')
|
||||||
|
}
|
||||||
|
|
||||||
|
function resolveWcdbDistRoot() {
|
||||||
|
const configured = process.env.TRACEMEMO_WCDB_DIST_ROOT
|
||||||
|
const candidates = [
|
||||||
|
configured,
|
||||||
|
path.resolve(ROOT, '..', 'wcdb-dist', 'build', 'macos-package-universal'),
|
||||||
|
path.resolve(ROOT, '..', '..', 'workspace', 'wcdb-dist', 'build', 'macos-package-universal')
|
||||||
|
].filter(Boolean)
|
||||||
|
return candidates.find((candidate) => fs.existsSync(candidate)) || candidates[0]
|
||||||
|
}
|
||||||
|
|
||||||
|
function findNativeBundleRoot(root) {
|
||||||
|
if (!fs.existsSync(root)) return root
|
||||||
|
const pending = [{ directory: root, depth: 0 }]
|
||||||
|
while (pending.length) {
|
||||||
|
const { directory, depth } = pending.shift()
|
||||||
|
const manifest = path.join(directory, 'manifest.json')
|
||||||
|
if (fs.existsSync(manifest)) {
|
||||||
|
try {
|
||||||
|
const parsed = JSON.parse(fs.readFileSync(manifest, 'utf8'))
|
||||||
|
if (
|
||||||
|
parsed.platform === 'macos' &&
|
||||||
|
parsed.architecture === 'arm64' &&
|
||||||
|
Array.isArray(parsed.files)
|
||||||
|
) {
|
||||||
|
return directory
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
// Ignore unrelated manifests while locating the native runtime bundle.
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (depth >= 3) continue
|
||||||
|
for (const entry of fs.readdirSync(directory, { withFileTypes: true })) {
|
||||||
|
if (entry.isDirectory())
|
||||||
|
pending.push({ directory: path.join(directory, entry.name), depth: depth + 1 })
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return root
|
||||||
|
}
|
||||||
|
|
||||||
|
function run(command, args) {
|
||||||
|
return execFileSync(command, args, { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] })
|
||||||
|
}
|
||||||
|
|
||||||
|
function binaryArchitectures(filePath) {
|
||||||
|
return readBinaryArchitectures(filePath)
|
||||||
|
}
|
||||||
|
|
||||||
|
function exportedSymbols(filePath) {
|
||||||
|
return run('/usr/bin/nm', ['-gU', filePath])
|
||||||
|
.split(/\r?\n/)
|
||||||
|
.map((line) => line.trim().split(/\s+/).pop())
|
||||||
|
.filter(Boolean)
|
||||||
|
.map((symbol) => symbol.replace(/^_/, ''))
|
||||||
|
}
|
||||||
|
|
||||||
|
function assertArm64(filePath, label) {
|
||||||
|
if (!binaryArchitectures(filePath).includes('arm64')) {
|
||||||
|
throw new Error(`${label} does not contain arm64: ${filePath}`)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function validateLicenseStatusRoute(hostPath) {
|
||||||
|
if (!fs.readFileSync(hostPath).includes(Buffer.from('/license/status'))) {
|
||||||
|
throw new Error(`Native Host does not implement GET /license/status: ${hostPath}`)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function validateWcdbPair(apiPath, dependencyPath, profile) {
|
||||||
|
if (!fs.existsSync(apiPath) || !fs.existsSync(dependencyPath)) {
|
||||||
|
throw new Error(`Missing ${profile} WCDB library pair: ${apiPath}`)
|
||||||
|
}
|
||||||
|
assertArm64(apiPath, `${profile} WCDB API`)
|
||||||
|
assertArm64(dependencyPath, `${profile} WCDB companion`)
|
||||||
|
const symbols = exportedSymbols(apiPath)
|
||||||
|
const missing = (profile === 'public' ? REQUIRED_PUBLIC_SYMBOLS : REQUIRED_NATIVE_SYMBOLS).filter(
|
||||||
|
(symbol) => !symbols.includes(symbol)
|
||||||
|
)
|
||||||
|
if (missing.length)
|
||||||
|
throw new Error(`${profile} WCDB API is missing exports: ${missing.join(', ')}`)
|
||||||
|
if (profile === 'public') {
|
||||||
|
const leaked = symbols.filter(
|
||||||
|
(symbol) => symbol.startsWith('wcdb_msg_insert_') && !PUBLIC_ALLOWED_MSG_INSERT.has(symbol)
|
||||||
|
)
|
||||||
|
if (leaked.length) {
|
||||||
|
throw new Error(
|
||||||
|
`Public WCDB API contains forbidden message-insert exports: ${leaked.join(', ')}`
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const dependencies = run('/usr/bin/otool', ['-L', apiPath])
|
||||||
|
if (!dependencies.includes('@loader_path/libWCDB.dylib')) {
|
||||||
|
throw new Error(`${profile} WCDB API does not resolve libWCDB.dylib via @loader_path`)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function readAndValidateNativeManifest(bundleRoot) {
|
||||||
|
const manifestPath = path.join(bundleRoot, 'manifest.json')
|
||||||
|
const manifest = JSON.parse(fs.readFileSync(manifestPath, 'utf8'))
|
||||||
|
if (manifest.platform !== 'macos' || manifest.architecture !== 'arm64') {
|
||||||
|
throw new Error('Native bundle manifest must target macos-arm64')
|
||||||
|
}
|
||||||
|
if (!Array.isArray(manifest.files) || manifest.files.length !== 7) {
|
||||||
|
throw new Error(
|
||||||
|
'Native bundle manifest must list exactly seven files (six runtime/wcdb artifacts plus libtmlicense.dylib)'
|
||||||
|
)
|
||||||
|
}
|
||||||
|
const normalized = new Set()
|
||||||
|
const listedNativePaths = new Set()
|
||||||
|
for (const entry of manifest.files) {
|
||||||
|
if (
|
||||||
|
!entry ||
|
||||||
|
typeof entry.path !== 'string' ||
|
||||||
|
!/^tracememo\/(runtime|wcdb)\//.test(entry.path)
|
||||||
|
) {
|
||||||
|
throw new Error('Native bundle manifest contains an unexpected resource path')
|
||||||
|
}
|
||||||
|
if (normalized.has(entry.path) || !/^[a-f0-9]{64}$/.test(entry.sha256 || '')) {
|
||||||
|
throw new Error(`Invalid native bundle manifest entry: ${String(entry.path)}`)
|
||||||
|
}
|
||||||
|
normalized.add(entry.path)
|
||||||
|
const source = path.join(bundleRoot, entry.path)
|
||||||
|
const stat = fs.statSync(source)
|
||||||
|
if (!stat.isFile() || stat.size !== entry.bytes || sha256(source) !== entry.sha256) {
|
||||||
|
throw new Error(`Native bundle manifest verification failed: ${entry.path}`)
|
||||||
|
}
|
||||||
|
listedNativePaths.add(entry.path)
|
||||||
|
if (/\/runtime\/(tm-wechat-host|libtmwechat\.dylib|libtmlicense\.dylib)$/.test(entry.path)) {
|
||||||
|
if (!binaryArchitectures(source).includes('arm64')) {
|
||||||
|
throw new Error(`Native runtime binary is not arm64: ${entry.path}`)
|
||||||
|
}
|
||||||
|
if (entry.path.endsWith('libtmlicense.dylib')) {
|
||||||
|
const signature = run('/usr/bin/codesign', ['--verify', '--strict', source])
|
||||||
|
if (signature.trim() !== '') {
|
||||||
|
throw new Error(`libtmlicense.dylib code signature is invalid: ${signature.trim()}`)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (/\/wcdb\/(libwcdb_api\.dylib|tm-wcdb-config-helper)$/.test(entry.path)) {
|
||||||
|
if (!binaryArchitectures(source).includes('arm64')) {
|
||||||
|
throw new Error(`Native WCDB binary is not arm64: ${entry.path}`)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const expected = [
|
||||||
|
'tracememo/runtime/libtmlicense.dylib',
|
||||||
|
'tracememo/runtime/libtmwechat.dylib',
|
||||||
|
'tracememo/runtime/runtime-manifest.json',
|
||||||
|
'tracememo/runtime/tm-wechat-host',
|
||||||
|
'tracememo/wcdb/libWCDB.dylib',
|
||||||
|
'tracememo/wcdb/libwcdb_api.dylib',
|
||||||
|
'tracememo/wcdb/tm-wcdb-config-helper'
|
||||||
|
]
|
||||||
|
if (expected.some((entry) => !normalized.has(entry))) {
|
||||||
|
throw new Error('Native bundle manifest file list is incomplete')
|
||||||
|
}
|
||||||
|
if (listedNativePaths.size !== expected.length)
|
||||||
|
throw new Error('Native bundle manifest has unexpected files')
|
||||||
|
return { manifest, files: manifest.files }
|
||||||
|
}
|
||||||
|
|
||||||
|
function validateNativeBundle(bundleRoot, files) {
|
||||||
|
const bySuffix = (suffix) => {
|
||||||
|
const entry = files.find((file) => file.path.endsWith(suffix))
|
||||||
|
if (!entry) throw new Error(`Missing native bundle manifest path: ${suffix}`)
|
||||||
|
return path.join(bundleRoot, entry.path)
|
||||||
|
}
|
||||||
|
const api = bySuffix('/wcdb/libwcdb_api.dylib')
|
||||||
|
const companion = bySuffix('/wcdb/libWCDB.dylib')
|
||||||
|
const helper = bySuffix('/wcdb/tm-wcdb-config-helper')
|
||||||
|
const host = bySuffix('/runtime/tm-wechat-host')
|
||||||
|
const runtimeDylib = bySuffix('/runtime/libtmwechat.dylib')
|
||||||
|
const runtimeManifestPath = bySuffix('/runtime/runtime-manifest.json')
|
||||||
|
const licenseDylib = bySuffix('/runtime/libtmlicense.dylib')
|
||||||
|
validateLicenseStatusRoute(host)
|
||||||
|
validateWcdbPair(api, companion, 'native')
|
||||||
|
for (const [binary, label] of [
|
||||||
|
[helper, 'WCDB helper'],
|
||||||
|
[host, 'WeChat host'],
|
||||||
|
[runtimeDylib, 'WeChat runtime'],
|
||||||
|
[licenseDylib, 'License core']
|
||||||
|
]) {
|
||||||
|
assertArm64(binary, label)
|
||||||
|
}
|
||||||
|
// libtmlicense must carry a valid ad-hoc signature; it is dlopen'd at runtime.
|
||||||
|
const licenseSignature = run('/usr/bin/codesign', ['--verify', '--strict', licenseDylib])
|
||||||
|
if (licenseSignature.trim() !== '') {
|
||||||
|
throw new Error(`libtmlicense.dylib code signature is invalid: ${licenseSignature.trim()}`)
|
||||||
|
}
|
||||||
|
if (!run('/usr/bin/otool', ['-L', helper]).includes('@loader_path/libwcdb_api.dylib')) {
|
||||||
|
throw new Error('WCDB helper does not resolve its API dylib via @loader_path')
|
||||||
|
}
|
||||||
|
const bundleManifest = JSON.parse(fs.readFileSync(path.join(bundleRoot, 'manifest.json'), 'utf8'))
|
||||||
|
const runtimeDependencies = run('/usr/bin/otool', ['-L', runtimeDylib])
|
||||||
|
if (!bundleManifest.compatibility || bundleManifest.proWcdbAbiVersion !== 1) {
|
||||||
|
throw new Error('Native bundle manifest does not declare the expected WCDB ABI')
|
||||||
|
}
|
||||||
|
const runtimeManifest = JSON.parse(fs.readFileSync(runtimeManifestPath, 'utf8'))
|
||||||
|
if (
|
||||||
|
runtimeManifest.platform !== 'darwin-arm64' ||
|
||||||
|
runtimeManifest.architecture !== 'arm64' ||
|
||||||
|
runtimeManifest.protocolVersion !== 1
|
||||||
|
) {
|
||||||
|
throw new Error('Runtime manifest platform, architecture, or protocol is invalid')
|
||||||
|
}
|
||||||
|
if (runtimeManifest.runtime !== 'tm-wechat-native') throw new Error('Runtime name is invalid')
|
||||||
|
if (
|
||||||
|
!Array.isArray(runtimeManifest.supportedWechatVersions) ||
|
||||||
|
runtimeManifest.supportedWechatVersions.length === 0
|
||||||
|
) {
|
||||||
|
throw new Error('Runtime manifest has no supported WeChat versions')
|
||||||
|
}
|
||||||
|
for (const capability of ['text', 'image', 'voice']) {
|
||||||
|
if (
|
||||||
|
!Array.isArray(runtimeManifest.capabilities) ||
|
||||||
|
!runtimeManifest.capabilities.includes(capability)
|
||||||
|
) {
|
||||||
|
throw new Error(`Runtime manifest is missing capability: ${capability}`)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const runtimeBytes = fs.readFileSync(runtimeDylib)
|
||||||
|
for (const key of ['tmSendSourceSha256', 'addressProfileSha256']) {
|
||||||
|
if (
|
||||||
|
!/^[a-f0-9]{64}$/.test(runtimeManifest[key] || '') ||
|
||||||
|
!runtimeBytes.includes(Buffer.from(runtimeManifest[key]))
|
||||||
|
) {
|
||||||
|
throw new Error(`Runtime dylib does not contain the manifest ${key}`)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const apiDependencies = run('/usr/bin/otool', ['-L', api])
|
||||||
|
if (!apiDependencies.includes('@loader_path/libWCDB.dylib'))
|
||||||
|
throw new Error('WCDB companion dependency missing')
|
||||||
|
if (!run('/usr/bin/otool', ['-L', host]).includes('libSystem')) {
|
||||||
|
throw new Error('Host is missing its system runtime dependency')
|
||||||
|
}
|
||||||
|
if (
|
||||||
|
runtimeDependencies.includes('@rpath/libtmwechat.dylib') &&
|
||||||
|
!runtimeDependencies.includes('/usr/lib/libSystem')
|
||||||
|
) {
|
||||||
|
throw new Error('Runtime dylib is missing required system dependencies')
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function assertStagingTargetDoesNotExist(stageRoot, outputRoot) {
|
||||||
|
for (const target of [stageRoot, outputRoot]) {
|
||||||
|
if (fs.existsSync(target))
|
||||||
|
throw new Error(`Refusing to overwrite existing build target: ${target}`)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function copyPublicResources(sourceResources, destination) {
|
||||||
|
for (const relative of PUBLIC_FILES) {
|
||||||
|
const source = path.join(sourceResources, relative)
|
||||||
|
if (!fs.existsSync(source)) throw new Error(`Missing public resource: ${source}`)
|
||||||
|
fs.mkdirSync(path.dirname(path.join(destination, relative)), { recursive: true })
|
||||||
|
fs.copyFileSync(source, path.join(destination, relative), fs.constants.COPYFILE_EXCL)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function copyFfmpegLicenses(destination) {
|
||||||
|
const suppliedLicenseRoot = String(process.env.TRACEMEMO_FFMPEG_LICENSE_DIR || '').trim()
|
||||||
|
const packageRoot = suppliedLicenseRoot || path.dirname(require.resolve('ffmpeg-static/package.json'))
|
||||||
|
const files = suppliedLicenseRoot
|
||||||
|
? [
|
||||||
|
['LICENSE', 'LICENSE', 'licenses/ffmpeg-static/LICENSE'],
|
||||||
|
['FFMPEG-LICENSE.txt', 'FFMPEG-LICENSE.txt', 'licenses/ffmpeg-static/FFMPEG-LICENSE.txt'],
|
||||||
|
['FFMPEG-BUILD-INFO.txt', 'FFMPEG-BUILD-INFO.txt', 'licenses/ffmpeg-static/FFMPEG-BUILD-INFO.txt']
|
||||||
|
]
|
||||||
|
: FFMPEG_LICENSE_FILES.map(([source, relative]) => [source, source, relative])
|
||||||
|
for (const [sourceName, inputName, destinationRelative] of files) {
|
||||||
|
const source = path.join(packageRoot, inputName)
|
||||||
|
if (!fs.existsSync(source)) throw new Error(`Missing FFmpeg license/source notice: ${source}`)
|
||||||
|
const target = path.join(destination, destinationRelative)
|
||||||
|
fs.mkdirSync(path.dirname(target), { recursive: true })
|
||||||
|
fs.copyFileSync(source, target, fs.constants.COPYFILE_EXCL)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function copyNative(source, destination) {
|
||||||
|
fs.mkdirSync(path.dirname(destination), { recursive: true })
|
||||||
|
fs.copyFileSync(source, destination, fs.constants.COPYFILE_EXCL)
|
||||||
|
}
|
||||||
|
|
||||||
|
async function downloadFfmpegArm64(destination) {
|
||||||
|
const url =
|
||||||
|
'https://github.com/eugeneware/ffmpeg-static/releases/download/b6.1.1/ffmpeg-darwin-arm64.gz'
|
||||||
|
const archivePath = `${destination}.gz`
|
||||||
|
await new Promise((resolve, reject) => {
|
||||||
|
const request = (target) =>
|
||||||
|
https.get(target, (response) => {
|
||||||
|
if (response.statusCode >= 300 && response.statusCode < 400 && response.headers.location) {
|
||||||
|
response.resume()
|
||||||
|
request(response.headers.location)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if (response.statusCode !== 200) {
|
||||||
|
response.resume()
|
||||||
|
reject(new Error(`FFmpeg download failed with HTTP ${response.statusCode}`))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
const output = fs.createWriteStream(archivePath, { flags: 'wx' })
|
||||||
|
pipeline(response, output).then(resolve, reject)
|
||||||
|
})
|
||||||
|
request(url).on('error', reject)
|
||||||
|
})
|
||||||
|
await pipeline(
|
||||||
|
fs.createReadStream(archivePath),
|
||||||
|
createGunzip(),
|
||||||
|
fs.createWriteStream(destination, { flags: 'wx' })
|
||||||
|
)
|
||||||
|
fs.unlinkSync(archivePath)
|
||||||
|
fs.chmodSync(destination, 0o755)
|
||||||
|
assertArm64(destination, 'Staged FFmpeg')
|
||||||
|
}
|
||||||
|
|
||||||
|
async function prepareFfmpeg(stagedResources) {
|
||||||
|
const destination = path.join(stagedResources, 'ffmpeg', 'ffmpeg')
|
||||||
|
fs.mkdirSync(path.dirname(destination), { recursive: true })
|
||||||
|
const supplied = process.env.TRACEMEMO_FFMPEG_ARM64_PATH
|
||||||
|
if (supplied) {
|
||||||
|
assertArm64(supplied, 'Provided FFmpeg')
|
||||||
|
copyNative(supplied, destination)
|
||||||
|
fs.chmodSync(destination, 0o755)
|
||||||
|
return sha256(destination)
|
||||||
|
}
|
||||||
|
await downloadFfmpegArm64(destination)
|
||||||
|
return sha256(destination)
|
||||||
|
}
|
||||||
|
|
||||||
|
function assertNoProtectedInputs(root) {
|
||||||
|
for (const relative of ['1.txt']) {
|
||||||
|
if (fs.existsSync(path.join(ROOT, relative))) {
|
||||||
|
throw new Error(`Protected file must not be used as a build input: ${relative}`)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for (const relative of PROTECTED_RESOURCE_PATHS) {
|
||||||
|
if (fs.existsSync(path.join(root, relative))) {
|
||||||
|
throw new Error(`Protected file must not be used as a build input: ${relative}`)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function prepareEdition(edition) {
|
||||||
|
if (edition !== 'public' && edition !== 'native')
|
||||||
|
throw new Error('Usage: prepare-macos-edition.cjs <public|native>')
|
||||||
|
const roots = resolveEditionRoots()
|
||||||
|
const stageRoot = path.join(roots.stageRoot, edition)
|
||||||
|
const outputRoot = path.join(roots.outputRoot, edition)
|
||||||
|
assertStagingTargetDoesNotExist(stageRoot, outputRoot)
|
||||||
|
|
||||||
|
const sourceResources = path.join(ROOT, 'resources')
|
||||||
|
assertNoProtectedInputs(sourceResources)
|
||||||
|
fs.mkdirSync(path.dirname(stageRoot), { recursive: true })
|
||||||
|
fs.mkdirSync(stageRoot)
|
||||||
|
try {
|
||||||
|
const stagedResources = path.join(stageRoot, 'resources')
|
||||||
|
fs.mkdirSync(stagedResources, { recursive: true })
|
||||||
|
copyPublicResources(sourceResources, stagedResources)
|
||||||
|
copyFfmpegLicenses(stagedResources)
|
||||||
|
const ffmpegSha256 = await prepareFfmpeg(stagedResources)
|
||||||
|
|
||||||
|
const marker = {
|
||||||
|
profile: edition,
|
||||||
|
appVersion: require(path.join(ROOT, 'package.json')).version,
|
||||||
|
ffmpegSha256,
|
||||||
|
ffmpegLicenseSource: process.env.TRACEMEMO_FFMPEG_LICENSE_DIR
|
||||||
|
? 'provided verified license files'
|
||||||
|
: 'ffmpeg-static package',
|
||||||
|
ffmpegLicenseSha256: Object.fromEntries(
|
||||||
|
FFMPEG_LICENSE_FILES.map(([, relative]) => [relative, sha256(path.join(stagedResources, relative))])
|
||||||
|
)
|
||||||
|
}
|
||||||
|
if (edition === 'public') {
|
||||||
|
const api = path.join(WCDB_DIST_ROOT, 'libwcdb_api.dylib')
|
||||||
|
const companion = path.join(WCDB_DIST_ROOT, 'libWCDB.dylib')
|
||||||
|
validateWcdbPair(api, companion, 'public')
|
||||||
|
copyNative(api, path.join(stagedResources, 'wcdb', 'macos', 'arm64', 'libwcdb_api.dylib'))
|
||||||
|
copyNative(companion, path.join(stagedResources, 'wcdb', 'macos', 'arm64', 'libWCDB.dylib'))
|
||||||
|
marker.nativeInput = {
|
||||||
|
source: path.relative(ROOT, WCDB_DIST_ROOT),
|
||||||
|
libwcdbApiSha256: sha256(api),
|
||||||
|
libWCDBSha256: sha256(companion)
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
const { manifest, files } = readAndValidateNativeManifest(NATIVE_BUNDLE_ROOT)
|
||||||
|
validateNativeBundle(NATIVE_BUNDLE_ROOT, files)
|
||||||
|
for (const entry of files) {
|
||||||
|
const remainder = entry.path.replace(/^tracememo\//, '')
|
||||||
|
let relative
|
||||||
|
if (remainder === 'runtime/libtmlicense.dylib') {
|
||||||
|
// libtmlicense 只给 WCDB helper 用(main 进程的内嵌授权核是静态编译进
|
||||||
|
// libtmwechat.dylib 的)。放到 helper 同目录,helper 的 dlopen 候选路径
|
||||||
|
// <exe dir>/libtmlicense.dylib 才能命中;放 runtime/ 子目录会让
|
||||||
|
// helper 找不到它而 fail-closed。
|
||||||
|
relative = path.join('wcdb', 'macos', 'arm64', 'libtmlicense.dylib')
|
||||||
|
} else if (remainder.startsWith('runtime/')) {
|
||||||
|
relative = path.join(remainder.replace(/^runtime\//, 'runtime/darwin-arm64/'))
|
||||||
|
} else {
|
||||||
|
relative = path.join('wcdb', 'macos', 'arm64', remainder.replace(/^wcdb\//, ''))
|
||||||
|
}
|
||||||
|
copyNative(path.join(NATIVE_BUNDLE_ROOT, entry.path), path.join(stagedResources, relative))
|
||||||
|
}
|
||||||
|
marker.nativeInput = {
|
||||||
|
bundleVersion: manifest.bundleVersion,
|
||||||
|
manifestSha256: sha256(path.join(NATIVE_BUNDLE_ROOT, 'manifest.json')),
|
||||||
|
files: files.map(({ path: relative, sha256: digest, bytes }) => ({
|
||||||
|
path: relative,
|
||||||
|
sha256: digest,
|
||||||
|
bytes
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
for (const relative of ['1.txt', 'runtime/runtime.zip']) {
|
||||||
|
if (fs.existsSync(path.join(stagedResources, relative))) {
|
||||||
|
throw new Error(`Protected file leaked into ${edition} staging: ${relative}`)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
fs.writeFileSync(
|
||||||
|
path.join(stagedResources, 'tracememo-build.json'),
|
||||||
|
`${JSON.stringify(marker, null, 2)}\n`,
|
||||||
|
{ flag: 'wx' }
|
||||||
|
)
|
||||||
|
console.log(`[prepare-macos-edition] ${edition} resources staged at ${stagedResources}`)
|
||||||
|
} catch (error) {
|
||||||
|
fs.rmSync(stageRoot, { recursive: true, force: true })
|
||||||
|
throw error
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function validateStagedEdition(edition) {
|
||||||
|
if (edition !== 'public' && edition !== 'native')
|
||||||
|
throw new Error('Usage: validate staged edition <public|native>')
|
||||||
|
const resources = path.join(resolveEditionRoots().stageRoot, edition, 'resources')
|
||||||
|
const markerPath = path.join(resources, 'tracememo-build.json')
|
||||||
|
if (!fs.existsSync(markerPath)) throw new Error(`Missing staged edition marker: ${markerPath}`)
|
||||||
|
const marker = JSON.parse(fs.readFileSync(markerPath, 'utf8'))
|
||||||
|
if (
|
||||||
|
marker.profile !== edition ||
|
||||||
|
marker.appVersion !== require(path.join(ROOT, 'package.json')).version
|
||||||
|
) {
|
||||||
|
throw new Error('Staged edition marker does not match the expected edition/version')
|
||||||
|
}
|
||||||
|
if (!/^[a-f0-9]{64}$/.test(marker.ffmpegSha256 || ''))
|
||||||
|
throw new Error('Staged FFmpeg hash is invalid')
|
||||||
|
const ffmpeg = path.join(resources, 'ffmpeg', 'ffmpeg')
|
||||||
|
if (!fs.existsSync(ffmpeg) || sha256(ffmpeg) !== marker.ffmpegSha256) {
|
||||||
|
throw new Error('Staged FFmpeg SHA-256 does not match the edition marker')
|
||||||
|
}
|
||||||
|
assertArm64(ffmpeg, 'Staged FFmpeg')
|
||||||
|
for (const [, relative] of FFMPEG_LICENSE_FILES) {
|
||||||
|
const licensePath = path.join(resources, relative)
|
||||||
|
const expected = marker.ffmpegLicenseSha256?.[relative]
|
||||||
|
if (!fs.existsSync(licensePath) || !/^[a-f0-9]{64}$/.test(expected || '') || sha256(licensePath) !== expected) {
|
||||||
|
throw new Error(`Staged FFmpeg license/source notice hash mismatch: ${relative}`)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const api = path.join(resources, 'wcdb', 'macos', 'arm64', 'libwcdb_api.dylib')
|
||||||
|
const companion = path.join(resources, 'wcdb', 'macos', 'arm64', 'libWCDB.dylib')
|
||||||
|
validateWcdbPair(api, companion, edition)
|
||||||
|
if (marker.nativeInput?.libwcdbApiSha256 && sha256(api) !== marker.nativeInput.libwcdbApiSha256) {
|
||||||
|
throw new Error('Staged public WCDB API does not match the recorded input hash')
|
||||||
|
}
|
||||||
|
if (marker.nativeInput?.libWCDBSha256 && sha256(companion) !== marker.nativeInput.libWCDBSha256) {
|
||||||
|
throw new Error('Staged public WCDB companion does not match the recorded input hash')
|
||||||
|
}
|
||||||
|
if (edition === 'native') {
|
||||||
|
const nativeManifest = marker.nativeInput?.files
|
||||||
|
if (!Array.isArray(nativeManifest) || nativeManifest.length !== 7) {
|
||||||
|
throw new Error(
|
||||||
|
'Staged native bundle is missing its verified source manifest (expected seven files)'
|
||||||
|
)
|
||||||
|
}
|
||||||
|
for (const item of nativeManifest) {
|
||||||
|
const relative = item.path.replace(/^tracememo\//, '')
|
||||||
|
let stagedRelative
|
||||||
|
if (relative === 'runtime/libtmlicense.dylib') {
|
||||||
|
stagedRelative = path.join('wcdb', 'macos', 'arm64', 'libtmlicense.dylib')
|
||||||
|
} else if (relative.startsWith('runtime/')) {
|
||||||
|
stagedRelative = relative.replace(/^runtime\//, 'runtime/darwin-arm64/')
|
||||||
|
} else {
|
||||||
|
stagedRelative = path.join('wcdb', 'macos', 'arm64', relative.replace(/^wcdb\//, ''))
|
||||||
|
}
|
||||||
|
const staged = path.join(resources, stagedRelative)
|
||||||
|
if (
|
||||||
|
!fs.existsSync(staged) ||
|
||||||
|
fs.statSync(staged).size !== item.bytes ||
|
||||||
|
sha256(staged) !== item.sha256
|
||||||
|
) {
|
||||||
|
throw new Error(`Staged native artifact hash mismatch: ${item.path}`)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
validateNativeBundleFromStaging(resources)
|
||||||
|
}
|
||||||
|
for (const relative of ['1.txt', 'runtime/runtime.zip']) {
|
||||||
|
if (fs.existsSync(path.join(resources, relative)))
|
||||||
|
throw new Error(`Protected file leaked into staging: ${relative}`)
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
edition,
|
||||||
|
appVersion: marker.appVersion,
|
||||||
|
apiSha256: sha256(api),
|
||||||
|
companionSha256: sha256(companion),
|
||||||
|
ffmpegSha256: sha256(ffmpeg)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function validateNativeBundleFromStaging(resources) {
|
||||||
|
const api = path.join(resources, 'wcdb', 'macos', 'arm64', 'libwcdb_api.dylib')
|
||||||
|
const companion = path.join(resources, 'wcdb', 'macos', 'arm64', 'libWCDB.dylib')
|
||||||
|
const helper = path.join(resources, 'wcdb', 'macos', 'arm64', 'tm-wcdb-config-helper')
|
||||||
|
const licenseDylib = path.join(resources, 'wcdb', 'macos', 'arm64', 'libtmlicense.dylib')
|
||||||
|
const host = path.join(resources, 'runtime', 'darwin-arm64', 'tm-wechat-host')
|
||||||
|
const runtimeDylib = path.join(resources, 'runtime', 'darwin-arm64', 'libtmwechat.dylib')
|
||||||
|
const runtimeManifestPath = path.join(
|
||||||
|
resources,
|
||||||
|
'runtime',
|
||||||
|
'darwin-arm64',
|
||||||
|
'runtime-manifest.json'
|
||||||
|
)
|
||||||
|
if (!fs.existsSync(licenseDylib)) {
|
||||||
|
throw new Error('Staged native edition is missing libtmlicense.dylib next to the WCDB helper')
|
||||||
|
}
|
||||||
|
const symbols = exportedSymbols(api)
|
||||||
|
const missing = REQUIRED_NATIVE_SYMBOLS.filter((symbol) => !symbols.includes(symbol))
|
||||||
|
if (missing.length) throw new Error(`Staged native WCDB ABI is missing: ${missing.join(', ')}`)
|
||||||
|
for (const [binary, label] of [
|
||||||
|
[companion, 'WCDB companion'],
|
||||||
|
[helper, 'WCDB helper'],
|
||||||
|
[licenseDylib, 'License core'],
|
||||||
|
[host, 'Host'],
|
||||||
|
[runtimeDylib, 'Runtime dylib']
|
||||||
|
]) {
|
||||||
|
assertArm64(binary, label)
|
||||||
|
}
|
||||||
|
// helper must be able to dlopen libtmlicense.dylib: it must sit in the same directory.
|
||||||
|
const licenseSignature = run('/usr/bin/codesign', ['--verify', '--strict', licenseDylib])
|
||||||
|
if (licenseSignature.trim() !== '') {
|
||||||
|
throw new Error(
|
||||||
|
`Staged libtmlicense.dylib code signature is invalid: ${licenseSignature.trim()}`
|
||||||
|
)
|
||||||
|
}
|
||||||
|
if (!run('/usr/bin/otool', ['-L', helper]).includes('@loader_path/libwcdb_api.dylib')) {
|
||||||
|
throw new Error('Staged helper lost its @loader_path WCDB dependency')
|
||||||
|
}
|
||||||
|
const runtimeManifest = JSON.parse(fs.readFileSync(runtimeManifestPath, 'utf8'))
|
||||||
|
const runtimeBytes = fs.readFileSync(runtimeDylib)
|
||||||
|
if (
|
||||||
|
runtimeManifest.runtime !== 'tm-wechat-native' ||
|
||||||
|
runtimeManifest.platform !== 'darwin-arm64' ||
|
||||||
|
runtimeManifest.architecture !== 'arm64' ||
|
||||||
|
runtimeManifest.protocolVersion !== 1
|
||||||
|
) {
|
||||||
|
throw new Error('Staged Runtime Manifest identity is invalid')
|
||||||
|
}
|
||||||
|
for (const key of ['tmSendSourceSha256', 'addressProfileSha256']) {
|
||||||
|
if (
|
||||||
|
!/^[a-f0-9]{64}$/.test(runtimeManifest[key] || '') ||
|
||||||
|
!runtimeBytes.includes(Buffer.from(runtimeManifest[key]))
|
||||||
|
) {
|
||||||
|
throw new Error(`Staged runtime hash verification failed: ${key}`)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (require.main === module) {
|
||||||
|
try {
|
||||||
|
prepareEdition(process.argv[2]).catch((error) => {
|
||||||
|
console.error(error instanceof Error ? error.message : String(error))
|
||||||
|
process.exitCode = 1
|
||||||
|
})
|
||||||
|
} catch (error) {
|
||||||
|
console.error(error instanceof Error ? error.message : String(error))
|
||||||
|
process.exitCode = 1
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = {
|
||||||
|
resolveEditionRoots,
|
||||||
|
validateLicenseStatusRoute,
|
||||||
|
assertNoProtectedInputs,
|
||||||
|
assertStagingTargetDoesNotExist,
|
||||||
|
copyPublicResources,
|
||||||
|
copyFfmpegLicenses,
|
||||||
|
downloadFfmpegArm64,
|
||||||
|
prepareFfmpeg,
|
||||||
|
prepareEdition,
|
||||||
|
validateNativeBundleFromStaging,
|
||||||
|
validateStagedEdition,
|
||||||
|
readAndValidateNativeManifest,
|
||||||
|
validateNativeBundle,
|
||||||
|
validateWcdbPair
|
||||||
|
}
|
||||||
@@ -1,436 +0,0 @@
|
|||||||
/*
|
|
||||||
* wechat_chatter runtime integration
|
|
||||||
*
|
|
||||||
* Upstream: https://github.com/yincongcyincong/wechat_chatter
|
|
||||||
* Runtime version: v0.0.18
|
|
||||||
* Upstream license: GNU General Public License version 3 (GPL-3.0)
|
|
||||||
*
|
|
||||||
* This file applies local compatibility patches to the upstream
|
|
||||||
* onebot/script.js. See docs/third-party/wechat-chatter/NOTICE.md.
|
|
||||||
*/
|
|
||||||
|
|
||||||
/* eslint-disable @typescript-eslint/explicit-function-return-type, @typescript-eslint/no-require-imports */
|
|
||||||
const { execFileSync } = require('node:child_process')
|
|
||||||
const fs = require('node:fs')
|
|
||||||
const os = require('node:os')
|
|
||||||
const path = require('node:path')
|
|
||||||
|
|
||||||
const release = 'v0.0.18'
|
|
||||||
const asset = 'onebot_mac_arm64.tar.gz'
|
|
||||||
const url = `https://github.com/yincongcyincong/wechat_chatter/releases/download/${release}/${asset}`
|
|
||||||
const projectRoot = path.resolve(__dirname, '..')
|
|
||||||
const outputDir = path.join(
|
|
||||||
projectRoot,
|
|
||||||
'resources',
|
|
||||||
'connectors',
|
|
||||||
'wechat-personal',
|
|
||||||
'darwin-arm64'
|
|
||||||
)
|
|
||||||
const archive = path.join(os.tmpdir(), `wechat-chatter-${release}-${asset}`)
|
|
||||||
const appleSilicon =
|
|
||||||
process.platform === 'darwin' &&
|
|
||||||
execFileSync('/usr/sbin/sysctl', ['-n', 'hw.optional.arm64'], { encoding: 'utf8' }).trim() === '1'
|
|
||||||
|
|
||||||
if (!appleSilicon) {
|
|
||||||
throw new Error('个人微信发送运行时当前仅支持 macOS arm64')
|
|
||||||
}
|
|
||||||
|
|
||||||
fs.mkdirSync(outputDir, { recursive: true })
|
|
||||||
let archiveReady = false
|
|
||||||
if (fs.existsSync(archive)) {
|
|
||||||
try {
|
|
||||||
execFileSync('/usr/bin/tar', ['-tzf', archive], { stdio: 'ignore' })
|
|
||||||
archiveReady = true
|
|
||||||
console.log(`[wechat-personal] 复用已下载归档:${archive}`)
|
|
||||||
} catch {
|
|
||||||
// The archive is partial or invalid; curl will resume it below.
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if (!archiveReady) {
|
|
||||||
console.log(`[wechat-personal] 下载 ${release},支持断点续传:${archive}`)
|
|
||||||
execFileSync(
|
|
||||||
'/usr/bin/curl',
|
|
||||||
['--http1.1', '-L', '--fail', '--retry', '3', '--continue-at', '-', '--output', archive, url],
|
|
||||||
{ stdio: 'inherit' }
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
const extractionDir = fs.mkdtempSync(path.join(os.tmpdir(), 'wechat-chatter-extract-'))
|
|
||||||
console.log(`[wechat-personal] 解压并原子安装到 ${outputDir}`)
|
|
||||||
try {
|
|
||||||
execFileSync('/usr/bin/tar', ['-xzf', archive, '-C', extractionDir], { stdio: 'inherit' })
|
|
||||||
fs.mkdirSync(path.join(outputDir, 'onebot'), { recursive: true })
|
|
||||||
fs.mkdirSync(path.join(outputDir, 'wechat_version'), { recursive: true })
|
|
||||||
fs.copyFileSync(
|
|
||||||
path.join(extractionDir, 'onebot', 'script.js'),
|
|
||||||
path.join(outputDir, 'onebot', 'script.js')
|
|
||||||
)
|
|
||||||
fs.cpSync(path.join(extractionDir, 'wechat_version'), path.join(outputDir, 'wechat_version'), {
|
|
||||||
recursive: true,
|
|
||||||
force: true
|
|
||||||
})
|
|
||||||
const stagedExecutable = path.join(outputDir, 'onebot', `.onebot-${process.pid}.tmp`)
|
|
||||||
fs.copyFileSync(path.join(extractionDir, 'onebot', 'onebot'), stagedExecutable)
|
|
||||||
fs.chmodSync(stagedExecutable, 0o755)
|
|
||||||
fs.renameSync(stagedExecutable, path.join(outputDir, 'onebot', 'onebot'))
|
|
||||||
} finally {
|
|
||||||
fs.rmSync(extractionDir, { recursive: true, force: true })
|
|
||||||
}
|
|
||||||
|
|
||||||
const executable = path.join(outputDir, 'onebot', 'onebot')
|
|
||||||
const script = path.join(outputDir, 'onebot', 'script.js')
|
|
||||||
const config = path.join(outputDir, 'wechat_version', '4_1_11_53_mac.json')
|
|
||||||
for (const required of [executable, script, config]) {
|
|
||||||
if (!fs.existsSync(required)) throw new Error(`运行时文件缺失:${required}`)
|
|
||||||
}
|
|
||||||
|
|
||||||
function patchPerSendPayload(scriptPath) {
|
|
||||||
let source = fs.readFileSync(scriptPath, 'utf8')
|
|
||||||
if (!source.includes('var activeTriggerX1Payload = ptr(0);')) return
|
|
||||||
|
|
||||||
const activeSend = ` const payloadData = hexToByteArray(payloadHex);
|
|
||||||
activeTriggerX1Payload = Memory.alloc(payloadData.length);
|
|
||||||
activeTriggerX1Payload.writeByteArray(payloadData);
|
|
||||||
activeTriggerX1Payload.add(0x18).writePointer(info.cgiAddr);
|
|
||||||
activeTriggerX1Payload.add(0xb8).writePointer(activeTriggerX1Payload.add(0xc0));
|
|
||||||
activeTriggerX1Payload.add(0x190).writePointer(activeTriggerX1Payload.add(0x198));`
|
|
||||||
const upstreamSend = ` const payloadData = hexToByteArray(payloadHex);
|
|
||||||
triggerX1Payload.writeByteArray(payloadData);
|
|
||||||
triggerX1Payload.add(0x18).writePointer(info.cgiAddr);
|
|
||||||
triggerX1Payload.add(0xb8).writePointer(triggerX1Payload.add(0xc0));
|
|
||||||
triggerX1Payload.add(0x190).writePointer(triggerX1Payload.add(0x198));`
|
|
||||||
if (!source.includes(activeSend)) throw new Error('无法定位 wechat_chatter 连续发送补丁位置')
|
|
||||||
source = source
|
|
||||||
.replace(
|
|
||||||
'var triggerX1Payload;\nvar activeTriggerX1Payload = ptr(0);\nvar triggerX0;',
|
|
||||||
'var triggerX1Payload;\nvar triggerX0;'
|
|
||||||
)
|
|
||||||
.replace(activeSend, upstreamSend)
|
|
||||||
.replace(
|
|
||||||
' MMStartTask(triggerX0, activeTriggerX1Payload);',
|
|
||||||
' MMStartTask(triggerX0, triggerX1Payload);'
|
|
||||||
)
|
|
||||||
.replace(
|
|
||||||
' activeTriggerX1Payload = ptr(0);\n console.error("[!] Error trigger " + msgType + " MMStartTask: " + e);',
|
|
||||||
' console.error("[!] Error trigger " + msgType + " MMStartTask: " + e);'
|
|
||||||
)
|
|
||||||
.replace(
|
|
||||||
'\t\t\t\tpendingSendMsgType = "";\n\t\t\t\tactiveTriggerX1Payload = ptr(0);\n\t\t\t\treturn',
|
|
||||||
'\t\t\t\tpendingSendMsgType = "";\n\t\t\t\treturn'
|
|
||||||
)
|
|
||||||
fs.writeFileSync(scriptPath, source)
|
|
||||||
console.log('[wechat-personal] 已恢复原生发送 payload 布局')
|
|
||||||
}
|
|
||||||
|
|
||||||
function patchSendContextCapture(scriptPath, strict = true) {
|
|
||||||
let source = fs.readFileSync(scriptPath, 'utf8')
|
|
||||||
if (source.includes('function isLikelySendContext(')) return
|
|
||||||
const original = `function AttachSendFunc() {
|
|
||||||
Interceptor.attach(sendFuncAddr.add(0x10), {
|
|
||||||
onEnter: function (args) {
|
|
||||||
|
|
||||||
if (triggerX1Payload) {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
triggerX0 = this.context.x0;
|
|
||||||
triggerX1Payload = this.context.x1;
|
|
||||||
console.log(\`[+] 捕获到 StartTask 调用,X0:\${triggerX0}, Payload: \${triggerX1Payload}\`);
|
|
||||||
}
|
|
||||||
})
|
|
||||||
}`
|
|
||||||
const patched = `function isLikelySendContext(candidateX0, candidateX1) {
|
|
||||||
try {
|
|
||||||
if (!isReadablePointer(candidateX0) || !isReadablePointer(candidateX1)) return false;
|
|
||||||
var manager = readPointerIfReadable(candidateX0.add(0x18));
|
|
||||||
var cgi = readUtf8StringIfReadable(readPointerIfReadable(candidateX1.add(0x18)));
|
|
||||||
console.log("[debug] StartTask candidate x0=" + candidateX0 + " x1=" + candidateX1 + " x0+0x18=" + manager + " cgi=" + cgi);
|
|
||||||
return !manager.equals(ptr(0));
|
|
||||||
} catch (e) {
|
|
||||||
console.error("[debug] StartTask candidate inspect failed: " + e);
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function AttachSendFunc() {
|
|
||||||
Interceptor.attach(sendFuncAddr.add(0x10), {
|
|
||||||
onEnter: function (args) {
|
|
||||||
if (triggerX1Payload) return;
|
|
||||||
var candidateX0 = this.context.x0;
|
|
||||||
var candidateX1 = this.context.x1;
|
|
||||||
if (!isLikelySendContext(candidateX0, candidateX1)) return;
|
|
||||||
triggerX0 = candidateX0;
|
|
||||||
triggerX1Payload = candidateX1;
|
|
||||||
console.log(\`[+] 捕获到有效 StartTask 上下文,X0:\${triggerX0}, Payload: \${triggerX1Payload}\`);
|
|
||||||
}
|
|
||||||
})
|
|
||||||
}`
|
|
||||||
if (!source.includes(original)) {
|
|
||||||
if (strict) throw new Error('无法定位 StartTask 上下文 Hook')
|
|
||||||
return
|
|
||||||
}
|
|
||||||
source = source.replace(original, patched)
|
|
||||||
fs.writeFileSync(scriptPath, source)
|
|
||||||
}
|
|
||||||
|
|
||||||
function patchVoiceAudioBuffer(scriptPath) {
|
|
||||||
let source = fs.readFileSync(scriptPath, 'utf8')
|
|
||||||
if (source.includes('voiceAudioDataAddr = Memory.alloc(audioLen + 1);')) return
|
|
||||||
|
|
||||||
const staticAllocation = 'voiceAudioDataAddr = Memory.alloc(5 * 1024 * 1024); // 预分配5MB'
|
|
||||||
if (!source.includes(staticAllocation)) {
|
|
||||||
throw new Error('无法定位 wechat_chatter 语音缓冲区')
|
|
||||||
}
|
|
||||||
source = source.replace(
|
|
||||||
staticAllocation,
|
|
||||||
'voiceAudioDataAddr = Memory.alloc(1); // 上传前按语音长度重新分配'
|
|
||||||
)
|
|
||||||
const audioLengthMarker = ' const audioLen = audioBytes.length;\n'
|
|
||||||
if (!source.includes(audioLengthMarker)) {
|
|
||||||
throw new Error('无法定位 wechat_chatter 语音上传逻辑')
|
|
||||||
}
|
|
||||||
source = source.replace(
|
|
||||||
audioLengthMarker,
|
|
||||||
`${audioLengthMarker} voiceAudioDataAddr = Memory.alloc(audioLen + 1);\n`
|
|
||||||
)
|
|
||||||
fs.writeFileSync(scriptPath, source)
|
|
||||||
console.log('[wechat-personal] 已应用按语音长度分配上传缓冲区补丁')
|
|
||||||
}
|
|
||||||
|
|
||||||
function patchImageHookReadiness(scriptPath) {
|
|
||||||
let source = fs.readFileSync(scriptPath, 'utf8')
|
|
||||||
if (
|
|
||||||
source.includes('捕获到图片上传上下文,uploadGlobalX0') &&
|
|
||||||
source.includes('图片上传 Hook Setup Complete')
|
|
||||||
)
|
|
||||||
return
|
|
||||||
const original = `\t\t\tuploadGlobalX0 = this.context.x0;`
|
|
||||||
const patched = `\t\t\tconst capturedUploadX0 = this.context.x0;
|
|
||||||
\t\t\tif (uploadGlobalX0.equals(ptr(0)) && !capturedUploadX0.equals(ptr(0))) {
|
|
||||||
\t\t\t\tconsole.log("[+] 捕获到图片上传上下文,uploadGlobalX0:" + capturedUploadX0);
|
|
||||||
\t\t\t}
|
|
||||||
\t\t\tuploadGlobalX0 = capturedUploadX0;`
|
|
||||||
if (!source.includes(original)) throw new Error('无法定位 wechat_chatter 图片 Hook 状态补丁位置')
|
|
||||||
source = source.replace(original, patched)
|
|
||||||
source = source.replace(
|
|
||||||
' })\n}\n\n\n\nfunction patchCdnOnComplete()',
|
|
||||||
' })\n console.log("[+] 图片上传 Hook Setup Complete.");\n}\n\n\n\nfunction patchCdnOnComplete()'
|
|
||||||
)
|
|
||||||
fs.writeFileSync(scriptPath, source)
|
|
||||||
console.log('[wechat-personal] 已应用图片 Hook 状态补丁')
|
|
||||||
}
|
|
||||||
|
|
||||||
// Backport of wechat_chatter PR #36 by @Leslielu:
|
|
||||||
// https://github.com/yincongcyincong/wechat_chatter/pull/36
|
|
||||||
// TraceMemo adds the verified macOS WeChat 4.1.11.53 addresses.
|
|
||||||
// macOS WeChat 4.1.11.53, located and verified by TraceMemo
|
|
||||||
function patchCdnColdStart(scriptPath) {
|
|
||||||
let source = fs.readFileSync(scriptPath, 'utf8')
|
|
||||||
if (source.includes('function resolveCdnManager()')) return
|
|
||||||
|
|
||||||
const initAddresses = ` uploadImageAddr = baseAddr.add({{.uploadImageAddr}});
|
|
||||||
cndOnCompleteAddr = baseAddr.add({{.cndOnCompleteAddr}});`
|
|
||||||
const patchedInitAddresses = ` uploadImageAddr = baseAddr.add({{.uploadImageAddr}});
|
|
||||||
cndOnCompleteAddr = baseAddr.add({{.cndOnCompleteAddr}});
|
|
||||||
// 冷启动 CdnManager 解析(旧版本缺少可选键时保持 hook 捕获行为)
|
|
||||||
{{if .cdnGetServiceAddr}}cdnGetServiceAddr = baseAddr.add({{.cdnGetServiceAddr}});{{end}}
|
|
||||||
{{if .cdnManagerGetterAddr}}cdnManagerGetterAddr = baseAddr.add({{.cdnManagerGetterAddr}});{{end}}`
|
|
||||||
if (!source.includes(initAddresses)) throw new Error('下载的微信版本配置与当前应用不兼容')
|
|
||||||
source = source.replace(initAddresses, patchedInitAddresses)
|
|
||||||
|
|
||||||
const downloadChunkEnd = `}
|
|
||||||
|
|
||||||
function fillUploadX1AndStart`
|
|
||||||
const resolver = `}
|
|
||||||
|
|
||||||
// 上传和下载共用同一个 mars::cdn::CdnManager。冷启动时通过服务定位器
|
|
||||||
// 取得 [ctx + 0x40],避免必须先手动发送图片才能让 Hook 捕获上下文。
|
|
||||||
function resolveCdnManager() {
|
|
||||||
if (cdnGetServiceAddr.equals(ptr(0)) || cdnManagerGetterAddr.equals(ptr(0))) {
|
|
||||||
return ptr(0);
|
|
||||||
}
|
|
||||||
try {
|
|
||||||
// libc++ SSO 短字符串:数据在 +0,长度写在 +0x17。
|
|
||||||
var strDefault = Memory.alloc(24);
|
|
||||||
strDefault.writeUtf8String("default");
|
|
||||||
strDefault.add(0x17).writeU8(7);
|
|
||||||
|
|
||||||
var getService = new NativeFunction(cdnGetServiceAddr, 'pointer', ['pointer']);
|
|
||||||
var svc = getService(strDefault);
|
|
||||||
if (!isReadablePointer(svc)) {
|
|
||||||
console.error("[!] GetService(\\"default\\") 返回不可读: " + svc);
|
|
||||||
return ptr(0);
|
|
||||||
}
|
|
||||||
var getCtx = new NativeFunction(cdnManagerGetterAddr, 'pointer', ['pointer']);
|
|
||||||
var ctx = getCtx(svc);
|
|
||||||
if (!isReadablePointer(ctx)) {
|
|
||||||
console.error("[!] CdnManager getter 返回不可读: " + ctx);
|
|
||||||
return ptr(0);
|
|
||||||
}
|
|
||||||
var mgr = readPointerIfReadable(ctx.add(0x40));
|
|
||||||
if (!isReadablePointer(mgr)) {
|
|
||||||
console.error("[!] ctx+0x40 管理器指针不可读: ctx=" + ctx);
|
|
||||||
return ptr(0);
|
|
||||||
}
|
|
||||||
return mgr;
|
|
||||||
} catch (e) {
|
|
||||||
console.error("[!] resolveCdnManager 异常: " + e);
|
|
||||||
return ptr(0);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function ensureCdnManagerX0() {
|
|
||||||
if (uploadGlobalX0.equals(ptr(0)) && downloadGlobalX0 && !downloadGlobalX0.equals(ptr(0))) {
|
|
||||||
uploadGlobalX0 = downloadGlobalX0;
|
|
||||||
console.log("[+] downloadGlobalX0 回填 uploadGlobalX0: " + uploadGlobalX0);
|
|
||||||
}
|
|
||||||
if ((!downloadGlobalX0 || downloadGlobalX0.equals(ptr(0))) && !uploadGlobalX0.equals(ptr(0))) {
|
|
||||||
downloadGlobalX0 = uploadGlobalX0;
|
|
||||||
console.log("[+] uploadGlobalX0 回填 downloadGlobalX0: " + downloadGlobalX0);
|
|
||||||
}
|
|
||||||
if (uploadGlobalX0.equals(ptr(0))) {
|
|
||||||
var mgr = resolveCdnManager();
|
|
||||||
if (!mgr.equals(ptr(0))) {
|
|
||||||
uploadGlobalX0 = mgr;
|
|
||||||
if (!downloadGlobalX0 || downloadGlobalX0.equals(ptr(0))) {
|
|
||||||
downloadGlobalX0 = mgr;
|
|
||||||
}
|
|
||||||
console.log("[+] 冷启动服务定位器解析 CdnManager: " + mgr);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return !uploadGlobalX0.equals(ptr(0));
|
|
||||||
}
|
|
||||||
|
|
||||||
function fillUploadX1AndStart`
|
|
||||||
if (!source.includes(downloadChunkEnd)) throw new Error('无法定位 wechat_chatter 媒体上传逻辑')
|
|
||||||
source = source.replace(downloadChunkEnd, resolver)
|
|
||||||
|
|
||||||
const declarations = 'var uploadImageAddr;\n'
|
|
||||||
const patchedDeclarations =
|
|
||||||
'var uploadImageAddr;\nvar cdnGetServiceAddr = ptr(0);\nvar cdnManagerGetterAddr = ptr(0);\n'
|
|
||||||
if (!source.includes(declarations)) throw new Error('无法定位 wechat_chatter 媒体地址声明')
|
|
||||||
source = source.replace(declarations, patchedDeclarations)
|
|
||||||
|
|
||||||
const uploadGuard = `function fillUploadX1AndStart(idAddr, pathAddr, x1Buffer, receiver, md5, filePath, payloadHex) {
|
|
||||||
if (uploadGlobalX0.equals(ptr(0))) {`
|
|
||||||
const patchedUploadGuard = `function fillUploadX1AndStart(idAddr, pathAddr, x1Buffer, receiver, md5, filePath, payloadHex) {
|
|
||||||
if (uploadGlobalX0.equals(ptr(0))) {
|
|
||||||
ensureCdnManagerX0();
|
|
||||||
}
|
|
||||||
if (uploadGlobalX0.equals(ptr(0))) {`
|
|
||||||
if (!source.includes(uploadGuard)) throw new Error('无法定位 wechat_chatter 媒体上传入口')
|
|
||||||
source = source.replace(uploadGuard, patchedUploadGuard)
|
|
||||||
|
|
||||||
const voiceGuard = `function triggerUploadVoice(receiver, voicePath, payloadHex, audioDataHex, durationMs) {
|
|
||||||
if (uploadGlobalX0.equals(ptr(0))) {`
|
|
||||||
const patchedVoiceGuard = `function triggerUploadVoice(receiver, voicePath, payloadHex, audioDataHex, durationMs) {
|
|
||||||
if (uploadGlobalX0.equals(ptr(0))) {
|
|
||||||
ensureCdnManagerX0();
|
|
||||||
}
|
|
||||||
if (uploadGlobalX0.equals(ptr(0))) {`
|
|
||||||
if (!source.includes(voiceGuard)) throw new Error('无法定位 wechat_chatter 语音上传入口')
|
|
||||||
source = source.replace(voiceGuard, patchedVoiceGuard)
|
|
||||||
|
|
||||||
const uploadHook = `\t\t\tuploadGlobalX0 = capturedUploadX0;`
|
|
||||||
const patchedUploadHook = `\t\t\tuploadGlobalX0 = capturedUploadX0;
|
|
||||||
if ((!downloadGlobalX0 || downloadGlobalX0.equals(ptr(0))) && !capturedUploadX0.equals(ptr(0))) {
|
|
||||||
downloadGlobalX0 = capturedUploadX0;
|
|
||||||
console.log("[+] 上传hook回填 downloadGlobalX0: " + downloadGlobalX0);
|
|
||||||
}`
|
|
||||||
if (!source.includes(uploadHook)) throw new Error('无法定位 wechat_chatter 图片 Hook')
|
|
||||||
source = source.replace(uploadHook, patchedUploadHook)
|
|
||||||
|
|
||||||
const downloadHook = ` downloadGlobalX0 = this.context.x0;`
|
|
||||||
const patchedDownloadHook = ` downloadGlobalX0 = this.context.x0;
|
|
||||||
if (uploadGlobalX0.equals(ptr(0)) && !downloadGlobalX0.equals(ptr(0))) {
|
|
||||||
uploadGlobalX0 = downloadGlobalX0;
|
|
||||||
console.log("[+] 下载hook回填 uploadGlobalX0: " + uploadGlobalX0);
|
|
||||||
}`
|
|
||||||
if (!source.includes(downloadHook)) throw new Error('无法定位 wechat_chatter 下载 Hook')
|
|
||||||
source = source.replace(downloadHook, patchedDownloadHook)
|
|
||||||
|
|
||||||
const downloadGuard = `function triggerDownload(receiver, cdnUrl, aesKey, filePath, fileType) {
|
|
||||||
if (!downloadGlobalX0) {`
|
|
||||||
const patchedDownloadGuard = `function triggerDownload(receiver, cdnUrl, aesKey, filePath, fileType) {
|
|
||||||
if (!downloadGlobalX0 || downloadGlobalX0.equals(ptr(0))) {
|
|
||||||
ensureCdnManagerX0();
|
|
||||||
}
|
|
||||||
if (!downloadGlobalX0) {`
|
|
||||||
if (!source.includes(downloadGuard)) throw new Error('无法定位 wechat_chatter 媒体下载入口')
|
|
||||||
source = source.replace(downloadGuard, patchedDownloadGuard)
|
|
||||||
|
|
||||||
fs.writeFileSync(scriptPath, source)
|
|
||||||
console.log('[wechat-personal] 已应用 CdnManager 冷启动解析补丁')
|
|
||||||
}
|
|
||||||
|
|
||||||
function patchCdnColdStartConfig(configPath) {
|
|
||||||
const source = fs.readFileSync(configPath, 'utf8')
|
|
||||||
let config
|
|
||||||
try {
|
|
||||||
config = JSON.parse(source)
|
|
||||||
} catch {
|
|
||||||
throw new Error('4.1.11.53 版本配置不是有效 JSON')
|
|
||||||
}
|
|
||||||
config.cdnGetServiceAddr = '0x50a15d0'
|
|
||||||
config.cdnManagerGetterAddr = '0x5259290'
|
|
||||||
fs.writeFileSync(configPath, `${JSON.stringify(config, null, 2)}\n`)
|
|
||||||
console.log('[wechat-personal] 已写入 4.1.11.53 CdnManager 地址')
|
|
||||||
}
|
|
||||||
|
|
||||||
function patchWechatCoreModuleBase(scriptPath) {
|
|
||||||
let source = fs.readFileSync(scriptPath, 'utf8')
|
|
||||||
if (source.includes('WeChat core module base:')) return
|
|
||||||
const initMarker = 'function initAddresses() {'
|
|
||||||
const initIndex = source.indexOf(initMarker)
|
|
||||||
if (initIndex < 0 || !source.startsWith('var targetPath = ')) {
|
|
||||||
throw new Error('无法定位 wechat_chatter 基址扫描逻辑')
|
|
||||||
}
|
|
||||||
const patchedHeader = `var targetPath = "/Applications/WeChat.app/Contents/Resources/wechat.dylib";
|
|
||||||
var module = Process.enumerateModules().find(function(m) {
|
|
||||||
return m.path === targetPath || m.path.endsWith("/Contents/Resources/wechat.dylib");
|
|
||||||
});
|
|
||||||
if (!module) {
|
|
||||||
throw new Error("[-] Cannot find WeChat core module: " + targetPath);
|
|
||||||
}
|
|
||||||
var moduleBase = module.base;
|
|
||||||
var baseAddr = moduleBase;
|
|
||||||
console.log("[+] WeChat core module base: " + baseAddr + " path=" + module.path);
|
|
||||||
setImmediate(initAddresses);
|
|
||||||
|
|
||||||
`
|
|
||||||
source = patchedHeader + source.slice(initIndex)
|
|
||||||
fs.writeFileSync(scriptPath, source)
|
|
||||||
console.log('[wechat-personal] 已应用微信核心模块基址补丁')
|
|
||||||
}
|
|
||||||
|
|
||||||
function addModifiedWorkNotice(scriptPath) {
|
|
||||||
let source = fs.readFileSync(scriptPath, 'utf8')
|
|
||||||
if (source.includes('TraceMemo wechat_chatter compatibility modifications')) return
|
|
||||||
|
|
||||||
const notice = `/*
|
|
||||||
* TraceMemo wechat_chatter compatibility modifications
|
|
||||||
* Modified: 2026-08-17
|
|
||||||
* Upstream: https://github.com/yincongcyincong/wechat_chatter
|
|
||||||
* Runtime version: v0.0.18
|
|
||||||
* License: GNU General Public License version 3 (GPL-3.0)
|
|
||||||
* Changes: WeChat module discovery, per-send payload isolation, dynamic voice upload buffers,
|
|
||||||
* CdnManager cold-start resolution, media hook backfill, and image Hook readiness logging.
|
|
||||||
* These modifications are not provided by the upstream author.
|
|
||||||
*/
|
|
||||||
|
|
||||||
`
|
|
||||||
source = notice + source
|
|
||||||
fs.writeFileSync(scriptPath, source)
|
|
||||||
console.log('[wechat-personal] 已写入 GPL 修改声明')
|
|
||||||
}
|
|
||||||
|
|
||||||
patchWechatCoreModuleBase(script)
|
|
||||||
patchPerSendPayload(script)
|
|
||||||
patchSendContextCapture(script)
|
|
||||||
patchVoiceAudioBuffer(script)
|
|
||||||
patchImageHookReadiness(script)
|
|
||||||
patchCdnColdStartConfig(config)
|
|
||||||
patchCdnColdStart(script)
|
|
||||||
addModifiedWorkNotice(script)
|
|
||||||
fs.chmodSync(executable, 0o755)
|
|
||||||
console.log('[wechat-personal] 运行时准备完成')
|
|
||||||
@@ -0,0 +1,201 @@
|
|||||||
|
#!/usr/bin/env node
|
||||||
|
|
||||||
|
/* eslint-disable @typescript-eslint/explicit-function-return-type */
|
||||||
|
/* eslint-disable @typescript-eslint/no-require-imports */
|
||||||
|
const crypto = require('node:crypto')
|
||||||
|
const fs = require('node:fs')
|
||||||
|
const path = require('node:path')
|
||||||
|
|
||||||
|
const REQUIRED_FILES = ['tm-wechat-host', 'libtmwechat.dylib', 'runtime-manifest.json']
|
||||||
|
|
||||||
|
function parseArgs(argv) {
|
||||||
|
const result = {}
|
||||||
|
for (let index = 0; index < argv.length; index += 1) {
|
||||||
|
const value = argv[index]
|
||||||
|
if (value === '--source' || value === '--target') {
|
||||||
|
if (!argv[index + 1]) throw new Error(`${value} requires a path`)
|
||||||
|
result[value.slice(2)] = argv[index + 1]
|
||||||
|
index += 1
|
||||||
|
} else {
|
||||||
|
throw new Error(`Unknown option: ${value}`)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return result
|
||||||
|
}
|
||||||
|
|
||||||
|
function sha256(filePath) {
|
||||||
|
return crypto.createHash('sha256').update(fs.readFileSync(filePath)).digest('hex')
|
||||||
|
}
|
||||||
|
|
||||||
|
function listFiles(root) {
|
||||||
|
const files = []
|
||||||
|
function visit(directory) {
|
||||||
|
for (const entry of fs.readdirSync(directory, { withFileTypes: true })) {
|
||||||
|
const absolute = path.join(directory, entry.name)
|
||||||
|
if (entry.isDirectory()) visit(absolute)
|
||||||
|
else if (entry.isFile()) files.push(path.relative(root, absolute))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
visit(root)
|
||||||
|
return files.sort()
|
||||||
|
}
|
||||||
|
|
||||||
|
function assertMachOArm64(filePath, label) {
|
||||||
|
const buffer = fs.readFileSync(filePath)
|
||||||
|
if (buffer.length < 8 || buffer.readUInt32LE(0) !== 0xfeedfacf) {
|
||||||
|
throw new Error(`${label} is not a 64-bit Mach-O binary: ${filePath}`)
|
||||||
|
}
|
||||||
|
if (buffer.readUInt32LE(4) !== 0x0100000c) {
|
||||||
|
throw new Error(`${label} is not arm64: ${filePath}`)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function readAndValidateArtifact(sourceDir) {
|
||||||
|
if (!fs.existsSync(sourceDir)) {
|
||||||
|
throw new Error('native runtime artifact not found: build the macOS runtime artifact first')
|
||||||
|
}
|
||||||
|
|
||||||
|
const actualFiles = listFiles(sourceDir)
|
||||||
|
const expectedFiles = [...REQUIRED_FILES].sort()
|
||||||
|
if (JSON.stringify(actualFiles) !== JSON.stringify(expectedFiles)) {
|
||||||
|
throw new Error(`native runtime artifact has an unexpected tree: ${actualFiles.join(', ')}`)
|
||||||
|
}
|
||||||
|
|
||||||
|
const manifestPath = path.join(sourceDir, 'runtime-manifest.json')
|
||||||
|
const manifest = JSON.parse(fs.readFileSync(manifestPath, 'utf8'))
|
||||||
|
if (manifest.runtime !== 'tm-wechat-native') throw new Error('Unexpected runtime name')
|
||||||
|
if (manifest.platform !== 'darwin-arm64') throw new Error('Runtime platform must be darwin-arm64')
|
||||||
|
if (manifest.architecture !== 'arm64') throw new Error('Runtime architecture must be arm64')
|
||||||
|
if (manifest.protocolVersion !== 1) throw new Error('Unsupported runtime protocolVersion')
|
||||||
|
if (!/^[a-f0-9]{64}$/.test(manifest.tmSendSourceSha256 || '')) {
|
||||||
|
throw new Error('Runtime manifest has no valid tmSendSourceSha256')
|
||||||
|
}
|
||||||
|
if (!/^[a-f0-9]{64}$/.test(manifest.addressProfileSha256 || '')) {
|
||||||
|
throw new Error('Runtime manifest has no valid addressProfileSha256')
|
||||||
|
}
|
||||||
|
const capabilities = new Set(manifest.capabilities || [])
|
||||||
|
for (const capability of ['text', 'image', 'voice']) {
|
||||||
|
if (!capabilities.has(capability)) throw new Error(`Runtime capability missing: ${capability}`)
|
||||||
|
}
|
||||||
|
if (
|
||||||
|
!Array.isArray(manifest.supportedWechatVersions) ||
|
||||||
|
manifest.supportedWechatVersions.length === 0
|
||||||
|
) {
|
||||||
|
throw new Error('Runtime manifest has no supportedWechatVersions')
|
||||||
|
}
|
||||||
|
|
||||||
|
for (const relative of REQUIRED_FILES) {
|
||||||
|
const absolute = path.join(sourceDir, relative)
|
||||||
|
if (!fs.statSync(absolute).isFile()) throw new Error(`Runtime file missing: ${relative}`)
|
||||||
|
}
|
||||||
|
const hostPath = path.join(sourceDir, 'tm-wechat-host')
|
||||||
|
const dylibPath = path.join(sourceDir, 'libtmwechat.dylib')
|
||||||
|
assertMachOArm64(hostPath, 'tm-wechat-host')
|
||||||
|
assertMachOArm64(dylibPath, 'libtmwechat.dylib')
|
||||||
|
if (!fs.readFileSync(dylibPath).includes(Buffer.from(manifest.tmSendSourceSha256, 'utf8'))) {
|
||||||
|
throw new Error('Embedded agent hash is not present in libtmwechat.dylib')
|
||||||
|
}
|
||||||
|
if (!fs.readFileSync(dylibPath).includes(Buffer.from(manifest.addressProfileSha256, 'utf8'))) {
|
||||||
|
throw new Error('Embedded address profile hash is not present in libtmwechat.dylib')
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
manifest,
|
||||||
|
hashes: Object.fromEntries(
|
||||||
|
REQUIRED_FILES.map((file) => [file, sha256(path.join(sourceDir, file))])
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function syncArtifact(sourceDir, targetDir) {
|
||||||
|
const source = readAndValidateArtifact(sourceDir)
|
||||||
|
const parent = path.dirname(targetDir)
|
||||||
|
const name = path.basename(targetDir)
|
||||||
|
const staging = path.join(parent, `.${name}.prepare-${process.pid}`)
|
||||||
|
const backup = path.join(parent, `.${name}.backup-${process.pid}`)
|
||||||
|
|
||||||
|
fs.mkdirSync(parent, { recursive: true })
|
||||||
|
fs.rmSync(staging, { recursive: true, force: true })
|
||||||
|
fs.rmSync(backup, { recursive: true, force: true })
|
||||||
|
fs.mkdirSync(staging, { recursive: true })
|
||||||
|
|
||||||
|
try {
|
||||||
|
for (const relative of REQUIRED_FILES) {
|
||||||
|
const destination = path.join(staging, relative)
|
||||||
|
fs.mkdirSync(path.dirname(destination), { recursive: true })
|
||||||
|
fs.copyFileSync(path.join(sourceDir, relative), destination)
|
||||||
|
}
|
||||||
|
fs.chmodSync(path.join(staging, 'tm-wechat-host'), 0o755)
|
||||||
|
|
||||||
|
const staged = readAndValidateArtifact(staging)
|
||||||
|
for (const relative of REQUIRED_FILES) {
|
||||||
|
if (source.hashes[relative] !== staged.hashes[relative]) {
|
||||||
|
throw new Error(`Packaged runtime hash mismatch: ${relative}`)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (fs.existsSync(targetDir)) fs.renameSync(targetDir, backup)
|
||||||
|
try {
|
||||||
|
fs.renameSync(staging, targetDir)
|
||||||
|
} catch (error) {
|
||||||
|
if (fs.existsSync(backup)) fs.renameSync(backup, targetDir)
|
||||||
|
throw error
|
||||||
|
}
|
||||||
|
fs.rmSync(backup, { recursive: true, force: true })
|
||||||
|
return staged
|
||||||
|
} finally {
|
||||||
|
fs.rmSync(staging, { recursive: true, force: true })
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function resolveSource(explicit) {
|
||||||
|
if (explicit) return path.resolve(explicit)
|
||||||
|
const fromEnv = String(process.env.TM_NATIVE_RUNTIME_DIR || '').trim()
|
||||||
|
if (fromEnv) return path.resolve(fromEnv)
|
||||||
|
// 本机路径写在这里即可,该文件不进仓库。
|
||||||
|
const localConfig = path.join(__dirname, '..', '.native-runtime-source')
|
||||||
|
if (fs.existsSync(localConfig)) {
|
||||||
|
const configured = fs.readFileSync(localConfig, 'utf8').trim()
|
||||||
|
if (configured) return path.resolve(configured)
|
||||||
|
}
|
||||||
|
throw new Error(
|
||||||
|
'runtime artifact source is required: pass --source <dir>, set TM_NATIVE_RUNTIME_DIR, ' +
|
||||||
|
'or write the path into .native-runtime-source'
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function main() {
|
||||||
|
const projectRoot = path.resolve(__dirname, '..')
|
||||||
|
const args = parseArgs(process.argv.slice(2))
|
||||||
|
const sourceDir = resolveSource(args.source)
|
||||||
|
const targetDir = path.resolve(
|
||||||
|
args.target || path.join(projectRoot, 'resources', 'runtime', 'darwin-arm64')
|
||||||
|
)
|
||||||
|
const result = syncArtifact(sourceDir, targetDir)
|
||||||
|
console.log(`[prepare-wechat-native] source: ${sourceDir}`)
|
||||||
|
console.log(`[prepare-wechat-native] target: ${targetDir}`)
|
||||||
|
console.log(
|
||||||
|
`[prepare-wechat-native] runtime: ${result.manifest.runtime}/${result.manifest.version}`
|
||||||
|
)
|
||||||
|
console.log(`[prepare-wechat-native] agent: ${result.manifest.tmSendSourceSha256}`)
|
||||||
|
console.log(`[prepare-wechat-native] address profile: ${result.manifest.addressProfileSha256}`)
|
||||||
|
console.log('[prepare-wechat-native] files: 3')
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = {
|
||||||
|
REQUIRED_FILES,
|
||||||
|
assertMachOArm64,
|
||||||
|
readAndValidateArtifact,
|
||||||
|
syncArtifact
|
||||||
|
}
|
||||||
|
|
||||||
|
if (require.main === module) {
|
||||||
|
try {
|
||||||
|
main()
|
||||||
|
} catch (error) {
|
||||||
|
console.error(
|
||||||
|
`[prepare-wechat-native] ${error instanceof Error ? error.message : String(error)}`
|
||||||
|
)
|
||||||
|
process.exitCode = 1
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -24,10 +24,17 @@ const avatarSvg = (label, color) =>
|
|||||||
`<svg xmlns="http://www.w3.org/2000/svg" width="96" height="96"><rect width="96" height="96" rx="18" fill="${color}"/><text x="48" y="58" text-anchor="middle" font-family="PingFang SC, sans-serif" font-size="36" fill="#0f172a">${label}</text></svg>`
|
`<svg xmlns="http://www.w3.org/2000/svg" width="96" height="96"><rect width="96" height="96" rx="18" fill="${color}"/><text x="48" y="58" text-anchor="middle" font-family="PingFang SC, sans-serif" font-size="36" fill="#0f172a">${label}</text></svg>`
|
||||||
).toString('base64')}`
|
).toString('base64')}`
|
||||||
|
|
||||||
const localImagePath = '/Users/user/Library/Containers/com.tencent.xinWeChat/Data/Documents/xwechat_files/fixture_account_1a2b/temp/RWTemp/2026-07/fixture-image-hash.png'
|
/**
|
||||||
const sampleImage = fs.existsSync(localImagePath)
|
* 可选的本地样例图(用于人工核对图片区块的排版)。
|
||||||
? `data:image/png;base64,${fs.readFileSync(localImagePath).toString('base64')}`
|
*
|
||||||
: avatarSvg('图', '#dbeafe')
|
* 走环境变量传入,**不要在源码里写本机路径** —— 微信数据目录会连带暴露
|
||||||
|
* 系统用户名与账号目录名。不传就退回内置的 SVG 头像占位。
|
||||||
|
*/
|
||||||
|
const localImagePath = process.env.REPORT_FIXTURE_IMAGE || ''
|
||||||
|
const sampleImage =
|
||||||
|
localImagePath && fs.existsSync(localImagePath)
|
||||||
|
? `data:image/png;base64,${fs.readFileSync(localImagePath).toString('base64')}`
|
||||||
|
: avatarSvg('图', '#dbeafe')
|
||||||
|
|
||||||
const avatars = {
|
const avatars = {
|
||||||
阿宇: avatarSvg('宇', '#dcfce7'),
|
阿宇: avatarSvg('宇', '#dcfce7'),
|
||||||
|
|||||||
@@ -67,4 +67,34 @@ assert.match(
|
|||||||
/https:\/\/example\.com\/skill/
|
/https:\/\/example\.com\/skill/
|
||||||
)
|
)
|
||||||
|
|
||||||
|
// source.version 曾经是死字段:传进来却被模板丢掉,于是安装指令不携带任何版本信息。
|
||||||
|
for (const target of ['codex', 'claude-code', 'openclaw', 'generic']) {
|
||||||
|
const text = buildSkillInstallInstruction({
|
||||||
|
target,
|
||||||
|
source: { ...local, version: '9.9.9' },
|
||||||
|
apiBaseUrl: { host: '127.0.0.1', port: 6131 }
|
||||||
|
})
|
||||||
|
assert.match(text, /Skill 版本是 9\.9\.9/, `${target} 指令应携带 source.version`)
|
||||||
|
assert.doesNotMatch(text, /v1\.0/, `${target} 不应残留 fixture 的旧版本号`)
|
||||||
|
assert.match(text, /覆盖/, `${target} 指令应说明用新版本覆盖旧版本`)
|
||||||
|
}
|
||||||
|
|
||||||
|
// 指令要同时提醒 Agent 做版本自检,否则更新机制又只能靠人记得。
|
||||||
|
const selfCheckText = buildSkillInstallInstruction({
|
||||||
|
target: 'codex',
|
||||||
|
source: local,
|
||||||
|
apiBaseUrl: { host: '127.0.0.1', port: 6131 }
|
||||||
|
})
|
||||||
|
assert.match(selfCheckText, /版本自检/)
|
||||||
|
assert.match(selfCheckText, /skill\.version/)
|
||||||
|
|
||||||
|
// 没有版本号时不编造:不输出版本段,其余指令保持可用。
|
||||||
|
const withoutVersion = buildSkillInstallInstruction({
|
||||||
|
target: 'codex',
|
||||||
|
source: { type: 'local', directoryPath: 'C:/skill/tracememo-reader', skillPath: 'x' },
|
||||||
|
apiBaseUrl: { host: '127.0.0.1', port: 6131 }
|
||||||
|
})
|
||||||
|
assert.doesNotMatch(withoutVersion, /Skill 版本是/)
|
||||||
|
assert.match(withoutVersion, /TRACEMEMO_API_TOKEN/)
|
||||||
|
|
||||||
console.log('skill install instruction tests passed')
|
console.log('skill install instruction tests passed')
|
||||||
@@ -0,0 +1,140 @@
|
|||||||
|
/*
|
||||||
|
* 测试文件的类型检查棘轮(ratchet)。
|
||||||
|
*
|
||||||
|
* 背景:`tsconfig.node.json` / `tsconfig.web.json` 的 include 都不含 `tests/`,
|
||||||
|
* 所以测试里的类型错误对 `pnpm typecheck` 与 CI 完全不可见——已经积累了一批历史债。
|
||||||
|
*
|
||||||
|
* 策略:**不阻塞既有债,但禁止新增**。
|
||||||
|
* - 基线按「文件 → 错误数」记录,而不是只记总数:
|
||||||
|
* 否则在 A 文件修掉 1 条、同时在 B 文件新增 1 条会互相抵消,棘轮形同虚设。
|
||||||
|
* - 某个文件的错误数超过基线即失败;新增了带类型错误的文件同样失败。
|
||||||
|
* - 需要主动下调基线时用 `--update`(只在确实修好了错误之后)。
|
||||||
|
*
|
||||||
|
* 用法:
|
||||||
|
* node scripts/typecheck-tests.cjs # 校验
|
||||||
|
* node scripts/typecheck-tests.cjs --update # 用当前结果重写基线
|
||||||
|
*/
|
||||||
|
/* eslint-disable @typescript-eslint/explicit-function-return-type, @typescript-eslint/no-require-imports */
|
||||||
|
const { spawnSync } = require('node:child_process')
|
||||||
|
const fs = require('node:fs')
|
||||||
|
const path = require('node:path')
|
||||||
|
|
||||||
|
const projectRoot = path.resolve(__dirname, '..')
|
||||||
|
const configPath = path.join(projectRoot, 'tsconfig.test.json')
|
||||||
|
const baselinePath = path.join(projectRoot, 'tests', 'typecheck-baseline.json')
|
||||||
|
const ERROR_LINE = /^(.+?)\((\d+),(\d+)\): error (TS\d+): (.*)$/
|
||||||
|
const MAX_REPORTED = 20
|
||||||
|
|
||||||
|
function runTypeScript() {
|
||||||
|
// 直接用本地 typescript 包,避免依赖 node_modules/.bin 在各平台的差异。
|
||||||
|
const tscPath = require.resolve('typescript/bin/tsc')
|
||||||
|
const result = spawnSync(
|
||||||
|
process.execPath,
|
||||||
|
[tscPath, '--noEmit', '--pretty', 'false', '-p', configPath],
|
||||||
|
{ cwd: projectRoot, encoding: 'utf8', maxBuffer: 64 * 1024 * 1024 }
|
||||||
|
)
|
||||||
|
if (result.error) throw result.error
|
||||||
|
return `${result.stdout || ''}${result.stderr || ''}`
|
||||||
|
}
|
||||||
|
|
||||||
|
function relative(file) {
|
||||||
|
const rel = path.relative(projectRoot, path.resolve(projectRoot, file))
|
||||||
|
return rel.split(path.sep).join('/')
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 解析出「文件 → 错误数」与「文件 → 错误信息列表」。 */
|
||||||
|
function collectErrors(output) {
|
||||||
|
const counts = new Map()
|
||||||
|
const details = new Map()
|
||||||
|
for (const line of output.split('\n')) {
|
||||||
|
const match = ERROR_LINE.exec(line.trim())
|
||||||
|
if (!match) continue
|
||||||
|
const file = relative(match[1])
|
||||||
|
counts.set(file, (counts.get(file) ?? 0) + 1)
|
||||||
|
if (!details.has(file)) details.set(file, [])
|
||||||
|
if (details.get(file).length < 3) details.get(file).push(`${match[2]}:${match[3]} ${match[4]}`)
|
||||||
|
}
|
||||||
|
return { counts, details }
|
||||||
|
}
|
||||||
|
|
||||||
|
function readBaseline() {
|
||||||
|
try {
|
||||||
|
const parsed = JSON.parse(fs.readFileSync(baselinePath, 'utf8'))
|
||||||
|
if (parsed && typeof parsed.files === 'object' && parsed.files !== null) return parsed
|
||||||
|
} catch {
|
||||||
|
// 基线缺失或损坏时按「空基线」处理,会在下面明确报错提示。
|
||||||
|
}
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
|
||||||
|
function total(counts) {
|
||||||
|
let sum = 0
|
||||||
|
for (const value of counts.values()) sum += value
|
||||||
|
return sum
|
||||||
|
}
|
||||||
|
|
||||||
|
function main() {
|
||||||
|
if (!fs.existsSync(configPath)) {
|
||||||
|
console.error(`[typecheck:test] 缺少 ${path.relative(projectRoot, configPath)}`)
|
||||||
|
process.exit(1)
|
||||||
|
}
|
||||||
|
const { counts, details } = collectErrors(runTypeScript())
|
||||||
|
|
||||||
|
if (process.argv.includes('--update')) {
|
||||||
|
const files = Object.fromEntries([...counts.entries()].sort(([a], [b]) => a.localeCompare(b)))
|
||||||
|
const payload = {
|
||||||
|
note: '测试文件类型检查基线:只允许下降,不允许上升。用 node scripts/typecheck-tests.cjs --update 下调。',
|
||||||
|
total: total(counts),
|
||||||
|
files
|
||||||
|
}
|
||||||
|
fs.mkdirSync(path.dirname(baselinePath), { recursive: true })
|
||||||
|
fs.writeFileSync(baselinePath, `${JSON.stringify(payload, null, 2)}\n`, 'utf8')
|
||||||
|
console.log(
|
||||||
|
`[typecheck:test] 基线已更新:${payload.total} 个错误 / ${Object.keys(files).length} 个文件`
|
||||||
|
)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
const baseline = readBaseline()
|
||||||
|
if (!baseline) {
|
||||||
|
console.error(
|
||||||
|
`[typecheck:test] 找不到基线 ${path.relative(projectRoot, baselinePath)}。\n` +
|
||||||
|
' 首次启用请运行:node scripts/typecheck-tests.cjs --update'
|
||||||
|
)
|
||||||
|
process.exit(1)
|
||||||
|
}
|
||||||
|
|
||||||
|
const regressions = []
|
||||||
|
for (const [file, count] of counts) {
|
||||||
|
const allowed = baseline.files[file] ?? 0
|
||||||
|
if (count > allowed) regressions.push({ file, count, allowed })
|
||||||
|
}
|
||||||
|
|
||||||
|
const now = total(counts)
|
||||||
|
const baselineTotal = Number(baseline.total) || 0
|
||||||
|
const improved = baselineTotal - now
|
||||||
|
|
||||||
|
if (regressions.length > 0) {
|
||||||
|
console.error('[typecheck:test] 测试文件出现新的类型错误 ❌')
|
||||||
|
console.error(` 基线 ${baselineTotal} → 当前 ${now}(+${now - baselineTotal})\n`)
|
||||||
|
let printed = 0
|
||||||
|
for (const item of regressions) {
|
||||||
|
console.error(` ${item.file} ${item.allowed} → ${item.count}`)
|
||||||
|
for (const line of details.get(item.file) ?? []) {
|
||||||
|
if (printed >= MAX_REPORTED) break
|
||||||
|
console.error(` ${line}`)
|
||||||
|
printed += 1
|
||||||
|
}
|
||||||
|
}
|
||||||
|
console.error('\n 修好之后用 --update 下调基线(不要为了过检查而放宽它)。')
|
||||||
|
process.exit(1)
|
||||||
|
}
|
||||||
|
|
||||||
|
console.log(
|
||||||
|
`[typecheck:test] PASS ✅ 当前 ${now} 个既有类型错误 / ${counts.size} 个文件` +
|
||||||
|
(improved > 0 ? `(比基线少 ${improved} 个,可运行 --update 下调)` : '')
|
||||||
|
)
|
||||||
|
console.log(' 注意:这是棘轮,只保证「不新增」。修完历史债后可改为阻断式检查。')
|
||||||
|
}
|
||||||
|
|
||||||
|
main()
|
||||||
@@ -1,21 +0,0 @@
|
|||||||
MIT License
|
|
||||||
|
|
||||||
Copyright (c) 2026 fastclaw-ai
|
|
||||||
|
|
||||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
||||||
of this software and associated documentation files (the "Software"), to deal
|
|
||||||
in the Software without restriction, including without limitation the rights
|
|
||||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
||||||
copies of the Software, and to permit persons to whom the Software is
|
|
||||||
furnished to do so, subject to the following conditions:
|
|
||||||
|
|
||||||
The above copyright notice and this permission notice shall be included in all
|
|
||||||
copies or substantial portions of the Software.
|
|
||||||
|
|
||||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
||||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
||||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
||||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
||||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
||||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
||||||
SOFTWARE.
|
|
||||||
@@ -1,25 +0,0 @@
|
|||||||
# TraceMemo WeChat Connector
|
|
||||||
|
|
||||||
This repository-local service provides the minimal WeChat bridge required by TraceMemo:
|
|
||||||
|
|
||||||
- QR-code login with a single persisted credential
|
|
||||||
- account discovery
|
|
||||||
- inbound long polling and authenticated webhook delivery
|
|
||||||
- local HTTP health and send endpoints
|
|
||||||
- text and local/remote media sending
|
|
||||||
|
|
||||||
The executable is managed by the Electron main process. It is not a general-purpose agent runtime and does not load external AI command-line tools.
|
|
||||||
|
|
||||||
## Commands
|
|
||||||
|
|
||||||
```bash
|
|
||||||
go run . login --json
|
|
||||||
go run . accounts --json
|
|
||||||
go run . start --foreground --api-addr 127.0.0.1:18011 --account-id <account-id>
|
|
||||||
```
|
|
||||||
|
|
||||||
Credential and synchronization state is stored under `~/.wechatexplorer/wechat-connector/accounts`. This legacy directory name is intentionally retained so upgrades can reuse existing accounts. A successful login is written before the older credential and synchronization state are removed, so an incomplete login cannot destroy the last working credential.
|
|
||||||
|
|
||||||
## Attribution
|
|
||||||
|
|
||||||
Low-level protocol and media transport portions are distributed under the MIT license in [LICENSE](LICENSE). TraceMemo-specific process management, webhook contract, product UI, and Agent Hub behavior live in the surrounding TraceMemo project.
|
|
||||||
@@ -1,135 +0,0 @@
|
|||||||
package api
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"encoding/json"
|
|
||||||
"fmt"
|
|
||||||
"log"
|
|
||||||
"net/http"
|
|
||||||
|
|
||||||
"github.com/Wxw-Gu/WechatExplorer/services/wechat-connector/ilink"
|
|
||||||
"github.com/Wxw-Gu/WechatExplorer/services/wechat-connector/messaging"
|
|
||||||
)
|
|
||||||
|
|
||||||
// Server provides an HTTP API for sending messages.
|
|
||||||
type Server struct {
|
|
||||||
clients []*ilink.Client
|
|
||||||
addr string
|
|
||||||
}
|
|
||||||
|
|
||||||
// NewServer creates an API server.
|
|
||||||
func NewServer(clients []*ilink.Client, addr string) *Server {
|
|
||||||
if addr == "" {
|
|
||||||
addr = "127.0.0.1:18011"
|
|
||||||
}
|
|
||||||
return &Server{clients: clients, addr: addr}
|
|
||||||
}
|
|
||||||
|
|
||||||
// SendRequest is the JSON body for POST /api/send.
|
|
||||||
type SendRequest struct {
|
|
||||||
AccountID string `json:"account_id,omitempty"`
|
|
||||||
To string `json:"to"`
|
|
||||||
Text string `json:"text,omitempty"`
|
|
||||||
MediaURL string `json:"media_url,omitempty"` // image/video/file URL
|
|
||||||
}
|
|
||||||
|
|
||||||
// Run starts the HTTP server. Blocks until ctx is cancelled.
|
|
||||||
func (s *Server) Run(ctx context.Context) error {
|
|
||||||
mux := http.NewServeMux()
|
|
||||||
mux.HandleFunc("/api/send", s.handleSend)
|
|
||||||
mux.HandleFunc("/health", func(w http.ResponseWriter, r *http.Request) {
|
|
||||||
w.WriteHeader(http.StatusOK)
|
|
||||||
fmt.Fprintln(w, "ok")
|
|
||||||
})
|
|
||||||
|
|
||||||
srv := &http.Server{Addr: s.addr, Handler: mux}
|
|
||||||
|
|
||||||
go func() {
|
|
||||||
<-ctx.Done()
|
|
||||||
srv.Shutdown(context.Background())
|
|
||||||
}()
|
|
||||||
|
|
||||||
log.Printf("[api] listening on %s", s.addr)
|
|
||||||
if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (s *Server) handleSend(w http.ResponseWriter, r *http.Request) {
|
|
||||||
if r.Method != http.MethodPost {
|
|
||||||
http.Error(w, "POST only", http.StatusMethodNotAllowed)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
var req SendRequest
|
|
||||||
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
|
||||||
http.Error(w, "invalid JSON: "+err.Error(), http.StatusBadRequest)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
if req.To == "" {
|
|
||||||
http.Error(w, `"to" is required`, http.StatusBadRequest)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
if req.Text == "" && req.MediaURL == "" {
|
|
||||||
http.Error(w, `"text" or "media_url" is required`, http.StatusBadRequest)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
if len(s.clients) == 0 {
|
|
||||||
http.Error(w, "no accounts configured", http.StatusServiceUnavailable)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
client := s.clientForAccount(req.AccountID)
|
|
||||||
if client == nil {
|
|
||||||
http.Error(w, "requested account is not available", http.StatusNotFound)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
ctx := r.Context()
|
|
||||||
|
|
||||||
// Send text if provided
|
|
||||||
if req.Text != "" {
|
|
||||||
if err := messaging.SendTextReply(ctx, client, req.To, req.Text, "", ""); err != nil {
|
|
||||||
log.Printf("[api] send text failed: %v", err)
|
|
||||||
http.Error(w, "send text failed: "+err.Error(), http.StatusInternalServerError)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
log.Printf("[api] sent text to %s: %q", req.To, req.Text)
|
|
||||||
|
|
||||||
// Extract and send any markdown images embedded in text
|
|
||||||
for _, imgURL := range messaging.ExtractImageURLs(req.Text) {
|
|
||||||
if err := messaging.SendMediaFromURL(ctx, client, req.To, imgURL, ""); err != nil {
|
|
||||||
log.Printf("[api] send extracted image failed: %v", err)
|
|
||||||
} else {
|
|
||||||
log.Printf("[api] sent extracted image to %s: %s", req.To, imgURL)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Send media if provided
|
|
||||||
if req.MediaURL != "" {
|
|
||||||
if err := messaging.SendMediaFromURL(ctx, client, req.To, req.MediaURL, ""); err != nil {
|
|
||||||
log.Printf("[api] send media failed: %v", err)
|
|
||||||
http.Error(w, "send media failed: "+err.Error(), http.StatusInternalServerError)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
log.Printf("[api] sent media to %s: %s", req.To, req.MediaURL)
|
|
||||||
}
|
|
||||||
|
|
||||||
w.Header().Set("Content-Type", "application/json")
|
|
||||||
json.NewEncoder(w).Encode(map[string]string{"status": "ok"})
|
|
||||||
}
|
|
||||||
|
|
||||||
func (s *Server) clientForAccount(accountID string) *ilink.Client {
|
|
||||||
if accountID == "" {
|
|
||||||
return s.clients[0]
|
|
||||||
}
|
|
||||||
for _, client := range s.clients {
|
|
||||||
if client.BotID() == accountID {
|
|
||||||
return client
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
@@ -1,20 +0,0 @@
|
|||||||
package api
|
|
||||||
|
|
||||||
import (
|
|
||||||
"testing"
|
|
||||||
|
|
||||||
"github.com/Wxw-Gu/WechatExplorer/services/wechat-connector/ilink"
|
|
||||||
)
|
|
||||||
|
|
||||||
func TestClientForAccountSelectsMatchingBot(t *testing.T) {
|
|
||||||
oldClient := ilink.NewClient(&ilink.Credentials{ILinkBotID: "bot-old"})
|
|
||||||
newClient := ilink.NewClient(&ilink.Credentials{ILinkBotID: "bot-new"})
|
|
||||||
server := NewServer([]*ilink.Client{oldClient, newClient}, "")
|
|
||||||
|
|
||||||
if got := server.clientForAccount("bot-new"); got != newClient {
|
|
||||||
t.Fatal("clientForAccount did not select the requested account")
|
|
||||||
}
|
|
||||||
if got := server.clientForAccount("missing"); got != nil {
|
|
||||||
t.Fatal("clientForAccount should reject an unknown account")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,8 +0,0 @@
|
|||||||
module github.com/Wxw-Gu/WechatExplorer/services/wechat-connector
|
|
||||||
|
|
||||||
go 1.23.0
|
|
||||||
|
|
||||||
require (
|
|
||||||
github.com/google/uuid v1.6.0
|
|
||||||
rsc.io/qr v0.2.0
|
|
||||||
)
|
|
||||||
@@ -1,4 +0,0 @@
|
|||||||
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
|
|
||||||
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
|
|
||||||
rsc.io/qr v0.2.0 h1:6vBLea5/NRMVTz8V66gipeLycZMl/+UlFmk8DvqQ6WY=
|
|
||||||
rsc.io/qr v0.2.0/go.mod h1:IF+uZjkb9fqyeF/4tlBoynqmQxUoPfWEKh921coOuXs=
|
|
||||||
@@ -1,236 +0,0 @@
|
|||||||
package ilink
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"encoding/json"
|
|
||||||
"fmt"
|
|
||||||
"os"
|
|
||||||
"path/filepath"
|
|
||||||
"strings"
|
|
||||||
"time"
|
|
||||||
)
|
|
||||||
|
|
||||||
const (
|
|
||||||
qrCodeURL = "https://ilinkai.weixin.qq.com/ilink/bot/get_bot_qrcode?bot_type=3"
|
|
||||||
qrStatusURL = "https://ilinkai.weixin.qq.com/ilink/bot/get_qrcode_status?qrcode="
|
|
||||||
statusWait = "wait"
|
|
||||||
statusScanned = "scaned"
|
|
||||||
statusConfirmed = "confirmed"
|
|
||||||
statusExpired = "expired"
|
|
||||||
)
|
|
||||||
|
|
||||||
// FetchQRCode retrieves a new QR code for login.
|
|
||||||
func FetchQRCode(ctx context.Context) (*QRCodeResponse, error) {
|
|
||||||
c := NewUnauthenticatedClient()
|
|
||||||
var resp QRCodeResponse
|
|
||||||
if err := c.doGet(ctx, qrCodeURL, &resp); err != nil {
|
|
||||||
return nil, fmt.Errorf("fetch QR code: %w", err)
|
|
||||||
}
|
|
||||||
return &resp, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// PollQRStatus polls for QR code scan status until confirmed or expired.
|
|
||||||
// It calls onStatus for each status change so the caller can display progress.
|
|
||||||
func PollQRStatus(ctx context.Context, qrcode string, onStatus func(status string)) (*Credentials, error) {
|
|
||||||
c := NewUnauthenticatedClient()
|
|
||||||
url := qrStatusURL + qrcode
|
|
||||||
|
|
||||||
for {
|
|
||||||
select {
|
|
||||||
case <-ctx.Done():
|
|
||||||
return nil, ctx.Err()
|
|
||||||
default:
|
|
||||||
}
|
|
||||||
|
|
||||||
pollCtx, cancel := context.WithTimeout(ctx, 40*time.Second)
|
|
||||||
var resp QRStatusResponse
|
|
||||||
err := c.doGet(pollCtx, url, &resp)
|
|
||||||
cancel()
|
|
||||||
|
|
||||||
if err != nil {
|
|
||||||
// Timeout is normal for long-poll, retry
|
|
||||||
if ctx.Err() != nil {
|
|
||||||
return nil, ctx.Err()
|
|
||||||
}
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
|
|
||||||
if onStatus != nil {
|
|
||||||
onStatus(resp.Status)
|
|
||||||
}
|
|
||||||
|
|
||||||
switch resp.Status {
|
|
||||||
case statusConfirmed:
|
|
||||||
creds := &Credentials{
|
|
||||||
BotToken: resp.BotToken,
|
|
||||||
ILinkBotID: resp.ILinkBotID,
|
|
||||||
BaseURL: resp.BaseURL,
|
|
||||||
ILinkUserID: resp.ILinkUserID,
|
|
||||||
}
|
|
||||||
return creds, nil
|
|
||||||
case statusExpired:
|
|
||||||
return nil, fmt.Errorf("QR code expired")
|
|
||||||
case statusWait, statusScanned:
|
|
||||||
// Continue polling
|
|
||||||
default:
|
|
||||||
// Unknown status, continue
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func accountsDir(rootName string) (string, error) {
|
|
||||||
home, err := os.UserHomeDir()
|
|
||||||
if err != nil {
|
|
||||||
return "", err
|
|
||||||
}
|
|
||||||
return filepath.Join(home, rootName, "wechat-connector", "accounts"), nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// AccountsDir returns the TraceMemo directory where new credentials are stored.
|
|
||||||
func AccountsDir() (string, error) {
|
|
||||||
return accountsDir(".tracememo")
|
|
||||||
}
|
|
||||||
|
|
||||||
// LegacyAccountsDir is read-only compatibility for v2.1.9 and earlier.
|
|
||||||
func LegacyAccountsDir() (string, error) {
|
|
||||||
return accountsDir(".wechatexplorer")
|
|
||||||
}
|
|
||||||
|
|
||||||
func accountDirectoryForID(accountID string) (string, error) {
|
|
||||||
current, err := AccountsDir()
|
|
||||||
if err != nil {
|
|
||||||
return "", err
|
|
||||||
}
|
|
||||||
if _, err := os.Stat(filepath.Join(current, accountID+".json")); err == nil {
|
|
||||||
return current, nil
|
|
||||||
}
|
|
||||||
legacy, err := LegacyAccountsDir()
|
|
||||||
if err != nil {
|
|
||||||
return "", err
|
|
||||||
}
|
|
||||||
if _, err := os.Stat(filepath.Join(legacy, accountID+".json")); err == nil {
|
|
||||||
return legacy, nil
|
|
||||||
}
|
|
||||||
return current, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// NormalizeAccountID converts raw bot ID to filesystem-safe format.
|
|
||||||
func NormalizeAccountID(raw string) string {
|
|
||||||
s := raw
|
|
||||||
for _, ch := range []string{"@", ".", ":"} {
|
|
||||||
s = filepath.Clean(s)
|
|
||||||
s = replaceAll(s, ch, "-")
|
|
||||||
}
|
|
||||||
return s
|
|
||||||
}
|
|
||||||
|
|
||||||
func replaceAll(s, old, new string) string {
|
|
||||||
for {
|
|
||||||
i := indexOf(s, old)
|
|
||||||
if i < 0 {
|
|
||||||
return s
|
|
||||||
}
|
|
||||||
s = s[:i] + new + s[i+len(old):]
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func indexOf(s, sub string) int {
|
|
||||||
for i := range s {
|
|
||||||
if i+len(sub) <= len(s) && s[i:i+len(sub)] == sub {
|
|
||||||
return i
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return -1
|
|
||||||
}
|
|
||||||
|
|
||||||
// SaveCredentials saves the latest credentials and removes older accounts.
|
|
||||||
// The new credential is written first so a failed login never destroys the
|
|
||||||
// previously working credential.
|
|
||||||
func SaveCredentials(creds *Credentials) error {
|
|
||||||
dir, err := AccountsDir()
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
if err := os.MkdirAll(dir, 0o700); err != nil {
|
|
||||||
return fmt.Errorf("create accounts dir: %w", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
id := NormalizeAccountID(creds.ILinkBotID)
|
|
||||||
path := filepath.Join(dir, id+".json")
|
|
||||||
|
|
||||||
data, err := json.MarshalIndent(creds, "", " ")
|
|
||||||
if err != nil {
|
|
||||||
return fmt.Errorf("marshal credentials: %w", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
if err := os.WriteFile(path, data, 0o600); err != nil {
|
|
||||||
return fmt.Errorf("write credentials: %w", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
entries, err := os.ReadDir(dir)
|
|
||||||
if err != nil {
|
|
||||||
return fmt.Errorf("prune old credentials: %w", err)
|
|
||||||
}
|
|
||||||
keepPrefix := id + "."
|
|
||||||
for _, entry := range entries {
|
|
||||||
if entry.IsDir() || strings.HasPrefix(entry.Name(), keepPrefix) {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
if filepath.Ext(entry.Name()) != ".json" {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
if err := os.Remove(filepath.Join(dir, entry.Name())); err != nil && !os.IsNotExist(err) {
|
|
||||||
return fmt.Errorf("remove old credential %s: %w", entry.Name(), err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func loadCredentialsFromDir(dir string) ([]*Credentials, error) {
|
|
||||||
entries, err := os.ReadDir(dir)
|
|
||||||
if err != nil {
|
|
||||||
if os.IsNotExist(err) {
|
|
||||||
return nil, nil
|
|
||||||
}
|
|
||||||
return nil, fmt.Errorf("read accounts dir: %w", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
var result []*Credentials
|
|
||||||
for _, e := range entries {
|
|
||||||
if e.IsDir() || filepath.Ext(e.Name()) != ".json" {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
data, err := os.ReadFile(filepath.Join(dir, e.Name()))
|
|
||||||
if err != nil {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
var creds Credentials
|
|
||||||
if json.Unmarshal(data, &creds) == nil && creds.BotToken != "" {
|
|
||||||
result = append(result, &creds)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return result, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// LoadAllCredentials loads TraceMemo credentials first and falls back to the
|
|
||||||
// untouched WechatExplorer directory for one-version upgrade compatibility.
|
|
||||||
func LoadAllCredentials() ([]*Credentials, error) {
|
|
||||||
current, err := AccountsDir()
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
credentials, err := loadCredentialsFromDir(current)
|
|
||||||
if err != nil || len(credentials) > 0 {
|
|
||||||
return credentials, err
|
|
||||||
}
|
|
||||||
legacy, err := LegacyAccountsDir()
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
return loadCredentialsFromDir(legacy)
|
|
||||||
}
|
|
||||||
|
|
||||||
// CredentialsPath returns the path for display purposes.
|
|
||||||
func CredentialsPath() (string, error) {
|
|
||||||
return AccountsDir()
|
|
||||||
}
|
|
||||||
@@ -1,86 +0,0 @@
|
|||||||
package ilink
|
|
||||||
|
|
||||||
import (
|
|
||||||
"encoding/json"
|
|
||||||
"os"
|
|
||||||
"path/filepath"
|
|
||||||
"testing"
|
|
||||||
)
|
|
||||||
|
|
||||||
func setTestHome(t *testing.T) string {
|
|
||||||
t.Helper()
|
|
||||||
home := t.TempDir()
|
|
||||||
t.Setenv("HOME", home)
|
|
||||||
t.Setenv("USERPROFILE", home)
|
|
||||||
return home
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestSaveCredentialsKeepsOnlyLatestAccount(t *testing.T) {
|
|
||||||
setTestHome(t)
|
|
||||||
old := &Credentials{ILinkBotID: "bot-old@im.bot", BotToken: "old-token"}
|
|
||||||
latest := &Credentials{ILinkBotID: "bot-new@im.bot", BotToken: "new-token"}
|
|
||||||
if err := SaveCredentials(old); err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
dir, err := AccountsDir()
|
|
||||||
if err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
if err := os.WriteFile(filepath.Join(dir, NormalizeAccountID(old.ILinkBotID)+".sync.json"), []byte(`{}`), 0o600); err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
if err := SaveCredentials(latest); err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
accounts, err := LoadAllCredentials()
|
|
||||||
if err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
if len(accounts) != 1 || accounts[0].ILinkBotID != latest.ILinkBotID {
|
|
||||||
t.Fatalf("accounts = %#v", accounts)
|
|
||||||
}
|
|
||||||
if _, err := os.Stat(filepath.Join(dir, NormalizeAccountID(old.ILinkBotID)+".sync.json")); !os.IsNotExist(err) {
|
|
||||||
t.Fatalf("old sync state still exists: %v", err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestAccountsDirUsesTraceMemoIdentity(t *testing.T) {
|
|
||||||
home := setTestHome(t)
|
|
||||||
dir, err := AccountsDir()
|
|
||||||
if err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
want := filepath.Join(home, ".tracememo", "wechat-connector", "accounts")
|
|
||||||
if dir != want {
|
|
||||||
t.Fatalf("AccountsDir() = %q, want %q", dir, want)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestLoadAllCredentialsFallsBackToLegacyDirectory(t *testing.T) {
|
|
||||||
setTestHome(t)
|
|
||||||
legacyDir, err := LegacyAccountsDir()
|
|
||||||
if err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
if err := os.MkdirAll(legacyDir, 0o700); err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
legacy := &Credentials{ILinkBotID: "legacy@im.bot", BotToken: "legacy-token"}
|
|
||||||
data, err := json.Marshal(legacy)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
if err := os.WriteFile(filepath.Join(legacyDir, NormalizeAccountID(legacy.ILinkBotID)+".json"), data, 0o600); err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
accounts, err := LoadAllCredentials()
|
|
||||||
if err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
if len(accounts) != 1 || accounts[0].BotToken != legacy.BotToken {
|
|
||||||
t.Fatalf("accounts = %#v", accounts)
|
|
||||||
}
|
|
||||||
if _, err := os.Stat(legacyDir); err != nil {
|
|
||||||
t.Fatalf("legacy directory changed or removed: %v", err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,218 +0,0 @@
|
|||||||
package ilink
|
|
||||||
|
|
||||||
import (
|
|
||||||
"bytes"
|
|
||||||
"context"
|
|
||||||
"crypto/rand"
|
|
||||||
"encoding/base64"
|
|
||||||
"encoding/binary"
|
|
||||||
"encoding/json"
|
|
||||||
"fmt"
|
|
||||||
"io"
|
|
||||||
"net/http"
|
|
||||||
"time"
|
|
||||||
)
|
|
||||||
|
|
||||||
const (
|
|
||||||
defaultBaseURL = "https://ilinkai.weixin.qq.com"
|
|
||||||
longPollTimeout = 35 * time.Second
|
|
||||||
sendTimeout = 15 * time.Second
|
|
||||||
)
|
|
||||||
|
|
||||||
// Client is an iLink HTTP API client.
|
|
||||||
type Client struct {
|
|
||||||
baseURL string
|
|
||||||
botToken string
|
|
||||||
botID string
|
|
||||||
httpClient *http.Client
|
|
||||||
wechatUIN string
|
|
||||||
}
|
|
||||||
|
|
||||||
// NewClient creates a new iLink API client.
|
|
||||||
func NewClient(creds *Credentials) *Client {
|
|
||||||
baseURL := creds.BaseURL
|
|
||||||
if baseURL == "" {
|
|
||||||
baseURL = defaultBaseURL
|
|
||||||
}
|
|
||||||
return &Client{
|
|
||||||
baseURL: baseURL,
|
|
||||||
botToken: creds.BotToken,
|
|
||||||
botID: creds.ILinkBotID,
|
|
||||||
httpClient: &http.Client{},
|
|
||||||
wechatUIN: generateWechatUIN(),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// NewUnauthenticatedClient creates a client without credentials for login flow.
|
|
||||||
func NewUnauthenticatedClient() *Client {
|
|
||||||
return &Client{
|
|
||||||
baseURL: defaultBaseURL,
|
|
||||||
httpClient: &http.Client{Timeout: 40 * time.Second},
|
|
||||||
wechatUIN: generateWechatUIN(),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// BotID returns the bot's user ID.
|
|
||||||
func (c *Client) BotID() string {
|
|
||||||
return c.botID
|
|
||||||
}
|
|
||||||
|
|
||||||
// GetUpdates performs a long-poll for new messages.
|
|
||||||
func (c *Client) GetUpdates(ctx context.Context, buf string) (*GetUpdatesResponse, error) {
|
|
||||||
reqBody := GetUpdatesRequest{
|
|
||||||
GetUpdatesBuf: buf,
|
|
||||||
BaseInfo: BaseInfo{ChannelVersion: "1.0.0"},
|
|
||||||
}
|
|
||||||
|
|
||||||
ctx, cancel := context.WithTimeout(ctx, longPollTimeout+5*time.Second)
|
|
||||||
defer cancel()
|
|
||||||
|
|
||||||
var resp GetUpdatesResponse
|
|
||||||
if err := c.doPost(ctx, "/ilink/bot/getupdates", reqBody, &resp); err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
return &resp, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// SendMessage sends a message through iLink.
|
|
||||||
func (c *Client) SendMessage(ctx context.Context, msg *SendMessageRequest) (*SendMessageResponse, error) {
|
|
||||||
ctx, cancel := context.WithTimeout(ctx, sendTimeout)
|
|
||||||
defer cancel()
|
|
||||||
|
|
||||||
var resp SendMessageResponse
|
|
||||||
if err := c.doPost(ctx, "/ilink/bot/sendmessage", msg, &resp); err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
return &resp, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// GetConfig fetches bot config for a user (includes typing_ticket).
|
|
||||||
func (c *Client) GetConfig(ctx context.Context, userID, contextToken string) (*GetConfigResponse, error) {
|
|
||||||
ctx, cancel := context.WithTimeout(ctx, 10*time.Second)
|
|
||||||
defer cancel()
|
|
||||||
|
|
||||||
req := GetConfigRequest{
|
|
||||||
ILinkUserID: userID,
|
|
||||||
ContextToken: contextToken,
|
|
||||||
BaseInfo: BaseInfo{},
|
|
||||||
}
|
|
||||||
|
|
||||||
var resp GetConfigResponse
|
|
||||||
if err := c.doPost(ctx, "/ilink/bot/getconfig", req, &resp); err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
return &resp, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// SendTyping sends a typing indicator to a user.
|
|
||||||
func (c *Client) SendTyping(ctx context.Context, userID, typingTicket string, status int) error {
|
|
||||||
ctx, cancel := context.WithTimeout(ctx, 10*time.Second)
|
|
||||||
defer cancel()
|
|
||||||
|
|
||||||
req := SendTypingRequest{
|
|
||||||
ILinkUserID: userID,
|
|
||||||
TypingTicket: typingTicket,
|
|
||||||
Status: status,
|
|
||||||
BaseInfo: BaseInfo{},
|
|
||||||
}
|
|
||||||
|
|
||||||
var resp SendTypingResponse
|
|
||||||
if err := c.doPost(ctx, "/ilink/bot/sendtyping", req, &resp); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
if resp.Ret != 0 {
|
|
||||||
return fmt.Errorf("sendtyping failed: ret=%d errmsg=%s", resp.Ret, resp.ErrMsg)
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// GetUploadURL gets a pre-signed CDN upload URL for media files.
|
|
||||||
func (c *Client) GetUploadURL(ctx context.Context, req *GetUploadURLRequest) (*GetUploadURLResponse, error) {
|
|
||||||
ctx, cancel := context.WithTimeout(ctx, sendTimeout)
|
|
||||||
defer cancel()
|
|
||||||
|
|
||||||
var resp GetUploadURLResponse
|
|
||||||
if err := c.doPost(ctx, "/ilink/bot/getuploadurl", req, &resp); err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
return &resp, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// BaseURL returns the base URL for CDN operations.
|
|
||||||
func (c *Client) BaseURL() string {
|
|
||||||
return c.baseURL
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *Client) doPost(ctx context.Context, path string, body interface{}, result interface{}) error {
|
|
||||||
data, err := json.Marshal(body)
|
|
||||||
if err != nil {
|
|
||||||
return fmt.Errorf("marshal request: %w", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
req, err := http.NewRequestWithContext(ctx, http.MethodPost, c.baseURL+path, bytes.NewReader(data))
|
|
||||||
if err != nil {
|
|
||||||
return fmt.Errorf("create request: %w", err)
|
|
||||||
}
|
|
||||||
c.setHeaders(req)
|
|
||||||
|
|
||||||
resp, err := c.httpClient.Do(req)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
defer resp.Body.Close()
|
|
||||||
|
|
||||||
respBody, err := io.ReadAll(resp.Body)
|
|
||||||
if err != nil {
|
|
||||||
return fmt.Errorf("read response: %w", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
if resp.StatusCode != http.StatusOK {
|
|
||||||
return fmt.Errorf("HTTP %d: %s", resp.StatusCode, string(respBody))
|
|
||||||
}
|
|
||||||
|
|
||||||
if err := json.Unmarshal(respBody, result); err != nil {
|
|
||||||
return fmt.Errorf("unmarshal response: %w", err)
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *Client) doGet(ctx context.Context, url string, result interface{}) error {
|
|
||||||
req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
|
|
||||||
if err != nil {
|
|
||||||
return fmt.Errorf("create request: %w", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
resp, err := c.httpClient.Do(req)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
defer resp.Body.Close()
|
|
||||||
|
|
||||||
respBody, err := io.ReadAll(resp.Body)
|
|
||||||
if err != nil {
|
|
||||||
return fmt.Errorf("read response: %w", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
if resp.StatusCode != http.StatusOK {
|
|
||||||
return fmt.Errorf("HTTP %d: %s", resp.StatusCode, string(respBody))
|
|
||||||
}
|
|
||||||
|
|
||||||
if err := json.Unmarshal(respBody, result); err != nil {
|
|
||||||
return fmt.Errorf("unmarshal response: %w", err)
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *Client) setHeaders(req *http.Request) {
|
|
||||||
req.Header.Set("Content-Type", "application/json")
|
|
||||||
req.Header.Set("AuthorizationType", "ilink_bot_token")
|
|
||||||
req.Header.Set("Authorization", "Bearer "+c.botToken)
|
|
||||||
req.Header.Set("X-WECHAT-UIN", c.wechatUIN)
|
|
||||||
}
|
|
||||||
|
|
||||||
func generateWechatUIN() string {
|
|
||||||
var n uint32
|
|
||||||
_ = binary.Read(rand.Reader, binary.LittleEndian, &n)
|
|
||||||
s := fmt.Sprintf("%d", n)
|
|
||||||
return base64.StdEncoding.EncodeToString([]byte(s))
|
|
||||||
}
|
|
||||||
@@ -1,181 +0,0 @@
|
|||||||
package ilink
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"encoding/json"
|
|
||||||
"fmt"
|
|
||||||
"log"
|
|
||||||
"os"
|
|
||||||
"path/filepath"
|
|
||||||
"time"
|
|
||||||
)
|
|
||||||
|
|
||||||
const (
|
|
||||||
maxConsecutiveFailures = 5
|
|
||||||
initialBackoff = 3 * time.Second
|
|
||||||
maxBackoff = 60 * time.Second
|
|
||||||
sessionExpiredBackoff = 5 * time.Second
|
|
||||||
errCodeSessionExpired = -14
|
|
||||||
)
|
|
||||||
|
|
||||||
// MessageHandler is called for each received message.
|
|
||||||
type MessageHandler func(ctx context.Context, client *Client, msg WeixinMessage)
|
|
||||||
|
|
||||||
// Monitor manages the long-poll loop for receiving messages.
|
|
||||||
type Monitor struct {
|
|
||||||
client *Client
|
|
||||||
handler MessageHandler
|
|
||||||
getUpdatesBuf string
|
|
||||||
bufPath string
|
|
||||||
failures int
|
|
||||||
lastActivity time.Time
|
|
||||||
}
|
|
||||||
|
|
||||||
// NewMonitor creates a new long-poll monitor.
|
|
||||||
func NewMonitor(client *Client, handler MessageHandler) (*Monitor, error) {
|
|
||||||
accountID := NormalizeAccountID(client.BotID())
|
|
||||||
accountsRoot, err := accountDirectoryForID(accountID)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
bufPath := filepath.Join(accountsRoot, accountID+".sync.json")
|
|
||||||
|
|
||||||
m := &Monitor{
|
|
||||||
client: client,
|
|
||||||
handler: handler,
|
|
||||||
bufPath: bufPath,
|
|
||||||
lastActivity: time.Now(),
|
|
||||||
}
|
|
||||||
m.loadBuf()
|
|
||||||
return m, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// Run starts the long-poll loop. It blocks until ctx is cancelled.
|
|
||||||
// Automatically recovers from errors with exponential backoff.
|
|
||||||
func (m *Monitor) Run(ctx context.Context) error {
|
|
||||||
log.Println("[monitor] starting long-poll loop")
|
|
||||||
|
|
||||||
for {
|
|
||||||
select {
|
|
||||||
case <-ctx.Done():
|
|
||||||
log.Println("[monitor] shutting down")
|
|
||||||
return ctx.Err()
|
|
||||||
default:
|
|
||||||
}
|
|
||||||
|
|
||||||
resp, err := m.client.GetUpdates(ctx, m.getUpdatesBuf)
|
|
||||||
if err != nil {
|
|
||||||
if ctx.Err() != nil {
|
|
||||||
return ctx.Err()
|
|
||||||
}
|
|
||||||
m.failures++
|
|
||||||
backoff := m.calcBackoff()
|
|
||||||
log.Printf("[monitor] GetUpdates error (%d/%d, backoff=%s): %v",
|
|
||||||
m.failures, maxConsecutiveFailures, backoff, err)
|
|
||||||
if m.failures == maxConsecutiveFailures {
|
|
||||||
log.Printf("[monitor] WARNING: %d consecutive failures; reconnect from TraceMemo if this persists.", maxConsecutiveFailures)
|
|
||||||
}
|
|
||||||
select {
|
|
||||||
case <-time.After(backoff):
|
|
||||||
case <-ctx.Done():
|
|
||||||
return ctx.Err()
|
|
||||||
}
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
|
|
||||||
// Reset failure counter on any successful response
|
|
||||||
m.failures = 0
|
|
||||||
m.lastActivity = time.Now()
|
|
||||||
|
|
||||||
// Session expired — reset sync buf and reconnect silently
|
|
||||||
if resp.ErrCode == errCodeSessionExpired {
|
|
||||||
if m.getUpdatesBuf != "" {
|
|
||||||
log.Printf("[monitor] session expired, resetting sync buf")
|
|
||||||
m.getUpdatesBuf = ""
|
|
||||||
m.saveBuf()
|
|
||||||
} else {
|
|
||||||
// Sync buf already empty but still getting session expired:
|
|
||||||
// the bot token itself has expired. The user needs to re-login.
|
|
||||||
log.Printf("[monitor] WARNING: WeChat session expired and cannot be auto-recovered; reconnect from TraceMemo.")
|
|
||||||
}
|
|
||||||
select {
|
|
||||||
case <-time.After(sessionExpiredBackoff):
|
|
||||||
case <-ctx.Done():
|
|
||||||
return ctx.Err()
|
|
||||||
}
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
|
|
||||||
// Other server errors
|
|
||||||
if resp.Ret != 0 && resp.ErrCode != 0 {
|
|
||||||
log.Printf("[monitor] server error: ret=%d errcode=%d errmsg=%s", resp.Ret, resp.ErrCode, resp.ErrMsg)
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
|
|
||||||
// Update buf for next poll
|
|
||||||
if resp.GetUpdatesBuf != "" {
|
|
||||||
m.getUpdatesBuf = resp.GetUpdatesBuf
|
|
||||||
m.saveBuf()
|
|
||||||
}
|
|
||||||
|
|
||||||
// Process messages concurrently — don't block the poll loop
|
|
||||||
for _, msg := range resp.Msgs {
|
|
||||||
go m.handler(ctx, m.client, msg)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// calcBackoff returns an exponential backoff duration capped at maxBackoff.
|
|
||||||
func (m *Monitor) calcBackoff() time.Duration {
|
|
||||||
d := initialBackoff
|
|
||||||
for i := 1; i < m.failures; i++ {
|
|
||||||
d *= 2
|
|
||||||
if d > maxBackoff {
|
|
||||||
return maxBackoff
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return d
|
|
||||||
}
|
|
||||||
|
|
||||||
type syncData struct {
|
|
||||||
GetUpdatesBuf string `json:"get_updates_buf"`
|
|
||||||
}
|
|
||||||
|
|
||||||
func (m *Monitor) loadBuf() {
|
|
||||||
data, err := os.ReadFile(m.bufPath)
|
|
||||||
if err != nil {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
var s syncData
|
|
||||||
if json.Unmarshal(data, &s) == nil && s.GetUpdatesBuf != "" {
|
|
||||||
m.getUpdatesBuf = s.GetUpdatesBuf
|
|
||||||
log.Printf("[monitor] loaded sync buf from %s", m.bufPath)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (m *Monitor) saveBuf() {
|
|
||||||
dir := filepath.Dir(m.bufPath)
|
|
||||||
if err := os.MkdirAll(dir, 0o700); err != nil {
|
|
||||||
log.Printf("[monitor] failed to create buf dir: %v", err)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
data, _ := json.Marshal(syncData{GetUpdatesBuf: m.getUpdatesBuf})
|
|
||||||
if err := os.WriteFile(m.bufPath, data, 0o600); err != nil {
|
|
||||||
log.Printf("[monitor] failed to save buf: %v", err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// FormatMessageSummary returns a short description of a message for logging.
|
|
||||||
func FormatMessageSummary(msg WeixinMessage) string {
|
|
||||||
text := ""
|
|
||||||
for _, item := range msg.ItemList {
|
|
||||||
if item.Type == ItemTypeText && item.TextItem != nil {
|
|
||||||
text = item.TextItem.Text
|
|
||||||
break
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if len(text) > 50 {
|
|
||||||
text = text[:50] + "..."
|
|
||||||
}
|
|
||||||
return fmt.Sprintf("from=%s type=%d state=%d text=%q", msg.FromUserID, msg.MessageType, msg.MessageState, text)
|
|
||||||
}
|
|
||||||
@@ -1,219 +0,0 @@
|
|||||||
package ilink
|
|
||||||
|
|
||||||
// Message types
|
|
||||||
const (
|
|
||||||
MessageTypeNone = 0
|
|
||||||
MessageTypeUser = 1
|
|
||||||
MessageTypeBot = 2
|
|
||||||
)
|
|
||||||
|
|
||||||
// Message states
|
|
||||||
const (
|
|
||||||
MessageStateNew = 0
|
|
||||||
MessageStateGenerating = 1
|
|
||||||
MessageStateFinish = 2
|
|
||||||
)
|
|
||||||
|
|
||||||
// Item types
|
|
||||||
const (
|
|
||||||
ItemTypeNone = 0
|
|
||||||
ItemTypeText = 1
|
|
||||||
ItemTypeImage = 2
|
|
||||||
ItemTypeVoice = 3
|
|
||||||
ItemTypeFile = 4
|
|
||||||
ItemTypeVideo = 5
|
|
||||||
)
|
|
||||||
|
|
||||||
// QRCodeResponse is the response from get_bot_qrcode.
|
|
||||||
type QRCodeResponse struct {
|
|
||||||
QRCode string `json:"qrcode"`
|
|
||||||
QRCodeImgContent string `json:"qrcode_img_content"`
|
|
||||||
}
|
|
||||||
|
|
||||||
// QRStatusResponse is the response from get_qrcode_status.
|
|
||||||
type QRStatusResponse struct {
|
|
||||||
Status string `json:"status"`
|
|
||||||
BotToken string `json:"bot_token"`
|
|
||||||
ILinkBotID string `json:"ilink_bot_id"`
|
|
||||||
BaseURL string `json:"baseurl"`
|
|
||||||
ILinkUserID string `json:"ilink_user_id"`
|
|
||||||
}
|
|
||||||
|
|
||||||
// Credentials stores login session data.
|
|
||||||
type Credentials struct {
|
|
||||||
BotToken string `json:"bot_token"`
|
|
||||||
ILinkBotID string `json:"ilink_bot_id"`
|
|
||||||
BaseURL string `json:"baseurl"`
|
|
||||||
ILinkUserID string `json:"ilink_user_id"`
|
|
||||||
}
|
|
||||||
|
|
||||||
// BaseInfo is included in request bodies.
|
|
||||||
type BaseInfo struct {
|
|
||||||
ChannelVersion string `json:"channel_version,omitempty"`
|
|
||||||
}
|
|
||||||
|
|
||||||
// GetUpdatesRequest is the body for getupdates.
|
|
||||||
type GetUpdatesRequest struct {
|
|
||||||
GetUpdatesBuf string `json:"get_updates_buf"`
|
|
||||||
BaseInfo BaseInfo `json:"base_info"`
|
|
||||||
}
|
|
||||||
|
|
||||||
// GetUpdatesResponse is the response from getupdates.
|
|
||||||
type GetUpdatesResponse struct {
|
|
||||||
Ret int `json:"ret"`
|
|
||||||
ErrCode int `json:"errcode,omitempty"`
|
|
||||||
ErrMsg string `json:"errmsg,omitempty"`
|
|
||||||
Msgs []WeixinMessage `json:"msgs"`
|
|
||||||
GetUpdatesBuf string `json:"get_updates_buf"`
|
|
||||||
LongPollingTimeoutMs int `json:"longpolling_timeout_ms,omitempty"`
|
|
||||||
}
|
|
||||||
|
|
||||||
// WeixinMessage represents a message from WeChat.
|
|
||||||
type WeixinMessage struct {
|
|
||||||
Seq int `json:"seq,omitempty"`
|
|
||||||
MessageID int64 `json:"message_id,omitempty"`
|
|
||||||
FromUserID string `json:"from_user_id"`
|
|
||||||
ToUserID string `json:"to_user_id"`
|
|
||||||
MessageType int `json:"message_type"`
|
|
||||||
MessageState int `json:"message_state"`
|
|
||||||
ItemList []MessageItem `json:"item_list"`
|
|
||||||
ContextToken string `json:"context_token"`
|
|
||||||
}
|
|
||||||
|
|
||||||
// MessageItem is a single item in a message.
|
|
||||||
type MessageItem struct {
|
|
||||||
Type int `json:"type"`
|
|
||||||
TextItem *TextItem `json:"text_item,omitempty"`
|
|
||||||
ImageItem *ImageItem `json:"image_item,omitempty"`
|
|
||||||
VoiceItem *VoiceItem `json:"voice_item,omitempty"`
|
|
||||||
VideoItem *VideoItem `json:"video_item,omitempty"`
|
|
||||||
FileItem *FileItem `json:"file_item,omitempty"`
|
|
||||||
}
|
|
||||||
|
|
||||||
// CDN media type constants.
|
|
||||||
const (
|
|
||||||
CDNMediaTypeImage = 1
|
|
||||||
CDNMediaTypeVideo = 2
|
|
||||||
CDNMediaTypeFile = 3
|
|
||||||
)
|
|
||||||
|
|
||||||
// GetUploadURLRequest is the body for getuploadurl.
|
|
||||||
type GetUploadURLRequest struct {
|
|
||||||
FileKey string `json:"filekey"`
|
|
||||||
MediaType int `json:"media_type"`
|
|
||||||
ToUserID string `json:"to_user_id"`
|
|
||||||
RawSize int `json:"rawsize"`
|
|
||||||
RawFileMD5 string `json:"rawfilemd5"`
|
|
||||||
FileSize int `json:"filesize"`
|
|
||||||
NoNeedThumb bool `json:"no_need_thumb"`
|
|
||||||
AESKey string `json:"aeskey"`
|
|
||||||
BaseInfo BaseInfo `json:"base_info"`
|
|
||||||
}
|
|
||||||
|
|
||||||
// GetUploadURLResponse is the response from getuploadurl.
|
|
||||||
type GetUploadURLResponse struct {
|
|
||||||
Ret int `json:"ret"`
|
|
||||||
ErrMsg string `json:"errmsg,omitempty"`
|
|
||||||
UploadParam string `json:"upload_param"`
|
|
||||||
UploadFullURL string `json:"upload_full_url,omitempty"`
|
|
||||||
}
|
|
||||||
|
|
||||||
// TextItem holds text content.
|
|
||||||
type TextItem struct {
|
|
||||||
Text string `json:"text"`
|
|
||||||
}
|
|
||||||
|
|
||||||
// MediaInfo holds CDN media reference for uploaded files.
|
|
||||||
type MediaInfo struct {
|
|
||||||
EncryptQueryParam string `json:"encrypt_query_param"`
|
|
||||||
AESKey string `json:"aes_key"` // base64-encoded
|
|
||||||
EncryptType int `json:"encrypt_type"` // 1 = AES-128-ECB
|
|
||||||
}
|
|
||||||
|
|
||||||
// VoiceItem holds voice content.
|
|
||||||
type VoiceItem struct {
|
|
||||||
Media *MediaInfo `json:"media,omitempty"`
|
|
||||||
VoiceSize int `json:"voice_size,omitempty"`
|
|
||||||
EncodeType int `json:"encode_type,omitempty"` // 1=pcm 2=adpcm 3=feature 4=speex 5=amr 6=silk 7=mp3
|
|
||||||
BitsPerSample int `json:"bits_per_sample,omitempty"`
|
|
||||||
SampleRate int `json:"sample_rate,omitempty"` // Hz
|
|
||||||
Playtime int `json:"playtime,omitempty"` // duration in milliseconds
|
|
||||||
Text string `json:"text,omitempty"` // speech-to-text transcription from WeChat
|
|
||||||
}
|
|
||||||
|
|
||||||
// ImageItem holds image content.
|
|
||||||
type ImageItem struct {
|
|
||||||
URL string `json:"url,omitempty"`
|
|
||||||
Media *MediaInfo `json:"media,omitempty"`
|
|
||||||
MidSize int `json:"mid_size,omitempty"` // ciphertext size
|
|
||||||
}
|
|
||||||
|
|
||||||
// VideoItem holds video content.
|
|
||||||
type VideoItem struct {
|
|
||||||
Media *MediaInfo `json:"media,omitempty"`
|
|
||||||
VideoSize int `json:"video_size,omitempty"`
|
|
||||||
}
|
|
||||||
|
|
||||||
// FileItem holds file content.
|
|
||||||
type FileItem struct {
|
|
||||||
Media *MediaInfo `json:"media,omitempty"`
|
|
||||||
FileName string `json:"file_name,omitempty"`
|
|
||||||
Len string `json:"len,omitempty"` // plaintext size as string
|
|
||||||
}
|
|
||||||
|
|
||||||
// SendMessageRequest is the body for sendmessage.
|
|
||||||
type SendMessageRequest struct {
|
|
||||||
Msg SendMsg `json:"msg"`
|
|
||||||
BaseInfo BaseInfo `json:"base_info"`
|
|
||||||
}
|
|
||||||
|
|
||||||
// SendMsg is the message payload for sending.
|
|
||||||
type SendMsg struct {
|
|
||||||
FromUserID string `json:"from_user_id"`
|
|
||||||
ToUserID string `json:"to_user_id"`
|
|
||||||
ClientID string `json:"client_id"`
|
|
||||||
MessageType int `json:"message_type"`
|
|
||||||
MessageState int `json:"message_state"`
|
|
||||||
ItemList []MessageItem `json:"item_list"`
|
|
||||||
ContextToken string `json:"context_token"`
|
|
||||||
}
|
|
||||||
|
|
||||||
// SendMessageResponse is the response from sendmessage.
|
|
||||||
type SendMessageResponse struct {
|
|
||||||
Ret int `json:"ret"`
|
|
||||||
ErrMsg string `json:"errmsg,omitempty"`
|
|
||||||
}
|
|
||||||
|
|
||||||
// Typing status constants.
|
|
||||||
const (
|
|
||||||
TypingStatusTyping = 1
|
|
||||||
TypingStatusCancel = 2
|
|
||||||
)
|
|
||||||
|
|
||||||
// GetConfigRequest is the body for getconfig.
|
|
||||||
type GetConfigRequest struct {
|
|
||||||
ILinkUserID string `json:"ilink_user_id"`
|
|
||||||
ContextToken string `json:"context_token,omitempty"`
|
|
||||||
BaseInfo BaseInfo `json:"base_info"`
|
|
||||||
}
|
|
||||||
|
|
||||||
// GetConfigResponse is the response from getconfig.
|
|
||||||
type GetConfigResponse struct {
|
|
||||||
Ret int `json:"ret"`
|
|
||||||
ErrMsg string `json:"errmsg,omitempty"`
|
|
||||||
TypingTicket string `json:"typing_ticket,omitempty"`
|
|
||||||
}
|
|
||||||
|
|
||||||
// SendTypingRequest is the body for sendtyping.
|
|
||||||
type SendTypingRequest struct {
|
|
||||||
ILinkUserID string `json:"ilink_user_id"`
|
|
||||||
TypingTicket string `json:"typing_ticket"`
|
|
||||||
Status int `json:"status"`
|
|
||||||
BaseInfo BaseInfo `json:"base_info"`
|
|
||||||
}
|
|
||||||
|
|
||||||
// SendTypingResponse is the response from sendtyping.
|
|
||||||
type SendTypingResponse struct {
|
|
||||||
Ret int `json:"ret"`
|
|
||||||
ErrMsg string `json:"errmsg,omitempty"`
|
|
||||||
}
|
|
||||||
@@ -1,200 +0,0 @@
|
|||||||
package main
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"encoding/base64"
|
|
||||||
"encoding/json"
|
|
||||||
"errors"
|
|
||||||
"flag"
|
|
||||||
"fmt"
|
|
||||||
"log"
|
|
||||||
"os"
|
|
||||||
"os/signal"
|
|
||||||
"strings"
|
|
||||||
"sync"
|
|
||||||
"syscall"
|
|
||||||
|
|
||||||
"github.com/Wxw-Gu/WechatExplorer/services/wechat-connector/api"
|
|
||||||
"github.com/Wxw-Gu/WechatExplorer/services/wechat-connector/ilink"
|
|
||||||
"github.com/Wxw-Gu/WechatExplorer/services/wechat-connector/messaging"
|
|
||||||
"rsc.io/qr"
|
|
||||||
)
|
|
||||||
|
|
||||||
type loginEvent struct {
|
|
||||||
Status string `json:"status"`
|
|
||||||
QRCodeDataURL string `json:"qr_code_data_url,omitempty"`
|
|
||||||
AccountID string `json:"account_id,omitempty"`
|
|
||||||
WeChatUserID string `json:"wechat_user_id,omitempty"`
|
|
||||||
}
|
|
||||||
|
|
||||||
type accountSummary struct {
|
|
||||||
AccountID string `json:"account_id"`
|
|
||||||
WeChatUserID string `json:"wechat_user_id"`
|
|
||||||
}
|
|
||||||
|
|
||||||
func main() {
|
|
||||||
if len(os.Args) < 2 {
|
|
||||||
fatal(errors.New("expected one of: login, accounts, start"))
|
|
||||||
}
|
|
||||||
var err error
|
|
||||||
switch os.Args[1] {
|
|
||||||
case "login":
|
|
||||||
err = runLogin(os.Args[2:])
|
|
||||||
case "accounts":
|
|
||||||
err = runAccounts(os.Args[2:])
|
|
||||||
case "start":
|
|
||||||
err = runStart(os.Args[2:])
|
|
||||||
default:
|
|
||||||
err = fmt.Errorf("unknown command %q", os.Args[1])
|
|
||||||
}
|
|
||||||
if err != nil {
|
|
||||||
fatal(err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func fatal(err error) {
|
|
||||||
fmt.Fprintln(os.Stderr, err)
|
|
||||||
os.Exit(1)
|
|
||||||
}
|
|
||||||
|
|
||||||
func signalContext() (context.Context, context.CancelFunc) {
|
|
||||||
return signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM)
|
|
||||||
}
|
|
||||||
|
|
||||||
func runLogin(args []string) error {
|
|
||||||
flags := flag.NewFlagSet("login", flag.ContinueOnError)
|
|
||||||
jsonOutput := flags.Bool("json", false, "emit JSON Lines events")
|
|
||||||
if err := flags.Parse(args); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
ctx, cancel := signalContext()
|
|
||||||
defer cancel()
|
|
||||||
creds, err := login(ctx, *jsonOutput)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
if !*jsonOutput {
|
|
||||||
fmt.Printf("WeChat account %s connected.\n", creds.ILinkBotID)
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func login(ctx context.Context, jsonOutput bool) (*ilink.Credentials, error) {
|
|
||||||
qrResponse, err := ilink.FetchQRCode(ctx)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
code, err := qr.Encode(qrResponse.QRCodeImgContent, qr.L)
|
|
||||||
if err != nil {
|
|
||||||
return nil, fmt.Errorf("encode QR image: %w", err)
|
|
||||||
}
|
|
||||||
emit := func(event loginEvent) {
|
|
||||||
if jsonOutput {
|
|
||||||
_ = json.NewEncoder(os.Stdout).Encode(event)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
emit(loginEvent{Status: "qrcode", QRCodeDataURL: "data:image/png;base64," + base64.StdEncoding.EncodeToString(code.PNG())})
|
|
||||||
lastStatus := ""
|
|
||||||
creds, err := ilink.PollQRStatus(ctx, qrResponse.QRCode, func(status string) {
|
|
||||||
if status != lastStatus {
|
|
||||||
lastStatus = status
|
|
||||||
emit(loginEvent{Status: status})
|
|
||||||
}
|
|
||||||
})
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
if err := ilink.SaveCredentials(creds); err != nil {
|
|
||||||
return nil, fmt.Errorf("save credentials: %w", err)
|
|
||||||
}
|
|
||||||
emit(loginEvent{Status: "active", AccountID: creds.ILinkBotID, WeChatUserID: creds.ILinkUserID})
|
|
||||||
return creds, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func runAccounts(args []string) error {
|
|
||||||
flags := flag.NewFlagSet("accounts", flag.ContinueOnError)
|
|
||||||
jsonOutput := flags.Bool("json", false, "print JSON")
|
|
||||||
if err := flags.Parse(args); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
accounts, err := ilink.LoadAllCredentials()
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
items := make([]accountSummary, 0, len(accounts))
|
|
||||||
for _, account := range accounts {
|
|
||||||
items = append(items, accountSummary{AccountID: account.ILinkBotID, WeChatUserID: account.ILinkUserID})
|
|
||||||
}
|
|
||||||
if *jsonOutput {
|
|
||||||
return json.NewEncoder(os.Stdout).Encode(map[string]any{"accounts": items})
|
|
||||||
}
|
|
||||||
for _, item := range items {
|
|
||||||
fmt.Printf("%s\t%s\n", item.AccountID, item.WeChatUserID)
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func runStart(args []string) error {
|
|
||||||
flags := flag.NewFlagSet("start", flag.ContinueOnError)
|
|
||||||
_ = flags.Bool("foreground", false, "kept for host compatibility")
|
|
||||||
apiAddr := flags.String("api-addr", "127.0.0.1:18011", "local send API address")
|
|
||||||
accountID := flags.String("account-id", "", "account to start")
|
|
||||||
if err := flags.Parse(args); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
accounts, err := ilink.LoadAllCredentials()
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
if len(accounts) == 0 {
|
|
||||||
return errors.New("no connected WeChat account; scan a QR code first")
|
|
||||||
}
|
|
||||||
selected := accounts[len(accounts)-1]
|
|
||||||
if *accountID != "" {
|
|
||||||
selected = nil
|
|
||||||
for _, account := range accounts {
|
|
||||||
if account.ILinkBotID == *accountID {
|
|
||||||
selected = account
|
|
||||||
break
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if selected == nil {
|
|
||||||
return fmt.Errorf("account %q not found", *accountID)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
ctx, cancel := signalContext()
|
|
||||||
defer cancel()
|
|
||||||
client := ilink.NewClient(selected)
|
|
||||||
server := api.NewServer([]*ilink.Client{client}, *apiAddr)
|
|
||||||
webhookURL := strings.TrimSpace(os.Getenv("WECHAT_CONNECTOR_INBOUND_WEBHOOK_URL"))
|
|
||||||
webhook := messaging.NewInboundWebhook(webhookURL, os.Getenv("WECHAT_CONNECTOR_INBOUND_WEBHOOK_TOKEN"))
|
|
||||||
|
|
||||||
monitor, err := ilink.NewMonitor(client, func(messageContext context.Context, source *ilink.Client, message ilink.WeixinMessage) {
|
|
||||||
if webhookURL != "" {
|
|
||||||
webhook.Dispatch(messageContext, source, message)
|
|
||||||
}
|
|
||||||
})
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
var wait sync.WaitGroup
|
|
||||||
wait.Add(2)
|
|
||||||
go func() {
|
|
||||||
defer wait.Done()
|
|
||||||
if err := server.Run(ctx); err != nil && ctx.Err() == nil {
|
|
||||||
log.Printf("[api] stopped: %v", err)
|
|
||||||
cancel()
|
|
||||||
}
|
|
||||||
}()
|
|
||||||
go func() {
|
|
||||||
defer wait.Done()
|
|
||||||
if err := monitor.Run(ctx); err != nil && ctx.Err() == nil {
|
|
||||||
log.Printf("[monitor] stopped: %v", err)
|
|
||||||
cancel()
|
|
||||||
}
|
|
||||||
}()
|
|
||||||
wait.Wait()
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
@@ -1,232 +0,0 @@
|
|||||||
package messaging
|
|
||||||
|
|
||||||
import (
|
|
||||||
"bytes"
|
|
||||||
"context"
|
|
||||||
"crypto/aes"
|
|
||||||
"crypto/md5"
|
|
||||||
"crypto/rand"
|
|
||||||
"encoding/base64"
|
|
||||||
"encoding/hex"
|
|
||||||
"fmt"
|
|
||||||
"io"
|
|
||||||
"net/http"
|
|
||||||
"net/url"
|
|
||||||
"strings"
|
|
||||||
"time"
|
|
||||||
|
|
||||||
"github.com/Wxw-Gu/WechatExplorer/services/wechat-connector/ilink"
|
|
||||||
)
|
|
||||||
|
|
||||||
const cdnBaseURL = "https://novac2c.cdn.weixin.qq.com/c2c"
|
|
||||||
|
|
||||||
// UploadedFile holds the result of a CDN upload.
|
|
||||||
type UploadedFile struct {
|
|
||||||
DownloadParam string // encrypted query param for download
|
|
||||||
AESKeyHex string // hex-encoded AES key
|
|
||||||
FileSize int // plaintext size
|
|
||||||
CipherSize int // ciphertext size
|
|
||||||
}
|
|
||||||
|
|
||||||
// UploadFileToCDN encrypts and uploads a file to the WeChat CDN.
|
|
||||||
func UploadFileToCDN(ctx context.Context, client *ilink.Client, data []byte, toUserID string, mediaType int) (*UploadedFile, error) {
|
|
||||||
// Generate random filekey and AES key
|
|
||||||
filekey := make([]byte, 16)
|
|
||||||
aeskey := make([]byte, 16)
|
|
||||||
if _, err := rand.Read(filekey); err != nil {
|
|
||||||
return nil, fmt.Errorf("generate filekey: %w", err)
|
|
||||||
}
|
|
||||||
if _, err := rand.Read(aeskey); err != nil {
|
|
||||||
return nil, fmt.Errorf("generate aeskey: %w", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
filekeyHex := hex.EncodeToString(filekey)
|
|
||||||
aeskeyHex := hex.EncodeToString(aeskey)
|
|
||||||
|
|
||||||
// Calculate MD5 of plaintext
|
|
||||||
hash := md5.Sum(data)
|
|
||||||
rawMD5 := hex.EncodeToString(hash[:])
|
|
||||||
|
|
||||||
// Calculate ciphertext size (PKCS7 padding)
|
|
||||||
cipherSize := aesECBPaddedSize(len(data))
|
|
||||||
|
|
||||||
// Get upload URL from iLink API
|
|
||||||
uploadReq := &ilink.GetUploadURLRequest{
|
|
||||||
FileKey: filekeyHex,
|
|
||||||
MediaType: mediaType,
|
|
||||||
ToUserID: toUserID,
|
|
||||||
RawSize: len(data),
|
|
||||||
RawFileMD5: rawMD5,
|
|
||||||
FileSize: cipherSize,
|
|
||||||
NoNeedThumb: true,
|
|
||||||
AESKey: aeskeyHex,
|
|
||||||
BaseInfo: ilink.BaseInfo{},
|
|
||||||
}
|
|
||||||
|
|
||||||
uploadResp, err := client.GetUploadURL(ctx, uploadReq)
|
|
||||||
if err != nil {
|
|
||||||
return nil, fmt.Errorf("get upload URL: %w", err)
|
|
||||||
}
|
|
||||||
if uploadResp.Ret != 0 {
|
|
||||||
return nil, fmt.Errorf("get upload URL failed: ret=%d errmsg=%s", uploadResp.Ret, uploadResp.ErrMsg)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Encrypt data with AES-128-ECB
|
|
||||||
encrypted, err := encryptAESECB(data, aeskey)
|
|
||||||
if err != nil {
|
|
||||||
return nil, fmt.Errorf("encrypt: %w", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Upload to CDN: prefer server-provided full URL, fall back to param-based construction
|
|
||||||
cdnURL := strings.TrimSpace(uploadResp.UploadFullURL)
|
|
||||||
if cdnURL == "" {
|
|
||||||
if uploadResp.UploadParam == "" {
|
|
||||||
return nil, fmt.Errorf("getuploadurl returned no upload URL (need upload_full_url or upload_param)")
|
|
||||||
}
|
|
||||||
cdnURL = fmt.Sprintf("%s/upload?encrypted_query_param=%s&filekey=%s",
|
|
||||||
cdnBaseURL, url.QueryEscape(uploadResp.UploadParam), url.QueryEscape(filekeyHex))
|
|
||||||
}
|
|
||||||
|
|
||||||
downloadParam, err := uploadToCDN(ctx, encrypted, cdnURL)
|
|
||||||
if err != nil {
|
|
||||||
return nil, fmt.Errorf("CDN upload: %w", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
return &UploadedFile{
|
|
||||||
DownloadParam: downloadParam,
|
|
||||||
AESKeyHex: aeskeyHex,
|
|
||||||
FileSize: len(data),
|
|
||||||
CipherSize: cipherSize,
|
|
||||||
}, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// AESKeyToBase64 converts a hex AES key to base64 format for message items.
|
|
||||||
func AESKeyToBase64(hexKey string) string {
|
|
||||||
return base64.StdEncoding.EncodeToString([]byte(hexKey))
|
|
||||||
}
|
|
||||||
|
|
||||||
// DownloadFileFromCDN downloads and decrypts a file from the WeChat CDN.
|
|
||||||
func DownloadFileFromCDN(ctx context.Context, encryptQueryParam, aesKeyBase64 string) ([]byte, error) {
|
|
||||||
// Decode AES key: base64 -> hex string -> raw bytes
|
|
||||||
aesKeyHexBytes, err := base64.StdEncoding.DecodeString(aesKeyBase64)
|
|
||||||
if err != nil {
|
|
||||||
return nil, fmt.Errorf("decode AES key base64: %w", err)
|
|
||||||
}
|
|
||||||
aesKey, err := hex.DecodeString(string(aesKeyHexBytes))
|
|
||||||
if err != nil {
|
|
||||||
return nil, fmt.Errorf("decode AES key hex: %w", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Download encrypted data from CDN
|
|
||||||
downloadURL := fmt.Sprintf("%s/download?encrypted_query_param=%s",
|
|
||||||
cdnBaseURL, url.QueryEscape(encryptQueryParam))
|
|
||||||
|
|
||||||
reqCtx, cancel := context.WithTimeout(ctx, 60*time.Second)
|
|
||||||
defer cancel()
|
|
||||||
|
|
||||||
req, err := http.NewRequestWithContext(reqCtx, http.MethodGet, downloadURL, nil)
|
|
||||||
if err != nil {
|
|
||||||
return nil, fmt.Errorf("create download request: %w", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
resp, err := http.DefaultClient.Do(req)
|
|
||||||
if err != nil {
|
|
||||||
return nil, fmt.Errorf("download from CDN: %w", err)
|
|
||||||
}
|
|
||||||
defer resp.Body.Close()
|
|
||||||
|
|
||||||
if resp.StatusCode != http.StatusOK {
|
|
||||||
body, _ := io.ReadAll(resp.Body)
|
|
||||||
return nil, fmt.Errorf("CDN download HTTP %d: %s", resp.StatusCode, string(body))
|
|
||||||
}
|
|
||||||
|
|
||||||
encrypted, err := io.ReadAll(resp.Body)
|
|
||||||
if err != nil {
|
|
||||||
return nil, fmt.Errorf("read CDN response: %w", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Decrypt AES-128-ECB
|
|
||||||
return decryptAESECB(encrypted, aesKey)
|
|
||||||
}
|
|
||||||
|
|
||||||
// decryptAESECB decrypts data encrypted with AES-128-ECB and removes PKCS7 padding.
|
|
||||||
func decryptAESECB(ciphertext, key []byte) ([]byte, error) {
|
|
||||||
block, err := aes.NewCipher(key)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
if len(ciphertext)%aes.BlockSize != 0 {
|
|
||||||
return nil, fmt.Errorf("ciphertext is not a multiple of block size")
|
|
||||||
}
|
|
||||||
|
|
||||||
plaintext := make([]byte, len(ciphertext))
|
|
||||||
for i := 0; i < len(ciphertext); i += aes.BlockSize {
|
|
||||||
block.Decrypt(plaintext[i:i+aes.BlockSize], ciphertext[i:i+aes.BlockSize])
|
|
||||||
}
|
|
||||||
|
|
||||||
// Remove PKCS7 padding
|
|
||||||
if len(plaintext) == 0 {
|
|
||||||
return plaintext, nil
|
|
||||||
}
|
|
||||||
padLen := int(plaintext[len(plaintext)-1])
|
|
||||||
if padLen > aes.BlockSize || padLen == 0 {
|
|
||||||
return nil, fmt.Errorf("invalid PKCS7 padding")
|
|
||||||
}
|
|
||||||
return plaintext[:len(plaintext)-padLen], nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func uploadToCDN(ctx context.Context, encrypted []byte, cdnURL string) (string, error) {
|
|
||||||
req, err := http.NewRequestWithContext(ctx, http.MethodPost, cdnURL, bytes.NewReader(encrypted))
|
|
||||||
if err != nil {
|
|
||||||
return "", err
|
|
||||||
}
|
|
||||||
req.Header.Set("Content-Type", "application/octet-stream")
|
|
||||||
|
|
||||||
client := &http.Client{Timeout: 60 * time.Second}
|
|
||||||
resp, err := client.Do(req)
|
|
||||||
if err != nil {
|
|
||||||
return "", err
|
|
||||||
}
|
|
||||||
defer resp.Body.Close()
|
|
||||||
|
|
||||||
if resp.StatusCode != http.StatusOK {
|
|
||||||
body, _ := io.ReadAll(resp.Body)
|
|
||||||
return "", fmt.Errorf("CDN upload HTTP %d: %s", resp.StatusCode, string(body))
|
|
||||||
}
|
|
||||||
|
|
||||||
downloadParam := resp.Header.Get("X-Encrypted-Param")
|
|
||||||
if downloadParam == "" {
|
|
||||||
return "", fmt.Errorf("CDN upload: missing X-Encrypted-Param header")
|
|
||||||
}
|
|
||||||
|
|
||||||
return downloadParam, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// encryptAESECB encrypts data using AES-128-ECB with PKCS7 padding.
|
|
||||||
func encryptAESECB(plaintext, key []byte) ([]byte, error) {
|
|
||||||
block, err := aes.NewCipher(key)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
// PKCS7 padding
|
|
||||||
padLen := aes.BlockSize - (len(plaintext) % aes.BlockSize)
|
|
||||||
padded := make([]byte, len(plaintext)+padLen)
|
|
||||||
copy(padded, plaintext)
|
|
||||||
for i := len(plaintext); i < len(padded); i++ {
|
|
||||||
padded[i] = byte(padLen)
|
|
||||||
}
|
|
||||||
|
|
||||||
// ECB mode: encrypt each block independently
|
|
||||||
encrypted := make([]byte, len(padded))
|
|
||||||
for i := 0; i < len(padded); i += aes.BlockSize {
|
|
||||||
block.Encrypt(encrypted[i:i+aes.BlockSize], padded[i:i+aes.BlockSize])
|
|
||||||
}
|
|
||||||
|
|
||||||
return encrypted, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func aesECBPaddedSize(plaintextSize int) int {
|
|
||||||
return (plaintextSize/aes.BlockSize + 1) * aes.BlockSize
|
|
||||||
}
|
|
||||||
@@ -1,121 +0,0 @@
|
|||||||
package messaging
|
|
||||||
|
|
||||||
import (
|
|
||||||
"bytes"
|
|
||||||
"context"
|
|
||||||
"encoding/json"
|
|
||||||
"fmt"
|
|
||||||
"io"
|
|
||||||
"log"
|
|
||||||
"net/http"
|
|
||||||
"strings"
|
|
||||||
"time"
|
|
||||||
|
|
||||||
"github.com/Wxw-Gu/WechatExplorer/services/wechat-connector/ilink"
|
|
||||||
)
|
|
||||||
|
|
||||||
const (
|
|
||||||
webhookAttempts = 3
|
|
||||||
webhookTimeout = 5 * time.Second
|
|
||||||
)
|
|
||||||
|
|
||||||
type InboundWebhook struct {
|
|
||||||
url string
|
|
||||||
token string
|
|
||||||
client *http.Client
|
|
||||||
}
|
|
||||||
|
|
||||||
type inboundWebhookPayload struct {
|
|
||||||
AccountID string `json:"account_id"`
|
|
||||||
FromUserID string `json:"from_user_id"`
|
|
||||||
MessageID int64 `json:"message_id"`
|
|
||||||
MessageType int `json:"message_type"`
|
|
||||||
Items []inboundWebhookItem `json:"items"`
|
|
||||||
ReceivedAt time.Time `json:"received_at"`
|
|
||||||
}
|
|
||||||
|
|
||||||
type inboundWebhookItem struct {
|
|
||||||
Type int `json:"type"`
|
|
||||||
Text string `json:"text,omitempty"`
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewInboundWebhook(url, token string) *InboundWebhook {
|
|
||||||
return &InboundWebhook{
|
|
||||||
url: strings.TrimSpace(url),
|
|
||||||
token: token,
|
|
||||||
client: &http.Client{Timeout: webhookTimeout},
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Dispatch is intentionally non-blocking so webhook failures never stall iLink polling.
|
|
||||||
func (w *InboundWebhook) Dispatch(ctx context.Context, client *ilink.Client, msg ilink.WeixinMessage) {
|
|
||||||
payload := normalizeInboundMessage(client.BotID(), msg)
|
|
||||||
go func() {
|
|
||||||
if err := w.deliver(ctx, payload); err != nil {
|
|
||||||
log.Printf("[webhook] inbound delivery failed for message %d: %v", msg.MessageID, err)
|
|
||||||
}
|
|
||||||
}()
|
|
||||||
}
|
|
||||||
|
|
||||||
func (w *InboundWebhook) deliver(ctx context.Context, payload inboundWebhookPayload) error {
|
|
||||||
body, err := json.Marshal(payload)
|
|
||||||
if err != nil {
|
|
||||||
return fmt.Errorf("encode payload: %w", err)
|
|
||||||
}
|
|
||||||
var lastErr error
|
|
||||||
for attempt := 1; attempt <= webhookAttempts; attempt++ {
|
|
||||||
if attempt > 1 {
|
|
||||||
timer := time.NewTimer(time.Duration(attempt-1) * time.Second)
|
|
||||||
select {
|
|
||||||
case <-ctx.Done():
|
|
||||||
timer.Stop()
|
|
||||||
return ctx.Err()
|
|
||||||
case <-timer.C:
|
|
||||||
}
|
|
||||||
}
|
|
||||||
req, reqErr := http.NewRequestWithContext(ctx, http.MethodPost, w.url, bytes.NewReader(body))
|
|
||||||
if reqErr != nil {
|
|
||||||
return fmt.Errorf("create request: %w", reqErr)
|
|
||||||
}
|
|
||||||
req.Header.Set("Content-Type", "application/json")
|
|
||||||
if w.token != "" {
|
|
||||||
req.Header.Set("Authorization", "Bearer "+w.token)
|
|
||||||
}
|
|
||||||
resp, doErr := w.client.Do(req)
|
|
||||||
if doErr != nil {
|
|
||||||
lastErr = doErr
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
responseBody, _ := io.ReadAll(io.LimitReader(resp.Body, 4096))
|
|
||||||
resp.Body.Close()
|
|
||||||
if resp.StatusCode >= 200 && resp.StatusCode < 300 {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
lastErr = fmt.Errorf("status %s: %s", resp.Status, strings.TrimSpace(string(responseBody)))
|
|
||||||
if resp.StatusCode >= 400 && resp.StatusCode < 500 {
|
|
||||||
break
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return lastErr
|
|
||||||
}
|
|
||||||
|
|
||||||
func normalizeInboundMessage(accountID string, msg ilink.WeixinMessage) inboundWebhookPayload {
|
|
||||||
items := make([]inboundWebhookItem, 0, len(msg.ItemList))
|
|
||||||
for _, item := range msg.ItemList {
|
|
||||||
normalized := inboundWebhookItem{Type: item.Type}
|
|
||||||
if item.TextItem != nil {
|
|
||||||
normalized.Text = item.TextItem.Text
|
|
||||||
} else if item.VoiceItem != nil {
|
|
||||||
normalized.Text = item.VoiceItem.Text
|
|
||||||
}
|
|
||||||
items = append(items, normalized)
|
|
||||||
}
|
|
||||||
return inboundWebhookPayload{
|
|
||||||
AccountID: accountID,
|
|
||||||
FromUserID: msg.FromUserID,
|
|
||||||
MessageID: msg.MessageID,
|
|
||||||
MessageType: msg.MessageType,
|
|
||||||
Items: items,
|
|
||||||
ReceivedAt: time.Now().UTC(),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,75 +0,0 @@
|
|||||||
package messaging
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"encoding/json"
|
|
||||||
"net/http"
|
|
||||||
"net/http/httptest"
|
|
||||||
"sync/atomic"
|
|
||||||
"testing"
|
|
||||||
|
|
||||||
"github.com/Wxw-Gu/WechatExplorer/services/wechat-connector/ilink"
|
|
||||||
)
|
|
||||||
|
|
||||||
func TestInboundWebhookDeliversNormalizedPayload(t *testing.T) {
|
|
||||||
var got inboundWebhookPayload
|
|
||||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
||||||
if r.Header.Get("Authorization") != "Bearer secret" {
|
|
||||||
t.Errorf("authorization = %q", r.Header.Get("Authorization"))
|
|
||||||
}
|
|
||||||
if err := json.NewDecoder(r.Body).Decode(&got); err != nil {
|
|
||||||
t.Errorf("decode: %v", err)
|
|
||||||
}
|
|
||||||
w.WriteHeader(http.StatusOK)
|
|
||||||
}))
|
|
||||||
defer server.Close()
|
|
||||||
|
|
||||||
webhook := NewInboundWebhook(server.URL, "secret")
|
|
||||||
err := webhook.deliver(context.Background(), normalizeInboundMessage("bot-new", ilink.WeixinMessage{
|
|
||||||
MessageID: 7, FromUserID: "user-1", MessageType: ilink.MessageTypeUser,
|
|
||||||
ItemList: []ilink.MessageItem{{Type: ilink.ItemTypeText, TextItem: &ilink.TextItem{Text: "最近5条消息"}}},
|
|
||||||
}))
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("deliver: %v", err)
|
|
||||||
}
|
|
||||||
if got.AccountID != "bot-new" || got.MessageID != 7 || len(got.Items) != 1 || got.Items[0].Text != "最近5条消息" {
|
|
||||||
t.Fatalf("payload = %#v", got)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestInboundWebhookRetriesServerErrors(t *testing.T) {
|
|
||||||
var calls atomic.Int32
|
|
||||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
|
||||||
if calls.Add(1) < 3 {
|
|
||||||
http.Error(w, "temporary", http.StatusServiceUnavailable)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
w.WriteHeader(http.StatusOK)
|
|
||||||
}))
|
|
||||||
defer server.Close()
|
|
||||||
|
|
||||||
webhook := NewInboundWebhook(server.URL, "")
|
|
||||||
if err := webhook.deliver(context.Background(), inboundWebhookPayload{}); err != nil {
|
|
||||||
t.Fatalf("deliver: %v", err)
|
|
||||||
}
|
|
||||||
if calls.Load() != 3 {
|
|
||||||
t.Fatalf("calls = %d, want 3", calls.Load())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestInboundWebhookDoesNotRetryClientErrors(t *testing.T) {
|
|
||||||
var calls atomic.Int32
|
|
||||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
|
||||||
calls.Add(1)
|
|
||||||
http.Error(w, "unauthorized", http.StatusUnauthorized)
|
|
||||||
}))
|
|
||||||
defer server.Close()
|
|
||||||
|
|
||||||
webhook := NewInboundWebhook(server.URL, "")
|
|
||||||
if err := webhook.deliver(context.Background(), inboundWebhookPayload{}); err == nil {
|
|
||||||
t.Fatal("deliver error = nil")
|
|
||||||
}
|
|
||||||
if calls.Load() != 1 {
|
|
||||||
t.Fatalf("calls = %d, want 1", calls.Load())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,103 +0,0 @@
|
|||||||
package messaging
|
|
||||||
|
|
||||||
import (
|
|
||||||
"regexp"
|
|
||||||
"strings"
|
|
||||||
)
|
|
||||||
|
|
||||||
var (
|
|
||||||
// Code blocks: strip fences, keep code content
|
|
||||||
reCodeBlock = regexp.MustCompile("(?s)```[^\n]*\n?(.*?)```")
|
|
||||||
// Inline code: strip backticks, keep content
|
|
||||||
reInlineCode = regexp.MustCompile("`([^`]+)`")
|
|
||||||
// Images: remove entirely
|
|
||||||
reImage = regexp.MustCompile(`!\[[^\]]*\]\([^)]*\)`)
|
|
||||||
// Links: keep display text only
|
|
||||||
reLink = regexp.MustCompile(`\[([^\]]+)\]\([^)]*\)`)
|
|
||||||
// Table separator rows: remove
|
|
||||||
reTableSep = regexp.MustCompile(`(?m)^\|[\s:|\-]+\|$`)
|
|
||||||
// Table rows: convert pipe-delimited to space-delimited
|
|
||||||
reTableRow = regexp.MustCompile(`(?m)^\|(.+)\|$`)
|
|
||||||
// Headers: remove # prefix
|
|
||||||
reHeader = regexp.MustCompile(`(?m)^#{1,6}\s+`)
|
|
||||||
// Bold: **text** or __text__
|
|
||||||
reBold = regexp.MustCompile(`\*\*(.+?)\*\*|__(.+?)__`)
|
|
||||||
// Italic: *text* or _text_
|
|
||||||
reItalic = regexp.MustCompile(`(?:^|[^*])\*([^*]+)\*(?:[^*]|$)|(?:^|[^_])_([^_]+)_(?:[^_]|$)`)
|
|
||||||
// Strikethrough: ~~text~~
|
|
||||||
reStrike = regexp.MustCompile(`~~(.+?)~~`)
|
|
||||||
// Blockquote: > prefix
|
|
||||||
reBlockquote = regexp.MustCompile(`(?m)^>\s?`)
|
|
||||||
// Horizontal rule
|
|
||||||
reHR = regexp.MustCompile(`(?m)^[-*_]{3,}\s*$`)
|
|
||||||
// Unordered list markers: -, *, +
|
|
||||||
reUL = regexp.MustCompile(`(?m)^(\s*)[-*+]\s+`)
|
|
||||||
)
|
|
||||||
|
|
||||||
// MarkdownToPlainText converts markdown to readable plain text for WeChat.
|
|
||||||
func MarkdownToPlainText(text string) string {
|
|
||||||
result := text
|
|
||||||
|
|
||||||
// Code blocks: strip fences, keep code content
|
|
||||||
result = reCodeBlock.ReplaceAllStringFunc(result, func(match string) string {
|
|
||||||
parts := reCodeBlock.FindStringSubmatch(match)
|
|
||||||
if len(parts) > 1 {
|
|
||||||
return strings.TrimSpace(parts[1])
|
|
||||||
}
|
|
||||||
return match
|
|
||||||
})
|
|
||||||
|
|
||||||
// Images: remove entirely
|
|
||||||
result = reImage.ReplaceAllString(result, "")
|
|
||||||
|
|
||||||
// Links: keep display text only
|
|
||||||
result = reLink.ReplaceAllString(result, "$1")
|
|
||||||
|
|
||||||
// Table separator rows: remove
|
|
||||||
result = reTableSep.ReplaceAllString(result, "")
|
|
||||||
|
|
||||||
// Table rows: pipe-delimited to space-delimited
|
|
||||||
result = reTableRow.ReplaceAllStringFunc(result, func(match string) string {
|
|
||||||
parts := reTableRow.FindStringSubmatch(match)
|
|
||||||
if len(parts) > 1 {
|
|
||||||
cells := strings.Split(parts[1], "|")
|
|
||||||
for i := range cells {
|
|
||||||
cells[i] = strings.TrimSpace(cells[i])
|
|
||||||
}
|
|
||||||
return strings.Join(cells, " ")
|
|
||||||
}
|
|
||||||
return match
|
|
||||||
})
|
|
||||||
|
|
||||||
// Headers: remove # prefix
|
|
||||||
result = reHeader.ReplaceAllString(result, "")
|
|
||||||
|
|
||||||
// Bold
|
|
||||||
result = reBold.ReplaceAllStringFunc(result, func(match string) string {
|
|
||||||
parts := reBold.FindStringSubmatch(match)
|
|
||||||
if parts[1] != "" {
|
|
||||||
return parts[1]
|
|
||||||
}
|
|
||||||
return parts[2]
|
|
||||||
})
|
|
||||||
|
|
||||||
// Strikethrough
|
|
||||||
result = reStrike.ReplaceAllString(result, "$1")
|
|
||||||
|
|
||||||
// Blockquote
|
|
||||||
result = reBlockquote.ReplaceAllString(result, "")
|
|
||||||
|
|
||||||
// Horizontal rule -> empty line
|
|
||||||
result = reHR.ReplaceAllString(result, "")
|
|
||||||
|
|
||||||
// Unordered list: replace markers with "• "
|
|
||||||
result = reUL.ReplaceAllString(result, "${1}• ")
|
|
||||||
|
|
||||||
// Inline code: strip backticks (do after code blocks)
|
|
||||||
result = reInlineCode.ReplaceAllString(result, "$1")
|
|
||||||
|
|
||||||
// Clean up excessive blank lines
|
|
||||||
result = regexp.MustCompile(`\n{3,}`).ReplaceAllString(result, "\n\n")
|
|
||||||
|
|
||||||
return strings.TrimSpace(result)
|
|
||||||
}
|
|
||||||
@@ -1,221 +0,0 @@
|
|||||||
package messaging
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"fmt"
|
|
||||||
"io"
|
|
||||||
"log"
|
|
||||||
"mime"
|
|
||||||
"net/http"
|
|
||||||
"os"
|
|
||||||
"path/filepath"
|
|
||||||
"regexp"
|
|
||||||
"strings"
|
|
||||||
"time"
|
|
||||||
|
|
||||||
"github.com/Wxw-Gu/WechatExplorer/services/wechat-connector/ilink"
|
|
||||||
)
|
|
||||||
|
|
||||||
// reMarkdownImage matches markdown image syntax: 
|
|
||||||
var reMarkdownImage = regexp.MustCompile(`!\[[^\]]*\]\(([^)]+)\)`)
|
|
||||||
|
|
||||||
// ExtractImageURLs extracts image URLs from markdown text.
|
|
||||||
func ExtractImageURLs(text string) []string {
|
|
||||||
matches := reMarkdownImage.FindAllStringSubmatch(text, -1)
|
|
||||||
var urls []string
|
|
||||||
for _, m := range matches {
|
|
||||||
url := strings.TrimSpace(m[1])
|
|
||||||
if strings.HasPrefix(url, "http://") || strings.HasPrefix(url, "https://") {
|
|
||||||
urls = append(urls, url)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return urls
|
|
||||||
}
|
|
||||||
|
|
||||||
// SendMediaFromURL sends a local file or downloads from a URL and sends it as a media message.
|
|
||||||
func SendMediaFromURL(ctx context.Context, client *ilink.Client, toUserID, mediaURL, contextToken string) error {
|
|
||||||
// Check if it's a local file
|
|
||||||
if _, err := os.Stat(mediaURL); err == nil {
|
|
||||||
return SendMediaFromPath(ctx, client, toUserID, mediaURL, contextToken)
|
|
||||||
}
|
|
||||||
// Must be a valid HTTP URL to download
|
|
||||||
if !strings.HasPrefix(mediaURL, "http://") && !strings.HasPrefix(mediaURL, "https://") {
|
|
||||||
return fmt.Errorf("unsupported media path (not a local file and not an HTTP URL): %s", mediaURL)
|
|
||||||
}
|
|
||||||
data, contentType, err := downloadFile(ctx, mediaURL)
|
|
||||||
if err != nil {
|
|
||||||
return fmt.Errorf("download %s: %w", mediaURL, err)
|
|
||||||
}
|
|
||||||
|
|
||||||
return sendMediaData(ctx, client, toUserID, filenameFromURL(mediaURL), mediaURL, data, contentType, contextToken)
|
|
||||||
}
|
|
||||||
|
|
||||||
// SendMediaFromPath reads a local file and sends it as a media message.
|
|
||||||
func SendMediaFromPath(ctx context.Context, client *ilink.Client, toUserID, path, contextToken string) error {
|
|
||||||
data, err := os.ReadFile(path)
|
|
||||||
if err != nil {
|
|
||||||
return fmt.Errorf("read %s: %w", path, err)
|
|
||||||
}
|
|
||||||
|
|
||||||
return sendMediaData(ctx, client, toUserID, filepath.Base(path), path, data, inferContentType(path), contextToken)
|
|
||||||
}
|
|
||||||
|
|
||||||
func sendMediaData(ctx context.Context, client *ilink.Client, toUserID, fileName, source string, data []byte, contentType, contextToken string) error {
|
|
||||||
if fileName == "" {
|
|
||||||
fileName = "file"
|
|
||||||
}
|
|
||||||
|
|
||||||
cdnMediaType, itemType := classifyMedia(contentType, source)
|
|
||||||
|
|
||||||
log.Printf("[media] uploading %s (%s, %d bytes) for %s", source, contentType, len(data), toUserID)
|
|
||||||
|
|
||||||
uploaded, err := UploadFileToCDN(ctx, client, data, toUserID, cdnMediaType)
|
|
||||||
if err != nil {
|
|
||||||
return fmt.Errorf("upload to CDN: %w", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
media := &ilink.MediaInfo{
|
|
||||||
EncryptQueryParam: uploaded.DownloadParam,
|
|
||||||
AESKey: AESKeyToBase64(uploaded.AESKeyHex),
|
|
||||||
EncryptType: 1,
|
|
||||||
}
|
|
||||||
|
|
||||||
var item ilink.MessageItem
|
|
||||||
switch itemType {
|
|
||||||
case ilink.ItemTypeImage:
|
|
||||||
item = ilink.MessageItem{
|
|
||||||
Type: ilink.ItemTypeImage,
|
|
||||||
ImageItem: &ilink.ImageItem{
|
|
||||||
Media: media,
|
|
||||||
MidSize: uploaded.CipherSize,
|
|
||||||
},
|
|
||||||
}
|
|
||||||
case ilink.ItemTypeVideo:
|
|
||||||
item = ilink.MessageItem{
|
|
||||||
Type: ilink.ItemTypeVideo,
|
|
||||||
VideoItem: &ilink.VideoItem{
|
|
||||||
Media: media,
|
|
||||||
VideoSize: uploaded.CipherSize,
|
|
||||||
},
|
|
||||||
}
|
|
||||||
default:
|
|
||||||
item = ilink.MessageItem{
|
|
||||||
Type: ilink.ItemTypeFile,
|
|
||||||
FileItem: &ilink.FileItem{
|
|
||||||
Media: media,
|
|
||||||
FileName: fileName,
|
|
||||||
Len: fmt.Sprintf("%d", uploaded.FileSize),
|
|
||||||
},
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
req := &ilink.SendMessageRequest{
|
|
||||||
Msg: ilink.SendMsg{
|
|
||||||
FromUserID: client.BotID(),
|
|
||||||
ToUserID: toUserID,
|
|
||||||
ClientID: NewClientID(),
|
|
||||||
MessageType: ilink.MessageTypeBot,
|
|
||||||
MessageState: ilink.MessageStateFinish,
|
|
||||||
ItemList: []ilink.MessageItem{item},
|
|
||||||
ContextToken: contextToken,
|
|
||||||
},
|
|
||||||
BaseInfo: ilink.BaseInfo{},
|
|
||||||
}
|
|
||||||
|
|
||||||
resp, err := client.SendMessage(ctx, req)
|
|
||||||
if err != nil {
|
|
||||||
return fmt.Errorf("send media message: %w", err)
|
|
||||||
}
|
|
||||||
if resp.Ret != 0 {
|
|
||||||
return fmt.Errorf("send media failed: ret=%d errmsg=%s", resp.Ret, resp.ErrMsg)
|
|
||||||
}
|
|
||||||
|
|
||||||
log.Printf("[media] sent %s to %s from %s", contentType, toUserID, source)
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func downloadFile(ctx context.Context, url string) ([]byte, string, error) {
|
|
||||||
ctx, cancel := context.WithTimeout(ctx, 60*time.Second)
|
|
||||||
defer cancel()
|
|
||||||
|
|
||||||
req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
|
|
||||||
if err != nil {
|
|
||||||
return nil, "", err
|
|
||||||
}
|
|
||||||
|
|
||||||
resp, err := http.DefaultClient.Do(req)
|
|
||||||
if err != nil {
|
|
||||||
return nil, "", err
|
|
||||||
}
|
|
||||||
defer resp.Body.Close()
|
|
||||||
|
|
||||||
if resp.StatusCode != http.StatusOK {
|
|
||||||
return nil, "", fmt.Errorf("HTTP %d", resp.StatusCode)
|
|
||||||
}
|
|
||||||
|
|
||||||
data, err := io.ReadAll(resp.Body)
|
|
||||||
if err != nil {
|
|
||||||
return nil, "", err
|
|
||||||
}
|
|
||||||
|
|
||||||
contentType := resp.Header.Get("Content-Type")
|
|
||||||
if contentType == "" {
|
|
||||||
contentType = inferContentType(url)
|
|
||||||
}
|
|
||||||
|
|
||||||
return data, contentType, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func classifyMedia(contentType, url string) (cdnMediaType int, itemType int) {
|
|
||||||
ct := strings.ToLower(contentType)
|
|
||||||
|
|
||||||
if strings.HasPrefix(ct, "image/") || isImageExt(url) {
|
|
||||||
return ilink.CDNMediaTypeImage, ilink.ItemTypeImage
|
|
||||||
}
|
|
||||||
if strings.HasPrefix(ct, "video/") || isVideoExt(url) {
|
|
||||||
return ilink.CDNMediaTypeVideo, ilink.ItemTypeVideo
|
|
||||||
}
|
|
||||||
return ilink.CDNMediaTypeFile, ilink.ItemTypeFile
|
|
||||||
}
|
|
||||||
|
|
||||||
func isImageExt(url string) bool {
|
|
||||||
ext := strings.ToLower(filepath.Ext(stripQuery(url)))
|
|
||||||
switch ext {
|
|
||||||
case ".png", ".jpg", ".jpeg", ".gif", ".webp", ".bmp":
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
|
|
||||||
func isVideoExt(url string) bool {
|
|
||||||
ext := strings.ToLower(filepath.Ext(stripQuery(url)))
|
|
||||||
switch ext {
|
|
||||||
case ".mp4", ".mov", ".webm", ".mkv", ".avi":
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
|
|
||||||
func inferContentType(url string) string {
|
|
||||||
ext := filepath.Ext(stripQuery(url))
|
|
||||||
if ct := mime.TypeByExtension(ext); ct != "" {
|
|
||||||
return ct
|
|
||||||
}
|
|
||||||
return "application/octet-stream"
|
|
||||||
}
|
|
||||||
|
|
||||||
func filenameFromURL(rawURL string) string {
|
|
||||||
u := stripQuery(rawURL)
|
|
||||||
name := filepath.Base(u)
|
|
||||||
if name == "" || name == "." || name == "/" {
|
|
||||||
return "file"
|
|
||||||
}
|
|
||||||
return name
|
|
||||||
}
|
|
||||||
|
|
||||||
func stripQuery(rawURL string) string {
|
|
||||||
if i := strings.IndexByte(rawURL, '?'); i >= 0 {
|
|
||||||
return rawURL[:i]
|
|
||||||
}
|
|
||||||
return rawURL
|
|
||||||
}
|
|
||||||
@@ -1,73 +0,0 @@
|
|||||||
package messaging
|
|
||||||
|
|
||||||
import "testing"
|
|
||||||
|
|
||||||
func TestExtractImageURLs(t *testing.T) {
|
|
||||||
text := "check  and "
|
|
||||||
urls := ExtractImageURLs(text)
|
|
||||||
if len(urls) != 2 {
|
|
||||||
t.Fatalf("expected 2 urls, got %d", len(urls))
|
|
||||||
}
|
|
||||||
if urls[0] != "https://example.com/a.png" {
|
|
||||||
t.Errorf("urls[0] = %q", urls[0])
|
|
||||||
}
|
|
||||||
if urls[1] != "https://example.com/b.jpg" {
|
|
||||||
t.Errorf("urls[1] = %q", urls[1])
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestExtractImageURLs_NoImages(t *testing.T) {
|
|
||||||
urls := ExtractImageURLs("just plain text")
|
|
||||||
if len(urls) != 0 {
|
|
||||||
t.Errorf("expected 0 urls, got %d", len(urls))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestExtractImageURLs_RelativeURL(t *testing.T) {
|
|
||||||
text := ""
|
|
||||||
urls := ExtractImageURLs(text)
|
|
||||||
if len(urls) != 0 {
|
|
||||||
t.Errorf("expected 0 urls for relative path, got %d", len(urls))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestFilenameFromURL(t *testing.T) {
|
|
||||||
tests := []struct {
|
|
||||||
url string
|
|
||||||
want string
|
|
||||||
}{
|
|
||||||
{"https://example.com/photo.png", "photo.png"},
|
|
||||||
{"https://example.com/path/to/report.pdf", "report.pdf"},
|
|
||||||
{"https://example.com/file", "file"},
|
|
||||||
}
|
|
||||||
for _, tt := range tests {
|
|
||||||
got := filenameFromURL(tt.url)
|
|
||||||
if got != tt.want {
|
|
||||||
t.Errorf("filenameFromURL(%q) = %q, want %q", tt.url, got, tt.want)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestFilenameFromURL_WithQuery(t *testing.T) {
|
|
||||||
got := filenameFromURL("https://example.com/photo.png?token=abc")
|
|
||||||
if got != "photo.png" {
|
|
||||||
t.Errorf("got %q, want %q", got, "photo.png")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestStripQuery(t *testing.T) {
|
|
||||||
tests := []struct {
|
|
||||||
input string
|
|
||||||
want string
|
|
||||||
}{
|
|
||||||
{"https://example.com/a?b=c", "https://example.com/a"},
|
|
||||||
{"https://example.com/a", "https://example.com/a"},
|
|
||||||
{"https://example.com/?x=1&y=2", "https://example.com/"},
|
|
||||||
}
|
|
||||||
for _, tt := range tests {
|
|
||||||
got := stripQuery(tt.input)
|
|
||||||
if got != tt.want {
|
|
||||||
t.Errorf("stripQuery(%q) = %q, want %q", tt.input, got, tt.want)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,86 +0,0 @@
|
|||||||
package messaging
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"fmt"
|
|
||||||
"log"
|
|
||||||
|
|
||||||
"github.com/Wxw-Gu/WechatExplorer/services/wechat-connector/ilink"
|
|
||||||
"github.com/google/uuid"
|
|
||||||
)
|
|
||||||
|
|
||||||
// NewClientID generates a new unique client ID for message correlation.
|
|
||||||
func NewClientID() string {
|
|
||||||
return uuid.New().String()
|
|
||||||
}
|
|
||||||
|
|
||||||
// SendTypingState sends a typing indicator to a user via the iLink sendtyping API.
|
|
||||||
// It first fetches a typing_ticket via getconfig, then sends the typing status.
|
|
||||||
func SendTypingState(ctx context.Context, client *ilink.Client, userID, contextToken string) error {
|
|
||||||
// Get typing ticket
|
|
||||||
configResp, err := client.GetConfig(ctx, userID, contextToken)
|
|
||||||
if err != nil {
|
|
||||||
return fmt.Errorf("get config for typing: %w", err)
|
|
||||||
}
|
|
||||||
if configResp.TypingTicket == "" {
|
|
||||||
return fmt.Errorf("no typing_ticket returned from getconfig")
|
|
||||||
}
|
|
||||||
|
|
||||||
// Send typing
|
|
||||||
if err := client.SendTyping(ctx, userID, configResp.TypingTicket, ilink.TypingStatusTyping); err != nil {
|
|
||||||
return fmt.Errorf("send typing: %w", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
log.Printf("[sender] sent typing indicator to %s", userID)
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// SendTextReply sends a text reply to a user through the iLink API.
|
|
||||||
// If clientID is empty, a new one is generated.
|
|
||||||
func SendTextReply(ctx context.Context, client *ilink.Client, toUserID, text, contextToken, clientID string) error {
|
|
||||||
if clientID == "" {
|
|
||||||
clientID = NewClientID()
|
|
||||||
}
|
|
||||||
|
|
||||||
// Convert markdown to plain text for WeChat display
|
|
||||||
plainText := MarkdownToPlainText(text)
|
|
||||||
|
|
||||||
req := &ilink.SendMessageRequest{
|
|
||||||
Msg: ilink.SendMsg{
|
|
||||||
FromUserID: client.BotID(),
|
|
||||||
ToUserID: toUserID,
|
|
||||||
ClientID: clientID,
|
|
||||||
MessageType: ilink.MessageTypeBot,
|
|
||||||
MessageState: ilink.MessageStateFinish,
|
|
||||||
ItemList: []ilink.MessageItem{
|
|
||||||
{
|
|
||||||
Type: ilink.ItemTypeText,
|
|
||||||
TextItem: &ilink.TextItem{
|
|
||||||
Text: plainText,
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
ContextToken: contextToken,
|
|
||||||
},
|
|
||||||
BaseInfo: ilink.BaseInfo{},
|
|
||||||
}
|
|
||||||
|
|
||||||
resp, err := client.SendMessage(ctx, req)
|
|
||||||
if err != nil {
|
|
||||||
return fmt.Errorf("send message: %w", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
if resp.Ret != 0 {
|
|
||||||
return fmt.Errorf("send message failed: ret=%d errmsg=%s", resp.Ret, resp.ErrMsg)
|
|
||||||
}
|
|
||||||
|
|
||||||
log.Printf("[sender] sent reply to %s: %q", toUserID, truncate(text, 50))
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func truncate(s string, n int) string {
|
|
||||||
if len(s) <= n {
|
|
||||||
return s
|
|
||||||
}
|
|
||||||
return s[:n] + "..."
|
|
||||||
}
|
|
||||||
@@ -1246,10 +1246,15 @@ async function runSingleExport(
|
|||||||
const wavChannels =
|
const wavChannels =
|
||||||
audioBuffer.length >= 44 ? audioBuffer.readUInt16LE(22) : 1
|
audioBuffer.length >= 44 ? audioBuffer.readUInt16LE(22) : 1
|
||||||
const pcmBytes = Math.max(0, audioBuffer.length - 44)
|
const pcmBytes = Math.max(0, audioBuffer.length - 44)
|
||||||
message.voiceDuration = Math.max(
|
// 口径统一:消息解析阶段已从 <voicemsg voicelength> 拿到微信的原始秒数(带小数),
|
||||||
1,
|
// 它是唯一权威来源,不要覆盖。只有拿不到时才退回用 PCM 字节数估算——
|
||||||
Math.round(pcmBytes / (wavSampleRate * wavChannels * 2))
|
// 那份估算是整秒、且下限 1 秒(WAV 缺失头部时的兜底),语义不同。
|
||||||
)
|
if (message.voiceDuration == null) {
|
||||||
|
message.voiceDuration = Math.max(
|
||||||
|
1,
|
||||||
|
Math.round(pcmBytes / (wavSampleRate * wavChannels * 2))
|
||||||
|
)
|
||||||
|
}
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
keepMediaError(
|
keepMediaError(
|
||||||
request,
|
request,
|
||||||
|
|||||||
@@ -0,0 +1,12 @@
|
|||||||
|
import { app } from 'electron'
|
||||||
|
import fs from 'node:fs'
|
||||||
|
import path from 'node:path'
|
||||||
|
import ffmpegStaticPath from 'ffmpeg-static'
|
||||||
|
|
||||||
|
export function resolveBundledFfmpegPath(): string {
|
||||||
|
if (process.platform === 'darwin' && app.isPackaged) {
|
||||||
|
const editionFfmpeg = path.join(process.resourcesPath, 'resources', 'ffmpeg', 'ffmpeg')
|
||||||
|
if (fs.existsSync(editionFfmpeg)) return editionFfmpeg
|
||||||
|
}
|
||||||
|
return String(ffmpegStaticPath || '').replace('app.asar', 'app.asar.unpacked').trim()
|
||||||
|
}
|
||||||
@@ -13,6 +13,8 @@ import {
|
|||||||
GroupReportRenderSnapshotExportRequest,
|
GroupReportRenderSnapshotExportRequest,
|
||||||
ReportHeat,
|
ReportHeat,
|
||||||
ReportSectionMeta,
|
ReportSectionMeta,
|
||||||
|
buildReportAvatarAliasIndex,
|
||||||
|
mergeReportAvatars,
|
||||||
selectHeroParticipantNames
|
selectHeroParticipantNames
|
||||||
} from '../shared/group-report'
|
} from '../shared/group-report'
|
||||||
import { resolveMd5, getGroupSnapshot } from './services/chat-service'
|
import { resolveMd5, getGroupSnapshot } from './services/chat-service'
|
||||||
@@ -99,51 +101,155 @@ const fallbackAvatar = (name: string): RenderedAvatar => {
|
|||||||
const hue = hashName(name) % 360
|
const hue = hashName(name) % 360
|
||||||
const initial = escapeHtml(Array.from(name.trim())[0] || '?')
|
const initial = escapeHtml(Array.from(name.trim())[0] || '?')
|
||||||
const svg = `<svg xmlns="http://www.w3.org/2000/svg" width="96" height="96"><rect width="96" height="96" rx="18" fill="hsl(${hue} 45% 82%)"/><text x="48" y="58" text-anchor="middle" font-family="-apple-system,BlinkMacSystemFont,PingFang SC,sans-serif" font-size="38" fill="hsl(${hue} 35% 28%)">${initial}</text></svg>`
|
const svg = `<svg xmlns="http://www.w3.org/2000/svg" width="96" height="96"><rect width="96" height="96" rx="18" fill="hsl(${hue} 45% 82%)"/><text x="48" y="58" text-anchor="middle" font-family="-apple-system,BlinkMacSystemFont,PingFang SC,sans-serif" font-size="38" fill="hsl(${hue} 35% 28%)">${initial}</text></svg>`
|
||||||
return { source: `data:image/svg+xml;base64,${Buffer.from(svg).toString('base64')}`, fallback: true }
|
return {
|
||||||
}
|
source: `data:image/svg+xml;base64,${Buffer.from(svg).toString('base64')}`,
|
||||||
|
fallback: true
|
||||||
const imageMimeType = (contentType: string | null, source: string): string => {
|
|
||||||
if (contentType?.startsWith('image/')) return contentType.split(';')[0]
|
|
||||||
const extension = path.extname(source).toLowerCase()
|
|
||||||
if (extension === '.png') return 'image/png'
|
|
||||||
if (extension === '.webp') return 'image/webp'
|
|
||||||
if (extension === '.gif') return 'image/gif'
|
|
||||||
return 'image/jpeg'
|
|
||||||
}
|
|
||||||
|
|
||||||
const embedAvatar = async (source: string | undefined, name: string): Promise<RenderedAvatar> => {
|
|
||||||
if (!source) return fallbackAvatar(name)
|
|
||||||
if (/^data:image\/[a-z0-9.+/-]+;base64,[a-z0-9+/=]+$/i.test(source)) return { source, fallback: false }
|
|
||||||
|
|
||||||
try {
|
|
||||||
if (/^https?:\/\//i.test(source)) {
|
|
||||||
const response = await fetch(source, {
|
|
||||||
headers: {
|
|
||||||
'User-Agent': 'Mozilla/5.0 TraceMemo',
|
|
||||||
Referer: 'https://weixin.qq.com/'
|
|
||||||
},
|
|
||||||
signal: AbortSignal.timeout(8000)
|
|
||||||
})
|
|
||||||
if (!response.ok) throw new Error(`HTTP ${response.status}`)
|
|
||||||
const mime = imageMimeType(response.headers.get('content-type'), source)
|
|
||||||
return { source: `data:${mime};base64,${Buffer.from(await response.arrayBuffer()).toString('base64')}`, fallback: false }
|
|
||||||
}
|
|
||||||
|
|
||||||
const localPath = source.startsWith('file://') ? new URL(source) : source
|
|
||||||
const buffer = await fs.readFile(localPath)
|
|
||||||
return { source: `data:${imageMimeType(null, source)};base64,${buffer.toString('base64')}`, fallback: false }
|
|
||||||
} catch (error) {
|
|
||||||
console.warn(`[GroupReport] avatar fallback for ${name}:`, error)
|
|
||||||
return fallbackAvatar(name)
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 只认真实图片字节。
|
||||||
|
*
|
||||||
|
* `content-type` 与 URL 扩展名都**不可信**:微信 CDN 在限流 / 反盗链时会返回 200 + HTML 正文。
|
||||||
|
* 旧实现按扩展名猜 mime 并默认 `image/jpeg`,会把 HTML 内联成"解码失败的 data URL" ——
|
||||||
|
* 在报告里表现为**空白头像**(比首字占位更糟:用户看不到任何东西,也不知道为什么)。
|
||||||
|
*/
|
||||||
|
const IMAGE_MAGIC: Array<{ mime: string; bytes: number[] }> = [
|
||||||
|
{ mime: 'image/jpeg', bytes: [0xff, 0xd8, 0xff] },
|
||||||
|
{ mime: 'image/png', bytes: [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a] },
|
||||||
|
{ mime: 'image/gif', bytes: [0x47, 0x49, 0x46, 0x38] },
|
||||||
|
{ mime: 'image/bmp', bytes: [0x42, 0x4d] }
|
||||||
|
]
|
||||||
|
|
||||||
|
export const detectImageMime = (bytes: Buffer): string | undefined => {
|
||||||
|
for (const signature of IMAGE_MAGIC) {
|
||||||
|
if (
|
||||||
|
bytes.length >= signature.bytes.length &&
|
||||||
|
signature.bytes.every((byte, index) => bytes[index] === byte)
|
||||||
|
) {
|
||||||
|
return signature.mime
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (
|
||||||
|
bytes.length >= 12 &&
|
||||||
|
bytes.toString('ascii', 0, 4) === 'RIFF' &&
|
||||||
|
bytes.toString('ascii', 8, 12) === 'WEBP'
|
||||||
|
) {
|
||||||
|
return 'image/webp'
|
||||||
|
}
|
||||||
|
const head = bytes.subarray(0, 64).toString('utf8').trimStart()
|
||||||
|
if (head.startsWith('<svg')) return 'image/svg+xml'
|
||||||
|
if (head.startsWith('<?xml') && head.includes('<svg')) return 'image/svg+xml'
|
||||||
|
return undefined
|
||||||
|
}
|
||||||
|
|
||||||
|
const AVATAR_FETCH_TIMEOUT_MS = 8000
|
||||||
|
/** 首次 + 一次重试:单次瞬时失败(限流 / 连接重置 / 超时)不该让一个人永久退回首字。 */
|
||||||
|
const AVATAR_FETCH_ATTEMPTS = 2
|
||||||
|
/** 同一 origin 的并发上限。几十个头像同时打一个 CDN 会显著抬高被限流的概率。 */
|
||||||
|
const AVATAR_FETCH_CONCURRENCY = 6
|
||||||
|
/** 进程内头像缓存条目上限(老报告重渲染 / 连续生成同一群时不必重复下载)。 */
|
||||||
|
const AVATAR_CACHE_LIMIT = 256
|
||||||
|
|
||||||
|
const sleep = (ms: number): Promise<void> => new Promise((resolve) => setTimeout(resolve, ms))
|
||||||
|
|
||||||
|
const avatarEmbedCache = new Map<string, RenderedAvatar>()
|
||||||
|
|
||||||
|
const rememberAvatarEmbed = (source: string, rendered: RenderedAvatar): void => {
|
||||||
|
if (rendered.fallback) return
|
||||||
|
avatarEmbedCache.set(source, rendered)
|
||||||
|
while (avatarEmbedCache.size > AVATAR_CACHE_LIMIT) {
|
||||||
|
const oldest = avatarEmbedCache.keys().next().value
|
||||||
|
if (oldest === undefined) break
|
||||||
|
avatarEmbedCache.delete(oldest)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 有界并发:把 N 个任务压到 limit 个同时在飞,结果顺序与输入一致。 */
|
||||||
|
export const mapWithConcurrency = async <T, R>(
|
||||||
|
items: readonly T[],
|
||||||
|
limit: number,
|
||||||
|
task: (item: T) => Promise<R>
|
||||||
|
): Promise<R[]> => {
|
||||||
|
const results: R[] = new Array(items.length)
|
||||||
|
let cursor = 0
|
||||||
|
const workers = Array.from({ length: Math.max(1, Math.min(limit, items.length)) }, async () => {
|
||||||
|
for (;;) {
|
||||||
|
const index = cursor
|
||||||
|
cursor += 1
|
||||||
|
if (index >= items.length) return
|
||||||
|
results[index] = await task(items[index])
|
||||||
|
}
|
||||||
|
})
|
||||||
|
await Promise.all(workers)
|
||||||
|
return results
|
||||||
|
}
|
||||||
|
|
||||||
|
const readAvatarSource = async (source: string): Promise<RenderedAvatar> => {
|
||||||
|
if (/^https?:\/\//i.test(source)) {
|
||||||
|
const response = await fetch(source, {
|
||||||
|
headers: {
|
||||||
|
'User-Agent': 'Mozilla/5.0 TraceMemo',
|
||||||
|
Referer: 'https://weixin.qq.com/'
|
||||||
|
},
|
||||||
|
signal: AbortSignal.timeout(AVATAR_FETCH_TIMEOUT_MS)
|
||||||
|
})
|
||||||
|
if (!response.ok) throw new Error(`HTTP ${response.status}`)
|
||||||
|
const bytes = Buffer.from(await response.arrayBuffer())
|
||||||
|
const mime = detectImageMime(bytes)
|
||||||
|
if (!mime) {
|
||||||
|
throw new Error(
|
||||||
|
`not an image (content-type=${response.headers.get('content-type') || 'unknown'}, ${bytes.length} bytes)`
|
||||||
|
)
|
||||||
|
}
|
||||||
|
return { source: `data:${mime};base64,${bytes.toString('base64')}`, fallback: false }
|
||||||
|
}
|
||||||
|
|
||||||
|
const localPath = source.startsWith('file://') ? new URL(source) : source
|
||||||
|
const bytes = await fs.readFile(localPath)
|
||||||
|
const mime = detectImageMime(bytes)
|
||||||
|
if (!mime) throw new Error(`not an image (${bytes.length} bytes)`)
|
||||||
|
return { source: `data:${mime};base64,${bytes.toString('base64')}`, fallback: false }
|
||||||
|
}
|
||||||
|
|
||||||
|
export const embedAvatar = async (
|
||||||
|
source: string | undefined,
|
||||||
|
name: string
|
||||||
|
): Promise<RenderedAvatar> => {
|
||||||
|
if (!source) return fallbackAvatar(name)
|
||||||
|
if (/^data:image\/[a-z0-9.+/-]+;base64,[a-z0-9+/=]+$/i.test(source))
|
||||||
|
return { source, fallback: false }
|
||||||
|
|
||||||
|
const cached = avatarEmbedCache.get(source)
|
||||||
|
if (cached) return cached
|
||||||
|
|
||||||
|
let lastError: unknown
|
||||||
|
for (let attempt = 1; attempt <= AVATAR_FETCH_ATTEMPTS; attempt += 1) {
|
||||||
|
try {
|
||||||
|
const embedded = await readAvatarSource(source)
|
||||||
|
rememberAvatarEmbed(source, embedded)
|
||||||
|
return embedded
|
||||||
|
} catch (error) {
|
||||||
|
lastError = error
|
||||||
|
if (attempt < AVATAR_FETCH_ATTEMPTS) await sleep(150 * attempt)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
console.warn(`[GroupReport] avatar fallback for ${name}:`, lastError)
|
||||||
|
return fallbackAvatar(name)
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 从群成员快照反推真头像,填进 metadata.avatars。
|
* 从群成员快照反推真头像,填进 metadata.avatars。
|
||||||
* - 没传 talker → 跳过(向后兼容)
|
* - 没传 talker → 跳过(向后兼容)
|
||||||
* - talker 解析失败 / snapshot 拿不到 → 200 + warn,继续走 fallback
|
* - talker 解析失败 / snapshot 拿不到 → 200 + warn,继续走 fallback
|
||||||
* - 客户端传的 avatars[name](非空)优先;否则从 snapshot 的 m_nsHeadImgUrl 补
|
* - 客户端传的 avatars[name](非空)优先;否则从 snapshot 的 m_nsHeadImgUrl 补
|
||||||
* - 同名取首条(P2 风险:群里两人同名)
|
* - 同名取首条(P2 风险:群里两人同名)
|
||||||
|
*
|
||||||
|
* **必须按多个别名建索引**:报告里的显示名取决于 `memberNameMode`
|
||||||
|
* (默认 `groupNickname` = 群昵称),而快照的 `nickname` 字段是
|
||||||
|
* `wechatNickname || groupNickname || username`(见 `normalizeGroupMembers`)。
|
||||||
|
* 一个成员同时有微信昵称与群昵称且两者不同时,只按 `nickname` 建索引就会**全部对不上**,
|
||||||
|
* 于是头像 enrichment 静默失效 —— 这正是原先只用单一索引键时的问题。
|
||||||
*/
|
*/
|
||||||
const enrichAvatarsFromGroup = async (metadata: GroupReportMetadata): Promise<void> => {
|
const enrichAvatarsFromGroup = async (metadata: GroupReportMetadata): Promise<void> => {
|
||||||
if (!metadata.talker) return
|
if (!metadata.talker) return
|
||||||
@@ -162,22 +268,16 @@ const enrichAvatarsFromGroup = async (metadata: GroupReportMetadata): Promise<vo
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
const index = new Map<string, string>()
|
// 每个成员的所有可用显示名都指向同一个头像 URL;先到先得,避免同名互相覆盖。
|
||||||
for (const member of snapshot.members) {
|
// 只按 `member.nickname` 建索引会在"微信昵称 ≠ 群昵称"时全部对不上 —— 见 shared 里的注释。
|
||||||
if (member.nickname && member.avatar && !index.has(member.nickname)) {
|
const index = buildReportAvatarAliasIndex(snapshot.members)
|
||||||
index.set(member.nickname, member.avatar)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
metadata.avatars = metadata.avatars ?? {}
|
metadata.avatars = metadata.avatars ?? {}
|
||||||
for (const [name, url] of index) {
|
const filled = mergeReportAvatars(metadata.avatars, index)
|
||||||
if (metadata.avatars[name]) continue
|
|
||||||
metadata.avatars[name] = url
|
|
||||||
}
|
|
||||||
|
|
||||||
metadata.warnings = metadata.warnings ?? []
|
metadata.warnings = metadata.warnings ?? []
|
||||||
metadata.warnings.push(
|
metadata.warnings.push(
|
||||||
`enriched ${index.size} member avatars from snapshot (${snapshot.memberCount} members)`
|
`enriched ${filled}/${index.size} member avatar aliases from snapshot (${snapshot.memberCount} members)`
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -276,12 +376,22 @@ const renderReportHtml = async (request: GroupReportExportRequest): Promise<stri
|
|||||||
report.media?.voiceHighlights?.forEach((item) => avatarNames.add(item.sender))
|
report.media?.voiceHighlights?.forEach((item) => avatarNames.add(item.sender))
|
||||||
report.media?.funBadges?.forEach((item) => avatarNames.add(item.owner))
|
report.media?.funBadges?.forEach((item) => avatarNames.add(item.owner))
|
||||||
|
|
||||||
const avatars = new Map<string, RenderedAvatar>()
|
// 有界并发 + 单条重试:几十个头像同时打同一个 CDN 会被限流,瞬时失败会让一个人
|
||||||
await Promise.all(
|
// 在整份报告里永久退化成首字占位(实测同一天三次生成:0% / 0% / 32% 失败)。
|
||||||
Array.from(avatarNames).map(async (name) => {
|
const renderedAvatars = await mapWithConcurrency(
|
||||||
avatars.set(name, await embedAvatar(metadata.avatars[name], name))
|
Array.from(avatarNames),
|
||||||
})
|
AVATAR_FETCH_CONCURRENCY,
|
||||||
|
async (name) => [name, await embedAvatar(metadata.avatars[name], name)] as const
|
||||||
)
|
)
|
||||||
|
const avatars = new Map(renderedAvatars)
|
||||||
|
const fallbackCount = renderedAvatars.filter(([, item]) => item.fallback).length
|
||||||
|
if (fallbackCount > 0) {
|
||||||
|
// 只记数量,不记人名:报告本身已经有名字,这里只需要一个可诊断的信号。
|
||||||
|
metadata.warnings = metadata.warnings ?? []
|
||||||
|
metadata.warnings.push(
|
||||||
|
`avatar fallback ${fallbackCount}/${renderedAvatars.length}: 未取到真实头像,已用首字占位`
|
||||||
|
)
|
||||||
|
}
|
||||||
const avatar = (name: string): RenderedAvatar => avatars.get(name) || fallbackAvatar(name)
|
const avatar = (name: string): RenderedAvatar => avatars.get(name) || fallbackAvatar(name)
|
||||||
const renderAvatar = (
|
const renderAvatar = (
|
||||||
name: string,
|
name: string,
|
||||||
@@ -295,9 +405,7 @@ const renderReportHtml = async (request: GroupReportExportRequest): Promise<stri
|
|||||||
}
|
}
|
||||||
|
|
||||||
const heroNames = selectHeroParticipantNames(metadata.heroParticipants)
|
const heroNames = selectHeroParticipantNames(metadata.heroParticipants)
|
||||||
const heroAvatars = heroNames
|
const heroAvatars = heroNames.map((name) => renderAvatar(name, 'hero', '', name)).join('')
|
||||||
.map((name) => renderAvatar(name, 'hero', '', name))
|
|
||||||
.join('')
|
|
||||||
const heroAvatarClass = heroNames.length ? `avatar-count-${heroNames.length}` : 'empty-section'
|
const heroAvatarClass = heroNames.length ? `avatar-count-${heroNames.length}` : 'empty-section'
|
||||||
|
|
||||||
const topicCards = report.topics
|
const topicCards = report.topics
|
||||||
@@ -480,7 +588,7 @@ const renderReportHtml = async (request: GroupReportExportRequest): Promise<stri
|
|||||||
(item, index) => `<div class="rank tm-fragment tm-ranking-item">
|
(item, index) => `<div class="rank tm-fragment tm-ranking-item">
|
||||||
${renderAvatar(item.sender, 'ranking')}
|
${renderAvatar(item.sender, 'ranking')}
|
||||||
<b>${index + 1}. ${escapeHtml(item.sender)}</b>
|
<b>${index + 1}. ${escapeHtml(item.sender)}</b>
|
||||||
<span>${item.count} 条 · ${item.durationSec} 秒</span>
|
<span>${item.count} 条 · ${Math.round(item.durationSec)} 秒</span>
|
||||||
</div>`
|
</div>`
|
||||||
)
|
)
|
||||||
.join('')
|
.join('')
|
||||||
@@ -656,7 +764,10 @@ const renderReportHtml = async (request: GroupReportExportRequest): Promise<stri
|
|||||||
for (const [key, value] of Object.entries(values)) html = replacePlaceholder(html, key, value)
|
for (const [key, value] of Object.entries(values)) html = replacePlaceholder(html, key, value)
|
||||||
// 清空模板中残留的未使用占位符(模板独有但 values 没提供的键)
|
// 清空模板中残留的未使用占位符(模板独有但 values 没提供的键)
|
||||||
html = html.replace(/\{\{[A-Z_]+\}\}/g, '')
|
html = html.replace(/\{\{[A-Z_]+\}\}/g, '')
|
||||||
return addReportCsp(injectReportTemplateFragmentContract(html), resolvedTemplate.source === 'builtin')
|
return addReportCsp(
|
||||||
|
injectReportTemplateFragmentContract(html),
|
||||||
|
resolvedTemplate.source === 'builtin'
|
||||||
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
const renderReportSnapshotHtml = async (
|
const renderReportSnapshotHtml = async (
|
||||||
@@ -679,7 +790,10 @@ const renderReportSnapshotHtml = async (
|
|||||||
REPORT_DATE: request.snapshot.values.REPORT_DATE || escapeHtml(request.snapshot.reportDate)
|
REPORT_DATE: request.snapshot.values.REPORT_DATE || escapeHtml(request.snapshot.reportDate)
|
||||||
}
|
}
|
||||||
for (const [key, value] of Object.entries(values)) html = replacePlaceholder(html, key, value)
|
for (const [key, value] of Object.entries(values)) html = replacePlaceholder(html, key, value)
|
||||||
return addReportCsp(html.replace(/\{\{[A-Z0-9_]+\}\}/g, ''), resolvedTemplate.source === 'builtin')
|
return addReportCsp(
|
||||||
|
html.replace(/\{\{[A-Z0-9_]+\}\}/g, ''),
|
||||||
|
resolvedTemplate.source === 'builtin'
|
||||||
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
export const extractGroupReportRenderSnapshot = async (
|
export const extractGroupReportRenderSnapshot = async (
|
||||||
@@ -1021,15 +1135,10 @@ export const exportGroupReport = async (
|
|||||||
await fs.writeFile(htmlPath, html, 'utf8')
|
await fs.writeFile(htmlPath, html, 'utf8')
|
||||||
const htmlEndedAt = new Date()
|
const htmlEndedAt = new Date()
|
||||||
const pngStartedAt = new Date()
|
const pngStartedAt = new Date()
|
||||||
const imageDataUrl = await captureFullPage(
|
const imageDataUrl = await captureFullPage(htmlPath, pngPath, request.templateId, {
|
||||||
htmlPath,
|
...resolvedTemplate.definition,
|
||||||
pngPath,
|
maxCaptureHeight: resolvedTemplate.captureMaxHeight
|
||||||
request.templateId,
|
})
|
||||||
{
|
|
||||||
...resolvedTemplate.definition,
|
|
||||||
maxCaptureHeight: resolvedTemplate.captureMaxHeight
|
|
||||||
}
|
|
||||||
)
|
|
||||||
const pngEndedAt = new Date()
|
const pngEndedAt = new Date()
|
||||||
return {
|
return {
|
||||||
success: true,
|
success: true,
|
||||||
@@ -1074,15 +1183,10 @@ export const exportGroupReportSnapshot = async (
|
|||||||
await fs.writeFile(htmlPath, html, 'utf8')
|
await fs.writeFile(htmlPath, html, 'utf8')
|
||||||
const htmlEndedAt = new Date()
|
const htmlEndedAt = new Date()
|
||||||
const pngStartedAt = new Date()
|
const pngStartedAt = new Date()
|
||||||
const imageDataUrl = await captureFullPage(
|
const imageDataUrl = await captureFullPage(htmlPath, pngPath, request.templateId, {
|
||||||
htmlPath,
|
...resolvedTemplate.definition,
|
||||||
pngPath,
|
maxCaptureHeight: resolvedTemplate.captureMaxHeight
|
||||||
request.templateId,
|
})
|
||||||
{
|
|
||||||
...resolvedTemplate.definition,
|
|
||||||
maxCaptureHeight: resolvedTemplate.captureMaxHeight
|
|
||||||
}
|
|
||||||
)
|
|
||||||
const pngEndedAt = new Date()
|
const pngEndedAt = new Date()
|
||||||
return {
|
return {
|
||||||
success: true,
|
success: true,
|
||||||
|
|||||||
+830
-70
File diff suppressed because it is too large.
Load diff
@@ -5,7 +5,7 @@ import os from 'os'
|
|||||||
import { app } from 'electron'
|
import { app } from 'electron'
|
||||||
import { execFile } from 'child_process'
|
import { execFile } from 'child_process'
|
||||||
import { Worker } from 'worker_threads'
|
import { Worker } from 'worker_threads'
|
||||||
import ffmpegStaticPath from 'ffmpeg-static'
|
import { resolveBundledFfmpegPath } from './ffmpeg-path'
|
||||||
import type { ImageDecoderSource, ImageDecoderStatus } from '../shared/image-decryption'
|
import type { ImageDecoderSource, ImageDecoderStatus } from '../shared/image-decryption'
|
||||||
import { imageFileQuality, imageQualityRank } from '../shared/image-quality'
|
import { imageFileQuality, imageQualityRank } from '../shared/image-quality'
|
||||||
import { loadSettings } from './services/settings-store'
|
import { loadSettings } from './services/settings-store'
|
||||||
@@ -78,9 +78,7 @@ function getFfmpegCandidates(selectedPath = loadSettings().ffmpegPath): FfmpegCa
|
|||||||
const selected = String(selectedPath || '').trim()
|
const selected = String(selectedPath || '').trim()
|
||||||
const environment = String(process.env['FFMPEG_BIN'] || '').trim()
|
const environment = String(process.env['FFMPEG_BIN'] || '').trim()
|
||||||
const executable = process.platform === 'win32' ? 'ffmpeg.exe' : 'ffmpeg'
|
const executable = process.platform === 'win32' ? 'ffmpeg.exe' : 'ffmpeg'
|
||||||
const staticExecutable = String(ffmpegStaticPath || '')
|
const staticExecutable = resolveBundledFfmpegPath()
|
||||||
.replace('app.asar', 'app.asar.unpacked')
|
|
||||||
.trim()
|
|
||||||
const candidates: FfmpegCandidate[] = [
|
const candidates: FfmpegCandidate[] = [
|
||||||
...(selected ? [{ executable: selected, source: 'selected' as const }] : []),
|
...(selected ? [{ executable: selected, source: 'selected' as const }] : []),
|
||||||
...(environment ? [{ executable: environment, source: 'environment' as const }] : []),
|
...(environment ? [{ executable: environment, source: 'environment' as const }] : []),
|
||||||
@@ -114,7 +112,11 @@ function getFfmpegCandidates(selectedPath = loadSettings().ffmpegPath): FfmpegCa
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
function resolveFfmpegExecutable(): string {
|
/**
|
||||||
|
* 解析可用的 ffmpeg 可执行文件。除图片解密自身使用外,也供 System OCR 的
|
||||||
|
* 图片归一化(GIF/BMP/WebP/TIFF → PNG)复用,避免重复一套路径探测逻辑。
|
||||||
|
*/
|
||||||
|
export function resolveFfmpegExecutable(): string {
|
||||||
for (const candidate of getFfmpegCandidates()) {
|
for (const candidate of getFfmpegCandidates()) {
|
||||||
const pathLike = candidate.executable.includes('/') || candidate.executable.includes('\\')
|
const pathLike = candidate.executable.includes('/') || candidate.executable.includes('\\')
|
||||||
if (pathLike) {
|
if (pathLike) {
|
||||||
|
|||||||
+1566
-144
File diff suppressed because it is too large.
Load diff
@@ -7,6 +7,8 @@ import { isValidDatabaseKey } from './database-key-store'
|
|||||||
import crypto from 'crypto'
|
import crypto from 'crypto'
|
||||||
import { findResource, getResourceCandidates } from './resource-paths'
|
import { findResource, getResourceCandidates } from './resource-paths'
|
||||||
import { detectWechatVersion } from './services/connection-diagnostics'
|
import { detectWechatVersion } from './services/connection-diagnostics'
|
||||||
|
import { getMacArchSnapshot } from './macos-arch'
|
||||||
|
import { ARCH_MISMATCH_X64_ON_ARM_ERROR, shouldProbeIntelEnvironment } from '../shared/macos-arch'
|
||||||
|
|
||||||
const execFileAsync = promisify(execFile)
|
const execFileAsync = promisify(execFile)
|
||||||
|
|
||||||
@@ -134,6 +136,15 @@ export function parseXkeyHelperOutput(output: string): DatabaseKeyResult {
|
|||||||
return mapXkeyHelperFailure(rawError)
|
return mapXkeyHelperFailure(rawError)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export const SIP_ENABLED_ERROR =
|
||||||
|
'macOS 系统完整性保护(SIP)已开启,无法自动获取数据库密钥。请先关闭 SIP,或改用手动粘贴。'
|
||||||
|
|
||||||
|
export function parseSipEnabled(statusOutput: string): boolean {
|
||||||
|
const status = statusOutput.match(/status:\s*([a-z]+)/i)?.[1]?.toLowerCase()
|
||||||
|
if (status) return status === 'enabled'
|
||||||
|
return statusOutput.toLowerCase().includes('enabled')
|
||||||
|
}
|
||||||
|
|
||||||
export class KeyServiceMac {
|
export class KeyServiceMac {
|
||||||
private getMacKeyRuntimeDir(): string {
|
private getMacKeyRuntimeDir(): string {
|
||||||
return path.join(app.getPath('userData'), 'key-runtime')
|
return path.join(app.getPath('userData'), 'key-runtime')
|
||||||
@@ -230,6 +241,15 @@ export class KeyServiceMac {
|
|||||||
fridaAvailable: boolean
|
fridaAvailable: boolean
|
||||||
wechatAdhocSigned: boolean
|
wechatAdhocSigned: boolean
|
||||||
}> {
|
}> {
|
||||||
|
// 方法内部再守一道:调用方漏判时也不能起 x86 helper。
|
||||||
|
if (!shouldProbeIntelEnvironment(getMacArchSnapshot().macKeyFlow)) {
|
||||||
|
return {
|
||||||
|
sipDisabled: false,
|
||||||
|
pythonAvailable: false,
|
||||||
|
fridaAvailable: false,
|
||||||
|
wechatAdhocSigned: false
|
||||||
|
}
|
||||||
|
}
|
||||||
const payload = await this.runMacKeyTool(
|
const payload = await this.runMacKeyTool(
|
||||||
['status', '--runtime-dir', this.getMacKeyRuntimeDir()],
|
['status', '--runtime-dir', this.getMacKeyRuntimeDir()],
|
||||||
15_000
|
15_000
|
||||||
@@ -245,7 +265,15 @@ export class KeyServiceMac {
|
|||||||
async installIntelKeyRuntime(
|
async installIntelKeyRuntime(
|
||||||
onStatus?: (message: string) => void
|
onStatus?: (message: string) => void
|
||||||
): Promise<{ success: boolean; error?: string; code?: string }> {
|
): Promise<{ success: boolean; error?: string; code?: string }> {
|
||||||
if (process.platform !== 'darwin' || process.arch !== 'x64') {
|
const arch = getMacArchSnapshot()
|
||||||
|
if (arch.macKeyFlow === 'arch-mismatch') {
|
||||||
|
return {
|
||||||
|
success: false,
|
||||||
|
code: 'ARCH_MISMATCH_X64_ON_ARM',
|
||||||
|
error: ARCH_MISMATCH_X64_ON_ARM_ERROR
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (arch.macKeyFlow !== 'intel') {
|
||||||
return { success: false, code: 'UNSUPPORTED_PLATFORM', error: '仅 Intel Mac 需要安装此运行环境' }
|
return { success: false, code: 'UNSUPPORTED_PLATFORM', error: '仅 Intel Mac 需要安装此运行环境' }
|
||||||
}
|
}
|
||||||
onStatus?.('正在准备连接环境,请保持网络连接…')
|
onStatus?.('正在准备连接环境,请保持网络连接…')
|
||||||
@@ -306,7 +334,7 @@ export class KeyServiceMac {
|
|||||||
private async isSipEnabled(): Promise<boolean> {
|
private async isSipEnabled(): Promise<boolean> {
|
||||||
try {
|
try {
|
||||||
const { stdout } = await execFileAsync('/usr/bin/csrutil', ['status'])
|
const { stdout } = await execFileAsync('/usr/bin/csrutil', ['status'])
|
||||||
return stdout.toLowerCase().includes('enabled')
|
return parseSipEnabled(stdout)
|
||||||
} catch {
|
} catch {
|
||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
@@ -345,15 +373,25 @@ export class KeyServiceMac {
|
|||||||
if (process.platform !== 'darwin') {
|
if (process.platform !== 'darwin') {
|
||||||
return { success: false, error: '自动获取密钥目前仅支持 macOS' }
|
return { success: false, error: '自动获取密钥目前仅支持 macOS' }
|
||||||
}
|
}
|
||||||
if (await this.isSipEnabled()) {
|
// 架构判定排在 SIP 之前:不匹配时先说明「当前跑的是 Intel 版」,
|
||||||
|
// 不能让用户先看到 SIP 提示、关闭 SIP 之后才发现问题依旧。
|
||||||
|
const arch = getMacArchSnapshot()
|
||||||
|
if (arch.macKeyFlow === 'arch-mismatch') {
|
||||||
return {
|
return {
|
||||||
success: false,
|
success: false,
|
||||||
error: '当前系统还未完成连接环境准备,请按页面提示完成设置。'
|
code: 'ARCH_MISMATCH_X64_ON_ARM',
|
||||||
|
error: ARCH_MISMATCH_X64_ON_ARM_ERROR
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
if (arch.macKeyFlow === 'unsupported') {
|
||||||
|
return { success: false, error: '自动获取密钥目前仅支持 macOS' }
|
||||||
|
}
|
||||||
|
if (await this.isSipEnabled()) {
|
||||||
|
return { success: false, code: 'SIP_ENABLED', error: SIP_ENABLED_ERROR }
|
||||||
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
if (process.arch === 'x64') {
|
if (arch.macKeyFlow === 'intel') {
|
||||||
onStatus?.('Intel Mac 将通过 Frida 获取微信主密钥,请让微信停留在未登录界面')
|
onStatus?.('Intel Mac 将通过 Frida 获取微信主密钥,请让微信停留在未登录界面')
|
||||||
const result = await this.captureIntelDbKey(accountRoot, timeoutMs, onStatus)
|
const result = await this.captureIntelDbKey(accountRoot, timeoutMs, onStatus)
|
||||||
onStatus?.(result.success ? '密钥获取成功' : '密钥获取失败')
|
onStatus?.(result.success ? '密钥获取成功' : '密钥获取失败')
|
||||||
|
|||||||
@@ -689,7 +689,7 @@ export class KeyService {
|
|||||||
return {
|
return {
|
||||||
success: false,
|
success: false,
|
||||||
error:
|
error:
|
||||||
'微信可能已经启动并登录,请先在微信客户端保持未登录状态,具体点击上方“查看5分钟上手教程” ',
|
'微信可能没有在上一步点击微信登录,请先在微信客户端保持未登录状态,具体点击上方“查看5分钟上手教程” ',
|
||||||
logs
|
logs
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,8 +1,10 @@
|
|||||||
import { monitorEventLoopDelay } from 'perf_hooks'
|
import { monitorEventLoopDelay } from 'perf_hooks'
|
||||||
import * as chat from '../services/chat-service'
|
import * as chat from '../services/chat-service'
|
||||||
import type {
|
import type {
|
||||||
|
KnowledgeImageOcrState,
|
||||||
KnowledgeAttachmentMetadata,
|
KnowledgeAttachmentMetadata,
|
||||||
KnowledgeEvidence,
|
KnowledgeEvidence,
|
||||||
|
KnowledgeMemberStatsResult,
|
||||||
KnowledgeMessageKind,
|
KnowledgeMessageKind,
|
||||||
KnowledgePassProgress,
|
KnowledgePassProgress,
|
||||||
KnowledgeRuntimeState,
|
KnowledgeRuntimeState,
|
||||||
@@ -24,6 +26,7 @@ import {
|
|||||||
emptyKnowledgeSearchTimings
|
emptyKnowledgeSearchTimings
|
||||||
} from '../../shared/knowledge'
|
} from '../../shared/knowledge'
|
||||||
import { KnowledgeService } from './knowledge-service'
|
import { KnowledgeService } from './knowledge-service'
|
||||||
|
import { sourceMessageId } from './message-identity'
|
||||||
import {
|
import {
|
||||||
voiceAccountIdentity,
|
voiceAccountIdentity,
|
||||||
voiceMessageIdentity
|
voiceMessageIdentity
|
||||||
@@ -118,11 +121,6 @@ function groupMemberDisplayName(member: chat.GroupSnapshot['members'][number]):
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
function sourceMessageId(message: chat.FormattedMessage): string {
|
|
||||||
if (message.localId) return `local:${message.localId}`
|
|
||||||
if (message.id) return String(message.id)
|
|
||||||
return `${message.createTime || 0}:${message.serverId || message.content}`
|
|
||||||
}
|
|
||||||
|
|
||||||
function sourceKind(message: chat.FormattedMessage): KnowledgeMessageKind {
|
function sourceKind(message: chat.FormattedMessage): KnowledgeMessageKind {
|
||||||
if (message.voiceTranscript || message.type === '语音') return 'voice'
|
if (message.voiceTranscript || message.type === '语音') return 'voice'
|
||||||
@@ -130,6 +128,16 @@ function sourceKind(message: chat.FormattedMessage): KnowledgeMessageKind {
|
|||||||
return message.exportMediaType
|
return message.exportMediaType
|
||||||
}
|
}
|
||||||
if (message.exportMediaType === 'file') return 'file'
|
if (message.exportMediaType === 'file') return 'file'
|
||||||
|
// 索引路径上 `exportMediaType` **不会被赋值**(只有 export-service 会设它),
|
||||||
|
// 所以图片/视频/表情包必须从 contentData.type 判定,否则图片会静默落成 'other',
|
||||||
|
// 进而让"图片文字索引"的 Evidence 丢掉真正的来源类型。
|
||||||
|
if (
|
||||||
|
message.contentData?.type === 'image' ||
|
||||||
|
message.contentData?.type === 'video' ||
|
||||||
|
message.contentData?.type === 'sticker'
|
||||||
|
) {
|
||||||
|
return message.contentData.type
|
||||||
|
}
|
||||||
if (message.contentData?.type === 'share' || message.contentData?.type === 'miniProgram') {
|
if (message.contentData?.type === 'share' || message.contentData?.type === 'miniProgram') {
|
||||||
return message.contentData.type === 'share' && message.contentData.typeVal === '6'
|
return message.contentData.type === 'share' && message.contentData.typeVal === '6'
|
||||||
? 'file'
|
? 'file'
|
||||||
@@ -201,12 +209,16 @@ function toSourceMessage(
|
|||||||
accountId: string,
|
accountId: string,
|
||||||
conversationId: string,
|
conversationId: string,
|
||||||
message: chat.FormattedMessage,
|
message: chat.FormattedMessage,
|
||||||
transcriptOverride?: string
|
transcriptOverride?: string,
|
||||||
|
imageOcr?: { state: KnowledgeImageOcrState; text: string }
|
||||||
): KnowledgeSourceMessage | null {
|
): KnowledgeSourceMessage | null {
|
||||||
if (!message.createTime) return null
|
if (!message.createTime) return null
|
||||||
const extracted = sourceTextAndAttachment(message)
|
const extracted = sourceTextAndAttachment(message)
|
||||||
const voiceTranscript = transcriptOverride?.trim() || message.voiceTranscript?.trim() || undefined
|
const voiceTranscript = transcriptOverride?.trim() || message.voiceTranscript?.trim() || undefined
|
||||||
if (!extracted.text && !extracted.attachment && !voiceTranscript) return null
|
// 图片 OCR 文本走与语音转写完全相同的派生通道:有文本才入库,
|
||||||
|
// 没有文字的图片(表情包/风景)不会污染索引。
|
||||||
|
const imageOcrText = imageOcr?.text?.trim() || undefined
|
||||||
|
if (!extracted.text && !extracted.attachment && !voiceTranscript && !imageOcrText) return null
|
||||||
return {
|
return {
|
||||||
accountId,
|
accountId,
|
||||||
conversationId,
|
conversationId,
|
||||||
@@ -218,7 +230,9 @@ function toSourceMessage(
|
|||||||
kind: sourceKind(message),
|
kind: sourceKind(message),
|
||||||
text: extracted.text,
|
text: extracted.text,
|
||||||
attachment: extracted.attachment,
|
attachment: extracted.attachment,
|
||||||
voiceTranscript
|
voiceTranscript,
|
||||||
|
...(imageOcrText ? { imageOcrText } : {}),
|
||||||
|
...(imageOcrText && imageOcr?.state ? { imageOcrState: imageOcr.state } : {})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -256,6 +270,14 @@ export class KnowledgeSearchService {
|
|||||||
private interactiveIdleResolve: (() => void) | null = null
|
private interactiveIdleResolve: (() => void) | null = null
|
||||||
private wcdbQueueMsTotal = 0
|
private wcdbQueueMsTotal = 0
|
||||||
private wcdbExecutionMsTotal = 0
|
private wcdbExecutionMsTotal = 0
|
||||||
|
/**
|
||||||
|
* 图片 OCR 文本解析器(由 main 注入)。
|
||||||
|
*
|
||||||
|
* 与语音同构:派生文本在**主进程**解析后贴到消息上,派生库不进 worker。
|
||||||
|
*/
|
||||||
|
private imageOcrResolver:
|
||||||
|
| ((conversationId: string, messageId: string) => { state: KnowledgeImageOcrState; text: string } | undefined)
|
||||||
|
| undefined
|
||||||
private voiceTranscriptResolver:
|
private voiceTranscriptResolver:
|
||||||
| ((reference: VoiceMessageReference) => VoiceTranscriptSnapshot)
|
| ((reference: VoiceMessageReference) => VoiceTranscriptSnapshot)
|
||||||
| undefined
|
| undefined
|
||||||
@@ -372,6 +394,15 @@ export class KnowledgeSearchService {
|
|||||||
this.voiceTranscriptResolver = resolver
|
this.voiceTranscriptResolver = resolver
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** 注入图片 OCR 文本解析器(本地 System OCR 的派生结果)。 */
|
||||||
|
setImageOcrResolver(
|
||||||
|
resolver:
|
||||||
|
| ((conversationId: string, messageId: string) => { state: KnowledgeImageOcrState; text: string } | undefined)
|
||||||
|
| undefined
|
||||||
|
): void {
|
||||||
|
this.imageOcrResolver = resolver
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* A successful recognition updates its source conversation. Consecutive
|
* A successful recognition updates its source conversation. Consecutive
|
||||||
* updates for the same conversation are coalesced because a complete
|
* updates for the same conversation are coalesced because a complete
|
||||||
@@ -468,6 +499,37 @@ export class KnowledgeSearchService {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 单群发言聚合(群员统计的数据来源)。
|
||||||
|
*
|
||||||
|
* 这一层只**如实**返回引擎能给出的东西(含 `indexLatestAt`),不做追赶决策 ——
|
||||||
|
* 「要不要等索引、要不要把结果标成不完整」是产品判断,属于 GroupStatsService。
|
||||||
|
* 同时返回一次 `sourceLatestAt`(同步、零额外 WCDB 调用),让调用方一次拿到
|
||||||
|
* freshness 的两个口径,不必再发一次 status 请求。
|
||||||
|
*/
|
||||||
|
async memberStats(request: {
|
||||||
|
conversationId: string
|
||||||
|
startTime: number
|
||||||
|
endTime: number
|
||||||
|
}): Promise<{ result: KnowledgeMemberStatsResult | null; sourceLatestAt: number | null }> {
|
||||||
|
const sourceLatestAt = this.sourceLatestAt()
|
||||||
|
const accountId = this.currentAccountId()
|
||||||
|
if (!accountId) return { result: null, sourceLatestAt }
|
||||||
|
try {
|
||||||
|
const result = await this.service.memberStats({
|
||||||
|
accountId,
|
||||||
|
fts: DEFAULT_KNOWLEDGE_FTS_CONFIG,
|
||||||
|
conversationId: request.conversationId,
|
||||||
|
startTime: request.startTime,
|
||||||
|
endTime: request.endTime
|
||||||
|
})
|
||||||
|
return { result, sourceLatestAt }
|
||||||
|
} catch (error) {
|
||||||
|
console.warn('[Knowledge] member stats failed:', error)
|
||||||
|
return { result: null, sourceLatestAt }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 源数据最新活跃时间(epoch ms)。派生索引看到不源数据,freshness 判定由它 + `indexLatestAt` 组成。
|
* 源数据最新活跃时间(epoch ms)。派生索引看到不源数据,freshness 判定由它 + `indexLatestAt` 组成。
|
||||||
*/
|
*/
|
||||||
@@ -1051,7 +1113,7 @@ export class KnowledgeSearchService {
|
|||||||
lane: WcdbReadLane = 'interactive'
|
lane: WcdbReadLane = 'interactive'
|
||||||
): ReturnType<typeof chat.listMessagesAsync> {
|
): ReturnType<typeof chat.listMessagesAsync> {
|
||||||
return this.enqueueWcdbRead(
|
return this.enqueueWcdbRead(
|
||||||
() => chat.listMessagesAsync(conversationId, startTime, endTime),
|
() => chat.listMessagesAsync(conversationId, startTime, endTime, undefined, undefined, 'knowledge'),
|
||||||
lane
|
lane
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
@@ -1074,8 +1136,16 @@ export class KnowledgeSearchService {
|
|||||||
const reference = this.voiceReferenceFromMessage(message)
|
const reference = this.voiceReferenceFromMessage(message)
|
||||||
const snapshot = reference ? this.voiceTranscriptResolver?.(reference) : undefined
|
const snapshot = reference ? this.voiceTranscriptResolver?.(reference) : undefined
|
||||||
const hydrated = this.withVoiceTranscript(message)
|
const hydrated = this.withVoiceTranscript(message)
|
||||||
const source = toSourceMessage(accountId, conversationId, hydrated, transcriptOverride)
|
const imageOcr = this.imageOcrResolver?.(conversationId, sourceMessageId(message))
|
||||||
if (!source || source.kind !== 'voice') return source
|
const source = toSourceMessage(
|
||||||
|
accountId,
|
||||||
|
conversationId,
|
||||||
|
hydrated,
|
||||||
|
transcriptOverride,
|
||||||
|
imageOcr
|
||||||
|
)
|
||||||
|
if (!source) return source
|
||||||
|
if (source.kind !== 'image' && source.kind !== 'voice') return source
|
||||||
return {
|
return {
|
||||||
...source,
|
...source,
|
||||||
voiceTranscriptState:
|
voiceTranscriptState:
|
||||||
@@ -1105,6 +1175,38 @@ export class KnowledgeSearchService {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 某个会话的图片 OCR 处理完成 → 重建该会话的索引。
|
||||||
|
*
|
||||||
|
* 与"语音转写完成后单会话重索引"完全同构:整会话重读 + completeSnapshot 重建,
|
||||||
|
* 让 OCR 派生文本进入 chunks/FTS,从而可被 search_messages 检索。
|
||||||
|
* 原图片消息仍然是 authoritative source —— 这里只是让它多了一段派生文本,
|
||||||
|
* 不产生任何"OCR 消息"。
|
||||||
|
*/
|
||||||
|
async indexImageOcr(conversationId: string): Promise<void> {
|
||||||
|
if (!chat.isReady()) return
|
||||||
|
const accountId = this.currentAccountId()
|
||||||
|
if (!accountId) return
|
||||||
|
const activeIndex = this.indexing.get(accountId)
|
||||||
|
if (activeIndex) await activeIndex
|
||||||
|
const contacts = await this.listContacts()
|
||||||
|
const contact = contacts.find((item) => item.md5 === conversationId)
|
||||||
|
if (!contact) return
|
||||||
|
const messages = await this.listMessages(contact.md5, undefined, undefined, 'background')
|
||||||
|
const sourceMessages = messages
|
||||||
|
.map((message) => this.toSourceMessage(accountId, contact.md5, message))
|
||||||
|
.filter((message): message is KnowledgeSourceMessage => Boolean(message))
|
||||||
|
await this.service.index({
|
||||||
|
accountId,
|
||||||
|
conversations: [
|
||||||
|
{ conversationId: contact.md5, completeSnapshot: true, messages: sourceMessages }
|
||||||
|
],
|
||||||
|
chunker: DEFAULT_KNOWLEDGE_CHUNKER,
|
||||||
|
fts: DEFAULT_KNOWLEDGE_FTS_CONFIG
|
||||||
|
})
|
||||||
|
await this.refreshStatus(accountId)
|
||||||
|
}
|
||||||
|
|
||||||
private async indexVoiceTranscriptNow(update: VoiceTranscriptUpdate): Promise<void> {
|
private async indexVoiceTranscriptNow(update: VoiceTranscriptUpdate): Promise<void> {
|
||||||
if (!chat.isReady()) return
|
if (!chat.isReady()) return
|
||||||
if (update.state === 'transcribed' && !update.transcript?.trim()) return
|
if (update.state === 'transcribed' && !update.transcript?.trim()) return
|
||||||
|
|||||||
@@ -5,6 +5,8 @@ import type {
|
|||||||
KnowledgeIndexProgress,
|
KnowledgeIndexProgress,
|
||||||
KnowledgeIndexRequest,
|
KnowledgeIndexRequest,
|
||||||
KnowledgeIndexResult,
|
KnowledgeIndexResult,
|
||||||
|
KnowledgeMemberStatsRequest,
|
||||||
|
KnowledgeMemberStatsResult,
|
||||||
KnowledgeRuntimeStatus,
|
KnowledgeRuntimeStatus,
|
||||||
KnowledgeSearchRequest,
|
KnowledgeSearchRequest,
|
||||||
KnowledgeSearchResult,
|
KnowledgeSearchResult,
|
||||||
@@ -53,6 +55,13 @@ export class KnowledgeService {
|
|||||||
return this.worker.highWaterMarks({ ...request, databaseRoot: this.databaseRoot })
|
return this.worker.highWaterMarks({ ...request, databaseRoot: this.databaseRoot })
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** 单个会话内「按发送者聚合」的发言统计(群员统计用)。 */
|
||||||
|
memberStats(
|
||||||
|
request: Omit<KnowledgeMemberStatsRequest, 'databaseRoot'>
|
||||||
|
): Promise<KnowledgeMemberStatsResult> {
|
||||||
|
return this.worker.memberStats({ ...request, databaseRoot: this.databaseRoot })
|
||||||
|
}
|
||||||
|
|
||||||
/** 只中止正在跑的索引任务;查询请求不受影响。 */
|
/** 只中止正在跑的索引任务;查询请求不受影响。 */
|
||||||
cancelIndex(): Promise<boolean> {
|
cancelIndex(): Promise<boolean> {
|
||||||
return this.worker.cancelActiveIndex()
|
return this.worker.cancelActiveIndex()
|
||||||
|
|||||||
@@ -13,13 +13,18 @@ import type {
|
|||||||
KnowledgeIndexProgress,
|
KnowledgeIndexProgress,
|
||||||
KnowledgeIndexRequest,
|
KnowledgeIndexRequest,
|
||||||
KnowledgeIndexResult,
|
KnowledgeIndexResult,
|
||||||
|
KnowledgeMemberStatsResult,
|
||||||
KnowledgeRuntimeStatus,
|
KnowledgeRuntimeStatus,
|
||||||
KnowledgeNormalizedMessage,
|
KnowledgeNormalizedMessage,
|
||||||
KnowledgeQuery,
|
KnowledgeQuery,
|
||||||
KnowledgeSearchTimings,
|
KnowledgeSearchTimings,
|
||||||
KnowledgeSearchResult
|
KnowledgeSearchResult
|
||||||
} from '../../shared/knowledge'
|
} from '../../shared/knowledge'
|
||||||
import { emptyKnowledgeSearchTimings, KNOWLEDGE_SCHEMA_VERSION } from '../../shared/knowledge'
|
import {
|
||||||
|
emptyKnowledgeSearchTimings,
|
||||||
|
KNOWLEDGE_SCHEMA_VERSION,
|
||||||
|
toEvidenceDisplayText
|
||||||
|
} from '../../shared/knowledge'
|
||||||
import { chunkConversation } from './chunker'
|
import { chunkConversation } from './chunker'
|
||||||
import { normalizeKnowledgeMessage } from './normalizer'
|
import { normalizeKnowledgeMessage } from './normalizer'
|
||||||
|
|
||||||
@@ -313,6 +318,93 @@ export class KnowledgeStore {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 单个会话在时间窗内的「按发送者聚合」统计。
|
||||||
|
*
|
||||||
|
* 只回聚合结果、不回消息正文:群员统计只需要「谁说了几条、最后一条是什么时候」,
|
||||||
|
* 把消息逐条搬到主进程再统计会把几十万行推过 IPC 边界。
|
||||||
|
*
|
||||||
|
* 三条硬规则**全部由 SQL 保证**,不指望调用方记得:
|
||||||
|
* 1. `kind <> 'system'`:系统消息不是任何成员的发言(微信侧 10000/10002 在建库时
|
||||||
|
* 已归一为 `kind = 'system'`,见 `knowledge-search-service` 的 kind 映射);
|
||||||
|
* 2. `sender_id IS NULL` 的行不归给任何人,只计入 `unattributedMessages` ——
|
||||||
|
* 硬塞给某个成员会让「未发言」名单出现错误否定;
|
||||||
|
* 3. 时间窗口是**闭区间**,单位 **epoch 毫秒**,与 knowledge 内部口径一致,
|
||||||
|
* 不经过 WCDB 的秒级边界(跨错单位会静默读到 0 条)。
|
||||||
|
*/
|
||||||
|
memberStats(request: {
|
||||||
|
conversationId: string
|
||||||
|
startTime: number
|
||||||
|
endTime: number
|
||||||
|
}): KnowledgeMemberStatsResult {
|
||||||
|
const { conversationId, startTime, endTime } = request
|
||||||
|
const indexLatestAt = this.readIndexLatestAt()
|
||||||
|
const empty: KnowledgeMemberStatsResult = {
|
||||||
|
conversationId,
|
||||||
|
totalMessages: 0,
|
||||||
|
senders: [],
|
||||||
|
unattributedMessages: 0,
|
||||||
|
excludedSystemMessages: 0,
|
||||||
|
earliestMessageTime: null,
|
||||||
|
indexLatestAt
|
||||||
|
}
|
||||||
|
if (!conversationId) return empty
|
||||||
|
|
||||||
|
// 用 `(conversation_id, create_time)` 索引直接命中:这是本查询唯一的访问路径,
|
||||||
|
// 写成全表扫描等价于把单群统计的 26ms 变成 10s。
|
||||||
|
const scope = 'conversation_id = ? AND create_time >= ? AND create_time <= ?'
|
||||||
|
const args = [conversationId, startTime, endTime]
|
||||||
|
|
||||||
|
const count = (extra: string): number => {
|
||||||
|
const row = this.database
|
||||||
|
.prepare(`SELECT COUNT(*) AS n FROM knowledge_messages WHERE ${scope} AND ${extra}`)
|
||||||
|
.get(...args) as DbRow | undefined
|
||||||
|
return Number(row?.n) || 0
|
||||||
|
}
|
||||||
|
|
||||||
|
const rows = asRows(
|
||||||
|
this.database
|
||||||
|
.prepare(
|
||||||
|
`SELECT sender_id,
|
||||||
|
COUNT(*) AS message_count,
|
||||||
|
MAX(create_time) AS last_message_time
|
||||||
|
FROM knowledge_messages
|
||||||
|
WHERE ${scope} AND kind <> 'system' AND sender_id IS NOT NULL
|
||||||
|
GROUP BY sender_id
|
||||||
|
ORDER BY message_count DESC, last_message_time DESC`
|
||||||
|
)
|
||||||
|
.all(...args)
|
||||||
|
)
|
||||||
|
|
||||||
|
const senders: KnowledgeMemberStatsResult['senders'] = []
|
||||||
|
for (const row of rows) {
|
||||||
|
const senderId = String(row.sender_id ?? '').trim()
|
||||||
|
if (!senderId) continue
|
||||||
|
senders.push({
|
||||||
|
senderId,
|
||||||
|
messageCount: Number(row.message_count) || 0,
|
||||||
|
lastMessageTime: Number(row.last_message_time) || 0
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// 窗口内最早一条消息:**不过滤 kind** —— 群的第一条常常是建群通知,
|
||||||
|
// 那才是用户认知里的「这个群第一条消息」。选「全部」时用它显示真实起点。
|
||||||
|
const earliestRow = this.database
|
||||||
|
.prepare(`SELECT MIN(create_time) AS m FROM knowledge_messages WHERE ${scope}`)
|
||||||
|
.get(...args) as DbRow | undefined
|
||||||
|
const earliestValue = Number(earliestRow?.m)
|
||||||
|
|
||||||
|
return {
|
||||||
|
conversationId,
|
||||||
|
totalMessages: count("kind <> 'system'"),
|
||||||
|
senders,
|
||||||
|
unattributedMessages: count("kind <> 'system' AND sender_id IS NULL"),
|
||||||
|
excludedSystemMessages: count("kind = 'system'"),
|
||||||
|
earliestMessageTime: Number.isFinite(earliestValue) && earliestValue > 0 ? earliestValue : null,
|
||||||
|
indexLatestAt
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 索引已经覆盖到的源数据时间(epoch ms)——「索引更新到哪」的权威口径。
|
* 索引已经覆盖到的源数据时间(epoch ms)——「索引更新到哪」的权威口径。
|
||||||
*
|
*
|
||||||
@@ -761,7 +853,8 @@ export class KnowledgeStore {
|
|||||||
evidence: asRows(
|
evidence: asRows(
|
||||||
this.database
|
this.database
|
||||||
.prepare(
|
.prepare(
|
||||||
`SELECT m.conversation_id, m.message_id, m.create_time, m.searchable_text, m.kind, m.sender_id, m.sender_name
|
`SELECT m.conversation_id, m.message_id, m.create_time, m.searchable_text, m.kind, m.sender_id, m.sender_name,
|
||||||
|
m.image_ocr_text, m.voice_transcript
|
||||||
FROM knowledge_messages m
|
FROM knowledge_messages m
|
||||||
WHERE ${clauses.join(' AND ')}
|
WHERE ${clauses.join(' AND ')}
|
||||||
ORDER BY m.create_time DESC
|
ORDER BY m.create_time DESC
|
||||||
@@ -789,7 +882,22 @@ export class KnowledgeStore {
|
|||||||
timestamp: Number(row.create_time),
|
timestamp: Number(row.create_time),
|
||||||
messageIds: chunk ? chunk.map((item) => String(item.message_id)) : [messageId],
|
messageIds: chunk ? chunk.map((item) => String(item.message_id)) : [messageId],
|
||||||
sourceKind: String(row.kind) as KnowledgeEvidence['sourceKind'],
|
sourceKind: String(row.kind) as KnowledgeEvidence['sourceKind'],
|
||||||
text: String(row.searchable_text),
|
// 内部前缀(`图片文字:`)绝不能进 Evidence:面向用户与模型的是可读文本,
|
||||||
|
// 来源信息由下面的结构化字段表达。
|
||||||
|
text: toEvidenceDisplayText(String(row.searchable_text)),
|
||||||
|
...(row.image_ocr_text ? { imageOcrText: String(row.image_ocr_text) } : {}),
|
||||||
|
/*
|
||||||
|
* 来源标记按"这条消息带什么派生内容"判定,与 `sourceKind` 正交:
|
||||||
|
* `image_ocr` = 靠图片里的文字命中,`voice_transcript` = 靠语音转写命中。
|
||||||
|
*
|
||||||
|
* 两者都有时以图片 OCR 为先 —— 图片消息不会同时带语音转写,这里只是取确定值,
|
||||||
|
* 实际不会出现需要二选一的数据。
|
||||||
|
*/
|
||||||
|
...(row.image_ocr_text
|
||||||
|
? { derivedSource: 'image_ocr' as const }
|
||||||
|
: String(row.voice_transcript || '').trim()
|
||||||
|
? { derivedSource: 'voice_transcript' as const }
|
||||||
|
: {}),
|
||||||
score: String(row.kind) === 'system' ? 1 : 0
|
score: String(row.kind) === 'system' ? 1 : 0
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -899,6 +1007,7 @@ export class KnowledgeStore {
|
|||||||
attachment_json TEXT,
|
attachment_json TEXT,
|
||||||
voice_transcript TEXT,
|
voice_transcript TEXT,
|
||||||
voice_transcript_state TEXT,
|
voice_transcript_state TEXT,
|
||||||
|
image_ocr_text TEXT,
|
||||||
PRIMARY KEY (conversation_id, message_id)
|
PRIMARY KEY (conversation_id, message_id)
|
||||||
) STRICT;
|
) STRICT;
|
||||||
CREATE INDEX IF NOT EXISTS knowledge_messages_conversation_time
|
CREATE INDEX IF NOT EXISTS knowledge_messages_conversation_time
|
||||||
@@ -957,6 +1066,14 @@ export class KnowledgeStore {
|
|||||||
if (!messageColumns.has('voice_transcript_state')) {
|
if (!messageColumns.has('voice_transcript_state')) {
|
||||||
this.database.exec('ALTER TABLE knowledge_messages ADD COLUMN voice_transcript_state TEXT')
|
this.database.exec('ALTER TABLE knowledge_messages ADD COLUMN voice_transcript_state TEXT')
|
||||||
}
|
}
|
||||||
|
// 图片 OCR 派生文本单独留一列(不只是埋进 searchable_text)。
|
||||||
|
//
|
||||||
|
// 为什么必须落列而不是从 searchable_text 里截字符串:Evidence 需要回答
|
||||||
|
// "这条结果是不是来自图片里的文字",并按此给出来源标记与 OCR 片段。
|
||||||
|
// 靠解析前缀来判来源,一旦前缀格式调整就会静默失效。
|
||||||
|
if (!messageColumns.has('image_ocr_text')) {
|
||||||
|
this.database.exec('ALTER TABLE knowledge_messages ADD COLUMN image_ocr_text TEXT')
|
||||||
|
}
|
||||||
this.writeMetaIfMissing('schema_version', String(KNOWLEDGE_SCHEMA_VERSION))
|
this.writeMetaIfMissing('schema_version', String(KNOWLEDGE_SCHEMA_VERSION))
|
||||||
const storedAccount = this.readMeta('account_id')
|
const storedAccount = this.readMeta('account_id')
|
||||||
if (storedAccount && storedAccount !== this.accountId) {
|
if (storedAccount && storedAccount !== this.accountId) {
|
||||||
@@ -1137,8 +1254,9 @@ export class KnowledgeStore {
|
|||||||
const upsert = this.database.prepare(
|
const upsert = this.database.prepare(
|
||||||
`INSERT INTO knowledge_messages (
|
`INSERT INTO knowledge_messages (
|
||||||
account_id, conversation_id, message_id, create_time, content_hash, searchable_text,
|
account_id, conversation_id, message_id, create_time, content_hash, searchable_text,
|
||||||
kind, sender_id, sender_name, attachment_json, voice_transcript, voice_transcript_state
|
kind, sender_id, sender_name, attachment_json, voice_transcript, voice_transcript_state,
|
||||||
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
image_ocr_text
|
||||||
|
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
||||||
ON CONFLICT(conversation_id, message_id) DO UPDATE SET
|
ON CONFLICT(conversation_id, message_id) DO UPDATE SET
|
||||||
create_time = excluded.create_time,
|
create_time = excluded.create_time,
|
||||||
content_hash = excluded.content_hash,
|
content_hash = excluded.content_hash,
|
||||||
@@ -1148,7 +1266,8 @@ export class KnowledgeStore {
|
|||||||
sender_name = excluded.sender_name,
|
sender_name = excluded.sender_name,
|
||||||
attachment_json = excluded.attachment_json,
|
attachment_json = excluded.attachment_json,
|
||||||
voice_transcript = excluded.voice_transcript,
|
voice_transcript = excluded.voice_transcript,
|
||||||
voice_transcript_state = excluded.voice_transcript_state`
|
voice_transcript_state = excluded.voice_transcript_state,
|
||||||
|
image_ocr_text = excluded.image_ocr_text`
|
||||||
)
|
)
|
||||||
for (let index = 0; index < messages.length; index += 1) {
|
for (let index = 0; index < messages.length; index += 1) {
|
||||||
this.assertNotAborted(signal)
|
this.assertNotAborted(signal)
|
||||||
@@ -1165,7 +1284,8 @@ export class KnowledgeStore {
|
|||||||
message.senderName ?? null,
|
message.senderName ?? null,
|
||||||
message.attachment ? encodedJson(message.attachment) : null,
|
message.attachment ? encodedJson(message.attachment) : null,
|
||||||
message.voiceTranscript ?? null,
|
message.voiceTranscript ?? null,
|
||||||
message.voiceTranscriptState ?? null
|
message.voiceTranscriptState ?? null,
|
||||||
|
message.imageOcrText ?? null
|
||||||
)
|
)
|
||||||
if (index % YIELD_EVERY === 0) {
|
if (index % YIELD_EVERY === 0) {
|
||||||
onProgress(index + 1, 0)
|
onProgress(index + 1, 0)
|
||||||
|
|||||||
@@ -6,6 +6,8 @@ import type {
|
|||||||
KnowledgeIndexProgress,
|
KnowledgeIndexProgress,
|
||||||
KnowledgeIndexRequest,
|
KnowledgeIndexRequest,
|
||||||
KnowledgeIndexResult,
|
KnowledgeIndexResult,
|
||||||
|
KnowledgeMemberStatsRequest,
|
||||||
|
KnowledgeMemberStatsResult,
|
||||||
KnowledgeRuntimeStatus,
|
KnowledgeRuntimeStatus,
|
||||||
KnowledgeSearchRequest,
|
KnowledgeSearchRequest,
|
||||||
KnowledgeSearchResult,
|
KnowledgeSearchResult,
|
||||||
@@ -19,6 +21,7 @@ type WorkerResult =
|
|||||||
| KnowledgeCapacityPreflight
|
| KnowledgeCapacityPreflight
|
||||||
| KnowledgeSearchResult
|
| KnowledgeSearchResult
|
||||||
| KnowledgeRuntimeStatus
|
| KnowledgeRuntimeStatus
|
||||||
|
| KnowledgeMemberStatsResult
|
||||||
| { marks: Record<string, number> }
|
| { marks: Record<string, number> }
|
||||||
| { removed: true }
|
| { removed: true }
|
||||||
type PendingRequest = {
|
type PendingRequest = {
|
||||||
@@ -76,6 +79,11 @@ export class KnowledgeWorkerHost {
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** 单个会话内「按发送者聚合」的发言统计(群员统计用,只回聚合不回正文)。 */
|
||||||
|
memberStats(payload: KnowledgeMemberStatsRequest): Promise<KnowledgeMemberStatsResult> {
|
||||||
|
return this.request('memberStats', payload) as Promise<KnowledgeMemberStatsResult>
|
||||||
|
}
|
||||||
|
|
||||||
/** 只中止正在跑的索引任务,返回是否真的有任务被中止。 */
|
/** 只中止正在跑的索引任务,返回是否真的有任务被中止。 */
|
||||||
async cancelActiveIndex(): Promise<boolean> {
|
async cancelActiveIndex(): Promise<boolean> {
|
||||||
const target = this.activeIndexRequestId
|
const target = this.activeIndexRequestId
|
||||||
|
|||||||
@@ -1,6 +1,8 @@
|
|||||||
import type {
|
import type {
|
||||||
KnowledgeCapacityPreflightRequest,
|
KnowledgeCapacityPreflightRequest,
|
||||||
KnowledgeIndexRequest,
|
KnowledgeIndexRequest,
|
||||||
|
KnowledgeMemberStatsRequest,
|
||||||
|
KnowledgeMemberStatsResult,
|
||||||
KnowledgeRuntimeStatus,
|
KnowledgeRuntimeStatus,
|
||||||
KnowledgeSearchRequest,
|
KnowledgeSearchRequest,
|
||||||
KnowledgeStatusRequest,
|
KnowledgeStatusRequest,
|
||||||
@@ -187,6 +189,38 @@ async function handleHighWater(
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 群员统计的按发送者聚合。
|
||||||
|
*
|
||||||
|
* 与 `handleSearch` 同样先判库是否存在:**「还没建索引」是正常状态,不是故障**,
|
||||||
|
* 返回空结果而不是抛错,让上层能稳定地区分「没人发言」与「索引不存在」。
|
||||||
|
*/
|
||||||
|
async function handleMemberStats(
|
||||||
|
request: KnowledgeWorkerRequest,
|
||||||
|
payload: KnowledgeMemberStatsRequest
|
||||||
|
): Promise<void> {
|
||||||
|
const path = getKnowledgeDatabasePath(payload.databaseRoot, payload.accountId)
|
||||||
|
if (!existsSync(path)) {
|
||||||
|
const unavailable: KnowledgeMemberStatsResult = {
|
||||||
|
conversationId: payload.conversationId,
|
||||||
|
totalMessages: 0,
|
||||||
|
senders: [],
|
||||||
|
unattributedMessages: 0,
|
||||||
|
excludedSystemMessages: 0,
|
||||||
|
earliestMessageTime: null,
|
||||||
|
indexLatestAt: null
|
||||||
|
}
|
||||||
|
send({ version: 1, type: 'result', requestId: request.requestId, payload: unavailable })
|
||||||
|
return
|
||||||
|
}
|
||||||
|
send({
|
||||||
|
version: 1,
|
||||||
|
type: 'result',
|
||||||
|
requestId: request.requestId,
|
||||||
|
payload: getStore(payload).memberStats(payload)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
async function handle(request: KnowledgeWorkerRequest, messageReceivedAt: number): Promise<void> {
|
async function handle(request: KnowledgeWorkerRequest, messageReceivedAt: number): Promise<void> {
|
||||||
try {
|
try {
|
||||||
if (request.type === 'cancel') {
|
if (request.type === 'cancel') {
|
||||||
@@ -226,6 +260,10 @@ async function handle(request: KnowledgeWorkerRequest, messageReceivedAt: number
|
|||||||
await handleHighWater(request, request.payload as KnowledgeStatusRequest)
|
await handleHighWater(request, request.payload as KnowledgeStatusRequest)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
if (request.type === 'memberStats') {
|
||||||
|
await handleMemberStats(request, request.payload as KnowledgeMemberStatsRequest)
|
||||||
|
return
|
||||||
|
}
|
||||||
if (request.type === 'index') {
|
if (request.type === 'index') {
|
||||||
await handleIndex(request, request.payload as KnowledgeIndexRequest)
|
await handleIndex(request, request.payload as KnowledgeIndexRequest)
|
||||||
return
|
return
|
||||||
|
|||||||
@@ -0,0 +1,24 @@
|
|||||||
|
/**
|
||||||
|
* 消息身份的**唯一真源**。
|
||||||
|
*
|
||||||
|
* 这个规则同时被三处需要:
|
||||||
|
* - Knowledge 索引写入 `knowledge_messages.message_id`
|
||||||
|
* - 图片文字索引的 binding(必须与 Knowledge 里的 message_id 完全一致,否则 OCR 文本贴不到消息上)
|
||||||
|
* - Evidence → 档案跳转的 messageRef
|
||||||
|
*
|
||||||
|
* 任何一处各自复制一份,都会在 `local:` 前缀上静默失配(项目里已经有这个坑的历史注释),
|
||||||
|
* 所以抽成一个模块,谁都不许再抄。
|
||||||
|
*/
|
||||||
|
import type * as chat from '../services/chat-service'
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 源消息 → 稳定消息 id。
|
||||||
|
*
|
||||||
|
* 降级顺序刻意保守:`localId` 是 WCDB 行内最稳的本地 id;其次用消息自带 id;
|
||||||
|
* 最后才退化成「时间 + 服务端 id / 内容」的组合(仅在极端缺字段时命中)。
|
||||||
|
*/
|
||||||
|
export function sourceMessageId(message: chat.FormattedMessage): string {
|
||||||
|
if (message.localId) return `local:${message.localId}`
|
||||||
|
if (message.id) return String(message.id)
|
||||||
|
return `${message.createTime || 0}:${message.serverId || message.content}`
|
||||||
|
}
|
||||||
@@ -24,6 +24,10 @@ export function normalizeKnowledgeMessage(
|
|||||||
const transcript = compact(source.voiceTranscript)
|
const transcript = compact(source.voiceTranscript)
|
||||||
if (transcript) sections.push(`语音转写:${transcript}`)
|
if (transcript) sections.push(`语音转写:${transcript}`)
|
||||||
|
|
||||||
|
// 图片 OCR 文本:与语音同样的"固定前缀"约定,让检索与展示都能识别这是派生内容。
|
||||||
|
const imageText = compact(source.imageOcrText)
|
||||||
|
if (imageText) sections.push(`图片文字:${imageText}`)
|
||||||
|
|
||||||
const attachmentName = compact(source.attachment?.name)
|
const attachmentName = compact(source.attachment?.name)
|
||||||
if (attachmentName) {
|
if (attachmentName) {
|
||||||
const label = source.attachment?.kind === 'link' ? '链接' : '附件'
|
const label = source.attachment?.kind === 'link' ? '链接' : '附件'
|
||||||
@@ -45,6 +49,7 @@ export function normalizeKnowledgeMessage(
|
|||||||
senderId: source.senderId || '',
|
senderId: source.senderId || '',
|
||||||
kind: source.kind,
|
kind: source.kind,
|
||||||
voiceTranscriptState: source.voiceTranscriptState || '',
|
voiceTranscriptState: source.voiceTranscriptState || '',
|
||||||
|
imageOcrState: source.imageOcrState || '',
|
||||||
searchableText
|
searchableText
|
||||||
})
|
})
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -0,0 +1,60 @@
|
|||||||
|
import { execFileSync } from 'node:child_process'
|
||||||
|
import { app } from 'electron'
|
||||||
|
import { buildMacArchSnapshot, type MacArchSnapshot, type MacHardwareArch } from '../shared/macos-arch'
|
||||||
|
|
||||||
|
let cachedSnapshot: MacArchSnapshot | null = null
|
||||||
|
|
||||||
|
/**
|
||||||
|
* `hw.optional.arm64` 是唯一可靠的硬件判据:它在 ARM 上恒为 1,
|
||||||
|
* 在 Intel 上不存在或为 0,且与进程是否被翻译无关。
|
||||||
|
*
|
||||||
|
* 读不到时返回 `unknown`,由上层保留兼容路径 —— 不能猜测硬件,
|
||||||
|
* 猜错会让真正的 Intel Mac 被误拦。
|
||||||
|
*/
|
||||||
|
function readHardwareArch(): MacHardwareArch {
|
||||||
|
try {
|
||||||
|
const stdout = execFileSync('/usr/sbin/sysctl', ['-n', 'hw.optional.arm64'], {
|
||||||
|
encoding: 'utf8',
|
||||||
|
timeout: 1000,
|
||||||
|
stdio: ['ignore', 'pipe', 'ignore']
|
||||||
|
})
|
||||||
|
const value = stdout.trim()
|
||||||
|
if (value === '1') return 'arm64'
|
||||||
|
if (value === '0') return 'x64'
|
||||||
|
return 'unknown'
|
||||||
|
} catch {
|
||||||
|
return 'unknown'
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function readTranslationFlag(platform: NodeJS.Platform): boolean {
|
||||||
|
if (platform !== 'darwin') return false
|
||||||
|
try {
|
||||||
|
return app.runningUnderARM64Translation === true
|
||||||
|
} catch {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 取当前进程的架构快照。
|
||||||
|
*
|
||||||
|
* 结果缓存一次:调用方包括每次刷新连接页都会走的 `key:getEnvironment`,
|
||||||
|
* 缓存后 sysctl 只在首次执行,避免刷 UI 反复起子进程。
|
||||||
|
*/
|
||||||
|
export function getMacArchSnapshot(): MacArchSnapshot {
|
||||||
|
if (cachedSnapshot) return cachedSnapshot
|
||||||
|
const platform = process.platform
|
||||||
|
cachedSnapshot = buildMacArchSnapshot({
|
||||||
|
platform,
|
||||||
|
hardwareArch: platform === 'darwin' ? readHardwareArch() : 'unknown',
|
||||||
|
runtimeArch: process.arch,
|
||||||
|
underARM64Translation: readTranslationFlag(platform)
|
||||||
|
})
|
||||||
|
return cachedSnapshot
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 仅供测试重置缓存;运行期不调用。 */
|
||||||
|
export function resetMacArchSnapshotCache(): void {
|
||||||
|
cachedSnapshot = null
|
||||||
|
}
|
||||||
+119
-8
@@ -125,7 +125,10 @@ export type ParsedContent =
|
|||||||
export function parseMessageContent(content: string, messageType: number): ParsedContent {
|
export function parseMessageContent(content: string, messageType: number): ParsedContent {
|
||||||
// Voice rows may keep their binary payload outside msgContent, so an empty
|
// Voice rows may keep their binary payload outside msgContent, so an empty
|
||||||
// content string is still a valid voice message.
|
// content string is still a valid voice message.
|
||||||
if (messageType === 34) return { type: 'voice' }
|
if (messageType === 34) {
|
||||||
|
const duration = parseVoiceDurationSeconds(content)
|
||||||
|
return duration === undefined ? { type: 'voice' } : { type: 'voice', duration }
|
||||||
|
}
|
||||||
if (!content || typeof content !== 'string') {
|
if (!content || typeof content !== 'string') {
|
||||||
return { type: 'unknown', raw: content || '' }
|
return { type: 'unknown', raw: content || '' }
|
||||||
}
|
}
|
||||||
@@ -157,6 +160,33 @@ export function parseMessageContent(content: string, messageType: number): Parse
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 语音时长藏在解压后的 message_content 里:`<voicemsg ... voicelength="1600" ...>`,单位毫秒。
|
||||||
|
* Msg_* 表没有 voice_length 列,这是唯一来源。
|
||||||
|
*
|
||||||
|
* `<voicemsg>` 上两个极易混淆的属性(真机实测,同一条 1.6 秒语音,2026-09-20):
|
||||||
|
*
|
||||||
|
* - `voicelength="1600"` → **毫秒时长**。这条语音微信气泡显示 2"(1.6 秒四舍五入)。
|
||||||
|
* **要取的是它。**
|
||||||
|
* - `length="6672"` → **SILK 编码数据的字节数,与时长无关**。
|
||||||
|
* 已验证:`wcdb_get_voice_data` 取出的 SILK 恰好是 6672 字节,
|
||||||
|
* 解码后为 51200 字节 PCM(1.6 秒)。误取它会算出 6.672 秒,把 2" 显示成 0:07。
|
||||||
|
*
|
||||||
|
* 换算成秒后**刻意保留小数**(1600ms → 1.6):在这里取整会把精度永久丢掉,
|
||||||
|
* 后面显示层再怎么四舍五入都对不回微信的口径(微信是四舍五入到整秒)。
|
||||||
|
*
|
||||||
|
* 注:`<videomsg length="...">` 的 `length` 同理是字节数,不是时长。
|
||||||
|
*/
|
||||||
|
function parseVoiceDurationSeconds(content: string): number | undefined {
|
||||||
|
if (!content || typeof content !== 'string') return undefined
|
||||||
|
const decoded = decodeXmlEntities(stripChatroomPrefix(content))
|
||||||
|
const rawLength = extractXmlAttribute(decoded, 'voicemsg', 'voicelength')
|
||||||
|
if (!rawLength) return undefined
|
||||||
|
const milliseconds = Number(rawLength)
|
||||||
|
if (!Number.isFinite(milliseconds) || milliseconds <= 0) return undefined
|
||||||
|
return milliseconds / 1000
|
||||||
|
}
|
||||||
|
|
||||||
function parseVideoMessage(content: string): ParsedContent {
|
function parseVideoMessage(content: string): ParsedContent {
|
||||||
const decoded = decodeXmlEntities(stripChatroomPrefix(content))
|
const decoded = decodeXmlEntities(stripChatroomPrefix(content))
|
||||||
const md5 = normalizeMd5(extractXmlAttribute(decoded, 'videomsg', 'md5'))
|
const md5 = normalizeMd5(extractXmlAttribute(decoded, 'videomsg', 'md5'))
|
||||||
@@ -181,6 +211,14 @@ function parseSystemMessage(content: string): ParsedContent {
|
|||||||
recall
|
recall
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
const templateText = extractSysmsgTemplateText(decoded)
|
||||||
|
if (templateText) {
|
||||||
|
return {
|
||||||
|
type: 'system',
|
||||||
|
content: templateText,
|
||||||
|
raw: content
|
||||||
|
}
|
||||||
|
}
|
||||||
const delChatroomMemberText = extractDelChatroomMemberText(decoded)
|
const delChatroomMemberText = extractDelChatroomMemberText(decoded)
|
||||||
if (delChatroomMemberText) {
|
if (delChatroomMemberText) {
|
||||||
return {
|
return {
|
||||||
@@ -189,16 +227,19 @@ function parseSystemMessage(content: string): ParsedContent {
|
|||||||
raw: content
|
raw: content
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
// <link_list> 里放的是富文本片段(可能含 hidden="1" 的可点击按钮),
|
||||||
|
// 不是消息正文;先剥掉再走通用提取,避免把按钮文案当成整条系统消息。
|
||||||
|
const withoutLinkList = stripSysmsgLinkList(decoded)
|
||||||
const plainText =
|
const plainText =
|
||||||
extractXmlNodeText(decoded, 'plain') ||
|
extractXmlNodeText(withoutLinkList, 'plain') ||
|
||||||
extractXmlNodeText(decoded, 'text') ||
|
extractXmlNodeText(withoutLinkList, 'text') ||
|
||||||
extractXmlNodeText(decoded, 'title') ||
|
extractXmlNodeText(withoutLinkList, 'title') ||
|
||||||
extractXmlValue(decoded, 'plain') ||
|
extractXmlValue(withoutLinkList, 'plain') ||
|
||||||
extractXmlValue(decoded, 'text') ||
|
extractXmlValue(withoutLinkList, 'text') ||
|
||||||
extractXmlValue(decoded, 'title') ||
|
extractXmlValue(withoutLinkList, 'title') ||
|
||||||
''
|
''
|
||||||
|
|
||||||
const normalized = normalizeSystemText(plainText || fallbackSystemText(decoded))
|
const normalized = normalizeSystemText(plainText || fallbackSystemText(withoutLinkList))
|
||||||
return {
|
return {
|
||||||
type: 'system',
|
type: 'system',
|
||||||
content: normalized || '[系统消息]',
|
content: normalized || '[系统消息]',
|
||||||
@@ -838,6 +879,76 @@ function extractDelChatroomMemberText(xml: string): string {
|
|||||||
return ''
|
return ''
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** 剥掉 <link_list> 区块 —— 其中的文案属于富文本片段,不是消息正文。 */
|
||||||
|
function stripSysmsgLinkList(xml: string): string {
|
||||||
|
return String(xml || '').replace(/<link_list\b[\s\S]*?<\/link_list>/gi, ' ')
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 微信 4.x 起,部分系统消息改成「模板」格式,正文不再写在 <plain> 里。
|
||||||
|
*
|
||||||
|
* 旧格式(正文就在 <plain>,取到即可):
|
||||||
|
*
|
||||||
|
* <sysmsg type="delchatroommember"><delchatroommember>
|
||||||
|
* <plain><![CDATA["成员昵称"通过扫描你分享的二维码加入群聊]]></plain>
|
||||||
|
* <link><scene>qrcode</scene><text><![CDATA[撤销]]></text>…</link>
|
||||||
|
* </delchatroommember></sysmsg>
|
||||||
|
*
|
||||||
|
* 新格式(<plain> 变空,正文挪进 <template>,用 $名称$ 引用 <link_list> 里的 link):
|
||||||
|
*
|
||||||
|
* <sysmsg type="sysmsgtemplate"><sysmsgtemplate>
|
||||||
|
* <content_template type="tmpl_type_profilewithrevokeqrcode">
|
||||||
|
* <plain><![CDATA[]]></plain>
|
||||||
|
* <template><![CDATA["$adder$"通过扫描你分享的二维码加入群聊 $revoke$]]></template>
|
||||||
|
* <link_list>
|
||||||
|
* <link name="adder" type="link_profile">
|
||||||
|
* <memberlist><member><nickname><![CDATA[成员昵称]]></nickname></member></memberlist>
|
||||||
|
* </link>
|
||||||
|
* <link name="revoke" type="link_revoke_qrcode" hidden="1">
|
||||||
|
* <title><![CDATA[撤销]]></title>
|
||||||
|
* </link>
|
||||||
|
* </link_list>
|
||||||
|
* </content_template>
|
||||||
|
* </sysmsgtemplate></sysmsg>
|
||||||
|
*
|
||||||
|
* 两个要点:
|
||||||
|
* 1. 正文取自 <template>,其中的 $名称$ 占位符按 <link_list> 的 link name 回填;
|
||||||
|
* 2. hidden="1" 的 link 在微信里是可点击按钮,纯文本展示时省略其文案。
|
||||||
|
*
|
||||||
|
* 漏掉这段会让新格式消息落进通用提取链:<plain> 为空、又没有 <text>,
|
||||||
|
* 于是取到 <title> —— 也就是那个隐藏按钮的标题,整条系统消息只剩一个按钮名。
|
||||||
|
*/
|
||||||
|
function extractSysmsgTemplateText(xml: string): string {
|
||||||
|
if (!/<sysmsgtemplate\b|<content_template\b/i.test(xml)) return ''
|
||||||
|
|
||||||
|
const template = extractXmlNodeText(xml, 'template')
|
||||||
|
if (!template) return ''
|
||||||
|
|
||||||
|
const links = new Map<string, { text: string; hidden: boolean }>()
|
||||||
|
const linkPattern = /<link\b([^>]*)>([\s\S]*?)<\/link>/gi
|
||||||
|
let linkMatch: RegExpExecArray | null
|
||||||
|
while ((linkMatch = linkPattern.exec(xml)) !== null) {
|
||||||
|
const name = extractXmlValue(linkMatch[1], 'name')
|
||||||
|
if (!name) continue
|
||||||
|
links.set(name, {
|
||||||
|
// title 用于按钮文案,nickname 用于成员展示名,text 作最后兜底。
|
||||||
|
text:
|
||||||
|
extractXmlNodeText(linkMatch[2], 'title') ||
|
||||||
|
extractXmlNodeText(linkMatch[2], 'nickname') ||
|
||||||
|
extractXmlNodeText(linkMatch[2], 'text') ||
|
||||||
|
'',
|
||||||
|
hidden: /hidden\s*=\s*["']1["']/i.test(linkMatch[1])
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
const rendered = template.replace(/\$([A-Za-z0-9_]+)\$/g, (_raw, name: string) => {
|
||||||
|
const link = links.get(name)
|
||||||
|
return link && !link.hidden ? link.text : ''
|
||||||
|
})
|
||||||
|
|
||||||
|
return normalizeSystemText(rendered)
|
||||||
|
}
|
||||||
|
|
||||||
function normalizeMd5(value: unknown): string | undefined {
|
function normalizeMd5(value: unknown): string | undefined {
|
||||||
const md5 = String(value || '')
|
const md5 = String(value || '')
|
||||||
.trim()
|
.trim()
|
||||||
|
|||||||
@@ -0,0 +1,90 @@
|
|||||||
|
import fs from 'node:fs'
|
||||||
|
import path from 'node:path'
|
||||||
|
import { app } from 'electron'
|
||||||
|
|
||||||
|
import { findResource } from './resource-paths'
|
||||||
|
|
||||||
|
export type NativeRuntimeProfile = 'public' | 'native'
|
||||||
|
|
||||||
|
const BUILD_MARKER = 'tracememo-build.json'
|
||||||
|
const RUNTIME_RELATIVE = 'runtime/darwin-arm64'
|
||||||
|
|
||||||
|
let cachedProfile: NativeRuntimeProfile | null = null
|
||||||
|
let cachedMarkerRead = false
|
||||||
|
|
||||||
|
function getNativeRuntimeProfile(): NativeRuntimeProfile {
|
||||||
|
const envProfile = !app.isPackaged ? process.env.TRACEMEMO_RUNTIME_PROFILE : undefined
|
||||||
|
if (envProfile === 'public' || envProfile === 'native') return envProfile
|
||||||
|
if (cachedMarkerRead && cachedProfile) return cachedProfile
|
||||||
|
cachedMarkerRead = true
|
||||||
|
const marker = findResource(BUILD_MARKER)
|
||||||
|
if (marker) {
|
||||||
|
try {
|
||||||
|
const parsed = JSON.parse(fs.readFileSync(marker, 'utf8')) as { profile?: unknown }
|
||||||
|
if (parsed.profile === 'public' || parsed.profile === 'native') {
|
||||||
|
cachedProfile = app.isPackaged ? parsed.profile : 'native'
|
||||||
|
return cachedProfile
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
// Packaged builds fail closed below when the marker cannot be read.
|
||||||
|
}
|
||||||
|
}
|
||||||
|
cachedProfile = app.isPackaged ? 'public' : 'native'
|
||||||
|
return cachedProfile
|
||||||
|
}
|
||||||
|
|
||||||
|
export function hasMacNativeBundle(): boolean {
|
||||||
|
return process.platform === 'darwin' && getNativeRuntimeProfile() === 'native'
|
||||||
|
}
|
||||||
|
|
||||||
|
export function isMacNativeRuntimeUnavailable(): boolean {
|
||||||
|
return process.platform === 'darwin' && !hasMacNativeBundle()
|
||||||
|
}
|
||||||
|
|
||||||
|
export function resolveWcdbLibrary(): string | null {
|
||||||
|
if (process.platform !== 'darwin') return null
|
||||||
|
const arch = process.arch === 'arm64' ? 'arm64' : 'x64'
|
||||||
|
return findResource(`wcdb/macos/${arch}/libwcdb_api.dylib`)
|
||||||
|
}
|
||||||
|
|
||||||
|
export function resolveWcdbDependency(): string | null {
|
||||||
|
const library = resolveWcdbLibrary()
|
||||||
|
if (!library) return null
|
||||||
|
const dependency = path.join(path.dirname(library), 'libWCDB.dylib')
|
||||||
|
return fs.existsSync(dependency) ? dependency : null
|
||||||
|
}
|
||||||
|
|
||||||
|
export function resolveWcdbConfigHelper(): string | null {
|
||||||
|
if (isMacNativeRuntimeUnavailable()) return null
|
||||||
|
const arch = process.arch === 'arm64' ? 'arm64' : 'x64'
|
||||||
|
return findResource(`wcdb/macos/${arch}/tm-wcdb-config-helper`)
|
||||||
|
}
|
||||||
|
|
||||||
|
export function resolveWechatRuntimeDirectory(): string | null {
|
||||||
|
if (!hasMacNativeBundle()) return null
|
||||||
|
const manifest =
|
||||||
|
findResource(`${RUNTIME_RELATIVE}/runtime-manifest.json`) ||
|
||||||
|
(!app.isPackaged ? findResource('runtime/darwin-arm64/runtime-manifest.json') : null)
|
||||||
|
return manifest ? path.dirname(manifest) : null
|
||||||
|
}
|
||||||
|
|
||||||
|
export function resolveWechatHost(): string | null {
|
||||||
|
const directory = resolveWechatRuntimeDirectory()
|
||||||
|
if (!directory) return null
|
||||||
|
const candidate = path.join(directory, 'tm-wechat-host')
|
||||||
|
return fs.existsSync(candidate) ? candidate : null
|
||||||
|
}
|
||||||
|
|
||||||
|
export function resolveWechatDylib(): string | null {
|
||||||
|
const directory = resolveWechatRuntimeDirectory()
|
||||||
|
if (!directory) return null
|
||||||
|
const candidate = path.join(directory, 'libtmwechat.dylib')
|
||||||
|
return fs.existsSync(candidate) ? candidate : null
|
||||||
|
}
|
||||||
|
|
||||||
|
export function resolveWechatRuntimeManifest(): string | null {
|
||||||
|
const directory = resolveWechatRuntimeDirectory()
|
||||||
|
if (!directory) return null
|
||||||
|
const candidate = path.join(directory, 'runtime-manifest.json')
|
||||||
|
return fs.existsSync(candidate) ? candidate : null
|
||||||
|
}
|
||||||
@@ -230,7 +230,12 @@ function builtInTemplate(template: ReportTemplateDefinition): InstalledReportTem
|
|||||||
}
|
}
|
||||||
|
|
||||||
export class ReportTemplateService {
|
export class ReportTemplateService {
|
||||||
private readonly directory = rootPath()
|
/* 延迟到首次真正用到时再取 app.getPath('userData')。
|
||||||
|
* 这个类在模块顶层被 new(见文件末尾),而 import 顺序一变,模块就可能
|
||||||
|
* 在 electron.app 可用之前被 require —— 那时 app 是 undefined,getPath 直接抛。 */
|
||||||
|
private get directory(): string {
|
||||||
|
return rootPath()
|
||||||
|
}
|
||||||
|
|
||||||
async list(): Promise<InstalledReportTemplate[]> {
|
async list(): Promise<InstalledReportTemplate[]> {
|
||||||
await fs.mkdir(path.join(this.directory, INSTALLED_DIR), { recursive: true })
|
await fs.mkdir(path.join(this.directory, INSTALLED_DIR), { recursive: true })
|
||||||
|
|||||||
@@ -7,6 +7,10 @@ function unique(values: string[]): string[] {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export function getResourceRoots(): string[] {
|
export function getResourceRoots(): string[] {
|
||||||
|
if (app.isPackaged && process.platform === 'darwin') {
|
||||||
|
const packagedResources = join(process.resourcesPath || '', 'resources')
|
||||||
|
return existsSync(packagedResources) ? [packagedResources] : []
|
||||||
|
}
|
||||||
const appPath = app.getAppPath()
|
const appPath = app.getAppPath()
|
||||||
const appPathDir = dirname(appPath)
|
const appPathDir = dirname(appPath)
|
||||||
const execDir = dirname(process.execPath)
|
const execDir = dirname(process.execPath)
|
||||||
|
|||||||
@@ -5,8 +5,13 @@ import { join } from 'path'
|
|||||||
export function isPackagedRuntime(): boolean {
|
export function isPackagedRuntime(): boolean {
|
||||||
if (app.isPackaged) return true
|
if (app.isPackaged) return true
|
||||||
|
|
||||||
|
// 非 Electron 进程(例如单元/集成测试)里 process.resourcesPath 不存在,
|
||||||
|
// 此时 join 会抛错。没有 resources 目录就必然不是打包运行时。
|
||||||
|
const resourcesPath = process.resourcesPath
|
||||||
|
if (!resourcesPath) return false
|
||||||
|
|
||||||
return (
|
return (
|
||||||
existsSync(join(process.resourcesPath, 'app.asar')) &&
|
existsSync(join(resourcesPath, 'app.asar')) &&
|
||||||
existsSync(join(process.resourcesPath, 'app-update.yml'))
|
existsSync(join(resourcesPath, 'app-update.yml'))
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
@@ -23,6 +23,45 @@ import {
|
|||||||
|
|
||||||
const aiProvider = new AIProviderService()
|
const aiProvider = new AIProviderService()
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 用真实群成员快照补全消息的显示名与头像。
|
||||||
|
*
|
||||||
|
* **头像与名称的门槛刻意不同**:
|
||||||
|
*
|
||||||
|
* 此前这里先用 `isInternalName(message.name)` 做整体早退 —— 只有当消息里的名字还是内部标识
|
||||||
|
* (空 / `wxid_*` / `*@chatroom` / 18+ 位字母数字)时才继续。但 `listMessages` 产出的 `name`
|
||||||
|
* 优先取 `senderNickname`,在真实群里通常是**已可读的昵称**,于是整条记录被跳过、
|
||||||
|
* `member.avatar` 永远补不上,导出层只能退化成首字头像;软件内日报没有这个门槛,
|
||||||
|
* 所以它能显示真实头像。
|
||||||
|
*
|
||||||
|
* 现在:**只要 senderId 命中真实群成员就允许补头像**;名称只在解析结果确实是可读名时才采用,
|
||||||
|
* 避免把调用方已有的昵称降级成空串或内部标识。消息自带的 `img` 始终优先。
|
||||||
|
*/
|
||||||
|
export function hydrateGroupMemberIdentity(
|
||||||
|
messages: Message[],
|
||||||
|
members: ReadonlyArray<NonNullable<ReturnType<typeof getGroupSnapshot>>['members'][number]>,
|
||||||
|
memberNameMode: ScheduledReportMemberNameMode
|
||||||
|
): Message[] {
|
||||||
|
const index = new Map(
|
||||||
|
members.map((member) => [
|
||||||
|
member.wxid,
|
||||||
|
{ name: resolveMemberName(member, memberNameMode), avatar: member.avatar }
|
||||||
|
])
|
||||||
|
)
|
||||||
|
return messages.map((message) => {
|
||||||
|
const member = index.get(String(message.senderId || message.name || ''))
|
||||||
|
if (!member) return message
|
||||||
|
const shouldFillAvatar = !message.img && Boolean(member.avatar)
|
||||||
|
const resolvedName = member.name && !isInternalName(member.name) ? member.name : message.name
|
||||||
|
if (!shouldFillAvatar && resolvedName === message.name) return message
|
||||||
|
return {
|
||||||
|
...message,
|
||||||
|
name: resolvedName,
|
||||||
|
...(shouldFillAvatar ? { img: member.avatar } : {})
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
export interface AgentGroupReportRequest {
|
export interface AgentGroupReportRequest {
|
||||||
group: string
|
group: string
|
||||||
range?: SummaryDateRange | 'recent24h'
|
range?: SummaryDateRange | 'recent24h'
|
||||||
@@ -101,22 +140,11 @@ export async function generateAgentGroupReport(
|
|||||||
|
|
||||||
const snapshot = getGroupSnapshot(contact.md5)
|
const snapshot = getGroupSnapshot(contact.md5)
|
||||||
if (snapshot) {
|
if (snapshot) {
|
||||||
const members = new Map(
|
messages = hydrateGroupMemberIdentity(
|
||||||
snapshot.members.map((member) => [
|
messages,
|
||||||
member.wxid,
|
snapshot.members,
|
||||||
{
|
request.memberNameMode || 'groupNickname'
|
||||||
name: resolveMemberName(member, request.memberNameMode || 'groupNickname'),
|
|
||||||
avatar: member.avatar
|
|
||||||
}
|
|
||||||
])
|
|
||||||
)
|
)
|
||||||
messages = messages.map((message) => {
|
|
||||||
if (!isInternalName(message.name)) return message
|
|
||||||
const member = members.get(String(message.senderId || message.name || ''))
|
|
||||||
return member?.name
|
|
||||||
? { ...message, name: member.name, img: message.img || member.avatar }
|
|
||||||
: message
|
|
||||||
})
|
|
||||||
}
|
}
|
||||||
|
|
||||||
const input = await buildGroupReportInput(messages, contact as Contact, true, 'full')
|
const input = await buildGroupReportInput(messages, contact as Contact, true, 'full')
|
||||||
|
|||||||
Loaded 100 of 455 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user