Compare commits

..
25 Commits
Author SHA1 Message Date
qingmao c398691792 Add files via upload 2026-11-16 15:02:44 +08:00
Wxw-Gu 804466aad8 chor: 修改文案 2026-11-10 10:01:54 +08:00
Wxw-Gu d1ee3bbd30 Merge remote-tracking branch 'origin/main' into develop 2026-11-09 16:51:46 +08:00
Wxw-Gu 7dcda8554e feat: 增加忽略本次更新 2026-11-09 16:51:03 +08:00
Wxw-Gu 6cadcb9a5a chore: 修改打包配置 2026-11-09 16:34:20 +08:00
Wxw-Gu f47af8024f feat: 完善mac发送逻辑 2026-11-09 11:19:59 +08:00
Wxw-Gu 05b881d79e fix: mac arm通过文件夹打开被判定为intel芯片
mac os升级27 权限问题解决文档
2026-11-06 11:10:01 +08:00
Wxw-Gu 80e0f43529 fix: bug 2026-11-05 18:06:28 +08:00
Wxw-Gu 39753d7784 Merge branch 'develop' of https://github.com/Wxw-Gu/TraceMemo into develop 2026-11-05 17:10:20 +08:00
Wxw-Gu f95e9d491c fix: 初始化链接 2026-11-05 17:09:12 +08:00
Wxw-Gu 780a19900b test: 补 electron mock,修复合并后 wcdb4-client 路径解析测试 2026-11-04 16:09:29 +08:00
Wxw-Gu 7e9997cc06 Merge branch 'develop_1030' into develop
# Conflicts:
#	.gitignore
2026-11-04 16:07:42 +08:00
Wxw-Gu 8c162969ff feat: mac发送完整支持4.1.13以上版本, 完善授权 2026-11-04 15:49:15 +08:00
qingmao 9db08dba1a feat: 上传文件 2026-11-03 16:21:04 +08:00
Wxw-Gu 49e3fcfb20 chore: 更新 wcdb_api 原生组件 2026-11-03 16:08:00 +08:00
Wxw-Gu 450668f5e6 feat: windows自动化下统一逻辑 2026-11-03 16:05:16 +08:00
Wxw-Gu 8804a16ad9 fix(wechat-send): HTTP 发送路径为语音补 self wxid
Windows hook 的语音对象需要发送者 wxid,IPC 路径(UI 点发送)会用
chat.getSelfAccountInfoAsync() 塞进 metadata.fromId,HTTP 路由漏了这一步,
表现为 type=voice 一律 SEND_FAILED「无法识别当前微信账号 wxid」。

- createWechatSendRoute 内懒加载 chat-service 取 self wxid(避免静态循环依赖)
- 仅在 contentType === 'voice' 时解析,其它类型不加开销
- 命中则并入 metadata.fromId,由 wechat-action-gateway 映射成 fromWxid 下发
2026-11-01 04:03:52 +08:00
Wxw-Gu d9d0672072 Merge branch 'develop' of https://github.com/Wxw-Gu/TraceMemo into develop 2026-11-01 01:50:40 +08:00
Wxw-Gu a328db687d chore: 暂存 2026-11-01 01:49:58 +08:00
Wxw-Gu 915ee73f95 chore: mac打包配置 2026-11-01 01:21:00 +08:00
qingmao df6388a86d Merge pull request #65 from xxoommd/fix/voice-media-shards-v2.5.2
fix: 修复媒体分库中的语音无法播放和转写
2026-10-30 10:20:23 +08:00
qingmao 695afd7c3e Merge pull request #66 from xxoommd/fix/automation-page-crash
fix: 修复打开自动化页面时应用崩溃
2026-10-30 10:18:34 +08:00
xxoommd 049b5a9495 fix: 修复打开自动化页面时应用崩溃 2026-10-29 17:49:17 +08:00
xxoommd 43c917a070 fix: 修复媒体分库中的语音无法播放和转写 2026-10-29 17:35:33 +08:00
Wxw-Gu 84737a7407 fix: 完善微信发送运行时状态识别 2026-10-29 17:16:44 +08:00
78 changed files with 7785 additions and 636 deletions

No files matched your search

+2
View File
@@ -28,4 +28,6 @@ progress.md
task_plan.md
*tm-wcdb-config-helper*
*libtmlicense*
debug-originals
/build/mac-staging/
+1
View File
@@ -45,6 +45,7 @@ Agent Hub 让微信机器人调用本机 TraceMemo;Reader Skill / Local HTTP A
- [导出聊天](./user-guide/export.md):导出 HTML、Markdown、CSV 或 JSON 档案。
- [数据、隐私与安全](./user-guide/privacy.md):本地处理、Provider、媒体和 Token 的数据边界。
- [常见问题与排查](./user-guide/troubleshooting.md):按安装、连接、AI、媒体和 Agent 现象排查。
- [macOS 更新27后读不到微信数据](./user-guide/macos27-permission-recovery.md):升级 macOS 或更新应用后失去微信数据访问权限的恢复步骤。
## 开发文档
@@ -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 开发环境,在「设置 → 微信发送」中查看发送能力与授权状态。
**注意:** 发送能力组件不包含授权。开发环境仍需使用有效的设备授权才能绑定微信和发送消息。
+30 -2
View File
@@ -19,7 +19,12 @@ TraceMemo 需要读取微信本地数据。macOS 会根据系统版本、微信
如果你在连接页看到「最近验证结果:无法读取微信数据库」(错误码 `DATABASE_PERMISSION_DENIED`),并且已经确认微信数据目录**实际存在**(例如在终端里能列出 `db_storage/session/session.db`),那说明是 **TraceMemo 这个进程**读不到,而不是文件缺失。
macOS 27 及更高版本对其他应用的容器数据有更严格的访问控制。给 TraceMemo 授予「完全磁盘访问权限」:
微信数据放在另一个应用的沙盒容器里,macOS 会对这种跨应用访问单独做校验。先看「完全磁盘访问权限」里 TraceMemo 的状态,再按情况处理:
- **不在列表里,或开关是关的**:按下面的步骤授权。
- **开关已经是开的,但仍然读不到**:这不是「没授权」,而是旧授权记录对不上当前版本的应用,需要先清掉旧记录再重新授权。完整步骤见[macOS 更新后读不到微信数据:权限恢复](../user-guide/macos27-permission-recovery.md)。
首次授权的步骤:
1. 打开 **系统设置 → 隐私与安全性 → 完全磁盘访问权限**
2. 找到 **TraceMemo**,打开开关
@@ -61,6 +66,29 @@ TraceMemo 同时支持两种 Mac 架构:
- Apple Silicon:`tracememo-<版本号>-arm64.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`。不同架构、微信版本和系统授权状态可能导致连接结果不同;文档不对所有组合做兼容性保证。
@@ -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 节即可,通常不需要重装、不需要重新取密钥。
- 彻底解决需要发布端改用稳定的开发者签名并完成公证,这属于打包流程的改动,不在用户侧。
正常使用、没有出现问题的用户,不需要提前做任何权限设置。授权不是安装前置条件。
+8 -4
View File
@@ -25,9 +25,10 @@
1. 数据目录是否指向当前登录账号,而不是旧备份或迁移前目录;
2. 微信版本是否属于当前代码面向的 4.x 数据结构;
3. 微信是否处于页面要求的登录/退出状态;
4. macOS 是否完成页面要求的授权;
4. macOS 是否完成页面要求的授权;如果是升级 macOS 或更新 TraceMemo 之后才失败的,按[权限恢复文档](./macos27-permission-recovery.md)处理,只打开开关通常不够;
5. 连接页面的诊断项是否明确指出密钥、账号或数据库问题;
6. macOS 上 Apple Silicon 与 Intel 使用不同的连接流程,按连接页面提示操作;两者都可以自动获取数据库密钥。
7. 页面显示「Intel Mac 自动获取」但电脑是 Apple 芯片时,多半是装了 Intel 版,见[架构不匹配说明](../platform/macos.md#提示intel-mac-自动获取但电脑是-apple-芯片)。
重新输入密钥或断开连接不会删除微信原始数据库。macOS 的 SIP 和授权说明见[平台说明](../platform/macos.md)。
@@ -35,11 +36,14 @@
这是**权限问题,不是文件缺失** —— 如果你在终端里能列出 `db_storage/session/session.db`,说明数据目录是完整的,只是 TraceMemo 这个进程读不到。
macOS 27 及更高版本需要给 TraceMemo 授予「完全磁盘访问权限」。注意:**终端能读到文件不代表 TraceMemo 有权限** —— macOS 的隐私权限按应用进程的身份判定,两者走的是不同的授权。
注意:**终端能读到文件不代表 TraceMemo 有权限** —— macOS 的隐私权限按应用进程的身份判定,两者走的是不同的授权。
处理步骤见 [macOS 数据访问与系统权限 → 提示「无法读取微信数据库」时](../platform/macos.md#提示无法读取微信数据库时)。
按出现时机分两种情况:
仍然失败时,记录 **macOS 版本、CPU 架构(Apple Silicon / Intel)、微信版本、TraceMemo 版本和页面错误提示**后 扫码 README 文档二维码进群提交消息, 或者提交 Issue。
- **首次连接就没成功**:给 TraceMemo 授予「完全磁盘访问权限」即可,步骤见 [macOS 数据访问与系统权限 → 提示「无法读取微信数据库」时](../platform/macos.md#提示无法读取微信数据库时)。
- **之前能用,升级 macOS 或更新 TraceMemo 之后才失败**:多数是旧授权记录对不上新版本的应用,只打开开关不够,需要先清掉旧记录再重新授权。完整步骤见[macOS 更新后读不到微信数据:权限恢复](./macos27-permission-recovery.md)。
仍然失败时,记录 **macOS 版本、CPU 架构(Apple Silicon / Intel)、微信版本、TraceMemo 版本和页面错误提示** 后,扫码 README 文档二维码进群反馈,或提交 Issue。连接页的「复制脱敏诊断摘要」可以直接提供这些环境信息。
## 连接成功但没有联系人或消息
+5 -1
View File
@@ -2,9 +2,12 @@ import { resolve } from 'path'
import { defineConfig } from 'electron-vite'
import react from '@vitejs/plugin-react'
const editionOutDir = process.env.TRACEMEMO_EDITION_OUT_DIR
export default defineConfig({
main: {
build: {
...(editionOutDir ? { outDir: editionOutDir } : {}),
rollupOptions: {
input: {
index: resolve('src/main/index.ts'),
@@ -20,8 +23,9 @@ export default defineConfig({
}
}
},
preload: {},
preload: editionOutDir ? { build: { outDir: editionOutDir } } : {},
renderer: {
...(editionOutDir ? { build: { outDir: editionOutDir } } : {}),
resolve: {
alias: {
'@renderer': resolve('src/renderer/src')
+6 -4
View File
@@ -1,6 +1,6 @@
{
"name": "tracememo",
"version": "2.5.2",
"version": "2.6.0",
"packageManager": "pnpm@7.33.7",
"description": "TraceMemo(迹忆)是一款本地优先、可追溯的 AI 微信知识与分析工作台。 原名 WechatExplorer,支持聊天记录搜索、知识库、微信群聊总结和 Agent 助手。",
"keywords": [
@@ -63,11 +63,13 @@
"build:win": "npm run typecheck && npm run prepare:win-runtime && electron-vite build && electron-builder --config electron-builder.win.yml --win --x64",
"build:mac:arm64": "npm run typecheck && npm run prepare:ffmpeg:mac:arm64 && electron-vite build && electron-builder --config electron-builder.yml --mac --arm64",
"build:mac:arm64:send-runtime": "npm run typecheck && npm run prepare:ffmpeg:mac:arm64 && electron-vite build && cross-env TM_SEND_RUNTIME_BUILD=1 electron-builder --config electron-builder.send-runtime.yml --mac --arm64",
"build:mac: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: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:x64": "npm run prepare:ffmpeg:mac:x64 && electron-builder --config electron-builder.yml --mac --x64 --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 --config.directories.output=dist/release/mac-x64",
"release:win": "npm run typecheck && npm run prepare:win-runtime && electron-vite build && electron-builder --config electron-builder.win.yml --win --x64 --publish always",
"release:beta": "cross-env EP_PRE_RELEASE=true npm run release",
"release:stable": "npm run release",
@@ -175,4 +177,4 @@
"ffmpeg-static"
]
}
}
}
Binary file not shown.

Before

Width:  |  Height:  |  Size: 152 KiB

After

Width:  |  Height:  |  Size: 153 KiB

Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
+293 -8
View File
@@ -1,5 +1,6 @@
/* 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 path = require('node:path')
const asar = require('@electron/asar')
@@ -24,6 +25,14 @@ const REQUIRED_RUNTIME_PACKAGES = [
// 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) {
const productName = context.packager.appInfo.productFilename
@@ -45,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 ffmpegPath = path.join(
runtimeResources,
@@ -61,6 +88,202 @@ function validateFfmpegRuntime(runtimeResources, platform = process.platform) {
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) {
const platformName = platform === 'win32' ? 'win' : platform
const basePath = path.join(
@@ -193,19 +416,28 @@ function isMacosCodeValid(targetPath, run = runCodesign) {
}
function findMacosHelperPaths(runtimeResources) {
return MACOS_HELPER_NAMES.map((name) => path.join(runtimeResources, 'resources', name)).filter(
(helperPath) => existsSync(helperPath)
)
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) {
chmodSync(helperPath, 0o755)
if (!helperPath.endsWith('.dylib')) chmodSync(helperPath, 0o755)
if (!isMacosCodeValid(helperPath, run)) {
run(['--force', '--sign', '-', helperPath])
}
for (const arch of ['arm64', 'x86_64']) {
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) {
@@ -333,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
* universal) macOS bundle can run. Every other target — Apple Silicon macOS,
@@ -483,7 +737,12 @@ function isSendRuntimeBuild() {
function enforceSendRuntimeBoundary(
runtimeResources,
platform,
bundlesSendRuntime = isSendRuntimeBuild()
bundlesSendRuntime =
process.env.TRACEMEMO_EDITION === 'native'
? true
: process.env.TRACEMEMO_EDITION === 'public'
? false
: isSendRuntimeBuild()
) {
if (platform !== 'darwin') return null
const found = findSendRuntime(runtimeResources)
@@ -523,6 +782,12 @@ exports.default = async function afterPack(context) {
validateReaderSkillRuntime(runtimeResources)
validateSilkWasmRuntime(runtimeResources)
const ffmpegPath = validateFfmpegRuntime(runtimeResources, context.electronPlatformName)
validateElectronMainBinary(
context.appOutDir,
context.packager.appInfo.productFilename,
context.electronPlatformName,
arch
)
validateRuntimeBinaryArchitecture(
ffmpegPath,
context.electronPlatformName,
@@ -532,6 +797,23 @@ exports.default = async function afterPack(context) {
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)
pruneForeignArchConnectors(runtimeResources, context.electronPlatformName, arch)
pruneForeignArchNativeRuntimes(runtimeResources, context.electronPlatformName, arch)
@@ -554,10 +836,13 @@ exports.validateSilkWasmRuntime = validateSilkWasmRuntime
exports.validateSherpaRuntime = validateSherpaRuntime
exports.validateSystemOcrRuntime = validateSystemOcrRuntime
exports.validateKoffiRuntime = validateKoffiRuntime
exports.validateMacEditionResources = validateMacEditionResources
exports.validateMacEditionProtectedFiles = validateMacEditionProtectedFiles
exports.pruneIntelMacKeyTool = pruneIntelMacKeyTool
exports.pruneForeignArchConnectors = pruneForeignArchConnectors
exports.pruneForeignArchNativeRuntimes = pruneForeignArchNativeRuntimes
exports.validateRuntimeBinaryArchitecture = validateRuntimeBinaryArchitecture
exports.validateElectronMainBinary = validateElectronMainBinary
exports.findMacosHelperPaths = findMacosHelperPaths
exports.isMacosCodeValid = isMacosCodeValid
exports.signMacosHelpers = signMacosHelpers
+174
View File
@@ -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 }
+660
View File
@@ -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
}
+12
View File
@@ -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()
}
+16 -1
View File
@@ -755,6 +755,19 @@ function createWechatSendRoute(
pathname: string,
deps: WechatSendApiDependencies
): RouteHandler | undefined {
// 语音发送必须带「当前账号 wxid」:Windows hook 的语音对象需要它。
// IPC 路径一直有(index.ts 里的 chat.getSelfAccountInfoAsync),HTTP 路径漏了,
// 表现为 type=voice 一律 SEND_FAILED「无法识别当前微信账号 wxid」。
// 懒加载,避免 http-server 与 chat-service 形成静态循环依赖。
const resolveSelfWxid = async (): Promise<string> => {
try {
const chat = await import('./services/chat-service')
const self = await chat.getSelfAccountInfoAsync()
return String(self?.wxid || '').trim()
} catch {
return ''
}
}
if (pathname !== WECHAT_SEND_ROUTE) return undefined
return withMethods(['POST'], async ({ res, body }) => {
@@ -815,13 +828,15 @@ function createWechatSendRoute(
let result: WechatActionResult
try {
const fromId = contentType === 'voice' ? await resolveSelfWxid() : ''
result = await deps.execute({
origin: 'http_api',
purpose: `api_${contentType}` as WechatActionRequest['purpose'],
triggerType: 'user',
recipient: parsed.recipient,
content: parsed.content,
...(parsed.idempotencyKey ? { idempotencyKey: parsed.idempotencyKey } : {})
...(parsed.idempotencyKey ? { idempotencyKey: parsed.idempotencyKey } : {}),
...(fromId ? { metadata: { fromId } } : {})
})
} catch (error) {
return sendWechatSendError(res, 500, 'INTERNAL_ERROR', '微信发送执行失败', {
+2 -4
View File
@@ -5,7 +5,7 @@ import os from 'os'
import { app } from 'electron'
import { execFile } from 'child_process'
import { Worker } from 'worker_threads'
import ffmpegStaticPath from 'ffmpeg-static'
import { resolveBundledFfmpegPath } from './ffmpeg-path'
import type { ImageDecoderSource, ImageDecoderStatus } from '../shared/image-decryption'
import { imageFileQuality, imageQualityRank } from '../shared/image-quality'
import { loadSettings } from './services/settings-store'
@@ -78,9 +78,7 @@ function getFfmpegCandidates(selectedPath = loadSettings().ffmpegPath): FfmpegCa
const selected = String(selectedPath || '').trim()
const environment = String(process.env['FFMPEG_BIN'] || '').trim()
const executable = process.platform === 'win32' ? 'ffmpeg.exe' : 'ffmpeg'
const staticExecutable = String(ffmpegStaticPath || '')
.replace('app.asar', 'app.asar.unpacked')
.trim()
const staticExecutable = resolveBundledFfmpegPath()
const candidates: FfmpegCandidate[] = [
...(selected ? [{ executable: selected, source: 'selected' as const }] : []),
...(environment ? [{ executable: environment, source: 'environment' as const }] : []),
+342 -25
View File
@@ -1,4 +1,5 @@
import path from 'node:path'
import { isWcdbDebugEnabled } from './wcdb-debug'
import {
isLegacyMigrationHelper,
isUserDataIsolated,
@@ -75,6 +76,8 @@ import type {
} from '../shared/image-insight'
import type { SystemOcrCapability, SystemOcrRequest, SystemOcrResult } from '../shared/system-ocr'
import { KeyServiceMac } from './key-service-mac'
import { getMacArchSnapshot } from './macos-arch'
import { shouldProbeIntelEnvironment } from '../shared/macos-arch'
import { KeyService as KeyServiceWin } from './key-service-win'
import * as chat from './services/chat-service'
import {
@@ -105,6 +108,7 @@ import {
saveSettings,
updateSettings,
getSettingsPath,
normalizeSkippedUpdateVersion,
AppSettings,
validateDbRoot
} from './services/settings-store'
@@ -152,6 +156,22 @@ import {
type MsgInsertSwitchName,
type MsgInsertSwitchesSnapshot
} from './services/msg-insert-switch-service'
import type { MsgInsertErrorCode, MsgInsertSwitchStatus } from '../shared/msg-insert-switch'
import {
msgInsertCapabilityService,
type MessageInsertCapability
} from './services/msg-insert-capability-service'
import { resolveExternalComponent } from './services/external-component-locator'
import {
cleanupMacWechatResidualProcesses,
inspectMacWechatResidualProcesses
} from './services/mac-wechat-residual-cleanup'
import {
isDefinitelyBlocked,
isEntitlementBlocked,
resolveExitNoticeGate,
resolveSwitchPresentation
} from './services/exit-notice-gate'
import { GroupStatsService } from './services/group-stats-service'
import {
configureWechatLocalExitNotice,
@@ -225,6 +245,123 @@ function buildMsgInsertSwitchesSnapshot(): MsgInsertSwitchesSnapshot {
}
}
/** 能力判定需要知道「微信库连没连」,但不需要知道发送是否就绪。 */
function capabilityDatabaseReady(): boolean {
return Boolean(chat.getChatDb()?.getWcdb4Client())
}
/**
* 退群提示与防撤回同为发送能力:授权/组件不成立时 desired 与 effective 一起压
* (UI 读 desired),探测失败不落盘,否则正常用户会被误关。
*/
/** 明确不可用时把本地开关落盘关掉;只写设置文件,不动监控范围。 */
function enforceExitNoticeGate(capability: MessageInsertCapability): void {
if (!isDefinitelyBlocked(capability)) return
if (!wechatLocalExitNoticeService.isEnabled()) return
const decision = resolveExitNoticeGate(capability, true)
if (!decision.persistDisable) return
const disabled = wechatLocalExitNoticeService.setEnabled(false)
syncExitNoticeScope()
appLogger.write({
level: 'warn',
scope: 'capability-gate',
message: '退群内提示已因发送能力不可用自动关闭',
details: {
reasonCode: capability.reasonCode,
entitlementState: capability.entitlementState,
nativeComponentState: capability.nativeComponentState,
persisted: !disabled.error
}
})
}
/** 把授权/组件判定挂到快照上;GET 仍是纯读,不写库不触发 DDL。 */
async function attachCapability(
snapshot: MsgInsertSwitchesSnapshot
): Promise<MsgInsertSwitchesSnapshot> {
const capability = await msgInsertCapabilityService.getCapability({
databaseReady: capabilityDatabaseReady()
})
enforceExitNoticeGate(capability)
/* 两个开关的呈现共用同一判定:授权不成立显示关闭,库没连只压 effective。 */
const switches = { ...snapshot.switches }
const applyPresentation = (
kind: 'recall_notice' | 'group_exit_notice',
status: MsgInsertSwitchStatus | undefined
): MsgInsertSwitchStatus | undefined => {
if (!status) return status
const current =
kind === 'group_exit_notice'
? wechatLocalExitNoticeService.isEnabled()
: status.desiredEnabled === true
const presentation = resolveSwitchPresentation(kind, current, capability)
if (presentation.effectiveEnabled) {
return {
...status,
desiredEnabled: true,
effectiveEnabled: true,
operationOk: true
}
}
/*
* 不要无脑覆盖 errorCode:授权没问题、只是暂时不生效时(库没连、分片没读到),
* 用 CAPABILITY_READY 盖上去会把真实原因擦掉,用户看到的是「授权与组件均已就绪」
* 配一个点不动的开关。
*/
const blocked = isEntitlementBlocked(capability)
return {
...status,
desiredEnabled: presentation.desiredEnabled,
effectiveEnabled: false,
operationOk: false,
errorCode: blocked
? (capability.reasonCode as MsgInsertErrorCode)
: (status.errorCode ?? (capability.reasonCode as MsgInsertErrorCode)),
message: blocked ? capability.message : (status.message ?? capability.message)
}
}
switches.recall_notice = applyPresentation('recall_notice', switches.recall_notice)!
switches.group_exit_notice = applyPresentation('group_exit_notice', switches.group_exit_notice)!
return {
...snapshot,
switches,
capability: capability,
/* 旧字段保留一个与真实判定一致的值,避免老调用方继续读到一个恒 true */
sendCapabilityAvailable: capability.canEnable
}
}
/** 能力原因 → 开关错误码。三种「不可用」必须能区分开。 */
function reasonToErrorCode(capability: MessageInsertCapability): MsgInsertErrorCode {
switch (capability.reasonCode) {
case 'LICENSE_REQUIRED':
return 'LICENSE_REQUIRED'
case 'LICENSE_PENDING':
return 'LICENSE_PENDING'
case 'LICENSE_EXPIRED':
return 'LICENSE_EXPIRED'
case 'COMPONENT_MISSING':
case 'COMPONENT_INVALID':
return 'COMPONENT_MISSING'
case 'DATABASE_UNAVAILABLE':
return 'DATABASE_UNAVAILABLE'
default:
return 'CAPABILITY_UNAVAILABLE'
}
}
/** 开启前的统一裁决:拿最新状态,不信页面缓存。 */
async function requireCapability(): Promise<{
ok: boolean
capability: MessageInsertCapability
}> {
const capability = await msgInsertCapabilityService.refresh({
databaseReady: capabilityDatabaseReady()
})
return { ok: capability.canEnable, capability }
}
/**
* 轻量 reconciliation —— 把退群监控选中的群缺失的规则补齐,不动开关值。
*
@@ -248,14 +385,14 @@ async function reconcileMsgInsertRulesOnStart(): Promise<void> {
if (!scope || !client) return
let enabled = false
let shardSignature = ''
try {
const shards = client.listMessageShardPaths()
const shardSignature = shards.map((item) => path.basename(item)).join(',')
shardSignature = shards.map((item) => path.basename(item)).join(',')
if (lastMsgInsertReconciledShards && lastMsgInsertReconciledShards !== shardSignature) {
/* 微信新建了 message_N.db(或清理了旧的)—— 分片集合变了就重新补齐。 */
console.log('[MsgInsert] 检测到消息分片变化,重新补齐规则')
}
lastMsgInsertReconciledShards = shardSignature
for (const shardPath of shards) {
const read = client.getMsgInsertSwitches(shardPath)
if (read.success && read.switches?.recall_notice) {
@@ -268,15 +405,23 @@ async function reconcileMsgInsertRulesOnStart(): Promise<void> {
return
}
if (!enabled) return
await reconcileMsgInsertRulesNow(recallRoomsForReconcile(scope))
/*
* 授权前置:没有有效授权时不许 spawn helper 装规则。
* 指纹**不在这里更新** —— 没补成功就记指纹,会让「无授权跳过 → 后来激活 →
* 分片没变 → 永远不再补」这个死循环成立。
*/
const gate = await requireCapability()
if (!gate.ok) {
console.log(
`[MsgInsert] 启动补齐已跳过:${gate.capability.reasonCode}(${gate.capability.message})`
)
return
}
const done = await reconcileMsgInsertRulesNow(recallRoomsForReconcile(scope))
if (done) lastMsgInsertReconciledShards = shardSignature
}
/**
* 防撤回的作用面 = 全部可定位会话(群聊 + 私聊)。
*
* native 侧有「定义漂移就 DROP + 重建」的能力,但只有显式复核时才会跑;
* 规则定义变了不自动铺开,用户就得手动关-开一次开关。
*/
function recallRoomsForReconcile(scope: MsgInsertScopeInput): string[] {
return resolveTargetRooms(scope, 'recall_notice').rooms
}
@@ -285,6 +430,15 @@ async function reconcileMsgInsertRulesNow(extraRooms: string[] = []): Promise<bo
const scope = resolveMsgInsertScopeInput()
const client = chat.getChatDb()?.getWcdb4Client()
if (!scope || !client) return false
/*
* 底层兜底:不管从哪条路径进来(启动 / 刷新 / 清理 / 未来的新调用方),
* 装规则前都过一次发送能力校验。上层已经判过也不亏——命中 TTL 缓存几乎零成本。
*/
const gate = await requireCapability()
if (!gate.ok) {
console.warn(`[MsgInsert] 拒绝安装规则:${gate.capability.reasonCode}`)
return false
}
try {
const result = await reconcileMsgInsertRules({
...scope,
@@ -345,8 +499,21 @@ async function cleanupLegacyRecallResidueOnStart(): Promise<void> {
* 删除必须借 helper 的可写连接:本进程对分片只有只读连接,自己发 DROP 一定失败。
* helper 那条链路会在装规则时顺手清掉残留,顺带把新规则铺到所有会话。
*/
/*
* 清理只能借 helper 的 ensure-rules 完成(没有独立的 drop-only 动作),
* 而 ensure-rules 会顺手把新规则铺到所有会话 —— 那属于写库动作。
* 所以没有授权时只保留残留、不执行清理,绝不拿「清理」当借口绕开门禁。
*/
const scope = resolveMsgInsertScopeInput()
const applied = scope ? await reconcileMsgInsertRulesNow(recallRoomsForReconcile(scope)) : false
let applied = false
if (scope) {
const gate = await requireCapability()
if (gate.ok) {
applied = await reconcileMsgInsertRulesNow(recallRoomsForReconcile(scope))
} else {
console.log(`[RecallResidue] 无有效授权,跳过残留清理(${gate.capability.reasonCode})`)
}
}
/* 收尾结论以「重新扫描」为准,不采信 helper 的自述。 */
const after = client.scanLegacyRecallResidue()
@@ -368,7 +535,10 @@ async function cleanupLegacyRecallResidueOnStart(): Promise<void> {
})
} catch (error) {
/* 清理失败绝不能挡住启动 —— 它只是收尾工作。 */
console.warn('[RecallResidue] 清理失败:', error)
console.warn(
'[RecallResidue] 清理失败:',
isWcdbDebugEnabled() ? error : error instanceof Error ? error.message : String(error)
)
appLogger.write({
level: 'warn',
scope: 'recall-residue',
@@ -1208,6 +1378,47 @@ app.whenReady().then(async () => {
message: 'TraceMemo 启动',
details: { build: BUILD_MARK, platform: process.platform, version: app.getVersion() }
})
/*
* 发送能力组件解析结果单独落一条日志。
* 现场排障时这是第一分界线:「组件没解析到」和「解析到了但授权不过」是两条完全不同的
* 排查路径,用户报「装了没生效」先看这一行,不要先去怀疑授权。
*/
const external = resolveExternalComponent()
console.log(
external
? `[Component] resolved version=${external.version} dirty=${external.dirty} dir=${external.dir}`
: '[Component] not resolved (no current.json, or manifest size/sha256 check failed)'
)
appLogger.write({
level: external ? 'info' : 'warn',
scope: 'component-locate',
message: external ? '已加载发送能力组件' : '未找到可用的发送能力组件',
details: external
? {
version: external.version,
dir: external.dir,
helper: external.helperPath,
worktreeDirty: external.dirty
}
: {
platform: process.platform,
expected: '%LOCALAPPDATA%\\TraceMemo\\Pro\\windows-x64\\current.json'
}
})
/* 启动即对齐本地开关,否则 enabled=true 会潜伏,授权一恢复就自己开跑。 */
void msgInsertCapabilityService
.refresh({ databaseReady: capabilityDatabaseReady() })
.then((capability) => {
enforceExitNoticeGate(capability)
})
.catch((error) => {
appLogger.write({
level: 'warn',
scope: 'capability-gate',
message: '启动对齐退群内提示失败',
details: { error: error instanceof Error ? error.message : String(error) }
})
})
process.on('uncaughtException', (error) => {
appLogger.write({
level: 'error',
@@ -1263,6 +1474,18 @@ app.whenReady().then(async () => {
ipcMain.handle('app-update:download', () => appUpdateService.download())
ipcMain.handle('app-update:install', () => appUpdateService.install())
ipcMain.handle('app-update:openDownloadPage', () => appUpdateService.openDownloadPage())
ipcMain.handle('app-update:getIgnoredVersion', () => loadSettings().skippedUpdateVersion)
/**
* 记录 / 清除「忽略此版本」。
*
* 传 null 或非法版本号 = 清除。校验放在主进程:渲染层传来的字符串不可信,
* 一个脏值会让「忽略」永远命中不了同一条记录,表现为每次都弹。
*/
ipcMain.handle('app-update:setIgnoredVersion', (_, version: unknown) => {
const normalized = normalizeSkippedUpdateVersion(version)
saveSettings({ ...loadSettings(), skippedUpdateVersion: normalized })
return normalized
})
appUpdateService.scheduleStartupCheck()
ipcMain.handle('cache:getSummary', () => getCacheSummary())
ipcMain.handle('cache:openKnowledgeDirectory', () => openKnowledgeDirectory())
@@ -1354,15 +1577,16 @@ app.whenReady().then(async () => {
/**
* 正式 MessageListener(Observation Mode 接入)。
*
* 本轮**只监听、回读、规范化、去重、统计**,不触发任何业务:
* 只监听、回读、规范化、去重、统计,不触发任何业务:
* 不匹配关键词、不判断 @我、不出日报、不回复、不调 AI / Agent、不发送。
* 下一层的 Trigger 由后续任务接入。
* 业务响应由上层消费者自行订阅,不在监听层实现。
*/
const messageListener = new MessageListenerService(wcdb4Client)
/**
* Automation v1(@我生成日报)。
*
* `isListening` 要等下面 `startMonitor` 有结果才知道,所以先用闭包变量占位。
* `isListening` 反映 `startMonitor` 的实际结果,因此通过闭包读取,
* 而不是在初始化时传入快照。
*/
let automationListening = false
initAutomationService(wcdb4Client, { isListening: () => automationListening })
@@ -1518,8 +1742,12 @@ app.whenReady().then(async () => {
)
return { success: true, monitoring }
} catch (error) {
console.error('Failed to init DB:', error)
const detail = error instanceof Error ? error.message : String(error)
if (isWcdbDebugEnabled()) {
console.error('Failed to init DB:', error)
} else {
console.error('Failed to init DB:', detail)
}
if (isWindowsVcRuntimeMissingError(detail, process.platform)) {
return {
success: false,
@@ -1560,11 +1788,18 @@ app.whenReady().then(async () => {
)
const self = chat.getSelfAccountInfo()
const settings = loadSettings()
const intelMac = process.platform === 'darwin' && process.arch === 'x64'
const arch = getMacArchSnapshot()
// 只有真正的 Intel Mac 才需要探测 Intel 运行环境。
// Apple 芯片上的 x64 进程(Rosetta)不能走这条路径,否则每次刷新环境都会起一个 x86 子进程。
const intelMac = shouldProbeIntelEnvironment(arch.macKeyFlow)
const intelEnvironment = intelMac ? await keyServiceMac.getIntelEnvironmentStatus() : undefined
const environment = {
platform: process.platform,
architecture: process.arch,
hardwareArchitecture: arch.hardwareArch,
underARM64Translation: arch.underARM64Translation,
macKeyFlow: arch.macKeyFlow,
archAnomalies: arch.anomalies,
osVersion: getOsVersionLabel(),
appVersion: `v${app.getVersion()}`,
wechatVersion: await detectWechatVersion(),
@@ -1761,7 +1996,8 @@ app.whenReady().then(async () => {
* 刻意不返回资源密钥、完整 XML、fileid 或任何 CDN 凭据。
*/
ipcMain.handle(
'image:getDebugInfo', async (_, request: ImageDebugInfoRequest): Promise<ImageDebugInfoResult> => {
'image:getDebugInfo',
async (_, request: ImageDebugInfoRequest): Promise<ImageDebugInfoResult> => {
try {
const service = ensureImageDecryptService()
const self = chat.getSelfAccountInfo()
@@ -1782,7 +2018,9 @@ app.whenReady().then(async () => {
// 复用真实选图逻辑;找不到就是 null,不根据文件名猜。
const filePath = service
? service.findImageFile(md5 || undefined, datName || undefined, { sessionId: sessionId || undefined })
? service.findImageFile(md5 || undefined, datName || undefined, {
sessionId: sessionId || undefined
})
: null
const quality = filePath ? toDebugQuality(imageFileQuality(filePath)) : 'unknown'
const relativePath =
@@ -2200,10 +2438,11 @@ app.whenReady().then(async () => {
* 状态里同时给出 desiredEnabled / effectiveEnabled:开关值写成功不等于功能
* 真的生效(规则可能没装齐),渲染层不能只看前者。
*/
ipcMain.handle('automation:getMsgInsertSwitches', () => {
ipcMain.handle('automation:getMsgInsertSwitches', async () => {
/* 🔴 纯读:任何 get/status 都不允许写微信库、不允许触发 DDL。
* 需要顺带补齐规则的场景走 automation:refreshMsgInsertSwitches。 */
return buildMsgInsertSwitchesSnapshot()
* 需要顺带补齐规则的场景走 automation:refreshMsgInsertSwitches。
* 授权判定只走本机 HTTP + 文件 stat,同样不碰数据库。 */
return attachCapability(buildMsgInsertSwitchesSnapshot())
})
/**
* 微信消息插入开关 —— **运行期刷新**(允许在分片集合变化时补一次规则)。
@@ -2223,16 +2462,28 @@ app.whenReady().then(async () => {
.listMessageShardPaths()
.map((item) => path.basename(item))
.join(',')
/*
* 分片变了只在「确实有授权」时补齐。
* 指纹必须**补齐成功之后**才更新:否则无授权跳过一次,等用户激活回来
* 分片没变,就再也不会补了(这正是原实现的坑)。
*/
if (signature !== lastMsgInsertReconciledShards) {
lastMsgInsertReconciledShards = signature
console.log('[MsgInsert] 运行期检测到消息分片变化,重新补齐规则')
await reconcileMsgInsertRulesNow(recallRoomsForReconcile(scope))
const gate = await requireCapability()
if (gate.ok) {
console.log('[MsgInsert] 运行期检测到消息分片变化,重新补齐规则')
const done = await reconcileMsgInsertRulesNow(recallRoomsForReconcile(scope))
if (done) lastMsgInsertReconciledShards = signature
} else {
console.log(
`[MsgInsert] 跳过运行期补齐:${gate.capability.reasonCode}(授权恢复后会自动重试)`
)
}
}
} catch (error) {
console.warn('[MsgInsert] 运行期补齐失败:', error)
}
}
return buildMsgInsertSwitchesSnapshot()
return attachCapability(buildMsgInsertSwitchesSnapshot())
})
/**
* 微信消息插入开关 —— 写入。
@@ -2252,6 +2503,19 @@ app.whenReady().then(async () => {
message: '未知的开关'
}
}
/* 只拦开启;关闭永远放行,否则规则会永久锁在微信库里。 */
if (payload.enabled === true) {
const gate = await requireCapability()
if (!gate.ok) {
const code = reasonToErrorCode(gate.capability)
return {
success: false,
status: emptyMsgInsertStatus(name, code, gate.capability.message),
errorCode: code,
message: gate.capability.message
}
}
}
/*
* 退群提示是**事件驱动**的(GroupExitMonitorService 发事件 → 一次性插一条),
* 不装任何 per-room 规则。所以它的开关只是本地设置:
@@ -3213,6 +3477,59 @@ app.whenReady().then(async () => {
return { success: true }
})
ipcMain.handle('wechat-personal:getStatus', () => currentPersonalWechatSenderStatus())
ipcMain.handle('wechat-personal:getMacLicenseStatus', () =>
macWechatRuntimeManager.getMacLicenseStatus()
)
ipcMain.handle('wechat-personal:getMacSendRuntimeAvailability', () =>
macWechatRuntimeManager.getSendRuntimeAvailability()
)
ipcMain.handle('wechat-personal:startMacSendRuntime', () => {
if (process.platform !== 'darwin') throw new Error('仅 macOS 支持微信发送组件')
return macWechatRuntimeManager.startAfterResidualCleanup()
})
ipcMain.handle('wechat-personal:listMacResidualProcesses', () =>
inspectMacWechatResidualProcesses()
)
ipcMain.handle('wechat-personal:cleanupMacResidualProcesses', async (_, pids: unknown) => {
if (process.platform !== 'darwin') throw new Error('仅 macOS 支持清理微信残留进程')
if (!Array.isArray(pids)) throw new Error('清理目标无效')
const requestedTargets = pids.filter(
(target): target is { pid: number; confirmationToken: string } =>
Boolean(target) &&
typeof target === 'object' &&
Number.isSafeInteger((target as { pid?: unknown }).pid) &&
typeof (target as { confirmationToken?: unknown }).confirmationToken === 'string'
)
if (requestedTargets.length === 0) throw new Error('没有确认的清理目标')
const currentTargets = await inspectMacWechatResidualProcesses()
const confirmedTargets = requestedTargets.filter((requested) =>
currentTargets.some(
(current) =>
current.pid === requested.pid && current.confirmationToken === requested.confirmationToken
)
)
if (confirmedTargets.length === 0) {
return { stopped: [], remaining: currentTargets }
}
let runtimeStopped = false
const result = await cleanupMacWechatResidualProcesses(
confirmedTargets,
undefined,
(targets) => {
if (
macWechatRuntimeManager.getPort() === 4290 &&
targets.some((target) => target.targets.includes('port_4290'))
) {
macWechatRuntimeManager.prepareForResidualCleanup()
runtimeStopped = true
}
}
)
return { ...result, runtimeStopped }
})
ipcMain.handle('wechat-personal:refreshMacLicense', () =>
macWechatRuntimeManager.refreshMacLicense()
)
ipcMain.handle('wechat-personal:checkStatus', (_, port?: string) =>
personalWechatSendService.checkWindowsStatus(port)
)
+34 -2
View File
@@ -7,6 +7,8 @@ import { isValidDatabaseKey } from './database-key-store'
import crypto from 'crypto'
import { findResource, getResourceCandidates } from './resource-paths'
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)
@@ -239,6 +241,15 @@ export class KeyServiceMac {
fridaAvailable: boolean
wechatAdhocSigned: boolean
}> {
// 方法内部再守一道:调用方漏判时也不能起 x86 helper。
if (!shouldProbeIntelEnvironment(getMacArchSnapshot().macKeyFlow)) {
return {
sipDisabled: false,
pythonAvailable: false,
fridaAvailable: false,
wechatAdhocSigned: false
}
}
const payload = await this.runMacKeyTool(
['status', '--runtime-dir', this.getMacKeyRuntimeDir()],
15_000
@@ -254,7 +265,15 @@ export class KeyServiceMac {
async installIntelKeyRuntime(
onStatus?: (message: string) => void
): 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 需要安装此运行环境' }
}
onStatus?.('正在准备连接环境,请保持网络连接…')
@@ -354,12 +373,25 @@ export class KeyServiceMac {
if (process.platform !== 'darwin') {
return { success: false, error: '自动获取密钥目前仅支持 macOS' }
}
// 架构判定排在 SIP 之前:不匹配时先说明「当前跑的是 Intel 版」,
// 不能让用户先看到 SIP 提示、关闭 SIP 之后才发现问题依旧。
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 === 'unsupported') {
return { success: false, error: '自动获取密钥目前仅支持 macOS' }
}
if (await this.isSipEnabled()) {
return { success: false, code: 'SIP_ENABLED', error: SIP_ENABLED_ERROR }
}
try {
if (process.arch === 'x64') {
if (arch.macKeyFlow === 'intel') {
onStatus?.('Intel Mac 将通过 Frida 获取微信主密钥,请让微信停留在未登录界面')
const result = await this.captureIntelDbKey(accountRoot, timeoutMs, onStatus)
onStatus?.(result.success ? '密钥获取成功' : '密钥获取失败')
+1 -1
View File
@@ -689,7 +689,7 @@ export class KeyService {
return {
success: false,
error:
'微信可能已经启动并登录,请先在微信客户端保持未登录状态,具体点击上方“查看5分钟上手教程” ',
'微信可能没有在上一步点击微信登录,请先在微信客户端保持未登录状态,具体点击上方“查看5分钟上手教程” ',
logs
}
}
+60
View File
@@ -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
}
+90
View File
@@ -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
}
+6 -1
View File
@@ -230,7 +230,12 @@ function builtInTemplate(template: ReportTemplateDefinition): InstalledReportTem
}
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[]> {
await fs.mkdir(path.join(this.directory, INSTALLED_DIR), { recursive: true })
+4
View File
@@ -7,6 +7,10 @@ function unique(values: string[]): 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 appPathDir = dirname(appPath)
const execDir = dirname(process.execPath)
+31 -7
View File
@@ -96,7 +96,15 @@ export class AIProviderRequestError extends Error {
constructor(
message: string,
details: { status?: number; code?: unknown; type?: unknown; responseBody?: unknown; contentType?: string; elapsedMs?: number; htmlInsteadOfJson?: boolean } = {}
details: {
status?: number
code?: unknown
type?: unknown
responseBody?: unknown
contentType?: string
elapsedMs?: number
htmlInsteadOfJson?: boolean
} = {}
) {
super(message)
this.name = 'AIProviderRequestError'
@@ -358,7 +366,10 @@ export class AIProviderService {
try {
if (options?.apiKey) throw new Error('Tool Calling 不支持 legacy provider 配置')
const resolved = this.resolveProvider(options)
if (resolved.provider.type !== 'openai-compatible' || resolved.provider.advanced.apiProtocol === 'responses') {
if (
resolved.provider.type !== 'openai-compatible' ||
resolved.provider.advanced.apiProtocol === 'responses'
) {
throw new Error('当前 Provider 协议暂不支持 Tool Calling POC')
}
const result = await requestOpenAICompatibleWithTools(
@@ -377,7 +388,8 @@ export class AIProviderService {
success: false,
error: safeAIError(error),
timedOut,
htmlInsteadOfJson: error instanceof AIProviderRequestError ? Boolean(error.htmlInsteadOfJson) : false,
htmlInsteadOfJson:
error instanceof AIProviderRequestError ? Boolean(error.htmlInsteadOfJson) : false,
...(error instanceof AIProviderRequestError
? {
...(error.status !== undefined ? { errorStatus: error.status } : {}),
@@ -638,7 +650,7 @@ function deepSeekProvider(baseUrl?: string, model?: string): AIProviderSummary {
}
],
defaultModel: modelId,
advanced: { timeoutMs: 120_000, temperature: 0.7, maxTokens: 4096, extraHeaders: {} },
advanced: { timeoutMs: 120_000, temperature: 0.7, maxTokens: 40960, extraHeaders: {} },
hasApiKey: false,
isDefault: true,
status: 'untested'
@@ -981,7 +993,12 @@ async function requestOpenAICompatibleWithTools(
messages: Array<Record<string, unknown>>,
tools: AIChatToolDefinition[],
signal?: AbortSignal
): Promise<{ data: string; toolCalls: AIChatToolCall[]; usage?: AIRequestResult['usage']; elapsedMs?: number }> {
): Promise<{
data: string
toolCalls: AIChatToolCall[]
usage?: AIRequestResult['usage']
elapsedMs?: number
}> {
const endpoint = provider.baseUrl.endsWith('/chat/completions')
? provider.baseUrl
: `${provider.baseUrl.replace(/\/+$/, '')}/chat/completions`
@@ -1013,7 +1030,8 @@ async function requestOpenAICompatibleWithTools(
}
if (!response.ok) {
throw new AIProviderRequestError(
payload?.error?.message || (parseError ? safeAIError(parseError) : `AI 请求失败 (${response.status})`),
payload?.error?.message ||
(parseError ? safeAIError(parseError) : `AI 请求失败 (${response.status})`),
{
status: timing.status,
contentType: timing.contentType,
@@ -1034,7 +1052,13 @@ async function requestOpenAICompatibleWithTools(
toolCalls: (message?.tool_calls || []).flatMap((call, index) => {
const name = call.function?.name
if (!name) return []
return [{ id: call.id || `tool-call-${index + 1}`, name, arguments: call.function?.arguments || '{}' }]
return [
{
id: call.id || `tool-call-${index + 1}`,
name,
arguments: call.function?.arguments || '{}'
}
]
}),
usage: toOpenAIUsage(payload.usage),
elapsedMs: timing.elapsedMs
+11 -21
View File
@@ -15,6 +15,7 @@ import {
WINDOWS_VC_RUNTIME_ERROR_MESSAGE
} from '../../shared/windows-runtime'
import { hasPermissionDeniedText, isPermissionDeniedError } from './path-access-probe'
import { getNativeErrorCode } from '../wcdb4-client'
import { mergeRecallArchiveMessages, recordRecallArchiveMessages } from './recall-archive-service'
import type { ExportImageQuality } from '../../shared/image-quality'
import type { ImageMessageCountProbe } from '../../shared/image-text-index'
@@ -1297,27 +1298,7 @@ export function databaseKeyErrorMessage(
return DATABASE_KEY_ERROR_MESSAGES[code]
}
/**
* 把底层抛出物归类成机器可读的错误码。
*
* 顺序是有约束的,别随意调整:
* 1. VC runtime —— Windows 专属,特征明确,先摘掉;
* 2. 账号不匹配 —— `-1005` 是 native 给出的确定信号;
* 3. **权限不足** —— 必须排在"文件缺失"之前。原因见下;
* 4. 文件缺失 / 根目录不可用 / 打开失败 —— 按文本兜底。
*
* 为什么权限要排在缺失之前:底层探测用的是 `fs.existsSync()`,它对 EPERM 也返回
* `false`,所以走到这里时错误文本常常已经变成「未找到 … session.db」这种**缺失**措辞。
* 只按文本判断就会永远归到 `DATABASE_FILE_MISSING`,把用户指向错误的方向。
* 因此 errno 优先(调用方在探测层用 `statSync` 补问过),文本特征只作兜底。
*
* 判断文本时逐个列举显式模式,不用 `includes('permission')` 这类过宽匹配 ——
* 那会把 "permission config not found" 之类无关错误也算进来。
*
* 导出是为了让分类规则本身可被回归测试钉住:这条链路上任何一处顺序调整都会让
* 权限问题重新落回"文件缺失",而那正是本函数要防的回归。
* `platform` 可注入,否则 Windows 专属分支在测试里无法触发(`process.platform` 是只读的)。
*/
// 顺序有约束:原生码先于文本匹配,权限先于文件缺失(existsSync 对 EPERM 返回 false)。
export function mapConnectionError(
error: unknown,
platform: NodeJS.Platform = process.platform
@@ -1325,6 +1306,15 @@ export function mapConnectionError(
const detail = error instanceof Error ? error.message : String(error)
const normalized = detail.toLowerCase()
if (isWindowsVcRuntimeMissingError(detail, platform)) return 'VC_RUNTIME_MISSING'
const nativeCode = getNativeErrorCode(error)
if (nativeCode !== null) {
if (nativeCode === -2003) return 'DATABASE_OPEN_FAILED'
if (nativeCode === -3003 || nativeCode === -3004) return 'ACCOUNT_MISMATCH'
if (nativeCode === -3006) return 'DATABASE_OPEN_FAILED'
if (nativeCode === -3005) return 'UNKNOWN_VALIDATION_ERROR'
}
if (normalized.includes('-1005') || normalized.includes('不匹配')) return 'ACCOUNT_MISMATCH'
if (isPermissionDeniedError(error) || hasPermissionDeniedText(normalized)) {
return 'DATABASE_PERMISSION_DENIED'
+78
View File
@@ -0,0 +1,78 @@
import type { MessageInsertCapability } from './msg-insert-capability-service'
/** 退群内提示开关的判定:授权或组件不成立时必须显示关闭;库没连只压 effective。 */
export interface ExitNoticeGateDecision {
/** 界面开关值 */
desiredEnabled: boolean
/** 是否真的在生效 */
effectiveEnabled: boolean
/** 只在明确否定时落盘;探测失败不落盘,避免误关正常用户的开关。 */
persistDisable: boolean
}
/** 授权维度是否成立(不含微信库连接)。 */
export function isEntitlementBlocked(capability: MessageInsertCapability): boolean {
return capability.entitlementState !== 'valid' || capability.nativeComponentState !== 'ready'
}
/** 明确否定(不含 unavailable:那是「不知道」,不是「不行」)。 */
export function isDefinitelyBlocked(capability: MessageInsertCapability): boolean {
return (
capability.entitlementState === 'invalid' ||
capability.entitlementState === 'unsupported' ||
capability.nativeComponentState === 'missing' ||
capability.nativeComponentState === 'invalid' ||
capability.nativeComponentState === 'incompatible'
)
}
export function resolveExitNoticeGate(
capability: MessageInsertCapability,
runtimeEnabled: boolean
): ExitNoticeGateDecision {
if (isEntitlementBlocked(capability)) {
return {
desiredEnabled: false,
effectiveEnabled: false,
persistDisable: isDefinitelyBlocked(capability) && runtimeEnabled
}
}
/*
* 授权与组件都就绪,只是微信库没连:用户意愿保留(连上自动恢复),
* 但此刻没有真的在跑。
*/
if (runtimeEnabled && !capability.canEnable) {
return { desiredEnabled: true, effectiveEnabled: false, persistDisable: false }
}
return {
desiredEnabled: runtimeEnabled,
effectiveEnabled: runtimeEnabled && capability.canEnable,
persistDisable: false
}
}
/** 界面呈现结果(只有开关的两个布尔值,不含落盘决策)。 */
export interface SwitchPresentation {
desiredEnabled: boolean
effectiveEnabled: boolean
}
/** 两个开关共用这套呈现判定:授权不成立时都显示关闭,但关闭操作永远放行。 */
export function resolveSwitchPresentation(
kind: 'recall_notice' | 'group_exit_notice',
currentDesired: boolean,
capability: MessageInsertCapability
): SwitchPresentation {
if (kind === 'group_exit_notice') {
const gate = resolveExitNoticeGate(capability, currentDesired)
return { desiredEnabled: gate.desiredEnabled, effectiveEnabled: gate.effectiveEnabled }
}
if (isEntitlementBlocked(capability)) {
return { desiredEnabled: false, effectiveEnabled: false }
}
return {
desiredEnabled: currentDesired,
effectiveEnabled: currentDesired && capability.canEnable
}
}
@@ -0,0 +1,133 @@
import crypto from 'node:crypto'
import fs from 'node:fs'
import path from 'node:path'
/**
* 发送能力组件定位:读 current.json 找目录,按 manifest 校验 size/sha256,不过当没装。
* 组件放用户目录,避免被自动更新清掉。
*/
export interface ComponentLocation {
dir: string
helperPath: string
version: string
/** 打包时工作区是否 dirty(内部调试构建标识,正式发布不应出现) */
dirty: boolean
}
interface ManifestFile {
path?: unknown
size?: unknown
sha256?: unknown
}
const HELPER_NAME = 'tm-wcdb-config-helper.exe'
const verifyCache = new Map<string, { stamp: string; ok: boolean; dirty: boolean }>()
function sha256File(filePath: string): string | null {
try {
const hash = crypto.createHash('sha256')
hash.update(fs.readFileSync(filePath))
return hash.digest('hex')
} catch {
return null
}
}
function verifyManifest(dir: string): { ok: boolean; dirty: boolean } {
const manifestPath = path.join(dir, 'manifest.json')
let stat: fs.Stats
try {
stat = fs.statSync(manifestPath)
} catch {
return { ok: false, dirty: false }
}
const stamp = `${dir}|${stat.mtimeMs}|${stat.size}`
const cached = verifyCache.get(dir)
if (cached && cached.stamp === stamp) return { ok: cached.ok, dirty: cached.dirty }
let ok = false
let dirty = false
try {
const manifest = JSON.parse(fs.readFileSync(manifestPath, 'utf8')) as {
worktreeDirty?: unknown
files?: ManifestFile[]
}
dirty = manifest.worktreeDirty === true
const files = Array.isArray(manifest.files) ? manifest.files : []
if (files.length === 0) {
ok = false
} else {
ok = files.every((entry) => {
const name = typeof entry.path === 'string' ? entry.path : ''
if (!name) return false
const target = path.join(dir, name)
let size = -1
try {
size = fs.statSync(target).size
} catch {
return false
}
if (typeof entry.size === 'number' && size !== entry.size) return false
if (typeof entry.sha256 === 'string' && entry.sha256.length === 64) {
return sha256File(target) === entry.sha256
}
return true
})
}
} catch {
ok = false
}
verifyCache.set(dir, { stamp, ok, dirty })
return { ok, dirty }
}
/**
* 返回发送能力组件位置;不存在、校验失败、非 Windows 一律返回 null。
* 调用方拿到 null 时应当把它当作「组件没装」,而不是「没授权」。
*/
export function resolveExternalComponent(
env: NodeJS.ProcessEnv = process.env,
platform: NodeJS.Platform = process.platform
): ComponentLocation | null {
if (platform !== 'win32') return null
const localAppData = env.LOCALAPPDATA
if (!localAppData) return null
const root = path.join(localAppData, 'TraceMemo', 'Pro', 'windows-x64')
const pointerPath = path.join(root, 'current.json')
if (!fs.existsSync(pointerPath)) return null
let version = ''
let dir = ''
try {
const pointer = JSON.parse(fs.readFileSync(pointerPath, 'utf8')) as {
version?: unknown
dir?: unknown
}
version = typeof pointer.version === 'string' ? pointer.version : ''
dir = typeof pointer.dir === 'string' ? pointer.dir : ''
} catch {
return null
}
if (!version || !dir) return null
try {
if (!fs.statSync(dir).isDirectory()) return null
} catch {
return null
}
const helperPath = path.join(dir, HELPER_NAME)
if (!fs.existsSync(helperPath)) return null
const verified = verifyManifest(dir)
if (!verified.ok) return null
return { dir, helperPath, version, dirty: verified.dirty }
}
/** 测试用:清掉校验缓存 */
export function resetComponentCache(): void {
verifyCache.clear()
}
@@ -0,0 +1,217 @@
import { execFile } from 'node:child_process'
import { createHash } from 'node:crypto'
import { promisify } from 'node:util'
import type { MacWechatResidualProcess } from '../../shared/personal-wechat-mac-runtime'
const execFileAsync = promisify(execFile)
type PidCommandRunner = (
executable: string,
args: string[],
options: { timeout: number }
) => Promise<{ stdout: string }>
export interface MacWechatResidualCleanupDependencies {
platform: NodeJS.Platform
listWechatPids: () => Promise<number[]>
listPortPids: () => Promise<number[]>
processName: (pid: number) => Promise<string>
processIdentity: (pid: number) => Promise<string>
signal: (pid: number, signal: NodeJS.Signals) => void
wait: (milliseconds: number) => Promise<void>
}
export async function readPids(
executable: string,
args: string[],
run: PidCommandRunner = async (file, commandArgs, options) =>
execFileAsync(file, commandArgs, options)
): Promise<number[]> {
try {
const { stdout } = await run(executable, args, { timeout: 4_000 })
return stdout
.split(/\s+/)
.map(Number)
.filter((pid) => Number.isSafeInteger(pid) && pid > 0)
} catch (error) {
const result = error as { code?: unknown; status?: unknown }
if (result.code === 'ENOENT' || result.code === 1 || result.status === 1) return []
throw error
}
}
const defaultDependencies: MacWechatResidualCleanupDependencies = {
platform: process.platform,
listWechatPids: async () => {
const results = await Promise.all([
readPids('/usr/bin/pgrep', ['-x', 'WeChat']),
readPids('/usr/bin/pgrep', ['-x', 'Weixin'])
])
return [...new Set(results.flat())]
},
listPortPids: () => readPids('/usr/sbin/lsof', ['-nP', '-t', '-iTCP:4290', '-sTCP:LISTEN']),
processName: async (pid) => {
try {
const { stdout } = await execFileAsync('/bin/ps', ['-p', String(pid), '-o', 'comm='], {
timeout: 2_000
})
return stdout.trim().split('/').pop() || 'unknown'
} catch {
return 'unknown'
}
},
processIdentity: async (pid) => {
try {
const { stdout } = await execFileAsync(
'/bin/ps',
['-p', String(pid), '-o', 'lstart=', '-o', 'comm='],
{ timeout: 2_000 }
)
return createHash('sha256').update(stdout.trim()).digest('hex')
} catch {
return ''
}
},
signal: (pid, signal) => process.kill(pid, signal),
wait: (milliseconds) => new Promise((resolve) => setTimeout(resolve, milliseconds))
}
interface ObservedTarget extends MacWechatResidualProcess {
confirmationToken: string
}
function mergeTargets(
wechatPids: number[],
portPids: number[],
processNames: Map<number, string>,
processIdentities: Map<number, string>
): ObservedTarget[] {
const targets = new Map<number, Set<'wechat' | 'port_4290'>>()
for (const pid of wechatPids) {
if (!Number.isSafeInteger(pid) || pid <= 0) continue
const reasons = targets.get(pid) || new Set<'wechat' | 'port_4290'>()
reasons.add('wechat')
targets.set(pid, reasons)
}
for (const pid of portPids) {
if (!Number.isSafeInteger(pid) || pid <= 0) continue
const reasons = targets.get(pid) || new Set<'wechat' | 'port_4290'>()
reasons.add('port_4290')
targets.set(pid, reasons)
}
return [...targets.entries()]
.sort(([first], [second]) => first - second)
.map(([pid, reasons]) => ({
pid,
name: processNames.get(pid) || 'unknown',
targets: [...reasons].sort(),
confirmationToken: processIdentities.get(pid) || ''
}))
}
async function inspectObservedTargets(
dependencies: MacWechatResidualCleanupDependencies
): Promise<ObservedTarget[]> {
if (dependencies.platform !== 'darwin') return []
const [rawWechatPids, rawPortPids] = await Promise.all([
dependencies.listWechatPids(),
dependencies.listPortPids()
])
const wechatPids = rawWechatPids.filter((pid) => pid !== process.pid)
const portPids = rawPortPids.filter((pid) => pid !== process.pid)
const pids = [...new Set([...wechatPids, ...portPids])].filter(
(pid) => Number.isSafeInteger(pid) && pid > 0
)
const [names, identities] = await Promise.all([
Promise.all(pids.map(async (pid) => [pid, await dependencies.processName(pid)] as const)),
Promise.all(pids.map(async (pid) => [pid, await dependencies.processIdentity(pid)] as const))
])
return mergeTargets(wechatPids, portPids, new Map(names), new Map(identities))
}
export async function inspectMacWechatResidualProcesses(
dependencies: MacWechatResidualCleanupDependencies = defaultDependencies
): Promise<MacWechatResidualProcess[]> {
return inspectObservedTargets(dependencies)
}
export async function cleanupMacWechatResidualProcesses(
confirmedTargets: Array<Pick<MacWechatResidualProcess, 'pid' | 'confirmationToken'>>,
dependencies: MacWechatResidualCleanupDependencies = defaultDependencies,
onTargetsConfirmed?: (targets: MacWechatResidualProcess[]) => void
): Promise<{ stopped: MacWechatResidualProcess[]; remaining: MacWechatResidualProcess[] }> {
if (dependencies.platform !== 'darwin') return { stopped: [], remaining: [] }
const confirmed = new Map(
confirmedTargets
.filter(
(target) =>
target.pid !== process.pid &&
Number.isSafeInteger(target.pid) &&
target.pid > 0 &&
typeof target.confirmationToken === 'string' &&
target.confirmationToken.length > 0
)
.map((target) => [target.pid, target.confirmationToken])
)
const current = await inspectObservedTargets(dependencies)
const selected = current.filter(
(target) => confirmed.get(target.pid) === target.confirmationToken
)
if (selected.length === 0) {
return {
stopped: [],
remaining: current.filter((target) => confirmed.has(target.pid))
}
}
let cleanupTargetsNotified = false
const signalMatchingTarget = async (
target: ObservedTarget,
expectedIdentity: string,
signal: NodeJS.Signals
): Promise<void> => {
const identity = await dependencies.processIdentity(target.pid)
if (!expectedIdentity || identity !== expectedIdentity) return
try {
dependencies.signal(target.pid, signal)
} catch (error) {
if ((error as NodeJS.ErrnoException).code !== 'ESRCH') throw error
}
if (target.targets.includes('port_4290') && !cleanupTargetsNotified) {
cleanupTargetsNotified = true
onTargetsConfirmed?.([target])
}
}
for (const target of selected.filter((item) => item.targets.includes('wechat'))) {
await signalMatchingTarget(target, confirmed.get(target.pid) || '', 'SIGTERM')
}
if (selected.some((item) => item.targets.includes('wechat'))) await dependencies.wait(1_000)
let remaining = (await inspectObservedTargets(dependencies)).filter((target) =>
confirmed.has(target.pid)
)
for (const target of remaining) {
const selectedTarget = selected.find((item) => item.pid === target.pid)
if (!selectedTarget || target.confirmationToken !== selectedTarget.confirmationToken) continue
await signalMatchingTarget(target, selectedTarget.confirmationToken, 'SIGTERM')
}
if (remaining.length > 0) await dependencies.wait(1_000)
remaining = (await inspectObservedTargets(dependencies)).filter((target) =>
confirmed.has(target.pid)
)
for (const target of remaining) {
const selectedTarget = selected.find((item) => item.pid === target.pid)
if (!selectedTarget || target.confirmationToken !== selectedTarget.confirmationToken) continue
await signalMatchingTarget(target, selectedTarget.confirmationToken, 'SIGKILL')
}
if (remaining.length > 0) await dependencies.wait(250)
remaining = (await inspectObservedTargets(dependencies)).filter((target) =>
confirmed.has(target.pid)
)
return {
stopped: selected
.filter((target) => !remaining.some((item) => item.pid === target.pid))
.map((target) => target),
remaining
}
}
+328 -33
View File
@@ -1,20 +1,30 @@
import { spawn, type ChildProcess } from 'child_process'
import { chmodSync, existsSync } from 'fs'
import { get } from 'http'
import { get, request as httpRequest } from 'http'
import { join } from 'path'
import { app } from 'electron'
import { appLogger } from '../app-logger'
import { isPackagedRuntime } from '../runtime-mode'
import {
isMacNativeRuntimeUnavailable,
resolveWechatRuntimeDirectory
} from '../native-runtime-paths'
import type { MacLicenseStatus } from '../../shared/personal-wechat-mac-license'
import {
offlineMacLicenseStatus,
parseMacLicenseStatus
} from '../../shared/personal-wechat-mac-license'
import type {
MacWechatBindResult,
MacWechatBindingStatus,
MacWechatRuntimeManifest,
MacWechatRuntimeLifecycle,
MacWechatRuntimeSnapshot
MacWechatRuntimeSnapshot,
MacWechatSendRuntimeAvailabilityResult
} from '../../shared/personal-wechat-mac-runtime'
import type { PersonalWechatSenderStatus } from '../../shared/personal-wechat'
import { hasValidWechatLicense } from '../../shared/personal-wechat-mac-send-action'
import {
bindingMatchesRuntimeManifest,
readMacWechatRuntimeManifest
@@ -38,11 +48,18 @@ import {
* auto-binding, that path dead-ends in a 20s attach timeout every time.
*/
const PORT = 4290
/* 默认 4290。进程会 fork 继承监听 fd(CLOEXEC 只挡 exec),
* host 崩溃后孤儿进程仍扣着端口,新 host bind 失败会返回 1 无限重启。
* 被占用时用 TM_WECHAT_HOST_PORT 指到备用端口。 */
const PORT = Number(process.env.TM_WECHAT_HOST_PORT) || 4290
const HOST = '127.0.0.1'
const START_TIMEOUT_MS = 15_000
const REQUEST_TIMEOUT_MS = 30_000
const CRASH_RESTART_DELAY_MS = 1_500
/* /license/status is a local cache read; keep it snappy. /license/refresh runs a
* real challenge->sign->check cycle inside the host, which is bounded at 15s. */
const LICENSE_STATUS_TIMEOUT_MS = 8_000
const LICENSE_REFRESH_TIMEOUT_MS = 20_000
interface MacWechatSenderStatusInput {
snapshot: MacWechatRuntimeSnapshot
@@ -66,6 +83,16 @@ export function deriveMacWechatSenderStatus({
}: MacWechatSenderStatusInput): PersonalWechatSenderStatus {
const identityMatches = binding !== null && bindingMatchesRuntimeManifest(binding, manifest)
const stale = binding?.bindingState === 'stale'
const versionCapabilities = binding?.wechatVersion
? manifest.capabilitiesByVersion?.[binding.wechatVersion]
: undefined
const nativeMechanism = versionCapabilities?.textMechanism === 'native-msg-object'
const nativeBindingReady =
identityMatches &&
nativeMechanism &&
binding?.runtimeState === 'ready' &&
binding.sessionAttached &&
binding.scriptLoaded
let state: PersonalWechatSenderStatus['state'] = 'stopped'
let message = '正在初始化微信发送能力'
@@ -78,12 +105,17 @@ export function deriveMacWechatSenderStatus({
} else if (binding && !binding.wechatRunning) {
state = 'wechat_not_running'
message = '微信未运行'
} else if (binding?.bindingState === 'ready') {
} else if (binding?.runtimeState === 'unsupported_version') {
state = 'error'
message = binding.wechatVersion
? `当前微信版本是 ${binding.wechatVersion},不在支持列表`
: '当前微信版本不在支持列表'
} else if (binding?.bindingState === 'ready' || nativeBindingReady) {
state = 'online'
message = '个人微信已准备好发送日报'
} else if (binding?.bindingState === 'bound' || binding?.bindingState === 'binding') {
state = 'hook_not_ready'
message = '已绑定,等待捕获微信发送上下文'
message = nativeMechanism ? '已绑定,等待原生发送 hook 就绪' : '已绑定,等待捕获微信发送上下文'
} else if (stale) {
state = 'stopped'
message = '检测到微信已重启,请重新绑定'
@@ -96,13 +128,17 @@ export function deriveMacWechatSenderStatus({
}
const runtimeCapabilities = new Set(manifest.capabilities)
const bindingReady = identityMatches && state === 'online' && binding?.sendContextReady === true
const canSendText =
bindingReady && runtimeCapabilities.has('text') && binding?.canSendText === true
const canSendImage =
bindingReady && runtimeCapabilities.has('image') && binding?.canSendImage === true
const canSendVoice =
bindingReady && runtimeCapabilities.has('voice') && binding?.canSendVoice === true
const supportsCapability = (name: 'text' | 'image' | 'voice'): boolean => {
if (manifest.capabilitiesByVersion) return versionCapabilities?.[name] === 'verified'
return runtimeCapabilities.has(name)
}
const bindingReady =
identityMatches &&
state === 'online' &&
(binding?.sendContextReady === true || nativeBindingReady)
const canSendText = bindingReady && supportsCapability('text') && binding?.canSendText === true
const canSendImage = bindingReady && supportsCapability('image') && binding?.canSendImage === true
const canSendVoice = bindingReady && supportsCapability('voice') && binding?.canSendVoice === true
const sessionAttached = identityMatches && (binding?.sessionAttached ?? false)
const scriptLoaded = identityMatches && (binding?.scriptLoaded ?? false)
@@ -135,6 +171,25 @@ export function deriveMacWechatSenderStatus({
}
}
/**
* 在线刷新失败时的返回策略:
* 缓存里还有可用授权就保留它(只把失败写进 message),否则明确报告网络故障。
* 单独抽出来是因为这两条分支都必须可测 —— 把网络故障错报成「已撤销」会让
* 用户去找客服,错报成「有效」又会掩盖真实故障。
*/
export function resolveLicenseRefreshFailure(
snapshot: MacLicenseStatus | null,
diagnostic: string
): MacLicenseStatus {
if (snapshot?.authorized) {
return {
...snapshot,
message: `本次刷新失败:${diagnostic}(仍使用本地缓存授权)`
}
}
return offlineMacLicenseStatus('server_unavailable', diagnostic)
}
class MacWechatRuntimeManager {
private child: ChildProcess | null = null
private lifecycle: MacWechatRuntimeLifecycle = 'stopped'
@@ -147,6 +202,7 @@ class MacWechatRuntimeManager {
private manifest: MacWechatRuntimeManifest | null = null
private lastError: string | null = null
private restartTimer: NodeJS.Timeout | null = null
private manuallyStopped = false
getPort(): number {
return PORT
@@ -158,43 +214,94 @@ class MacWechatRuntimeManager {
wechatRestartRequired: this.wechatRestartRequired,
endpoint: `http://${HOST}:${PORT}`,
port: PORT,
runtimeDir: this.resolveRuntimeDir(),
manifest: this.manifest ?? undefined,
runtimeDir: this.resolveRuntimeDir() ?? undefined,
error: this.lastError ?? undefined,
binding: this.lastBinding ?? undefined
}
}
private resolveRuntimeDir(): string {
const base = isPackagedRuntime() ? process.resourcesPath : app.getAppPath()
return join(base, 'resources', 'runtime', 'darwin-arm64')
prepareForResidualCleanup(): void {
if (this.restartTimer) {
clearTimeout(this.restartTimer)
this.restartTimer = null
}
this.lifecycle = 'stopped'
this.manuallyStopped = true
this.child = null
this.lastBinding = null
this.lastError = null
}
async startAfterResidualCleanup(): Promise<MacWechatRuntimeSnapshot> {
return this.ensureStarted({ allowManualRestart: true })
}
private resolveRuntimeDir(): string | null {
if (isMacNativeRuntimeUnavailable()) return null
const resolved = resolveWechatRuntimeDirectory()
if (resolved) return resolved
if (app.isPackaged) return null
return join(app.getAppPath(), 'resources', 'runtime', 'darwin-arm64')
}
private resolveHostPath(): string {
return join(this.resolveRuntimeDir(), 'tm-wechat-host')
return join(this.resolveRuntimeDir() || '', 'tm-wechat-host')
}
/** Runtime binaries present and executable? Cheap check for the settings UI. */
isRuntimePresent(): boolean {
if (isMacNativeRuntimeUnavailable()) return false
try {
this.manifest = readMacWechatRuntimeManifest(this.resolveRuntimeDir())
const runtimeDir = this.resolveRuntimeDir()
if (!runtimeDir) return false
this.manifest = readMacWechatRuntimeManifest(runtimeDir)
return true
} catch {
return false
}
}
getSendRuntimeAvailability(): MacWechatSendRuntimeAvailabilityResult {
if (isMacNativeRuntimeUnavailable()) {
return { state: 'unavailable', message: '当前版本没有微信发送能力' }
}
try {
const runtimeDir = this.resolveRuntimeDir()
if (!runtimeDir) throw new Error('发送 Runtime 目录缺失')
this.manifest = readMacWechatRuntimeManifest(runtimeDir)
return { state: 'available', message: '微信发送组件可用' }
} catch (error) {
const detail = error instanceof Error ? error.message : String(error)
return { state: 'component_error', message: `发送组件缺失或异常:${detail}` }
}
}
/**
* Start the host if it is not already running. Deliberately lazy: the host
* comes up WITHOUT touching WeChat (lazy init inside the host), so "runtime
* online" and "WeChat bound" stay two independent states.
*/
async ensureStarted(): Promise<MacWechatRuntimeSnapshot> {
async ensureStarted(
options: { allowManualRestart?: boolean } = {}
): Promise<MacWechatRuntimeSnapshot> {
if (this.manuallyStopped && !options.allowManualRestart) return this.getSnapshot()
if (options.allowManualRestart) this.manuallyStopped = false
if (isMacNativeRuntimeUnavailable()) {
this.manifest = null
this.lifecycle = 'stopped'
this.lastError = '当前环境不包含微信发送能力'
return this.getSnapshot()
}
if (this.lifecycle === 'starting') {
return this.getSnapshot()
}
const runtimeDir = this.resolveRuntimeDir()
if (!runtimeDir) {
this.lifecycle = 'stopped'
this.lastError = '暂无发送能力'
return this.getSnapshot()
}
try {
this.manifest = readMacWechatRuntimeManifest(runtimeDir)
appLogger.write({
@@ -385,11 +492,28 @@ class MacWechatRuntimeManager {
private request(
method: string,
path: string,
timeoutMs = REQUEST_TIMEOUT_MS
timeoutMs = REQUEST_TIMEOUT_MS,
body?: string
): Promise<{ status: number | null; body: string }> {
return new Promise((resolve) => {
const request = get(
{ host: HOST, port: PORT, path, method, timeout: timeoutMs },
const payload = body !== undefined ? Buffer.from(body, 'utf8') : undefined
// GET keeps using `get()` (auto-end); POST goes through `request()` so we
// can attach a JSON body. Both funnel into the same resolve contract.
const transport = method === 'GET' || method === 'HEAD' ? get : httpRequest
const req = transport(
{
host: HOST,
port: PORT,
path,
method,
timeout: timeoutMs,
headers: payload
? {
'Content-Type': 'application/json',
'Content-Length': payload.length
}
: undefined
},
(response) => {
let body = ''
response.on('data', (chunk) => {
@@ -400,14 +524,15 @@ class MacWechatRuntimeManager {
})
}
)
request.on('timeout', () => {
request.destroy()
req.on('timeout', () => {
req.destroy()
resolve({ status: null, body: '' })
})
request.on('error', () => {
req.on('error', () => {
resolve({ status: null, body: '' })
})
request.end()
if (payload) req.write(payload)
req.end()
})
}
@@ -450,7 +575,11 @@ class MacWechatRuntimeManager {
const { status, body } = await this.request('GET', '/bindingStatus')
if (status !== 200) return null
try {
this.lastBinding = JSON.parse(body) as MacWechatBindingStatus
const binding = JSON.parse(body) as MacWechatBindingStatus & {
supportedVersions?: string
}
delete binding.supportedVersions
this.lastBinding = binding
/*
* A 20s bind timeout is NOT proof of the orphan-agent wall: in the
* stale-rebind path the host worker waits up to 45s for the old session
@@ -485,6 +614,109 @@ class MacWechatRuntimeManager {
return this.lastBinding
}
// GET reads the local snapshot; POST runs one real online check.
// Neither touches the WeChat binding.
/** Local snapshot. Never attaches to WeChat, never forces a network refresh.
* 404 means the host predates these endpoints — not "unlicensed". */
async getMacLicenseStatus(): Promise<MacLicenseStatus> {
const availability = this.getSendRuntimeAvailability()
if (availability.state === 'unavailable') {
return offlineMacLicenseStatus('platform_unsupported', '当前构建不包含 Mac 发送能力')
}
if (availability.state !== 'available') {
return offlineMacLicenseStatus('runtime_missing', availability.message)
}
if (this.manuallyStopped) {
return offlineMacLicenseStatus(
'runtime_missing',
'Mac 发送组件已停止,请在发送页点击“绑定微信”重新启动。'
)
}
if (this.lifecycle === 'stopped') await this.ensureStarted()
const { status, body } = await this.request('GET', '/license/status', LICENSE_STATUS_TIMEOUT_MS)
if (status === null) {
return offlineMacLicenseStatus('runtime_missing', 'Mac 发送组件未运行,请先启动发送组件')
}
if (status === 404) {
return offlineMacLicenseStatus(
'unsupported',
'当前发送组件版本较旧,不支持授权检测。请升级或重启发送组件后再试。'
)
}
if (status !== 200) {
return offlineMacLicenseStatus('runtime_missing', `授权状态查询失败(HTTP ${status})`)
}
try {
return parseMacLicenseStatus(JSON.parse(body))
} catch {
return offlineMacLicenseStatus('runtime_missing', '授权状态响应无法解析')
}
}
/**
* One real online check; re-entrant calls return the current snapshot instead
* of minting a duplicate challenge. Network failure maps to server_unavailable,
* never to revoked.
*/
async refreshMacLicense(): Promise<MacLicenseStatus> {
const availability = this.getSendRuntimeAvailability()
if (availability.state === 'unavailable') {
return offlineMacLicenseStatus('platform_unsupported', '当前构建不包含 Mac 发送能力')
}
if (availability.state !== 'available') {
return offlineMacLicenseStatus('runtime_missing', availability.message)
}
if (this.manuallyStopped) {
return offlineMacLicenseStatus(
'runtime_missing',
'Mac 发送组件已停止,请在发送页点击“绑定微信”重新启动。'
)
}
if (this.lifecycle === 'stopped') await this.ensureStarted()
if (this.licenseRefreshInFlight) {
// A refresh is already running; answer from the local snapshot so the
// button click is a no-op instead of stacking a second online check.
return this.getMacLicenseStatus()
}
this.licenseRefreshInFlight = true
try {
const { status, body } = await this.request(
'POST',
'/license/refresh',
LICENSE_REFRESH_TIMEOUT_MS,
'{}'
)
if (status === null) {
const snapshot = await this.getMacLicenseStatus().catch(() => null)
return resolveLicenseRefreshFailure(snapshot, '无法连接授权服务器,请检查网络后重试')
}
if (status === 404) {
return offlineMacLicenseStatus(
'unsupported',
'当前发送组件版本较旧,不支持授权检测。请升级或重启发送组件后再试。'
)
}
let envelope: Record<string, unknown>
try {
envelope = JSON.parse(body) as Record<string, unknown>
} catch {
return offlineMacLicenseStatus('runtime_missing', '授权刷新响应无法解析')
}
// The host wraps the result: { ok, code, message, status: MacLicenseStatus }
const nested = envelope.status ?? envelope
const parsed = parseMacLicenseStatus(nested)
if (typeof envelope.errorCode === 'number' && parsed.errorCode == null) {
parsed.errorCode = envelope.errorCode
}
return parsed
} finally {
this.licenseRefreshInFlight = false
}
}
private licenseRefreshInFlight = false
/*
* Build the legacy PersonalWechatSenderStatus contract from the live mac
* runtime state. Lives here (not in the capability service) so BOTH the
@@ -492,6 +724,32 @@ class MacWechatRuntimeManager {
* circular import.
*/
async buildSenderStatus(): Promise<PersonalWechatSenderStatus> {
if (isMacNativeRuntimeUnavailable()) {
const message = '当前环境不包含微信发送能力'
return {
state: 'runtime_missing',
platform: 'darwin',
arch: process.arch,
sipDisabled: true,
wechatRunning: false,
endpoint: `http://${HOST}:${PORT}`,
endpointReady: false,
runtimeReady: false,
attachReady: false,
baseAddressReady: false,
textHookInstalled: false,
textHookReady: false,
imageHookInstalled: false,
imageHookReady: false,
messageListenerReady: false,
canSend: false,
canSendText: false,
canSendImage: false,
canSendVoice: false,
message,
error: message
}
}
/*
* Lazy-start the host from status reads.
*
@@ -503,13 +761,15 @@ class MacWechatRuntimeManager {
* never succeed because the check itself is what should start the host.
* Starting it never touches WeChat, so doing it from a read is safe.
*/
if (this.lifecycle === 'stopped') {
if (this.lifecycle === 'stopped' && !this.manuallyStopped) {
await this.ensureStarted().catch(() => undefined)
}
/* Self-heal the status card too: if WeChat was restarted, drop the stale
* restartRequired before it is read into the UI as an error. */
try {
this.manifest = readMacWechatRuntimeManifest(this.resolveRuntimeDir())
const runtimeDir = this.resolveRuntimeDir()
if (!runtimeDir) throw new Error('runtime missing')
this.manifest = readMacWechatRuntimeManifest(runtimeDir)
} catch (error) {
const detail = error instanceof Error ? error.message : String(error)
appLogger.write({
@@ -580,8 +840,20 @@ class MacWechatRuntimeManager {
* live WeChat pid again returns attached=false and never double-attaches.
*/
async bind(): Promise<MacWechatBindResult> {
const availability = this.getSendRuntimeAvailability()
if (availability.state === 'unavailable') {
return {
ok: false,
attached: false,
state: 'runtime_offline',
message: '当前环境不包含微信发送能力'
}
}
if (availability.state !== 'available') {
return { ok: false, attached: false, state: 'runtime_offline', message: availability.message }
}
if (this.lifecycle !== 'online') {
const snapshot = await this.ensureStarted()
const snapshot = await this.ensureStarted({ allowManualRestart: true })
if (snapshot.lifecycle !== 'online') {
return {
ok: false,
@@ -606,6 +878,28 @@ class MacWechatRuntimeManager {
}
}
const license = await this.getMacLicenseStatus()
const licenseAllowed = hasValidWechatLicense(license)
if (!licenseAllowed) {
const tokenExpiresAt = license.tokenExpiresAt
? Date.parse(license.tokenExpiresAt)
: Number.NaN
const message =
license.state === 'revoked'
? 'LICENSE_REVOKED: 微信发送授权已撤销'
: license.state === 'expired' ||
(Number.isFinite(tokenExpiresAt) && tokenExpiresAt <= Date.now())
? 'LICENSE_EXPIRED: 微信发送授权已过期'
: license.state === 'device_mismatch'
? 'LICENSE_DEVICE_MISMATCH: 授权与当前设备不匹配'
: license.state === 'identity_error'
? 'LICENSE_IDENTITY_ERROR: 设备身份异常'
: license.authorized && !license.features.includes('wechat')
? 'LICENSE_FEATURE_DENIED: 未开通微信发送'
: 'LICENSE_REQUIRED: 需要有效的微信发送授权'
return { ok: false, attached: false, state: 'host_error', message }
}
const { status, body } = await this.request('POST', '/bindWeChat')
await this.refreshBinding().catch(() => null)
@@ -644,7 +938,7 @@ class MacWechatRuntimeManager {
async reload(): Promise<MacWechatRuntimeSnapshot> {
await this.shutdown().catch(() => undefined)
await new Promise((resolve) => setTimeout(resolve, 2_000))
return this.ensureStarted()
return this.ensureStarted({ allowManualRestart: true })
}
private isProcessAlive(pid: number): boolean {
@@ -662,6 +956,7 @@ class MacWechatRuntimeManager {
* leave its injected agent inside WeChat and make the next attach hang.
*/
async shutdown(): Promise<void> {
if (isMacNativeRuntimeUnavailable()) return
if (this.restartTimer) {
clearTimeout(this.restartTimer)
this.restartTimer = null
@@ -0,0 +1,417 @@
import fs from 'node:fs'
import http from 'node:http'
import type { CapabilityReasonCode } from '../../shared/msg-insert-switch'
import { hasMacNativeBundle, isMacNativeRuntimeUnavailable } from '../native-runtime-paths'
import { resolveHelperPath } from './msg-insert-switch-service'
/**
* 发送能力的唯一判定入口:授权、原生组件、库连接分开算,任一项不确定都不许开启。
* 4290 的 JSON 本机可伪造,这里只是应用层门禁,真正的校验在原生 helper。
*/
export type { CapabilityReasonCode }
export type EntitlementState = 'valid' | 'invalid' | 'pending' | 'unavailable' | 'unsupported'
export type NativeComponentState = 'ready' | 'missing' | 'invalid' | 'incompatible'
export interface MessageInsertCapability {
/** 授权 */
entitlementState: EntitlementState
/** 发送能力组件 */
nativeComponentState: NativeComponentState
/** 微信数据库是否已连接(不代表发送能力) */
databaseReady: boolean
/** 是否允许「开启」发送能力 */
canEnable: boolean
/** 关闭永远不因授权被拒,否则用户没法把自己开过的功能关掉。 */
canDisable: boolean
reasonCode: CapabilityReasonCode
/** 给人看的一句话 */
message: string
/** Hook 原始状态名,仅用于诊断展示 */
licenseStatus?: string
/** 判定时间戳 */
checkedAt: number
}
export interface CapabilityInput {
/** 微信库是否已连接(由主进程按 chat 状态传入) */
databaseReady: boolean
}
export interface LicenseProbeResult {
ok: boolean
status?: string
error?: string
}
export interface CapabilityDeps {
platform: NodeJS.Platform
/** mac:是否 native 包 */
hasMacNativeBundle: () => boolean
/** mac:是否 public 包(拿不到 native 运行时) */
isMacRuntimeUnavailable: () => boolean
/** 发送能力组件路径;null = 缺失 */
resolveNativeComponent: () => string | null
/** 授权探测(Windows) */
probeLicense: (timeoutMs: number) => Promise<LicenseProbeResult>
/** 组件文件探测(便于测试注入) */
statFile?: (filePath: string) => { size: number } | null
now?: () => number
}
const DEFAULT_TTL_MS = 30_000
const PROBE_TIMEOUT_MS = 1_200
/** Hook 的 LicenseStatus → 授权状态。只有明确可接受的结果才算 valid。 */
export function mapLicenseStatus(status: string | undefined): {
entitlement: EntitlementState
reasonCode: CapabilityReasonCode
message: string
} {
switch (status) {
case 'LICENSE_OK':
return { entitlement: 'valid', reasonCode: 'CAPABILITY_READY', message: '授权有效' }
case 'LICENSE_CHECKING':
return {
entitlement: 'pending',
reasonCode: 'LICENSE_PENDING',
message: '授权正在验证,请稍候'
}
case 'LICENSE_EXPIRED':
return {
entitlement: 'invalid',
reasonCode: 'LICENSE_EXPIRED',
message: '授权已过期,请重新激活后再开启'
}
case 'LICENSE_MACHINE_MISMATCH':
return {
entitlement: 'invalid',
reasonCode: 'LICENSE_MACHINE_MISMATCH',
message: '这份授权不属于本机'
}
case 'LICENSE_REVOKED':
return {
entitlement: 'invalid',
reasonCode: 'LICENSE_REVOKED',
message: '授权已被吊销'
}
case 'LICENSE_INVALID':
case 'LICENSE_TAMPERED':
return {
entitlement: 'invalid',
reasonCode: 'LICENSE_INVALID',
message: '授权无效,请重新激活'
}
case 'LICENSE_NOT_FOUND':
return {
entitlement: 'invalid',
reasonCode: 'LICENSE_REQUIRED',
message: '未检测到有效授权'
}
case 'LICENSE_NETWORK_ERROR':
case 'LICENSE_SERVER_ERROR':
return {
entitlement: 'unavailable',
reasonCode: 'LICENSE_UNAVAILABLE',
message: '授权服务暂时不可用,稍后再试'
}
default:
// 未知状态一律 fail-closed,但要说清「是未知」而不是「你没买」
return {
entitlement: 'unavailable',
reasonCode: 'LICENSE_UNAVAILABLE',
message: '暂时无法确认授权状态'
}
}
}
/** 探测本机 Hook 的授权接口。失败只报失败,不臆测状态。 */
export function probeLicenseStatus(timeoutMs = PROBE_TIMEOUT_MS): Promise<LicenseProbeResult> {
return new Promise((resolve) => {
let settled = false
const done = (result: LicenseProbeResult): void => {
if (settled) return
settled = true
resolve(result)
}
let req: http.ClientRequest
try {
req = http.get(
{ host: '127.0.0.1', port: Number(process.env.TM_WECHAT_HOST_PORT) || 4290, path: '/license/status', timeout: timeoutMs },
(res) => {
const chunks: Buffer[] = []
res.on('data', (chunk: Buffer) => chunks.push(chunk))
res.on('end', () => {
try {
const body = JSON.parse(Buffer.concat(chunks).toString('utf8')) as {
status?: unknown
}
done({ ok: true, status: typeof body.status === 'string' ? body.status : '' })
} catch {
done({ ok: false, error: 'BAD_JSON' })
}
})
res.on('error', () => done({ ok: false, error: 'RESPONSE_ERROR' }))
}
)
} catch (error) {
done({ ok: false, error: error instanceof Error ? error.message : String(error) })
return
}
req.on('timeout', () => {
req.destroy()
done({ ok: false, error: 'TIMEOUT' })
})
req.on('error', (error: Error) => done({ ok: false, error: error.message }))
})
}
/**
* 检查原生组件的文件格式及 CPU 架构兼容性。
* 支持 macOS Mach-O 和 Windows PE。
*/
export function inspectNativeComponent(
filePath: string | null,
arch: string,
statFile: (p: string) => { size: number } | null
): NativeComponentState {
if (!filePath) return 'missing'
const stat = statFile(filePath)
if (!stat || stat.size < 1024) return 'missing'
try {
const fd = fs.openSync(filePath, 'r')
try {
const head = Buffer.alloc(0x40)
fs.readSync(fd, head, 0, 0x40, 0)
const magicLE = head.readUInt32LE(0)
if (magicLE === 0xfeedfacf || magicLE === 0xfeedface) {
const cpuType = head.readUInt32LE(4)
const expected = arch === 'arm64' ? 0x0100000c : 0x01000007
return cpuType === expected ? 'ready' : 'incompatible'
}
if (magicLE === 0xbebafeca || magicLE === 0xcafebabe) {
const count = head.readUInt32BE(4)
if (count === 0 || count > 16) return 'invalid'
const expected = arch === 'arm64' ? 0x0100000c : 0x01000007
const slice = Buffer.alloc(20)
for (let index = 0; index < count; index += 1) {
fs.readSync(fd, slice, 0, 20, 8 + index * 20)
if (slice.readUInt32BE(0) === expected) return 'ready'
}
return 'incompatible'
}
if (head[0] !== 0x4d || head[1] !== 0x5a) return 'invalid' // "MZ"
const peOffset = head.readUInt32LE(0x3c)
const pe = Buffer.alloc(6)
fs.readSync(fd, pe, 0, 6, peOffset)
if (pe[0] !== 0x50 || pe[1] !== 0x45) return 'invalid' // "PE"
const machine = pe.readUInt16LE(4)
const expected = arch === 'arm64' ? 0xaa64 : 0x8664
return machine === expected ? 'ready' : 'incompatible'
} finally {
fs.closeSync(fd)
}
} catch {
return 'invalid'
}
}
export class MessageInsertCapabilityService {
private cached: MessageInsertCapability | null = null
private inflight: Promise<MessageInsertCapability> | null = null
private readonly now: () => number
constructor(private readonly deps: CapabilityDeps) {
this.now = deps.now || (() => Date.now())
}
/** 读缓存(页面刷新用);过期或从未算过就重新评估。 */
async getCapability(input: CapabilityInput): Promise<MessageInsertCapability> {
const now = this.now()
if (this.cached && now - this.cached.checkedAt < DEFAULT_TTL_MS) {
/* 数据库连接状态可能瞬间变化,缓存命中时也要用最新入参重算这一项 */
const merged = this.compose(input, this.cached.entitlementState, this.cached.licenseStatus)
this.cached = merged
return merged
}
return this.refresh(input)
}
/** 强制重新评估(写库前必须调用,不能相信页面上那份缓存)。 */
async refresh(input: CapabilityInput): Promise<MessageInsertCapability> {
if (this.inflight) return this.inflight
this.inflight = this.evaluate(input).finally(() => {
this.inflight = null
})
const result = await this.inflight
this.cached = result
return result
}
/** 供主进程做「开启」前的最终裁决。 */
async ensureCanEnable(input: CapabilityInput): Promise<MessageInsertCapability> {
return this.refresh(input)
}
/** 测试与设置变化时清缓存。 */
invalidate(): void {
this.cached = null
}
private async evaluate(input: CapabilityInput): Promise<MessageInsertCapability> {
const platform = this.deps.platform
if (platform !== 'win32' && platform !== 'darwin') {
return this.build({
input,
entitlement: 'unsupported',
licenseStatus: undefined,
reasonCode: 'UNSUPPORTED_PLATFORM',
message: '微信内消息写入目前仅支持 Windows 与 macOS'
})
}
if (platform === 'darwin') {
if (!this.deps.hasMacNativeBundle()) {
// OSS 包:如实说不提供,不假装「未授权」
return this.build({
input,
entitlement: 'unsupported',
licenseStatus: undefined,
reasonCode: 'UNSUPPORTED_PLATFORM',
message: '当前版本不包含微信内消息发送能力'
})
}
return this.build({
input,
entitlement: 'valid',
licenseStatus: undefined,
reasonCode: 'CAPABILITY_READY',
message: '授权有效'
})
}
const probe = await this.deps.probeLicense(PROBE_TIMEOUT_MS)
if (!probe.ok) {
return this.build({
input,
entitlement: 'unavailable',
licenseStatus: undefined,
reasonCode: 'LICENSE_UNAVAILABLE',
message: '暂时无法确认授权状态'
})
}
const mapped = mapLicenseStatus(probe.status)
return this.build({
input,
entitlement: mapped.entitlement,
licenseStatus: probe.status,
reasonCode: mapped.reasonCode,
message: mapped.message
})
}
private build(args: {
input: CapabilityInput
entitlement: EntitlementState
licenseStatus?: string
reasonCode: CapabilityReasonCode
message: string
}): MessageInsertCapability {
return this.compose(
args.input,
args.entitlement,
args.licenseStatus,
args.reasonCode,
args.message
)
}
private compose(
input: CapabilityInput,
entitlement: EntitlementState,
licenseStatus: string | undefined,
reasonCode?: CapabilityReasonCode,
message?: string
): MessageInsertCapability {
const platform = this.deps.platform
const supportedPlatform = platform === 'win32' || platform === 'darwin'
const component = supportedPlatform
? inspectNativeComponent(
this.deps.resolveNativeComponent(),
process.arch,
this.deps.statFile || defaultStat
)
: 'missing'
const databaseReady = input.databaseReady === true
let code: CapabilityReasonCode = reasonCode || 'CAPABILITY_READY'
let text = message || ''
if (!code || code === 'CAPABILITY_READY') {
if (entitlement === 'unsupported') {
code = 'UNSUPPORTED_PLATFORM'
text = text || '当前版本不包含微信内消息发送能力'
} else if (entitlement === 'unavailable') {
code = 'LICENSE_UNAVAILABLE'
text = text || '暂时无法确认授权状态'
} else if (entitlement === 'pending') {
code = 'LICENSE_PENDING'
text = text || '授权正在验证,请稍候'
} else if (entitlement === 'invalid') {
code = 'LICENSE_REQUIRED'
text = text || '未检测到有效授权'
} else if (component !== 'ready') {
code = component === 'missing' ? 'COMPONENT_MISSING' : 'COMPONENT_INVALID'
text = component === 'missing' ? '未安装发送能力组件' : '发送能力组件不完整或版本不匹配'
} else if (!databaseReady) {
code = 'DATABASE_UNAVAILABLE'
text = '微信数据库尚未连接'
} else {
code = 'CAPABILITY_READY'
text = '授权与组件均已就绪'
}
}
const canEnable =
supportedPlatform &&
entitlement === 'valid' &&
component === 'ready' &&
databaseReady &&
code === 'CAPABILITY_READY'
/* 关闭不受授权限制:用户丢了授权也必须能把已有规则关掉 */
const canDisable = supportedPlatform
return {
entitlementState: entitlement,
nativeComponentState: component,
databaseReady,
canEnable,
canDisable,
reasonCode: code,
message: text,
...(licenseStatus ? { licenseStatus } : {}),
checkedAt: this.now()
}
}
}
function defaultStat(filePath: string): { size: number } | null {
try {
const stat = fs.statSync(filePath)
return stat.isFile() ? { size: stat.size } : null
} catch {
return null
}
}
export const msgInsertCapabilityService = new MessageInsertCapabilityService({
platform: process.platform,
hasMacNativeBundle,
isMacRuntimeUnavailable: isMacNativeRuntimeUnavailable,
resolveNativeComponent: resolveHelperPath,
probeLicense: probeLicenseStatus
})
+19 -2
View File
@@ -29,6 +29,8 @@ import { createHash } from 'node:crypto'
import path from 'node:path'
import { findResource } from '../resource-paths'
import { isMacNativeRuntimeUnavailable, resolveWcdbConfigHelper } from '../native-runtime-paths'
import { resolveExternalComponent } from './external-component-locator'
import type { Wcdb4Client } from '../wcdb4-client'
import {
MSG_INSERT_SWITCHES,
@@ -156,10 +158,14 @@ export function emptyMsgInsertStatus(
* 开发态与打包态都靠 findResource 解析,不依赖当前工作目录。
*/
export function resolveHelperPath(): string | null {
if (process.platform === 'darwin') return resolveWcdbConfigHelper()
/* 优先用外置目录里的发送能力组件,避免自动更新清掉;校验不过当没装。 */
const external = resolveExternalComponent()
if (external) return external.helperPath
/*
* 平台/架构都要分。Windows 交付在 `resources/wcdb/win32/x64/`(注意是 win32 不是 windows),
* 文件名带 `.exe`。以前这里三个候选全写死 macos —— Windows 上会恒返回 null,
* 表现为「缺少写入组件」+ 开关永久置灰。
* 表现为「缺少发送能力组件」+ 开关永久置灰。
*
* 同目录还有 wcdb_api.dll / WCDB.dll / SDL2.dll,MSVC 运行库在 resources/runtime/win32/,
* 两者都由 preload-env.ts 加进 DLL 搜索路径,所以 helper.exe 能直接加载。
@@ -640,6 +646,14 @@ export async function applyMsgInsertSwitch(
}
}
if (isMacNativeRuntimeUnavailable()) {
return {
success: false,
status: emptyMsgInsertStatus(input.name, 'HELPER_NOT_FOUND', '微信内消息插入仅在 TraceMemo 具备发送能力时开放'),
errorCode: 'HELPER_NOT_FOUND',
message: '微信内防撤回与退群消息插入仅在 TraceMemo 具备发送能力时开放;退群检测和历史记录不受影响'
}
}
const helperPath = resolveHelperPath()
if (!helperPath) {
return {
@@ -647,7 +661,7 @@ export async function applyMsgInsertSwitch(
status: emptyMsgInsertStatus(input.name, 'HELPER_NOT_FOUND', '暂无法使用'),
errorCode: 'HELPER_NOT_FOUND',
/* 面向用户是能力语义;errorCode 仍是 HELPER_NOT_FOUND,门禁/授权层照旧能判。 */
message: '暂无法使用:当前安装不包含微信内消息写入组件'
message: '暂无法使用:当前安装不包含发送能力组件'
}
}
@@ -716,6 +730,9 @@ export async function applyMsgInsertSwitch(
export async function reconcileMsgInsertRules(
input: MsgInsertScopeInput & { myWxid: string; databaseKey: string; extraRooms?: string[] }
): Promise<{ done: boolean; rooms: number; written: number; errorCode?: MsgInsertErrorCode }> {
if (isMacNativeRuntimeUnavailable()) {
return { done: false, rooms: 0, written: 0, errorCode: 'HELPER_NOT_FOUND' }
}
const helperPath = resolveHelperPath()
if (!helperPath || !input.databaseKey) {
return {
@@ -12,7 +12,7 @@ import {
} from 'fs'
import { homedir, tmpdir } from 'os'
import { delimiter, dirname, extname, join, sep } from 'path'
import ffmpegStaticPath from 'ffmpeg-static'
import { resolveBundledFfmpegPath } from '../ffmpeg-path'
import { promisify } from 'util'
import type {
PersonalWechatSendRequest,
@@ -64,9 +64,7 @@ function windowsHookHost(port?: unknown): string | null {
export function buildPersonalWechatRuntimePath(): string {
const existing = String(process.env['PATH'] || '')
const bundledFfmpeg = String(ffmpegStaticPath || '')
.replace('app.asar', 'app.asar.unpacked')
.trim()
const bundledFfmpeg = resolveBundledFfmpegPath()
if (!bundledFfmpeg || !existsSync(bundledFfmpeg)) return existing
return [dirname(bundledFfmpeg), existing].filter(Boolean).join(delimiter)
}
@@ -174,7 +172,7 @@ async function detectVoiceDurationMs(filePath: string): Promise<number | undefin
}
}
const ffmpegPath = String(ffmpegStaticPath || '').replace('app.asar', 'app.asar.unpacked')
const ffmpegPath = resolveBundledFfmpegPath()
if (!ffmpegPath || !existsSync(ffmpegPath)) return undefined
let output = ''
try {
@@ -203,7 +201,7 @@ async function prepareWindowsVoiceFile(filePath: string): Promise<{
return { filePath, durationMs: await detectVoiceDurationMs(filePath), temporary: false }
}
const ffmpegPath = String(ffmpegStaticPath || '').replace('app.asar', 'app.asar.unpacked')
const ffmpegPath = resolveBundledFfmpegPath()
if (!ffmpegPath || !existsSync(ffmpegPath)) {
throw new Error('Windows 语音发送需要可用的 FFmpeg 才能转换为 SILK')
}
+24 -2
View File
@@ -60,6 +60,21 @@ export interface AppSettings {
* 设置页随时可以改回来。
*/
closeAction: CloseAction
/**
* 用户点过「忽略此版本」的更新版本号(不含 `v` 前缀)。
*
* 只影响**启动时的自动弹窗**:同一版本不再打扰。手动检查更新与「设置 → 关于」
* 始终展示最新版本 —— 忽略的是提示,不是版本本身。空串表示没有忽略任何版本。
*/
skippedUpdateVersion: string
}
/** 只接受 `1.2.3` / `1.2.3-beta.1` 这类版本号;其它输入一律按"没有忽略"处理。 */
const UPDATE_VERSION_PATTERN = /^\d{1,6}\.\d{1,6}\.\d{1,6}(?:[-+][0-9A-Za-z.-]{1,32})?$/
export function normalizeSkippedUpdateVersion(value: unknown): string {
const text = String(value ?? '').trim()
return UPDATE_VERSION_PATTERN.test(text) ? text : ''
}
function getDefaultDbRoot(): string {
@@ -145,7 +160,8 @@ const DEFAULT_SETTINGS: AppSettings = {
windowsWechatPort: '',
reportImagePostfixText: '今日日报',
queryAgentEnabled: true,
closeAction: 'ask'
closeAction: 'ask',
skippedUpdateVersion: ''
}
const SETTINGS_FILE = path.join(
@@ -192,9 +208,15 @@ export function loadSettings(): AppSettings {
}
// 关闭行为可能来自旧版本或手改过的 settings.json —— 非法值一律收敛回 `ask`。
// 放任非法值会造成最难排查的一种表现:点关闭窗口什么也不发生。
if (cache.closeAction !== 'ask' && cache.closeAction !== 'tray' && cache.closeAction !== 'quit') {
if (
cache.closeAction !== 'ask' &&
cache.closeAction !== 'tray' &&
cache.closeAction !== 'quit'
) {
cache.closeAction = 'ask'
}
// 版本号是拿来逐字比对的:脏值会让「忽略」永远命中不了同一条记录。
cache.skippedUpdateVersion = normalizeSkippedUpdateVersion(cache.skippedUpdateVersion)
// 防撤回已下线(设置入口已隐藏):历史版本可能把它持久化为 true。
// 这里强制收敛为 false 并回写磁盘,确保旧的撤回监听与撤回日志不会继续运行。
if (cache.recallProtectionEnabled || retiredKeepProcess !== undefined) {
+2 -1
View File
@@ -36,6 +36,7 @@
// - macOS 没有"语言包缺失"这一失败模式。
import crypto from 'node:crypto'
import { resolveBundledFfmpegPath } from '../ffmpeg-path'
import { spawn } from 'node:child_process'
import {
SYSTEM_OCR_CACHE_TTL_MS,
@@ -125,7 +126,7 @@ const defaultResolveFfmpegExecutable = (): string => {
const fromEnvironment = String(process.env['FFMPEG_BIN'] || '').trim()
if (fromEnvironment) return fromEnvironment
try {
const bundled = require('ffmpeg-static') as string | null
const bundled = resolveBundledFfmpegPath()
if (bundled) return bundled
} catch {
// 忽略:退回到 PATH 上的 ffmpeg
@@ -33,7 +33,9 @@ import { app } from 'electron'
import type { GroupMemberExitedEvent } from '../../shared/group-exit-event'
import { renderLeaveNotificationText } from '../../shared/group-exit-event'
import { GROUP_EXIT_NOTIFICATION_TEMPLATE } from '../../shared/group-exit-monitor'
import { findResource } from '../resource-paths'
import { resolveWcdbConfigHelper } from '../native-runtime-paths'
import { msgInsertCapabilityService } from './msg-insert-capability-service'
import { resolveHelperPath } from './msg-insert-switch-service'
export type LocalExitNoticeOutcome =
| 'inserted'
@@ -57,27 +59,18 @@ interface StoredState {
enabled?: boolean
}
const HELPER_NAME = 'tm-wcdb-config-helper'
const HELPER_TIMEOUT_MS = 20_000
/** 最近若干次插入结果,只用于诊断展示,不参与判定 */
const RECENT_LIMIT = 50
function helperPath(): string | null {
/* 与 msg-insert-switch-service 的 resolveHelperPath 保持一致:
* Windows 走 wcdb/win32/<arch>/ 且文件名带 .exe。 */
const arch = process.arch === 'x64' ? 'x64' : 'arm64'
const other = arch === 'arm64' ? 'x64' : 'arm64'
const platformDir = process.platform === 'win32' ? 'win32' : 'macos'
const suffix = process.platform === 'win32' ? '.exe' : ''
for (const candidate of [
`wcdb/${platformDir}/${arch}/${HELPER_NAME}${suffix}`,
`wcdb/${platformDir}/${other}/${HELPER_NAME}${suffix}`,
`wcdb/${platformDir}/${HELPER_NAME}${suffix}`
]) {
const resolved = findResource(candidate)
if (resolved) return resolved
}
return null
if (process.platform === 'darwin') return resolveWcdbConfigHelper()
/*
* 不在这里重复一份 resources 搜索逻辑。
* Windows 上 helper 可能被部署到外置目录,
* 只有一处解析入口,两条链路才不会各解析各的。
*/
return resolveHelperPath()
}
/**
@@ -150,6 +143,13 @@ export class WechatLocalExitNoticeService {
try {
this.ensureLoaded()
if (!this.enabled) return this.finish({ ...base, outcome: 'disabled', code: 'DISABLED' })
/* 判定走统一服务;未授权或超时一律不写,普通退群检测不受影响。 */
const capability = await msgInsertCapabilityService.getCapability({
databaseReady: true
})
if (!capability.canEnable) {
return this.finish({ ...base, outcome: 'disabled', code: capability.reasonCode })
}
if (!event.eventId || !event.conversationId) {
return this.finish({ ...base, outcome: 'failed', code: 'EVENT_INCOMPLETE' })
}
+208 -55
View File
@@ -5,7 +5,8 @@ import crypto from 'crypto'
import { createRequire } from 'module'
import { createConnection, Socket } from 'net'
import { getResourceRoots } from './resource-paths'
import { wcdbDebugLog } from './wcdb-debug'
import { resolveWcdbLibrary } from './native-runtime-paths'
import { wcdbDebugLog, isWcdbDebugEnabled } from './wcdb-debug'
import { looksLikePermissionDenied, PathAccessDeniedError } from './services/path-access-probe'
import type { ImageMessageCountProbe } from '../shared/image-text-index'
import { imageTextWindowToSeconds } from '../shared/image-text-index'
@@ -147,6 +148,71 @@ type KoffiModule = {
// library reference for every Wcdb4Client instance.
let wcdbBootstrapLib: KoffiLibrary | null = null
const DB_COMPONENT_UNAVAILABLE_MESSAGE = '本地数据库组件初始化失败,请确认应用安装完整。'
class NativeDbInitError extends Error {
readonly nativeCode: number
readonly phase: string
constructor(message: string, nativeCode: number, phase: string) {
super(message)
this.name = 'NativeDbInitError'
this.nativeCode = nativeCode
this.phase = phase
}
}
// -3002 一码四因(密钥错、不存在、不可读、损坏),先看文件系统事实再判码。
function describeDbOpenFailure(code: number, sessionDbPath: string): string {
if (code === -2003) return DB_COMPONENT_UNAVAILABLE_MESSAGE
let exists = false
try {
exists = Boolean(sessionDbPath) && fs.existsSync(sessionDbPath)
} catch {
exists = false
}
if (!exists) {
return '未找到微信数据库文件,请确认微信已登录目标账号,并重新选择数据目录。'
}
try {
fs.accessSync(sessionDbPath, fs.constants.R_OK)
} catch {
return '数据库文件不可读,请在系统设置中授予文件访问权限后重试。'
}
if (code === -3002) {
return '数据库无法打开:密钥与当前账号不匹配,或数据库文件已损坏。'
}
return '本地数据库初始化失败,请稍后重试。'
}
class NativeWcdbError extends Error {
readonly nativeCode: number
readonly phase = 'query'
constructor(nativeCode: number) {
super(describeWcdbQueryFailure(nativeCode))
this.name = 'NativeWcdbError'
this.nativeCode = nativeCode
}
}
function describeWcdbQueryFailure(code: number): string {
if (code === -2003) return DB_COMPONENT_UNAVAILABLE_MESSAGE
if (code === -3003 || code === -3004) {
return '读取微信数据库失败:密钥可能与该账号不匹配,或数据库文件已损坏。'
}
if (code === -3006) return '数据库连接已失效,请重新连接。'
return '本地数据库读取失败,请稍后重试。'
}
export function getNativeErrorCode(error: unknown): number | null {
const code = (error as { nativeCode?: unknown } | null | undefined)?.nativeCode
return typeof code === 'number' ? code : null
}
let wcdbBootstrapAsyncPromise: Promise<KoffiLibrary> | null = null
export function bootstrapWcdbNative(libPath?: string, libDirOverride?: string): KoffiLibrary {
@@ -205,16 +271,28 @@ export function bootstrapWcdbNative(libPath?: string, libDirOverride?: string):
}
}
if (!initOk) {
console.warn(
`[WCDB4] bootstrap InitProtection 返回 ${lastCode},继续尝试 wcdb_init/open; tried=${resourceRoots.join(' | ')}`
)
if (lastCode === -2003) {
// -2003 重试无效;其他非 0 仍要继续,兼容旧构建。
throw new NativeDbInitError(DB_COMPONENT_UNAVAILABLE_MESSAGE, lastCode, 'InitProtection')
}
if (isWcdbDebugEnabled()) {
console.warn(
`[WCDB4] bootstrap InitProtection rc=${lastCode},继续尝试 wcdb_init/open; tried=${resourceRoots.join(' | ')}`
)
} else {
console.warn('[WCDB4] bootstrap InitProtection 未成功,继续尝试后续初始化')
}
} else {
const wcdbInit = lib.func('int32 wcdb_init()') as () => number
console.log('[WCDB4] bootstrap wcdb_init begin')
const initRc = Number(wcdbInit())
console.log(`[WCDB4] bootstrap wcdb_init rc=${initRc}`)
if (initRc !== 0) {
console.warn(`[WCDB4] bootstrap wcdb_init 返回 ${initRc},继续尝试 wcdb_open_account`)
console.warn(
isWcdbDebugEnabled()
? `[WCDB4] bootstrap wcdb_init rc=${initRc},继续尝试 wcdb_open_account`
: '[WCDB4] bootstrap wcdb_init 未成功,继续尝试打开数据库'
)
}
}
@@ -261,9 +339,11 @@ export function bootstrapWcdbNativeAsync(
)
)
let initOk = false
let lastInitCode = -1
for (const resourceRoot of resourceRoots) {
try {
if (Number(initProtection(resourceRoot)) === 0) {
lastInitCode = Number(initProtection(resourceRoot))
if (lastInitCode === 0) {
initOk = true
break
}
@@ -271,6 +351,9 @@ export function bootstrapWcdbNativeAsync(
// Try the next resource root.
}
}
if (!initOk && lastInitCode === -2003) {
throw new NativeDbInitError(DB_COMPONENT_UNAVAILABLE_MESSAGE, lastInitCode, 'InitProtection')
}
if (initOk) {
const wcdbInit = lib.func('int32 wcdb_init()') as KoffiAsyncFunction
await new Promise<void>((resolve, reject) => {
@@ -569,9 +652,6 @@ export class Wcdb4Client {
private wcdbMsgInsertGetSwitches:
| ((handle: number, dbPath: string, outJson: WcdbVoidOut) => number)
| null = null
private wcdbMsgInsertListShardCatalog:
| ((handle: number, outJson: WcdbVoidOut) => number)
| null = null
private wcdbGetGroupNicknames:
| ((handle: number, chatroomId: string, outJson: WcdbVoidOut) => number)
| null = null
@@ -782,12 +862,16 @@ export class Wcdb4Client {
openResult = this.wcdbOpenAccount(this.sessionDbPath, this.key, handleOut)
if (openResult !== 0 || handleOut[0] <= 0) {
const hint =
openResult === -1005
? ';这通常表示密钥与当前账号数据库不匹配,请确认微信已登录目标账号,并重新自动获取密钥'
: ''
throw new Error(
`wcdb_open_account 失败,错误码: ${openResult}${hint}; sessionDb=${this.sessionDbPath}; accountRoot=${this.accountRoot}; wxid=${this.wxid}; keyLength=${this.key.length}`
// message 只放分类文案;路径与 wxid 不进 message,原生码在 nativeCode 字段上。
if (isWcdbDebugEnabled()) {
console.warn(
`[WCDB4] wcdb_open_account rc=${openResult}; sessionDb=${this.sessionDbPath}; accountRoot=${this.accountRoot}; wxid=${this.wxid}; keyLength=${this.key.length}`
)
}
throw new NativeDbInitError(
describeDbOpenFailure(openResult, this.sessionDbPath),
openResult,
'wcdb_open_account'
)
}
@@ -815,8 +899,15 @@ export class Wcdb4Client {
handleOut
)
if (openResult !== 0 || handleOut[0] <= 0) {
throw new Error(
`wcdb_open_account failed, code=${openResult}; sessionDb=${this.sessionDbPath}; accountRoot=${this.accountRoot}; wxid=${this.wxid}; keyLength=${this.key.length}`
if (isWcdbDebugEnabled()) {
console.warn(
`[WCDB4] wcdb_open_account(async) rc=${openResult}; sessionDb=${this.sessionDbPath}; accountRoot=${this.accountRoot}; wxid=${this.wxid}; keyLength=${this.key.length}`
)
}
throw new NativeDbInitError(
describeDbOpenFailure(openResult, this.sessionDbPath),
openResult,
'wcdb_open_account_async'
)
}
this.handle = handleOut[0]
@@ -923,7 +1014,11 @@ export class Wcdb4Client {
)
if (startResult !== 0) {
this.monitorCallback = null
console.warn(`[WCDB4] wcdb_start_monitor_pipe 失败,错误码: ${startResult}`)
console.warn(
isWcdbDebugEnabled()
? `[WCDB4] wcdb_start_monitor_pipe rc=${startResult}`
: '[WCDB4] 消息监听启动失败,将退回轮询'
)
return false
}
this.monitorStarted = true
@@ -938,7 +1033,11 @@ export class Wcdb4Client {
outName
)
if (nameResult !== 0 || !outName[0]) {
console.warn(`[WCDB4] wcdb_get_monitor_pipe_name 失败,错误码: ${nameResult}`)
console.warn(
isWcdbDebugEnabled()
? `[WCDB4] wcdb_get_monitor_pipe_name rc=${nameResult}`
: '[WCDB4] 消息监听通道不可用,将退回轮询'
)
this.stopMonitor()
return false
}
@@ -1938,7 +2037,7 @@ export class Wcdb4Client {
/**
* 读取「微信消息插入规则」的分片目录(只读)。
*
* 每个分片只跑两条查询(表清单 + 规则清单),拿回来之后调用方可以在本地用
* 每个分片只跑一条 sqlite_master 查询,拿回来之后调用方可以在本地用
* md5(roomId) 匹配出「每个会话落在哪些分片、规则齐不齐」。这样即使会话很多,
* 判断全部会话的状态也只是一次目录读取,不需要按会话逐个查库。
*/
@@ -1950,29 +2049,40 @@ export class Wcdb4Client {
shard: string
dbPath: string
configTable: boolean
storeTables: { capture: boolean; names: boolean; queue: boolean }
tables: string[]
rules: Array<{ name: string; table: string }>
}>
}
error?: string
} {
if (!this.wcdbMsgInsertListShardCatalog) {
if (!this.wcdbExecQuery) {
return { success: false, error: '当前 WCDB 服务不支持消息插入规则目录' }
}
try {
const catalog = this.callJson<{
shardCount: number
shards: Array<{
shard: string
dbPath: string
configTable: boolean
storeTables: { capture: boolean; names: boolean; queue: boolean }
tables: string[]
rules: Array<{ name: string; table: string }>
}>
}>((handle, outJson) => this.wcdbMsgInsertListShardCatalog!(handle, outJson))
return { success: true, catalog }
// 专用 native 目录接口在部分 Windows 数据库上会终止进程,改走已有的只读 SQL 通道。
const shards = this.listMessageShardPaths().map((dbPath) => {
const rows = this.callJson<{ name: string; type: string; tbl_name: string }[]>(
(handle, outJson) =>
this.wcdbExecQuery!(
handle,
'message',
dbPath,
"SELECT name, type, tbl_name FROM sqlite_master WHERE type IN ('table', 'trigger')",
outJson
)
)
const tables = rows.filter((row) => row.type === 'table').map((row) => row.name)
return {
shard: path.basename(dbPath),
dbPath,
configTable: tables.includes('_tm_config'),
tables,
rules: rows
.filter((row) => row.type === 'trigger')
.map((row) => ({ name: row.name, table: row.tbl_name }))
}
})
return { success: true, catalog: { shardCount: shards.length, shards } }
} catch (error) {
return { success: false, error: error instanceof Error ? error.message : String(error) }
}
@@ -2923,7 +3033,7 @@ export class Wcdb4Client {
const handle = this.ensureHandle()
const fn = this.wcdbGetVoiceData as unknown as KoffiAsyncFunction
return this.createTrackedNativeCall<Wcdb4VoiceDataResult>((resolve, reject) => {
const result = await this.createTrackedNativeCall<Wcdb4VoiceDataResult>((resolve, reject) => {
const outHex: WcdbVoidOut = [null]
fn.async(
handle,
@@ -2948,7 +3058,9 @@ export class Wcdb4Client {
resolve(
hex === null
? { success: false, error: '解析语音数据失败' }
: { success: true, hex, error: '' }
: hex
? { success: true, hex, error: '' }
: { success: false, error: '语音数据为空' }
)
} finally {
this.wcdbFreeString?.(outHex[0])
@@ -2956,6 +3068,51 @@ export class Wcdb4Client {
}
)
})
if (result.success) return result
return (
(await this.getVoiceDataFromMediaShards(sessionId, createTime, candidates, localId, svrId)) || result
)
}
private async getVoiceDataFromMediaShards(
sessionId: string,
createTime: number,
candidates: string[],
localId: number,
svrId: string | number
): Promise<Wcdb4VoiceDataResult | null> {
if (!this.wcdbExecQuery || !sessionId) return null
const serverId = String(svrId || 0)
const identity = /^-?[1-9]\d*$/.test(serverId)
? `v.svr_id = ${serverId}`
: Number.isSafeInteger(localId) &&
localId > 0 &&
Number.isSafeInteger(createTime) &&
createTime > 0
? `v.local_id = ${localId} AND v.create_time = ${createTime}`
: ''
if (!identity) return null
const sessions = this.uniq([sessionId, ...candidates])
.map((name) => `'${name.replace(/'/g, "''")}'`)
.join(',')
const messageRoot = path.join(this.dbStoragePath, 'message')
if (!fs.existsSync(messageRoot)) return null
// 部分 native 版本漏读后续媒体分片;按完整消息身份查询,避免同秒语音串条。
const shards = fs.readdirSync(messageRoot).filter((file) => /^media_\d+\.db$/.test(file)).sort()
for (const name of shards) {
try {
const rows = await this.callJsonAsync<{ hex?: string }[]>(
this.wcdbExecQuery as unknown as KoffiAsyncFunction,
'message',
path.join(messageRoot, name),
`SELECT hex(v.voice_data) AS hex FROM VoiceInfo v JOIN Name2Id n ON n.rowid = v.chat_name_id WHERE n.user_name IN (${sessions}) AND ${identity} AND length(v.voice_data) > 0 LIMIT 1`
)
if (rows[0]?.hex) return { success: true, hex: rows[0].hex, error: '' }
} catch (error) {
console.warn(`[WCDB4] voice lookup failed in ${name}:`, error)
}
}
return null
}
async getVoiceDataBatch(requests: Wcdb4VoiceDataRequest[]): Promise<Wcdb4VoiceDataResult[]> {
@@ -3340,14 +3497,6 @@ export class Wcdb4Client {
this.wcdbMsgInsertGetSwitches = null
}
try {
this.wcdbMsgInsertListShardCatalog = lib.func(
'int32 wcdb_msg_insert_list_shard_catalog(int64 handle, _Out_ void** outJson)'
) as (handle: number, outJson: WcdbVoidOut) => number
} catch {
this.wcdbMsgInsertListShardCatalog = null
}
try {
this.wcdbGetGroupNicknames = lib.func(
'int32 wcdb_get_group_nicknames(int64 handle, const char* chatroomId, _Out_ void** outJson)'
@@ -3485,16 +3634,14 @@ export class Wcdb4Client {
}
static resolveNativeLibrary(): string {
const libName =
process.platform === 'darwin'
? 'libwcdb_api.dylib'
: process.platform === 'linux'
? 'libwcdb_api.so'
: 'wcdb_api.dll'
if (process.platform === 'darwin') {
const library = resolveWcdbLibrary()
if (library) return library
throw new Error('找不到当前发行版对应的 WCDB native 库')
}
const libName = process.platform === 'linux' ? 'libwcdb_api.so' : 'wcdb_api.dll'
const platformDir =
process.platform === 'darwin'
? 'macos'
: process.platform === 'win32'
process.platform === 'win32'
? 'win32'
: process.platform
const archDir = process.arch === 'arm64' ? 'arm64' : 'x64'
@@ -3571,7 +3718,10 @@ export class Wcdb4Client {
const outJson: WcdbVoidOut = [null]
const result = call(handle, outJson)
if (result !== 0 || !outJson[0]) {
throw new Error(`WCDB 调用失败,错误码: ${result}`)
if (isWcdbDebugEnabled()) {
console.warn(`[WCDB4] native query rc=${result} handle=${handle}`)
}
throw new NativeWcdbError(result)
}
try {
@@ -3593,7 +3743,10 @@ export class Wcdb4Client {
}
const code = Number(result)
if (code !== 0 || !outJson[0]) {
reject(new Error(`WCDB async call failed, code: ${code}`))
if (isWcdbDebugEnabled()) {
console.warn(`[WCDB4] native query(async) rc=${code} handle=${handle}`)
}
reject(new NativeWcdbError(code))
return
}
try {
+18 -3
View File
@@ -84,6 +84,13 @@ import type {
PersonalWechatVoiceDiagnostic
} from '../shared/personal-wechat'
import type { PersonalWechatSendCapability } from '../shared/personal-wechat'
import type { MacLicenseStatus } from '../shared/personal-wechat-mac-license'
import type {
MacWechatResidualCleanupResult,
MacWechatResidualProcess,
MacWechatRuntimeSnapshot,
MacWechatSendRuntimeAvailabilityResult
} from '../shared/personal-wechat-mac-runtime'
import type { GroupMemberStatsQuery, GroupMemberStatsResult } from '../shared/group-stats'
import type {
ScheduledReportExecution,
@@ -232,6 +239,8 @@ declare global {
downloadAppUpdate: () => Promise<AppUpdateCheckResult>
installAppUpdate: () => Promise<AppUpdateInstallResult>
openAppUpdateDownloadPage: () => Promise<AppUpdateOpenDownloadPageResult>
getIgnoredUpdateVersion: () => Promise<string>
setIgnoredUpdateVersion: (version: string | null) => Promise<string>
onAppUpdateState: (callback: (state: AppUpdateState) => void) => () => void
getCacheSummary: () => Promise<CacheSummary>
clearCache: (scope: CacheClearScope) => Promise<CacheSummary>
@@ -751,6 +760,14 @@ declare global {
repairImageTextIndex: () => Promise<ImageTextIndexRepairResult>
onImageTextIndexStatus: (callback: (status: ImageTextIndexStatus) => void) => () => void
getPersonalWechatSenderStatus: () => Promise<PersonalWechatSenderStatus>
getMacLicenseStatus: () => Promise<MacLicenseStatus>
getMacSendRuntimeAvailability: () => Promise<MacWechatSendRuntimeAvailabilityResult>
startMacSendRuntime: () => Promise<MacWechatRuntimeSnapshot>
listMacWechatResidualProcesses: () => Promise<MacWechatResidualProcess[]>
cleanupMacWechatResidualProcesses: (
targets: Array<Pick<MacWechatResidualProcess, 'pid' | 'confirmationToken'>>
) => Promise<MacWechatResidualCleanupResult>
refreshMacLicense: () => Promise<MacLicenseStatus>
getPersonalWechatSendCapability: () => Promise<PersonalWechatSendCapability>
checkPersonalWechatSenderStatus: (port?: string) => Promise<PersonalWechatSenderStatus>
checkPersonalWechatVoiceEncodingEnvironment: () => Promise<PersonalWechatVoiceEncodingEnvironment>
@@ -769,9 +786,7 @@ declare global {
ruleId: string
) => Promise<{ success: boolean; error?: string; data?: ScheduledRuleRunOutcome }>
/** 定时日报:旧执行记录**只读存档**(旧记录无法无损转换,原样展示)。 */
listScheduledReportLegacyExecutions: (
ruleId?: string
) => Promise<ScheduledReportExecution[]>
listScheduledReportLegacyExecutions: (ruleId?: string) => Promise<ScheduledReportExecution[]>
/** 定时日报:微信异常通知开关与能力检测。 */
getScheduledReportNotificationSettings: () => Promise<ScheduledReportNotificationSettings>
getScheduledReportNotificationCapability: () => Promise<ScheduledReportNotificationCapability>
+26
View File
@@ -14,6 +14,13 @@ import type {
SaveGeneratedReportRequest,
UpdateGeneratedReportTemplateRequest
} from '../shared/report-history'
import type { MacLicenseStatus } from '../shared/personal-wechat-mac-license'
import type {
MacWechatResidualCleanupResult,
MacWechatResidualProcess,
MacWechatRuntimeSnapshot,
MacWechatSendRuntimeAvailabilityResult
} from '../shared/personal-wechat-mac-runtime'
import type {
AIChatRequestOptions,
AiSearchExternalAuthorizationRequest,
@@ -135,6 +142,11 @@ const api = {
downloadAppUpdate: () => ipcRenderer.invoke('app-update:download'),
installAppUpdate: () => ipcRenderer.invoke('app-update:install'),
openAppUpdateDownloadPage: () => ipcRenderer.invoke('app-update:openDownloadPage'),
getIgnoredUpdateVersion: (): Promise<string> =>
ipcRenderer.invoke('app-update:getIgnoredVersion'),
/** 传 `null` 清除忽略记录并恢复启动提示;返回写入后的值(非法版本会被收敛成空串)。 */
setIgnoredUpdateVersion: (version: string | null): Promise<string> =>
ipcRenderer.invoke('app-update:setIgnoredVersion', version),
onAppUpdateState: (callback: (state: AppUpdateState) => void) => {
const listener = (_event: Electron.IpcRendererEvent, state: AppUpdateState): void =>
callback(state)
@@ -585,6 +597,20 @@ const api = {
},
getPersonalWechatSenderStatus: (): Promise<PersonalWechatSenderStatus> =>
ipcRenderer.invoke('wechat-personal:getStatus'),
getMacLicenseStatus: (): Promise<MacLicenseStatus> =>
ipcRenderer.invoke('wechat-personal:getMacLicenseStatus'),
getMacSendRuntimeAvailability: (): Promise<MacWechatSendRuntimeAvailabilityResult> =>
ipcRenderer.invoke('wechat-personal:getMacSendRuntimeAvailability'),
startMacSendRuntime: (): Promise<MacWechatRuntimeSnapshot> =>
ipcRenderer.invoke('wechat-personal:startMacSendRuntime'),
listMacWechatResidualProcesses: (): Promise<MacWechatResidualProcess[]> =>
ipcRenderer.invoke('wechat-personal:listMacResidualProcesses'),
cleanupMacWechatResidualProcesses: (
targets: Array<Pick<MacWechatResidualProcess, 'pid' | 'confirmationToken'>>
): Promise<MacWechatResidualCleanupResult> =>
ipcRenderer.invoke('wechat-personal:cleanupMacResidualProcesses', targets),
refreshMacLicense: (): Promise<MacLicenseStatus> =>
ipcRenderer.invoke('wechat-personal:refreshMacLicense'),
getPersonalWechatSendCapability: (): Promise<PersonalWechatSendCapability> =>
ipcRenderer.invoke('wechat-personal:getSendCapability'),
checkPersonalWechatSenderStatus: (port?: string): Promise<PersonalWechatSenderStatus> =>
@@ -136,8 +136,11 @@ export function DatabaseConnectionPage({
onClearKey
}: DatabaseConnectionPageProps): React.ReactElement {
const isMac = platform === 'darwin'
const isIntelMac = isMac && environment?.architecture === 'x64'
const isAppleSiliconMac = isMac && !isIntelMac
// 流程由主进程的 macKeyFlow 决定;只有旧版主进程不回传该字段时才回落到运行架构。
const macKeyFlow = environment?.macKeyFlow
const isArchMismatch = isMac && macKeyFlow === 'arch-mismatch'
const isIntelMac = isMac && (macKeyFlow ? macKeyFlow === 'intel' : environment?.architecture === 'x64')
const isAppleSiliconMac = isMac && !isIntelMac && !isArchMismatch
const defaultPath = isMac
? '~/Library/Containers/com.tencent.xinWeChat/Data/Library/Application Support/com.tencent.xinWeChat/'
: 'C:\\Users\\...\\WeChat Files\\Msg'
@@ -282,6 +285,21 @@ export function DatabaseConnectionPage({
</div>
{guideStep === 1 && (
<>
{isArchMismatch && (
<div className="database-login-arch-mismatch" role="alert">
<strong>当前电脑使用 Apple 芯片,但你正在运行 Intel 版 TraceMemo。</strong>
<p>这个版本无法使用当前的 Apple Silicon 自动获取密钥流程。</p>
<p>请下载并安装 arm64 版本,然后重新启动 TraceMemo。</p>
<p>已保存的微信数据库密钥无需重新获取。</p>
<a
href="https://github.com/Wxw-Gu/TraceMemo/releases"
target="_blank"
rel="noreferrer"
>
前往 GitHub Releases 下载 arm64 版本
</a>
</div>
)}
<dl className="database-login-diagnostics">
<div>
<dt>操作系统</dt>
@@ -420,7 +438,7 @@ export function DatabaseConnectionPage({
<Button
className="database-login-primary"
onClick={onGuideNext}
disabled={!selectedAccountId}
disabled={!selectedAccountId || isArchMismatch}
>
检查完成,继续
</Button>
@@ -446,7 +464,11 @@ export function DatabaseConnectionPage({
</Button>
)}
{guideStep === 3 && (
<Button className="database-login-primary" onClick={onAutoGetKey}>
<Button
className="database-login-primary"
onClick={onAutoGetKey}
disabled={isArchMismatch}
>
{isMac ? '开始获取密钥' : '开始准备连接组件'}
</Button>
)}
@@ -8,19 +8,20 @@ interface PersonalWechatSetupGuideProps {
binding: boolean
detecting: boolean
sessionBound: boolean
onBind: () => void
onStartSending: () => void
onBind?: () => void
onStartSending?: () => void
onOpenTextToSpeechSettings?: () => void
}
function capabilityLabel(ready: boolean, initializing: boolean): string {
if (ready) return '已就绪'
return initializing ? '初始化中' : '未就绪'
showBindAction?: boolean
showStartSendingAction?: boolean
showCapabilityStatus?: boolean
showBindingInstructionsInInitialization?: boolean
showAuthorizationWarning?: boolean
canBind?: boolean
}
function bindingHint(status: PersonalWechatSenderStatus): string {
if (status.state === 'wechat_not_running') {
return '请保持微信未登录窗口状态,点击“绑定微信”后,再点击微信窗口登录。'
return '4.1.13以下请保持微信未登录窗口状态,点击“绑定微信”后,再点击微信窗口登录。4.1.13以上登录状态微信直接点击“绑定微信”'
}
if (status.state === 'unsupported_platform') return '当前系统暂不支持个人微信发送。'
if (status.state === 'unsupported_version')
@@ -29,7 +30,7 @@ function bindingHint(status: PersonalWechatSenderStatus): string {
return '请先完成发送运行时准备。'
}
if (status.state === 'error') return '连接微信时遇到问题,请稍后重试。'
return '请保持微信未登录窗口状态,点击“绑定微信”后,再点击微信窗口登录。'
return '4.1.13以下请保持微信未登录窗口状态,点击“绑定微信”后,再点击微信窗口登录。4.1.13以上登录状态微信直接点击“绑定微信”'
}
function isWechatBound(status: PersonalWechatSenderStatus): boolean {
@@ -41,6 +42,11 @@ function isWechatBound(status: PersonalWechatSenderStatus): boolean {
)
}
function capabilityLabel(ready: boolean, initializing: boolean): string {
if (ready) return '已就绪'
return initializing ? '初始化中' : '未就绪'
}
export function PersonalWechatSetupGuide({
senderStatus,
binding,
@@ -48,7 +54,13 @@ export function PersonalWechatSetupGuide({
sessionBound,
onBind,
onStartSending,
onOpenTextToSpeechSettings
onOpenTextToSpeechSettings,
showBindAction = true,
showStartSendingAction = true,
showCapabilityStatus = true,
showBindingInstructionsInInitialization = false,
showAuthorizationWarning = true,
canBind = true
}: PersonalWechatSetupGuideProps): React.ReactElement {
const runtimeUnavailable = senderStatus?.state === 'runtime_missing'
const runtimeLabel = '发送运行时'
@@ -64,7 +76,7 @@ export function PersonalWechatSetupGuide({
<div>
<span className="personal-wechat-eyebrow">首次使用</span>
<h2>先准备好微信消息功能</h2>
<p>只需几步,TraceMemo 就能在当前会话中生成并发送语音。</p>
<p>只需几步,TraceMemo 就能具备微信消息发送能力。</p>
</div>
{allReady && <span className="personal-wechat-setup-complete">已完成</span>}
</div>
@@ -76,7 +88,7 @@ export function PersonalWechatSetupGuide({
<strong>准备 {runtimeLabel}</strong>
<p>
{runtimeUnavailable
? `个人微信发送需要${runtimeLabel},授权后即可使用。`
? '当前版本没有微信发送能力。'
: `${runtimeLabel}随 TraceMemo 一起提供,无需额外安装。`}
</p>
{runtimeReady ? (
@@ -89,68 +101,86 @@ export function PersonalWechatSetupGuide({
</div>
</li>
<li
className={
connected
? 'is-complete'
: binding
? 'is-active'
: runtimeReady
? 'is-current'
: 'is-pending'
}
>
<span className="personal-wechat-step-number">{connected ? '✓' : '2'}</span>
<div className="personal-wechat-step-content">
<strong>绑定个人微信</strong>
<p>请保持微信未登录窗口状态,点击“绑定微信”后,再点击微信窗口登录。</p>
{connected ? (
<span className="personal-wechat-step-status">✓ 微信已绑定</span>
) : (
<Button
size="sm"
variant="outline"
onClick={onBind}
disabled={runtimeUnavailable || !runtimeReady || binding}
>
{binding ? '正在绑定…' : '绑定微信'}
</Button>
)}
{!connected && senderStatus && !runtimeUnavailable && (
<p className="personal-wechat-step-hint">{bindingHint(senderStatus)}</p>
)}
{!connected && runtimeUnavailable && (
<div className="personal-wechat-authorization-warning" role="alert">
<span aria-hidden>!</span>
<p>
发送能力属授权制,需要联系群主。请先加入交流群,然后在群内添加群主申请授权。
进群请点击{' '}
<a href={GROUP_README_URL} target="_blank" rel="noreferrer">
这里
</a>{' '}
跳转。
</p>
</div>
)}
{!connected && !runtimeUnavailable && (
<p className="personal-wechat-step-warning" role="note">
绑定微信可能导致当前微信异常闪退,这是正常现象。若微信退出,请重新启动微信后,再回到这里重新检测/绑定。
{showBindAction ? (
<li
className={
connected
? 'is-complete'
: binding
? 'is-active'
: runtimeReady
? 'is-current'
: 'is-pending'
}
>
<span className="personal-wechat-step-number">{connected ? '✓' : '2'}</span>
<div className="personal-wechat-step-content">
<strong>绑定个人微信</strong>
<p>
4.1.13以下请保持微信未登录窗口状态,点击“绑定微信”后,再点击微信窗口登录。
<br />
微信总是自动更新?请在微信左下角打开“设置 →
通用”,取消勾选“有更新时自动升级微信”,否则版本变化后可能无法绑定。
4.1.13以上登录状态微信直接点击“绑定微信”
</p>
)}
</div>
</li>
{connected ? (
<span className="personal-wechat-step-status">✓ 微信已绑定</span>
) : (
<Button
size="sm"
variant="outline"
onClick={() => onBind?.()}
disabled={!canBind || runtimeUnavailable || !runtimeReady || binding}
>
{binding ? '正在绑定…' : '绑定微信'}
</Button>
)}
{!connected && senderStatus && !runtimeUnavailable ? (
<p className="personal-wechat-step-hint">{bindingHint(senderStatus)}</p>
) : null}
{!connected && runtimeUnavailable && showAuthorizationWarning ? (
<div className="personal-wechat-authorization-warning" role="alert">
<span aria-hidden>!</span>
<p>
发送能力属授权制,需要联系群主。请先加入交流群,然后在群内添加群主申请授权。
进群请点击{' '}
<a href={GROUP_README_URL} target="_blank" rel="noreferrer">
这里
</a>{' '}
跳转。
</p>
</div>
) : null}
{!connected && !runtimeUnavailable ? (
<p className="personal-wechat-step-warning" role="note">
绑定微信可能导致当前微信异常闪退,这是正常现象。若微信退出,请重新启动微信后,再回到这里重新检测/绑定。
<br />
微信总是自动更新?请在微信左下角打开“设置 →
通用”,取消勾选“有更新时自动升级微信”,否则版本变化后可能无法绑定。
</p>
) : null}
</div>
</li>
) : null}
<li className={allReady ? 'is-complete' : connected ? 'is-current' : 'is-pending'}>
<span className="personal-wechat-step-number">{allReady ? '✓' : '3'}</span>
<span className="personal-wechat-step-number">
{allReady ? '✓' : showBindAction ? '3' : '2'}
</span>
<div className="personal-wechat-step-content">
<strong>初始化发送能力</strong>
<p>绑定微信后,TraceMemo 会自动完成文字、图片和语音发送所需的初始化。</p>
<p>每个微信进程只能绑定一次</p>
{showBindingInstructionsInInitialization && (
<>
<p>4.1.13以下请保持微信未登录窗口状态,点击“绑定微信”后,再点击微信窗口登录。</p>
<p>4.1.13以上登录状态微信直接点击“绑定微信”</p>
</>
)}
{initializing && (
<p className="personal-wechat-step-hint" role="status">
{detecting ? '正在初始化发送能力…' : '正在等待发送运行时完成初始化…'}
{detecting
? '正在初始化发送能力…'
: runtimeReady
? '微信已绑定,正在等待发送能力完成初始化…'
: '正在等待发送运行时完成初始化…'}
</p>
)}
{senderStatus?.state === 'error' && (
@@ -161,37 +191,43 @@ export function PersonalWechatSetupGuide({
</div>
</li>
<li className={allReady ? 'is-complete' : initializing ? 'is-current' : 'is-pending'}>
<span className="personal-wechat-step-number">{allReady ? '✓' : '4'}</span>
<div className="personal-wechat-step-content">
<strong>能力检测</strong>
<div className="personal-wechat-capabilities" aria-label="微信消息能力">
{[
['文字消息', Boolean(senderStatus?.canSendText)],
['图片消息', Boolean(senderStatus?.canSendImage)],
['语音消息', canSendVoice]
].map(([label, ready]) => (
<span key={String(label)} className={ready ? 'is-ready' : ''}>
<b aria-hidden>{ready ? '✓' : '−'}</b>
{label}
<small>{capabilityLabel(Boolean(ready), initializing)}</small>
</span>
))}
{showCapabilityStatus ? (
<li className={allReady ? 'is-complete' : initializing ? 'is-current' : 'is-pending'}>
<span className="personal-wechat-step-number">
{allReady ? '✓' : showBindAction ? '4' : '3'}
</span>
<div className="personal-wechat-step-content">
<strong>能力检测</strong>
<div className="personal-wechat-capabilities" aria-label="微信消息能力">
{[
['文字消息', Boolean(senderStatus?.canSendText)],
['图片消息', Boolean(senderStatus?.canSendImage)],
['语音消息', canSendVoice]
].map(([label, ready]) => (
<span key={String(label)} className={ready ? 'is-ready' : ''}>
<b aria-hidden>{ready ? '✓' : '−'}</b>
{label}
<small>{capabilityLabel(Boolean(ready), initializing)}</small>
</span>
))}
</div>
{allReady ? (
<>
<span className="personal-wechat-step-status">微信消息发送已配置完成</span>
{showStartSendingAction && (
<Button size="sm" onClick={() => onStartSending?.()}>
开始发送
</Button>
)}
</>
) : initializing ? (
<p className="personal-wechat-step-hint" role="status">
发送能力准备完成后会自动进入已就绪状态。
</p>
) : null}
</div>
{allReady ? (
<>
<span className="personal-wechat-step-status">微信消息发送已配置完成</span>
<Button size="sm" onClick={onStartSending}>
开始发送
</Button>
</>
) : initializing ? (
<p className="personal-wechat-step-hint" role="status">
发送能力准备完成后会自动进入已就绪状态。
</p>
) : null}
</div>
</li>
</li>
) : null}
</ol>
{!runtimeReady && runtimeUnavailable && onOpenTextToSpeechSettings && (
@@ -1,4 +1,4 @@
import { useState } from 'react'
import { useEffect, useState } from 'react'
import {
AlertDialog,
AlertDialogAction,
@@ -21,14 +21,53 @@ export function AppUpdatePrompt({
}): React.ReactElement {
const update = useAppUpdateState()
const [dismissedVersion, setDismissedVersion] = useState<string>()
/**
* 已忽略的版本号。`null` 表示还没读回来 —— 这期间不弹,否则用户会看到
* 弹窗闪一下就消失(启动时状态先到、设置后到)。
*/
const [ignoredVersion, setIgnoredVersion] = useState<string | null>(null)
useEffect(() => {
let active = true
void window.api
.getIgnoredUpdateVersion()
.then((version) => {
if (active) setIgnoredVersion(version || '')
})
.catch(() => {
// 读不到就按"没有忽略"处理:宁可多弹一次,也不要静默吞掉更新提示。
if (active) setIgnoredVersion('')
})
return () => {
active = false
}
}, [])
const shouldPrompt =
update.status === 'available' &&
update.source === 'startup' &&
Boolean(update.version) &&
ignoredVersion !== null &&
update.version !== ignoredVersion &&
update.version !== dismissedVersion
const dismiss = (): void => setDismissedVersion(update.version)
const ignoreVersion = async (): Promise<void> => {
const version = update.version
if (!version) return
setIgnoredVersion(version)
dismiss()
try {
await window.api.setIgnoredUpdateVersion(version)
onNotice(`已忽略 v${version} 的更新提示,可在「设置 → 关于」恢复`)
} catch (error) {
// 没写进磁盘就当作没忽略,否则用户以为设置生效了,下次启动照样弹。
setIgnoredVersion('')
onNotice(error instanceof Error ? error.message : '忽略更新提示失败')
}
}
const continueUpdate = async (): Promise<void> => {
dismiss()
if (update.delivery === 'release-page') {
@@ -55,6 +94,9 @@ export function AppUpdatePrompt({
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<Button variant="ghost" className="sm:mr-auto" onClick={() => void ignoreVersion()}>
忽略此版本
</Button>
<AlertDialogCancel asChild>
<Button variant="outline" onClick={dismiss}>
取消
@@ -122,7 +122,7 @@ export function MessageInsertSwitches(): React.JSX.Element {
/** 把结果里的失败原因翻成人话;native code 只进日志。 */
const humanize = React.useCallback((result: MsgInsertApplyResult): string => {
const status = result.status
if (result.errorCode === 'HELPER_NOT_FOUND') return '缺少写入组件,请重新安装或更新 TraceMemo'
if (result.errorCode === 'HELPER_NOT_FOUND') return '缺少发送能力组件,请重新安装或更新 TraceMemo'
if (result.errorCode === 'DATABASE_UNAVAILABLE') return '微信数据库未连接'
if (result.errorCode === 'NO_TARGET_ROOMS') return '没有可作用的目标会话'
if (status && status.failedShards > 0) {
@@ -174,29 +174,61 @@ export function MessageInsertSwitches(): React.JSX.Element {
[humanize, pending, refresh, toast]
)
/*
* helper 缺失时**提前**禁用,而不是等用户点了再弹「缺少写入组件」。
* 写开关必须靠那个一次性子进程,缺了它这个开关根本没法工作 ——
* 让人点了才失败是最差的一种交互。
*/
/*
* 写入组件缺失 = **这个能力还没开放**,不是安装坏了。
*
* 主进程对微信库只有只读连接,任何写入都要 spawn 那个一次性写入组件;当前分发的
* 安装包不带它(它随发送运行时按需分发),所以「微信内防撤回提示」与
* 「微信内退群监控消息」一律按"下个版本开放"呈现 —— 不该让用户去排查自己的安装。
* (machine-readable 的原因仍然是 snapshot.helperAvailable,授权层可以据此判断。)
*/
/* 开启要全绿,关闭永远放行——授权过期后关不掉比开不了更糟。 */
const capability = snapshot?.capability
const helperMissing = snapshot?.helperAvailable === false
const blocked = blockedReason ?? (helperMissing ? '该能力将在下个版本开放' : null)
const disabled = blocked !== null
const noticeForEnable = ((): string | null => {
if (capability) {
if (capability.canEnable) return blockedReason ?? null
switch (capability.reasonCode) {
case 'LICENSE_REQUIRED':
return '需要有效授权才能开启'
case 'LICENSE_PENDING':
return '授权正在验证,稍等片刻再试'
case 'LICENSE_EXPIRED':
return '授权已过期,重新激活后可开启'
case 'LICENSE_INVALID':
return '授权无效,请重新激活'
case 'LICENSE_MACHINE_MISMATCH':
return '这份授权不属于本机'
case 'LICENSE_REVOKED':
return '授权已被吊销'
case 'LICENSE_UNAVAILABLE':
return '暂时无法确认授权状态'
case 'COMPONENT_MISSING':
return '当前安装未包含发送能力组件'
case 'COMPONENT_INVALID':
return '发送能力组件不完整,请重新安装'
case 'DATABASE_UNAVAILABLE':
return '微信数据库尚未连接'
case 'UNSUPPORTED_PLATFORM':
return '当前版本不包含此能力'
default:
return capability.message || null
}
}
if (helperMissing) return '该能力暂不可用'
return blockedReason ?? null
})()
const anyEnabled = MSG_INSERT_SWITCH_LABELS.some(
({ name }) => snapshot?.switches?.[name]?.desiredEnabled === true
)
/* 顶部只给「想开但开不了」的场景一条总提示,避免每个开关重复一遍 */
const capabilityNotice = noticeForEnable && !anyEnabled ? noticeForEnable : null
return (
<div className="automation-msg-insert-switches" title={blocked ?? undefined}>
<div className="automation-msg-insert-switches" title={capabilityNotice ?? undefined}>
{capabilityNotice ? <p className="automation-notice warning" role="status">{capabilityNotice}</p> : null}
{loading ? <Spinner /> : null}
{MSG_INSERT_SWITCH_LABELS.map(({ name, label, hint }) => {
const status: MsgInsertSwitchStatus | undefined = snapshot?.switches?.[name]
const busy = pending === name
const desired = status?.desiredEnabled === true
/* 已开启 → 允许关;未开启 → 必须满足开启条件 */
const switchNotice = desired ? null : noticeForEnable
const switchDisabled = pending !== null || (!desired && switchNotice !== null)
/* rules 型:显示「已就绪 / 可安装」;事件驱动型没有覆盖率这个概念。 */
const showCoverage = status?.mode === 'rules' && status.totalInstallableRooms > 0
const partial =
@@ -214,8 +246,8 @@ export function MessageInsertSwitches(): React.JSX.Element {
于是「点文字」也会切换开关。写微信库的开关不该这么容易被误触。 */
<span
key={name}
className={`automation-msg-insert-switch ${disabled ? 'is-disabled' : ''}`}
title={[hint, status?.message].filter(Boolean).join('\n') || blocked || hint}
className={`automation-msg-insert-switch ${switchDisabled ? 'is-disabled' : ''}`}
title={[hint, status?.message, switchNotice].filter(Boolean).join('\n') || hint}
>
<span className="automation-msg-insert-switch-label">{label}</span>
{/* 写微信库要 spawn 子进程 + 装规则,耗时以秒计。
@@ -227,8 +259,8 @@ export function MessageInsertSwitches(): React.JSX.Element {
</span>
) : null}
<Switch
checked={status?.desiredEnabled === true}
disabled={disabled || pending !== null}
checked={desired}
disabled={switchDisabled}
onCheckedChange={(checked) => void handleToggle(name, checked === true)}
aria-label={label}
/>
@@ -25,8 +25,11 @@ export function DatabaseKeyAutoDetect({
const environment = state.environment
const platform = environment?.platform || runtimePlatform
const isMac = platform === 'darwin'
const isIntelMac = platform === 'darwin' && environment?.architecture === 'x64'
const isAppleSiliconMac = isMac && !isIntelMac
// 与连接页同源:读主进程给出的 macKeyFlow,不在这里重新推断硬件。
const macKeyFlow = environment?.macKeyFlow
const isArchMismatch = isMac && macKeyFlow === 'arch-mismatch'
const isIntelMac = isMac && (macKeyFlow ? macKeyFlow === 'intel' : environment?.architecture === 'x64')
const isAppleSiliconMac = isMac && !isIntelMac && !isArchMismatch
const supported = environment?.autoDetectSupported ?? (platform === 'win32' || isMac)
const phases = isAppleSiliconMac ? MAC_LOGIN_PHASES : DEFAULT_PHASES
if (!supported) {
@@ -41,20 +44,43 @@ export function DatabaseKeyAutoDetect({
}
return (
<section className="settings-card database-key-auto">
{isArchMismatch && (
<div className="database-login-arch-mismatch" role="alert">
<strong>当前电脑使用 Apple 芯片,但你正在运行 Intel 版 TraceMemo。</strong>
<p>这个版本无法使用当前的 Apple Silicon 自动获取密钥流程。</p>
<p>请下载并安装 arm64 版本,然后重新启动 TraceMemo。</p>
<p>已保存的微信数据库密钥无需重新获取。</p>
<a href="https://github.com/Wxw-Gu/TraceMemo/releases" target="_blank" rel="noreferrer">
前往 GitHub Releases 下载 arm64 版本
</a>
</div>
)}
<div className="database-key-auto-heading">
<div>
<strong>
{isIntelMac ? 'Intel Mac 自动获取' : isMac ? 'macOS 自动获取' : 'Windows 自动获取'}
{isArchMismatch
? '架构不匹配'
: isIntelMac
? 'Intel Mac 自动获取'
: isMac
? 'macOS 自动获取'
: 'Windows 自动获取'}
</strong>
<p>
{isIntelMac
? '请让微信停在未登录界面,按页面提示操作即可。'
: isAppleSiliconMac
? '执行时会请求管理员授权;授权后在微信登录界面点击“登录”即可,已有登录凭据时通常不需要扫码。监听最长两分钟,结束后会明确显示结果。'
: 'TraceMemo 可在微信桌面端正在运行时,通过本机内存扫描尝试获取数据库密钥。'}
{isArchMismatch
? '当前应用的运行架构与这台 Mac 的芯片不匹配,自动获取已停用。'
: isIntelMac
? '请让微信停在未登录界面,按页面提示操作即可。'
: isAppleSiliconMac
? '执行时会请求管理员授权;授权后在微信登录界面点击“登录”即可,已有登录凭据时通常不需要扫码。监听最长两分钟,结束后会明确显示结果。'
: 'TraceMemo 可在微信桌面端正在运行时,通过本机内存扫描尝试获取数据库密钥。'}
</p>
</div>
<Button variant="outline" onClick={onDetect} disabled={disabled}>
<Button
variant="outline"
onClick={onDetect}
disabled={disabled || isArchMismatch}
>
{state.status === 'auto-detecting' ? '正在获取…' : '自动获取密钥'}
</Button>
</div>
@@ -1,4 +1,4 @@
import { useMemo, useState } from 'react'
import { useEffect, useMemo, useState } from 'react'
import { Button, Progress } from '../../../components/ui'
import { useAppUpdateState } from '../../app-update/useAppUpdateState'
@@ -19,6 +19,30 @@ export function AboutPage({
}): React.ReactElement {
const update = useAppUpdateState()
const [busy, setBusy] = useState(false)
const [ignoredUpdateVersion, setIgnoredUpdateVersion] = useState('')
useEffect(() => {
let active = true
void window.api
.getIgnoredUpdateVersion()
.then((version) => {
if (active) setIgnoredUpdateVersion(version || '')
})
.catch(() => undefined)
return () => {
active = false
}
}, [])
const restoreUpdatePrompt = async (): Promise<void> => {
try {
await window.api.setIgnoredUpdateVersion(null)
setIgnoredUpdateVersion('')
onNotice('已恢复启动时的更新提示')
} catch (error) {
onNotice(error instanceof Error ? error.message : '恢复更新提示失败')
}
}
const action = useMemo(() => {
if (update.status === 'available') {
@@ -153,6 +177,20 @@ export function AboutPage({
</div>
</section>
{ignoredUpdateVersion ? (
<section className="settings-card flex flex-wrap items-center justify-between gap-3">
<div>
<strong>已忽略 v{ignoredUpdateVersion} 的更新提示</strong>
<span className="mt-1 block text-sm text-muted-foreground">
该版本不会在启动时弹窗;更高版本仍会提醒。
</span>
</div>
<Button variant="outline" size="sm" onClick={() => void restoreUpdatePrompt()}>
恢复提示
</Button>
</section>
) : null}
<h2 className="settings-section-heading">支持</h2>
<section className="settings-card about-links-card">
<a href={RELEASES_URL} target="_blank" rel="noreferrer">
@@ -1,9 +1,27 @@
import { useCallback, useEffect, useState, type ReactElement } from 'react'
import { useCallback, useEffect, useRef, useState, type ReactElement } from 'react'
import type {
PersonalWechatSendCapability,
PersonalWechatSenderStatus
} from '../../../../../shared/personal-wechat'
import { Button, Input, Skeleton } from '../../../components/ui'
import type {
MacLicenseState,
MacLicenseStatus
} from '../../../../../shared/personal-wechat-mac-license'
import type { MacWechatSendRuntimeAvailabilityResult } from '../../../../../shared/personal-wechat-mac-runtime'
import { resolveMacSendPrimaryAction } from '../../../../../shared/personal-wechat-mac-send-action'
import {
AlertDialog,
AlertDialogAction,
AlertDialogCancel,
AlertDialogContent,
AlertDialogDescription,
AlertDialogFooter,
AlertDialogHeader,
AlertDialogTitle,
Button,
Input,
Skeleton
} from '../../../components/ui'
import { PersonalWechatSetupGuide } from '../../../components/chat/PersonalWechatSetupGuide'
import { isMac, isWindows } from '../../../utils/runtime-environment'
@@ -27,6 +45,15 @@ function normalizeWindowsPort(value: string): string | null {
return Number.isInteger(port) && port >= 1 && port <= 65_535 ? String(port) : null
}
function getEndpointPort(endpoint: string | undefined): string | null {
if (!endpoint) return null
try {
return new URL(endpoint).port || null
} catch {
return null
}
}
function boundToCurrentWechat(status: PersonalWechatSenderStatus | null): boolean {
if (!status) return false
return (
@@ -60,6 +87,208 @@ function SendCapabilityAuthorizationCard(): ReactElement {
)
}
const macLicenseStateLabel: Record<MacLicenseState, string> = {
unlicensed: '当前设备暂无发送能力授权',
valid: '已授权',
cached: '授权有效(本地缓存)',
expired: '授权已过期',
revoked: '授权已撤销',
device_mismatch: '授权与当前设备不匹配',
identity_error: '设备身份异常',
server_unavailable: '授权服务器不可用',
checking: '检测中…',
unsupported: '发送组件版本较旧',
runtime_missing: '发送组件未运行',
platform_unsupported: '当前构建不支持'
}
const macLicenseFeatureLabel: Record<string, string> = {
basic: '基础功能',
wechat: '微信发送',
advanced: '高级功能',
api: 'API 接口'
}
function licenseTone(state: MacLicenseState): string {
if (state === 'valid' || state === 'cached') return 'is-ready'
if (state === 'revoked' || state === 'expired' || state === 'identity_error') return 'is-error'
return 'is-neutral'
}
function licenseStateConflictsWithExpiry(license: MacLicenseStatus): boolean {
const expiresAt = license.licenseExpiresAt ? Date.parse(license.licenseExpiresAt) : NaN
return license.state === 'expired' && Number.isFinite(expiresAt) && expiresAt > Date.now()
}
function macLicenseStatusLabel(license: MacLicenseStatus): string {
if (license.state === 'valid' || license.state === 'cached') return '设备已授权'
if (licenseStateConflictsWithExpiry(license)) return '授权状态需刷新'
return macLicenseStateLabel[license.state]
}
function macLicenseStatusTone(license: MacLicenseStatus): string {
return licenseStateConflictsWithExpiry(license) ? 'is-neutral' : licenseTone(license.state)
}
function macLicenseStatusHint(license: MacLicenseStatus): string {
if (licenseStateConflictsWithExpiry(license)) {
return '当前授权状态与到期日不一致,请点击「重新检测授权」更新状态。'
}
return '将设备 ID 提供给授权管理员,完成授权后点击「重新检测授权」。'
}
function formatMacLicenseDateTime(iso: string | null): string {
if (!iso) return '—'
const parsed = new Date(iso)
if (Number.isNaN(parsed.getTime())) return iso
return parsed.toLocaleString('zh-CN', {
year: 'numeric',
month: '2-digit',
day: '2-digit',
hour: '2-digit',
minute: '2-digit'
})
}
function formatMacLicenseDate(iso: string | null): string {
if (!iso) return '—'
const parsed = new Date(iso)
if (Number.isNaN(parsed.getTime())) return iso
return parsed.toLocaleDateString('zh-CN', {
year: 'numeric',
month: '2-digit',
day: '2-digit'
})
}
function summarizeDeviceId(deviceId: string): string {
return deviceId.length === 68 ? `${deviceId.slice(0, 12)}…${deviceId.slice(-6)}` : deviceId
}
/** 展示当前设备的授权状态,并提供刷新与复制设备 ID 的操作。 */
export function MacNativeLicenseCard({
onNotice,
onStatusChange
}: {
onNotice: (message: string) => void
onStatusChange: (status: MacLicenseStatus) => void
}): ReactElement {
const [license, setLicense] = useState<MacLicenseStatus | null>(null)
const [refreshing, setRefreshing] = useState(false)
const [copied, setCopied] = useState(false)
const load = useCallback(async (): Promise<void> => {
try {
const next = await window.api.getMacLicenseStatus()
setLicense(next)
onStatusChange(next)
} catch {
setLicense(null)
}
}, [onStatusChange])
useEffect(() => {
void load()
}, [load])
const refresh = async (): Promise<void> => {
if (refreshing) return
setRefreshing(true)
try {
const next = await window.api.refreshMacLicense()
setLicense(next)
onStatusChange(next)
if (next.authorized) {
onNotice('授权检测完成:已授权')
} else {
onNotice(next.message || '授权检测完成')
}
} catch (reason) {
onNotice(reason instanceof Error ? reason.message : '授权检测失败')
} finally {
setRefreshing(false)
}
}
const copyDeviceId = async (): Promise<void> => {
if (!license?.deviceId) return
try {
await navigator.clipboard.writeText(license.deviceId)
setCopied(true)
onNotice('设备 ID 已复制')
window.setTimeout(() => setCopied(false), 2_000)
} catch {
onNotice('复制失败,请手动选择设备 ID 复制')
}
}
if (!license) {
return <Skeleton className="h-24 w-full" />
}
// OSS 构建走到这里(platform_unsupported)时不渲染卡片,保证免费版不出现授权入口。
if (license.state === 'platform_unsupported') {
return <></>
}
return (
<section className="settings-card mac-native-license-card" aria-label="发送能力授权">
<header className="mac-native-license-header">
<strong>发送能力授权</strong>
<span className={`mac-native-license-status ${macLicenseStatusTone(license)}`}>
{macLicenseStatusLabel(license)}
</span>
</header>
<div className="mac-native-device-row">
<div className="mac-native-device-value">
<span>本机设备 ID</span>
<code title={license.deviceId || undefined}>
{license.deviceId ? summarizeDeviceId(license.deviceId) : '(尚未生成)'}
</code>
</div>
<Button
variant="ghost"
size="sm"
disabled={!license.deviceId}
aria-label="复制完整设备 ID"
onClick={() => void copyDeviceId()}
>
{copied ? '已复制' : '复制'}
</Button>
</div>
{license.deviceId && (!license.authorized || licenseStateConflictsWithExpiry(license)) ? (
<p className="mac-native-license-hint">{macLicenseStatusHint(license)}</p>
) : null}
{license.authorized && license.features.length > 0 ? (
<div className="mac-native-license-features" aria-label="已开通功能">
{license.features.map((feature) => (
<span key={feature}>{macLicenseFeatureLabel[feature] || feature}</span>
))}
</div>
) : null}
<div className="mac-native-license-meta">
<span>
授权到期 <strong>{formatMacLicenseDate(license.licenseExpiresAt)}</strong>
</span>
<span>
最近检测 <strong>{formatMacLicenseDateTime(license.lastCheckedAt)}</strong>
</span>
</div>
<div className="mac-native-license-footer">
<span />
<Button
variant="outline"
size="sm"
disabled={refreshing || license.state === 'unsupported'}
onClick={() => void refresh()}
>
{refreshing ? '检测中…' : '重新检测授权'}
</Button>
</div>
</section>
)
}
export function PersonalWechatSendPage({
onNotice,
onOpenTextToSpeechSettings
@@ -79,6 +308,37 @@ export function PersonalWechatSendPage({
const [windowsPortInput, setWindowsPortInput] = useState('')
const [windowsDetectedPort, setWindowsDetectedPort] = useState('')
const [windowsEndpointBusy, setWindowsEndpointBusy] = useState(false)
const [setupExpanded, setSetupExpanded] = useState<boolean | null>(null)
const [macLicenseStatus, setMacLicenseStatus] = useState<MacLicenseStatus | null>(null)
const [macRuntimeAvailability, setMacRuntimeAvailability] =
useState<MacWechatSendRuntimeAvailabilityResult | null>(null)
const [macResidualProcesses, setMacResidualProcesses] = useState<
Awaited<ReturnType<typeof window.api.listMacWechatResidualProcesses>>
>([])
const [macResidualDialogOpen, setMacResidualDialogOpen] = useState(false)
const [macResidualBusy, setMacResidualBusy] = useState(false)
const [macResidualRuntimeStopped, setMacResidualRuntimeStopped] = useState(false)
const [macWechatRebindRequired, setMacWechatRebindRequired] = useState(false)
const [mac4290PortStatus, setMac4290PortStatus] = useState<
| { state: 'loading' | 'available' | 'error'; processes: [] }
| { state: 'occupied'; processes: Array<{ pid: number; name: string }> }
>({ state: 'loading', processes: [] })
const setupDefaultInitialized = useRef(false)
const refreshMac4290PortStatus = useCallback(async (): Promise<void> => {
try {
const processes = await window.api.listMacWechatResidualProcesses()
const listeners = processes
.filter((process) => process.targets.includes('port_4290'))
.map(({ pid, name }) => ({ pid, name }))
setMac4290PortStatus(
listeners.length > 0
? { state: 'occupied', processes: listeners }
: { state: 'available', processes: [] }
)
} catch {
setMac4290PortStatus({ state: 'error', processes: [] })
}
}, [])
const refresh = useCallback(async (): Promise<void> => {
if (isWindows) {
setLoading(false)
@@ -101,9 +361,68 @@ export function PersonalWechatSendPage({
useEffect(() => {
if (isWindows) return
void refresh()
let active = true
const loadMacStatus = async (): Promise<void> => {
try {
const availability = await window.api.getMacSendRuntimeAvailability()
if (!active) return
setMacRuntimeAvailability(availability)
if (availability.state !== 'available') {
setSenderStatus({
state: 'runtime_missing',
platform: 'darwin',
arch: 'arm64',
sipDisabled: true,
wechatRunning: false,
endpoint: '',
endpointReady: false,
runtimeReady: false,
attachReady: false,
baseAddressReady: false,
textHookInstalled: false,
textHookReady: false,
imageHookInstalled: false,
imageHookReady: false,
messageListenerReady: false,
canSend: false,
canSendText: false,
canSendImage: false,
canSendVoice: false,
message: availability.message,
error: availability.message
})
setLoading(false)
return
}
const [nextCapability, nextSender, license] = await Promise.all([
window.api.getPersonalWechatSendCapability(),
window.api.getPersonalWechatSenderStatus(),
window.api.getMacLicenseStatus()
])
if (!active) return
setCapability(nextCapability)
setSenderStatus(nextSender)
setMacLicenseStatus(license)
} catch (reason) {
if (!active) return
setError(reason instanceof Error ? reason.message : '微信发送能力读取失败')
} finally {
if (active) setLoading(false)
}
}
void loadMacStatus()
return () => {
active = false
}
}, [refresh])
useEffect(() => {
if (!isMac) return undefined
void refreshMac4290PortStatus()
const timer = window.setInterval(() => void refreshMac4290PortStatus(), 5_000)
return () => window.clearInterval(timer)
}, [refreshMac4290PortStatus])
useEffect(() => {
if (isWindows || !senderStatus || senderStatus.canSend || senderStatus.state === 'error') {
return undefined
@@ -148,6 +467,9 @@ export function PersonalWechatSendPage({
try {
const nextStatus = await window.api.rebindPersonalWechatSender()
setSenderStatus(nextStatus)
if (boundToCurrentWechat(nextStatus)) {
setMacWechatRebindRequired(false)
}
const nextCapability = await window.api.getPersonalWechatSendCapability()
setCapability(nextCapability)
if (nextStatus.state === 'error' && nextStatus.message) setError(nextStatus.message)
@@ -172,6 +494,99 @@ export function PersonalWechatSendPage({
}
}
const inspectMacResidualProcesses = async (): Promise<void> => {
if (macResidualBusy) return
setMacResidualBusy(true)
try {
const targets = await window.api.listMacWechatResidualProcesses()
setMacResidualProcesses(targets)
const listeners = targets
.filter((process) => process.targets.includes('port_4290'))
.map(({ pid, name }) => ({ pid, name }))
setMac4290PortStatus(
listeners.length > 0
? { state: 'occupied', processes: listeners }
: { state: 'available', processes: [] }
)
if (targets.length === 0) {
onNotice('没有发现微信进程或占用 4290 端口的进程')
return
}
setMacResidualDialogOpen(true)
} catch (reason) {
onNotice(reason instanceof Error ? reason.message : '读取残留进程失败')
} finally {
setMacResidualBusy(false)
}
}
const cleanupMacResidualProcesses = async (): Promise<void> => {
if (macResidualBusy || macResidualProcesses.length === 0) return
setMacResidualBusy(true)
try {
const result = await window.api.cleanupMacWechatResidualProcesses(
macResidualProcesses.map(({ pid, confirmationToken }) => ({ pid, confirmationToken }))
)
if (result.runtimeStopped) setMacResidualRuntimeStopped(true)
if (result.stopped.some((target) => target.targets.includes('wechat'))) {
setMacWechatRebindRequired(true)
}
if (result.stopped.length === 0) {
if (result.remaining.length > 0) {
setMacResidualProcesses(result.remaining)
onNotice('进程状态已变化,请核对更新后的清理目标。')
return
}
setMacResidualDialogOpen(false)
setMacResidualProcesses([])
await refreshMac4290PortStatus()
await refresh()
onNotice('目标进程已退出,发送环境状态已刷新。')
return
}
if (result.remaining.length > 0) {
setMacResidualProcesses(result.remaining)
onNotice(
'已结束 ' +
result.stopped.length +
' 个进程,仍有 ' +
result.remaining.length +
' 个;请核对后重试。'
)
} else {
setMacResidualDialogOpen(false)
setMacResidualProcesses([])
}
await refreshMac4290PortStatus()
await refresh()
if (result.remaining.length === 0) {
onNotice('已结束 ' + result.stopped.length + ' 个残留进程;发送环境状态已刷新。')
}
} catch (reason) {
onNotice(reason instanceof Error ? reason.message : '清理残留进程失败')
} finally {
setMacResidualBusy(false)
}
}
const restartMacSendRuntime = async (): Promise<void> => {
if (macResidualBusy) return
setMacResidualBusy(true)
try {
const snapshot = await window.api.startMacSendRuntime()
if (snapshot.lifecycle !== 'online') {
throw new Error(snapshot.error || '发送组件启动失败')
}
setMacResidualRuntimeStopped(false)
await refresh()
onNotice('发送组件已启动;如刚才关闭了微信,请重新打开微信并绑定。')
} catch (reason) {
onNotice(reason instanceof Error ? reason.message : '发送组件启动失败')
} finally {
setMacResidualBusy(false)
}
}
const normalizedWindowsPort = normalizeWindowsPort(windowsPortInput)
const windowsCanSave = Boolean(
normalizedWindowsPort &&
@@ -266,7 +681,28 @@ export function PersonalWechatSendPage({
const pageMessage = isWindows
? windowsSenderStatus?.message || '请输入端口并检测 Windows 微信发送能力'
: capability?.message || '微信发送能力暂不可用'
const macUnavailable = isMac && senderStatus?.state === 'runtime_missing'
const macUnavailable = isMac && macRuntimeAvailability?.state === 'unavailable'
const macComponentError = isMac && macRuntimeAvailability?.state === 'component_error'
const macBound = boundToCurrentWechat(senderStatus)
const macSendPort = getEndpointPort(senderStatus?.endpoint)
const macEnvironmentReady = Boolean(
senderStatus?.runtimeReady && macBound && senderStatus.canSend
)
useEffect(() => {
if (isMac && senderStatus && !setupDefaultInitialized.current) {
setSetupExpanded(!macEnvironmentReady)
setupDefaultInitialized.current = true
}
}, [macEnvironmentReady, senderStatus])
const setupBodyId = 'personal-wechat-first-use-setup'
const macPrimaryAction = resolveMacSendPrimaryAction({
runtime: macRuntimeAvailability,
license: macLicenseStatus,
senderStatus,
binding,
detecting: loading || detecting
})
return (
<>
@@ -279,7 +715,13 @@ export function PersonalWechatSendPage({
<span
className={`settings-status-badge ${loading ? 'checking' : pageReady ? '' : pageStatus === 'unsupported' ? 'unavailable' : 'warning'}`}
>
{loading ? '检测中' : macUnavailable ? '暂不可用' : capabilityLabel[pageStatus]}
{loading
? '检测中'
: macUnavailable
? '没有微信发送能力'
: macComponentError
? '发送组件异常'
: capabilityLabel[pageStatus]}
</span>
</header>
<div className="settings-page-scroll">
@@ -407,18 +849,194 @@ export function PersonalWechatSendPage({
</>
) : isMac ? (
<>
<h2 className="settings-section-heading">配置状态</h2>
<PersonalWechatSetupGuide
senderStatus={senderStatus}
binding={binding}
detecting={detecting}
sessionBound={boundToCurrentWechat(senderStatus)}
onBind={() => void bindWechat()}
onStartSending={() =>
onNotice('微信消息发送能力已就绪,请在档案中选择会话开始发送。')
}
onOpenTextToSpeechSettings={onOpenTextToSpeechSettings}
/>
{/* 发送能力授权卡片:仅在加载了发送组件的档位渲染。
OSS(runtime_missing)下不渲染,保证免费版不出现授权入口。 */}
{macRuntimeAvailability?.state === 'available' ? (
<MacNativeLicenseCard
onNotice={onNotice}
onStatusChange={setMacLicenseStatus}
/>
) : null}
<section
className="settings-card mac-wechat-environment-card"
aria-label="微信发送环境"
>
<header className="mac-wechat-environment-header">
<strong>微信发送环境</strong>
<span
className={`mac-wechat-environment-status ${macEnvironmentReady ? 'is-ready' : 'is-neutral'}`}
>
{loading
? '正在检查环境'
: macUnavailable
? '当前版本没有微信发送能力'
: macComponentError
? '发送组件缺失或异常'
: macEnvironmentReady
? '运行环境已就绪'
: '需要完成配置'}
</span>
</header>
<div className="mac-wechat-status-grid" aria-label="环境状态">
{[
['运行时正常', Boolean(senderStatus?.runtimeReady)],
['微信已绑定', macBound],
['发送组件正常', Boolean(senderStatus?.canSend)]
].map(([label, complete]) => (
<div className="mac-wechat-status-item" key={String(label)}>
<span
className={complete ? 'is-ready' : 'is-pending'}
aria-hidden="true"
>
{complete ? '✓' : '○'}
</span>
<strong>{label}</strong>
<small>{loading ? '检测中' : complete ? '正常' : '待完成'}</small>
</div>
))}
</div>
{macSendPort && senderStatus?.endpointReady ? (
<p
className="mt-3 rounded-md border border-border-subtle p-3 text-sm"
role="status"
>
当前发送能力占用端口为 {macSendPort}(TM_WECHAT_HOST_PORT)。
</p>
) : null}
<section
className="mt-4 flex flex-wrap items-center justify-between gap-2 rounded-md border border-border-subtle p-3"
aria-label="4290 端口状态"
>
<div>
<strong className="text-sm">4290 端口</strong>
<p className="mt-1 text-sm text-muted-foreground" role="status">
{mac4290PortStatus.state === 'loading'
? '正在检查占用状态…'
: mac4290PortStatus.state === 'error'
? '占用状态读取失败'
: mac4290PortStatus.state === 'available'
? '未被占用'
: '已被占用:' +
mac4290PortStatus.processes
.map(({ name, pid }) => name + '(PID ' + pid + ')')
.join('、')}
</p>
</div>
<Button
size="sm"
variant="outline"
disabled={macResidualBusy}
onClick={() => void refreshMac4290PortStatus()}
>
刷新端口状态
</Button>
</section>
{macWechatRebindRequired ? (
<div
className="mt-3 rounded-md border border-amber-500/40 bg-amber-500/10 p-3 text-sm"
role="status"
>
微信进程已清理。请重新打开微信,然后点击“绑定微信”;绑定完成后此提示会自动消失。
</div>
) : null}
{senderStatus && macRuntimeAvailability?.state === 'available' ? (
<div
className="mac-wechat-capability-details"
aria-label="文字、图片和语音能力"
>
{(
[
['文字', senderStatus.canSendText],
['图片', senderStatus.canSendImage],
['语音', senderStatus.canSendVoice]
] as const
).map(([label, available]) => (
<span key={label} className={available ? 'is-ready' : 'is-pending'}>
{label} {available ? '可用' : '未就绪'}
</span>
))}
</div>
) : null}
<button
type="button"
className="mac-wechat-setup-toggle"
aria-expanded={setupExpanded ?? !macEnvironmentReady}
aria-controls={setupBodyId}
onClick={() =>
setSetupExpanded((expanded) => !(expanded ?? !macEnvironmentReady))
}
>
<span>首次使用配置</span>
<span className="mac-wechat-setup-chevron" aria-hidden="true">
⌄
</span>
</button>
<div
id={setupBodyId}
className="mac-wechat-setup-content"
hidden={!(setupExpanded ?? !macEnvironmentReady)}
>
{macRuntimeAvailability?.state === 'available' ? (
<PersonalWechatSetupGuide
senderStatus={senderStatus}
binding={binding}
detecting={detecting}
sessionBound={macBound}
showBindAction={false}
showCapabilityStatus={false}
showBindingInstructionsInInitialization
showAuthorizationWarning={false}
canBind={macPrimaryAction.action === 'bind'}
onStartSending={() =>
onNotice('微信消息发送能力已就绪,请在档案中选择会话开始发送。')
}
showStartSendingAction={false}
onOpenTextToSpeechSettings={onOpenTextToSpeechSettings}
/>
) : null}
</div>
<div className="mac-wechat-primary-action">
<Button
className="w-full"
disabled={macPrimaryAction.disabled}
onClick={() => {
if (macPrimaryAction.action === 'bind') {
void bindWechat()
} else if (macPrimaryAction.action === 'send') {
onNotice('微信消息发送能力已就绪,请在档案中选择会话开始发送。')
} else if (!macPrimaryAction.disabled) {
setSetupExpanded(true)
}
}}
>
{macPrimaryAction.label}
</Button>
<Button
className="mt-2 w-full"
variant="outline"
disabled={macResidualBusy}
onClick={() => void inspectMacResidualProcesses()}
>
{macResidualBusy ? '检查中…' : '清理残留以及微信进程'}
</Button>
{macResidualRuntimeStopped ? (
<Button
className="mt-2 w-full"
variant="outline"
disabled={macResidualBusy}
onClick={() => void restartMacSendRuntime()}
>
{macResidualBusy ? '启动中…' : '重新启动发送组件'}
</Button>
) : null}
</div>
</section>
{macUnavailable ? (
<>
<h2 className="settings-section-heading">发送能力授权</h2>
<SendCapabilityAuthorizationCard />
</>
) : null}
</>
) : null}
</>
@@ -426,6 +1044,43 @@ export function PersonalWechatSendPage({
</div>
</div>
</div>
<AlertDialog open={macResidualDialogOpen} onOpenChange={setMacResidualDialogOpen}>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>清理微信残留进程?</AlertDialogTitle>
<AlertDialogDescription>
将结束下面列出的微信进程或占用 4290
端口的进程。若列表包含微信,微信会关闭;如曾绑定发送组件,之后需要重新打开微信并绑定。
</AlertDialogDescription>
</AlertDialogHeader>
<ul className="grid gap-2 rounded-md border border-border-subtle p-3 text-sm">
{macResidualProcesses.map((item) => (
<li key={item.pid} className="flex justify-between gap-4">
<span className="break-all">{item.name}</span>
<span className="shrink-0 text-muted-foreground">
PID {item.pid} ·{' '}
{item.targets
.map((target) => (target === 'wechat' ? '微信进程' : '4290 端口'))
.join('、')}
</span>
</li>
))}
</ul>
<AlertDialogFooter>
<AlertDialogCancel disabled={macResidualBusy}>取消</AlertDialogCancel>
<AlertDialogAction
className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
disabled={macResidualBusy}
onClick={(event) => {
event.preventDefault()
void cleanupMacResidualProcesses()
}}
>
{macResidualBusy ? '清理中…' : '确认结束进程'}
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
</>
)
}
+30
View File
@@ -2158,6 +2158,36 @@
word-break: break-word;
}
.database-login-arch-mismatch {
margin: 0 0 16px;
padding: 14px 16px;
border: 1px solid #f0c9a8;
border-radius: 10px;
background: #fff7ef;
color: #6b4a2f;
font-size: 12px;
line-height: 1.6;
}
.database-login-arch-mismatch strong {
display: block;
margin-bottom: 6px;
color: #8a4b12;
font-size: 13px;
}
.database-login-arch-mismatch p {
margin: 0 0 4px;
}
.database-login-arch-mismatch a {
display: inline-block;
margin-top: 8px;
color: #8a4b12;
font-weight: 600;
text-decoration: underline;
}
.database-login-diagnostics {
margin: 0;
border-top: 1px solid #e2e7e4;
+242
View File
@@ -249,6 +249,248 @@
background: var(--wxex-bg-elevated);
padding: 24px 26px;
}
.mac-native-license-card,
.mac-wechat-environment-card {
display: grid;
gap: 14px;
min-width: 0;
padding: 20px 22px;
}
.mac-native-license-header,
.mac-wechat-environment-header {
display: flex;
min-width: 0;
align-items: center;
justify-content: space-between;
gap: 12px;
> strong {
color: var(--wxex-text-primary);
font-size: 15px;
font-weight: 650;
}
}
.mac-native-license-status,
.mac-wechat-environment-status {
flex: 0 0 auto;
color: var(--wxex-text-secondary);
font-size: 12px;
}
.mac-native-license-status.is-ready,
.mac-wechat-environment-status.is-ready,
.mac-wechat-status-item .is-ready,
.mac-wechat-capability-details .is-ready {
color: var(--wxex-success);
}
.mac-native-license-status.is-error {
color: var(--wxex-danger);
}
.mac-native-license-status.is-neutral,
.mac-wechat-environment-status.is-neutral {
color: var(--wxex-text-muted);
}
.mac-native-device-row {
display: flex;
min-width: 0;
align-items: center;
gap: 10px;
border-radius: var(--wxex-radius-md);
background: color-mix(in srgb, var(--wxex-text-primary) 4%, transparent);
padding: 10px 12px;
}
.mac-native-device-value {
display: grid;
min-width: 0;
flex: 1;
gap: 4px;
> span {
color: var(--wxex-text-muted);
font-size: 11px;
}
code {
overflow: hidden;
color: var(--wxex-text-primary);
font-size: 13px;
text-overflow: ellipsis;
white-space: nowrap;
}
}
.mac-native-license-hint {
margin: -5px 0 0;
color: var(--wxex-text-secondary);
font-size: 12px;
}
.mac-native-license-features {
display: flex;
flex-wrap: wrap;
gap: 6px;
> span {
border-radius: 999px;
background: color-mix(in srgb, var(--wxex-text-primary) 5%, transparent);
padding: 3px 8px;
color: var(--wxex-text-secondary);
font-size: 11px;
}
}
.mac-native-license-meta {
display: flex;
flex-wrap: wrap;
gap: 8px 24px;
color: var(--wxex-text-muted);
font-size: 11px;
strong {
margin-left: 4px;
color: var(--wxex-text-secondary);
font-weight: 550;
}
}
.mac-native-license-footer {
display: flex;
min-width: 0;
align-items: center;
justify-content: space-between;
gap: 12px;
}
.mac-native-identity-note {
margin: 0;
}
.mac-wechat-status-grid {
display: grid;
grid-template-columns: repeat(3, minmax(0, 1fr));
gap: 8px;
}
.mac-wechat-status-item {
display: grid;
min-width: 0;
justify-items: center;
gap: 5px;
border-radius: var(--wxex-radius-md);
background: color-mix(in srgb, var(--wxex-text-primary) 3%, transparent);
padding: 12px 8px;
text-align: center;
> span {
font-size: 18px;
line-height: 1;
}
.is-pending {
color: var(--wxex-text-muted);
}
strong {
color: var(--wxex-text-primary);
font-size: 12px;
font-weight: 550;
}
small {
color: var(--wxex-text-muted);
font-size: 10px;
}
}
.mac-wechat-capability-details {
display: flex;
flex-wrap: wrap;
gap: 6px 14px;
color: var(--wxex-text-muted);
font-size: 11px;
.is-pending {
color: var(--wxex-text-muted);
}
}
.mac-wechat-setup-toggle {
display: flex;
width: 100%;
align-items: center;
justify-content: space-between;
gap: 12px;
border: 0;
border-top: 1px solid var(--wxex-border);
background: transparent;
padding: 12px 0 0;
color: var(--wxex-text-primary);
cursor: pointer;
font: inherit;
font-size: 13px;
font-weight: 600;
text-align: left;
&:focus-visible {
border-radius: 4px;
outline: 2px solid var(--wxex-brand);
outline-offset: 3px;
}
}
.mac-wechat-setup-chevron {
color: var(--wxex-text-muted);
font-size: 18px;
transition: transform 160ms ease;
}
.mac-wechat-setup-toggle[aria-expanded='true'] .mac-wechat-setup-chevron {
transform: rotate(180deg);
}
.mac-wechat-setup-content {
min-width: 0;
&[hidden] {
display: none;
}
.personal-wechat-setup {
gap: 12px;
border: 0;
padding: 2px 0 0;
}
.personal-wechat-setup-heading h2,
.personal-wechat-eyebrow {
display: none;
}
}
.mac-wechat-primary-action {
padding-top: 2px;
}
@media (prefers-reduced-motion: reduce) {
.mac-wechat-setup-chevron {
transition: none;
}
}
@media (max-width: 560px) {
.mac-native-license-card,
.mac-wechat-environment-card {
padding: 16px;
}
.mac-native-license-header,
.mac-wechat-environment-header {
align-items: flex-start;
flex-direction: column;
gap: 4px;
}
.mac-wechat-status-grid {
gap: 5px;
}
.mac-wechat-status-item {
padding: 10px 4px;
strong {
font-size: 10px;
}
}
.mac-native-license-meta {
flex-direction: column;
gap: 5px;
}
}
.settings-account-overview {
display: grid;
grid-template-columns: minmax(190px, 1fr) minmax(220px, 1fr) auto;
+7
View File
@@ -7,6 +7,13 @@ export function buildSafeDiagnosticSummary(
`TraceMemo: ${environment.appVersion}`,
`操作系统: ${environment.osVersion}`,
...(environment.architecture ? [`处理器架构: ${environment.architecture}`] : []),
...(environment.hardwareArchitecture
? [
`硬件架构: ${environment.hardwareArchitecture}${
environment.underARM64Translation ? '(Rosetta 转译)' : ''
}`
]
: []),
`微信客户端: ${environment.wechatVersion}`,
`数据结构: ${environment.dataStructureVersion}`,
`数据目录: ${environment.dataDirectoryDetected ? '已检测到' : '未检测到'}`,
+17
View File
@@ -1,3 +1,5 @@
import type { MacHardwareArch, MacKeyFlow } from './macos-arch'
export type DatabaseKeyValidationCode =
| 'INVALID_FORMAT'
| 'DATABASE_OPEN_FAILED'
@@ -66,7 +68,22 @@ export interface AccountDiscoveryResult {
export interface DatabaseKeyEnvironment {
platform: NodeJS.Platform
/**
* 进程运行架构(`process.arch`)。原生库按它选择,不要用硬件架构替换:
* Rosetta 下的 x64 进程无法加载 arm64 动态库。
*/
architecture?: string
/** CPU 实际架构,来自 `hw.optional.arm64`。 */
hardwareArchitecture?: MacHardwareArch
/** 当前进程是否被 Rosetta 翻译。 */
underARM64Translation?: boolean
/**
* 密钥流程的唯一判据。UI 读它,主进程分流也读它,避免两侧各自推断。
* 缺省时 UI 回落到 `architecture`,用于主进程尚未提供该字段的场景。
*/
macKeyFlow?: MacKeyFlow
/** 架构信号矛盾时的诊断标记,例如 `hardware_arch_unknown`。 */
archAnomalies?: string[]
osVersion: string
appVersion: string
wechatVersion: string
+80
View File
@@ -0,0 +1,80 @@
/**
* macOS 硬件架构与密钥流程的判定规则。
*
* 三个概念必须分开,混用会把 Apple Silicon 上的 x64 运行时当成 Intel 机器:
*
* - hardwareArch CPU 实际架构,来自 `hw.optional.arm64`
* - runtimeArch 当前 Electron 可执行文件的架构(`process.arch`)
* - underARM64Translation 该进程是否被 Rosetta 翻译
*
* 密钥流程只能由这三者共同决定;原生库加载仍然只看 runtimeArch,
* 因为同一进程内不能混用 arm64 与 x86_64 代码。
*/
export type MacHardwareArch = 'arm64' | 'x64' | 'unknown'
export type MacKeyFlow = 'apple-silicon' | 'intel' | 'arch-mismatch' | 'unsupported'
export interface MacArchSnapshot {
platform: NodeJS.Platform
hardwareArch: MacHardwareArch
runtimeArch: string
underARM64Translation: boolean
macKeyFlow: MacKeyFlow
/** 检测到的矛盾信号,仅用于诊断上报,不参与流程选择。 */
anomalies: string[]
}
export interface MacArchInput {
platform: NodeJS.Platform
hardwareArch: MacHardwareArch
runtimeArch: string
underARM64Translation: boolean
}
export const ARCH_MISMATCH_X64_ON_ARM_ERROR =
'当前 Mac 使用 Apple 芯片,但 TraceMemo 正在运行 Intel 版本。请安装 Apple Silicon(arm64)版本后重试。'
/**
* 判定顺序有约束,不能调整:
*
* 1. 转译标志排在 sysctl 之前 —— 它由内核按当前进程直接给出,比一次外部命令更可信。
* 即使 sysctl 失败(hardwareArch 为 unknown),只要进程被翻译且运行 x64,
* 硬件就必然是 Apple 芯片,必须拦下。
* 2. 硬件明确为 arm64 时,即使转译标志缺失,也不能走 Intel 流程 ——
* 那等于在 Apple 芯片上装 Intel 运行环境。
* 3. 只有硬件为 x64 或无法确认、且未经转译的 x64 进程,才允许走 Intel 流程。
* 无法确认时保留兼容路径,避免无故阻断真正的 Intel Mac。
*/
export function resolveMacKeyFlow(input: MacArchInput): MacKeyFlow {
if (input.platform !== 'darwin') return 'unsupported'
if (input.runtimeArch === 'arm64') return 'apple-silicon'
if (input.runtimeArch !== 'x64') return 'unsupported'
if (input.underARM64Translation) return 'arch-mismatch'
if (input.hardwareArch === 'arm64') return 'arch-mismatch'
return 'intel'
}
/**
* Intel 运行环境探测要起一个 x86 子进程,只在真正的 Intel Mac 上才有意义。
* 其它流程(尤其 `arch-mismatch`)一律跳过,避免刷新连接页就拉起错误的 helper。
*/
export function shouldProbeIntelEnvironment(flow: MacKeyFlow): boolean {
return flow === 'intel'
}
export function buildMacArchSnapshot(input: MacArchInput): MacArchSnapshot {
const anomalies: string[] = []
if (input.hardwareArch === 'unknown') anomalies.push('hardware_arch_unknown')
if (input.runtimeArch === 'arm64' && input.underARM64Translation) {
anomalies.push('translation_flag_with_native_arm64')
}
if (input.runtimeArch === 'x64' && input.hardwareArch === 'arm64' && !input.underARM64Translation) {
// 硬件是 ARM、进程是 x64、却无转译标志:信号矛盾。流程仍按 arch-mismatch,
// 这个名字只用于诊断,不参与判定。
anomalies.push('x64_runtime_on_arm_without_translation_flag')
}
if (input.runtimeArch === 'x64' && input.underARM64Translation && input.hardwareArch !== 'arm64') {
anomalies.push('translation_flag_without_arm_hardware')
}
return { ...input, macKeyFlow: resolveMacKeyFlow(input), anomalies }
}
+53 -6
View File
@@ -104,12 +104,56 @@ export interface MsgInsertSwitchStatus {
message?: string
}
/** 授权状态(与「能不能发消息」无关) */
export type EntitlementState = 'valid' | 'invalid' | 'pending' | 'unavailable' | 'unsupported'
/** 发送能力组件状态 */
export type NativeComponentState = 'ready' | 'missing' | 'invalid' | 'incompatible'
/**
* 发送能力被拒的原因。**不要用 HELPER_NOT_FOUND 表达授权问题** ——
* 那会让「没装组件」「没授权」「发不了消息」三种情况在界面上无法区分。
*/
export type CapabilityReasonCode =
| 'CAPABILITY_READY'
| 'UNSUPPORTED_PLATFORM'
| 'LICENSE_REQUIRED'
| 'LICENSE_PENDING'
| 'LICENSE_EXPIRED'
| 'LICENSE_INVALID'
| 'LICENSE_MACHINE_MISMATCH'
| 'LICENSE_REVOKED'
| 'LICENSE_UNAVAILABLE'
| 'COMPONENT_MISSING'
| 'COMPONENT_INVALID'
| 'DATABASE_UNAVAILABLE'
/** 主进程算好的发送能力视图,渲染层只读这个,不再自己判断 */
export interface CapabilityView {
entitlementState: EntitlementState
nativeComponentState: NativeComponentState
databaseReady: boolean
canEnable: boolean
canDisable: boolean
reasonCode: CapabilityReasonCode
message: string
licenseStatus?: string
checkedAt?: number
}
export interface MsgInsertSwitchesSnapshot {
success: boolean
switches: Record<MsgInsertSwitchName, MsgInsertSwitchStatus>
/** helper 是否可用(不可用时只能读不能写) */
/** 原生发送能力(授权 + 组件 + 数据库),两个开关共用 */
capability?: CapabilityView
/**
* **能力标志**:本机是否存在「微信内消息写入组件」(那个一次性 helper)。
* @deprecated 语义漂移过:曾等于「这是不是 mac native 包」,在 Windows 上恒为 true。
* 新代码请用 `capability.canEnable`;这里只留一个与它一致的值给旧调用方。
*/
sendCapabilityAvailable?: boolean
switches: Record<MsgInsertSwitchName, MsgInsertSwitchStatus>
/** 发送能力组件是否可用(不可用时只能读不能写) */
/**
* **能力标志**:本机是否存在「微信内发送能力组件」。
*
* 这是「微信内防撤回提示」和「微信内退群监控消息」的**唯一硬门槛**:
* 主进程对微信库只持只读连接,任何写入都必须 spawn 那个组件,没有它两个功能都做不了。
@@ -117,9 +161,7 @@ export interface MsgInsertSwitchesSnapshot {
* 语义上它是 **capability(能力)**,不是 error(错误)——
* 缺失时 UI 显示「暂无法使用」,而不是「请重新安装」。
*
* ⚠️ 它是**唯一**的能力判据,不要再新增第二份(曾经因为 native 与 TS 各存一份判据
* 而出现 946 里莫名少 323 的假象)。将来的授权/付费门禁应当**并列**加在它旁边
* (capability && entitlement),而不是替换它。
* 它是组件能力判据;授权状态应与其并列,不能替换它。
*/
helperAvailable: boolean
/** native code 只放这里,不往 UI 上抛 */
@@ -152,6 +194,11 @@ export type MsgInsertErrorCode =
| 'UNSUPPORTED_SWITCH'
| 'NO_TARGET_ROOMS'
| 'DATABASE_UNAVAILABLE'
| 'LICENSE_REQUIRED'
| 'LICENSE_PENDING'
| 'LICENSE_EXPIRED'
| 'COMPONENT_MISSING'
| 'CAPABILITY_UNAVAILABLE'
| 'UNKNOWN'
/** 界面上要展示的两个开关(顺序即展示顺序) */
+149
View File
@@ -0,0 +1,149 @@
/**
* macOS 设备授权接口的 wire 类型。
* 所有字段都由 `parseMacLicenseStatus` 运行时校验后才会交给上层使用。
*/
export type MacLicenseState =
| 'unlicensed' // no license for this device
| 'valid' // online check passed in this process
| 'cached' // local cache verified, not re-confirmed online
| 'expired'
| 'revoked'
| 'device_mismatch' // token belongs to a different device
| 'identity_error' // device key unusable
| 'server_unavailable' // network / 5xx; cache may still hold
| 'checking' // an online refresh is in flight
| 'unsupported' // host is running but has no /license endpoints (old build)
| 'runtime_missing' // host not reachable / runtime absent
| 'platform_unsupported' // not macOS native (Windows / OSS)
const MAC_LICENSE_STATES = new Set<MacLicenseState>([
'unlicensed',
'valid',
'cached',
'expired',
'revoked',
'device_mismatch',
'identity_error',
'server_unavailable',
'checking',
'unsupported',
'runtime_missing',
'platform_unsupported'
])
export interface MacLicenseStatus {
deviceId: string | null
state: MacLicenseState
authorized: boolean
source: 'online' | 'cache' | 'none'
features: string[]
lastCheckedAt: string | null
licenseExpiresAt: string | null
tokenExpiresAt: string | null
message: string
/** False when the running host predates the license endpoints (404). */
runtimeProtocolSupported?: boolean
/** Host-reported numeric TM_WECHAT_* code when a refresh failed. */
errorCode?: number | null
}
const DEVICE_ID_PATTERN = /^mac_[0-9a-f]{64}$/
function asOptionalString(value: unknown): string | null {
return typeof value === 'string' && value.length > 0 ? value : null
}
function asOptionalIsoDate(value: unknown): string | null {
if (typeof value !== 'string' || value.length === 0) return null
// Accept RFC3339 (what the native core emits); reject obvious garbage.
if (!/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}/.test(value)) return null
return value
}
function asStringArray(value: unknown): string[] {
if (!Array.isArray(value)) return []
return value.filter((entry): entry is string => typeof entry === 'string')
}
/**
* 把任意 JSON 校验成 MacLicenseStatus;无法确认的字段一律落到安全默认值。
* `authorized` 由 state 重算,伪造的 `authorized: true` 覆盖不了已撤销状态。
*/
export function parseMacLicenseStatus(raw: unknown): MacLicenseStatus {
const base: MacLicenseStatus = {
deviceId: null,
state: 'unlicensed',
authorized: false,
source: 'none',
features: [],
lastCheckedAt: null,
licenseExpiresAt: null,
tokenExpiresAt: null,
message: '当前设备暂无发送能力授权'
}
if (raw === null || typeof raw !== 'object') return base
const record = raw as Record<string, unknown>
const deviceId = asOptionalString(record.deviceId)
if (deviceId !== null && DEVICE_ID_PATTERN.test(deviceId)) {
base.deviceId = deviceId
}
const state = asOptionalString(record.state)
if (state !== null && MAC_LICENSE_STATES.has(state as MacLicenseState)) {
base.state = state as MacLicenseState
}
const source = asOptionalString(record.source)
if (source === 'online' || source === 'cache' || source === 'none') {
base.source = source
}
base.features = asStringArray(record.features)
base.lastCheckedAt = asOptionalIsoDate(record.lastCheckedAt)
base.licenseExpiresAt = asOptionalIsoDate(record.licenseExpiresAt)
base.tokenExpiresAt = asOptionalIsoDate(record.tokenExpiresAt)
const message = asOptionalString(record.message)
if (message !== null) base.message = message
if (typeof record.runtimeProtocolSupported === 'boolean') {
base.runtimeProtocolSupported = record.runtimeProtocolSupported
}
if (typeof record.errorCode === 'number' && Number.isFinite(record.errorCode)) {
base.errorCode = record.errorCode
}
/*
* authorized is DERIVED, not copied: only a small whitelist of states may
* present as authorized, and even then the payload's own boolean must agree.
* This keeps a forged {"authorized": true} from flipping a revoked state.
*/
const trustedStates: ReadonlySet<MacLicenseState> = new Set(['valid', 'cached'])
base.authorized = trustedStates.has(base.state) && record.authorized === true
return base
}
/**
* Build the "runtime missing / old host" status without a network round-trip.
* Used when the host is down or answered 404 on /license/status.
*/
export function offlineMacLicenseStatus(
state: 'runtime_missing' | 'unsupported' | 'platform_unsupported' | 'server_unavailable',
message: string
): MacLicenseStatus {
return {
deviceId: null,
state,
authorized: false,
source: 'none',
features: [],
lastCheckedAt: null,
licenseExpiresAt: null,
tokenExpiresAt: null,
message,
runtimeProtocolSupported: state === 'unsupported' ? false : undefined
}
}
+30 -2
View File
@@ -15,6 +15,26 @@ export type MacWechatRuntimeLifecycle =
| 'crashed_unbound' // died while unbound — safe to auto-restart
| 'crashed_bound' // died while bound — WeChat keeps an orphan agent
export type MacWechatSendRuntimeAvailability = 'unavailable' | 'component_error' | 'available'
export interface MacWechatSendRuntimeAvailabilityResult {
state: MacWechatSendRuntimeAvailability
message: string
}
export interface MacWechatResidualProcess {
pid: number
name: string
targets: Array<'wechat' | 'port_4290'>
confirmationToken: string
}
export interface MacWechatResidualCleanupResult {
stopped: MacWechatResidualProcess[]
remaining: MacWechatResidualProcess[]
runtimeStopped: boolean
}
export type MacWechatHostRuntimeState =
| 'not_initialized'
| 'wechat_not_running'
@@ -45,6 +65,16 @@ export interface MacWechatRuntimeManifest {
addressProfileSha256: string
supportedWechatVersions: string[]
capabilities: Array<'text' | 'image' | 'voice'>
capabilitiesByVersion?: Record<
string,
{
text?: 'verified' | 'addresses-only' | 'unsupported'
image?: 'verified' | 'addresses-only' | 'unsupported'
voice?: 'verified' | 'addresses-only' | 'unsupported'
downloadImage?: 'verified' | 'addresses-only' | 'unsupported'
textMechanism?: string
}
>
}
export interface MacWechatBindingStatus {
@@ -60,7 +90,6 @@ export interface MacWechatBindingStatus {
wechatPid: number
wechatVersion?: string
supported: boolean
supportedVersions?: string
bindingState: MacWechatBindingState
bound: boolean
boundWechatPid: number
@@ -82,7 +111,6 @@ export interface MacWechatRuntimeSnapshot {
endpoint: string
port: number
runtimeDir?: string
manifest?: MacWechatRuntimeManifest
error?: string
binding?: MacWechatBindingStatus
}
@@ -0,0 +1,103 @@
import type { MacLicenseStatus } from './personal-wechat-mac-license'
import type { MacWechatSendRuntimeAvailabilityResult } from './personal-wechat-mac-runtime'
import type { PersonalWechatSenderStatus } from './personal-wechat'
export type MacSendPrimaryActionKind = 'none' | 'bind' | 'send'
export interface MacSendPrimaryAction {
label: string
disabled: boolean
loading: boolean
action: MacSendPrimaryActionKind
reason:
| 'runtime_unavailable'
| 'runtime_error'
| 'license_pending'
| 'license_invalid'
| 'license_feature_denied'
| 'binding'
| 'unbound'
| 'initializing'
| 'ready'
}
export function hasValidWechatLicense(license: MacLicenseStatus | null): boolean {
if (
!license ||
!license.authorized ||
(license.state !== 'valid' && license.state !== 'cached') ||
!license.features.includes('wechat')
) {
return false
}
const tokenExpiresAt = license.tokenExpiresAt ? Date.parse(license.tokenExpiresAt) : Number.NaN
return Number.isFinite(tokenExpiresAt) && tokenExpiresAt > Date.now()
}
export function resolveMacSendPrimaryAction(input: {
runtime: MacWechatSendRuntimeAvailabilityResult | null
license: MacLicenseStatus | null
senderStatus: PersonalWechatSenderStatus | null
binding: boolean
detecting: boolean
}): MacSendPrimaryAction {
const { runtime, license, senderStatus, binding, detecting } = input
const result = (
label: string,
disabled: boolean,
loading: boolean,
action: MacSendPrimaryActionKind,
reason: MacSendPrimaryAction['reason']
): MacSendPrimaryAction => ({ label, disabled, loading, action, reason })
if (!runtime || (detecting && !senderStatus)) {
return result('正在检查发送组件…', true, true, 'none', 'runtime_error')
}
if (runtime.state === 'unavailable') {
return result('当前版本没有微信发送能力', true, false, 'none', 'runtime_unavailable')
}
if (runtime.state === 'component_error') {
return result('发送组件缺失或异常', true, false, 'none', 'runtime_error')
}
if (license === null) {
return result('正在检测授权…', true, true, 'none', 'license_pending')
}
if (license.state === 'valid' || license.state === 'cached') {
if (license.authorized && !license.features.includes('wechat')) {
return result('未开通微信发送', true, false, 'none', 'license_feature_denied')
}
if (hasValidWechatLicense(license)) {
if (binding) return result('正在绑定…', true, true, 'none', 'binding')
const bound = Boolean(
senderStatus &&
(senderStatus.state === 'online' ||
Boolean(
senderStatus.wechatPid &&
senderStatus.boundWechatPid === senderStatus.wechatPid &&
senderStatus.attachReady &&
senderStatus.baseAddressReady
))
)
if (!bound) return result('绑定微信', false, false, 'bind', 'unbound')
if (senderStatus?.canSend) return result('开始发送', false, false, 'send', 'ready')
return result('正在准备发送能力…', true, detecting, 'none', 'initializing')
}
}
const bound = Boolean(
senderStatus &&
(senderStatus.state === 'online' ||
Boolean(
senderStatus.wechatPid &&
senderStatus.boundWechatPid === senderStatus.wechatPid &&
senderStatus.attachReady &&
senderStatus.baseAddressReady
))
)
return result(
bound ? '授权后可开始发送' : '授权后可绑定微信',
true,
false,
'none',
'license_invalid'
)
}
+93 -1
View File
@@ -16,13 +16,18 @@ const api = {
updateListener = listener
return vi.fn()
}),
revealAppLog: vi.fn()
revealAppLog: vi.fn(),
getIgnoredUpdateVersion: vi.fn(async () => ''),
setIgnoredUpdateVersion: vi.fn(async (version: string | null) => version ?? '')
}
describe('app update UI', () => {
beforeEach(() => {
vi.clearAllMocks()
updateListener = undefined
// clearAllMocks 不清实现,逐个用例重设,避免上一条的"已忽略版本"串到下一题。
api.getIgnoredUpdateVersion.mockResolvedValue('')
api.setIgnoredUpdateVersion.mockImplementation(async (version: string | null) => version ?? '')
Object.defineProperty(window, 'api', { configurable: true, value: api })
})
@@ -54,6 +59,93 @@ describe('app update UI', () => {
)
})
it('stays quiet on startup for a version the user already ignored', async () => {
api.getAppUpdateState.mockResolvedValue({
status: 'available',
currentVersion: '1.9.0',
delivery: 'automatic',
version: '2.0.0',
source: 'startup',
isSimulation: true
})
api.getIgnoredUpdateVersion.mockResolvedValue('2.0.0')
render(<AppUpdatePrompt onDownloadStart={vi.fn()} onNotice={vi.fn()} />)
await waitFor(() => expect(api.getIgnoredUpdateVersion).toHaveBeenCalled())
await act(async () => {
await Promise.resolve()
})
expect(screen.queryByRole('alertdialog', { name: '发现新版本 v2.0.0' })).not.toBeInTheDocument()
})
it('prompts again once a newer version supersedes the ignored one', async () => {
api.getAppUpdateState.mockResolvedValue({
status: 'available',
currentVersion: '1.9.0',
delivery: 'automatic',
version: '2.1.0',
source: 'startup',
isSimulation: true
})
api.getIgnoredUpdateVersion.mockResolvedValue('2.0.0')
render(<AppUpdatePrompt onDownloadStart={vi.fn()} onNotice={vi.fn()} />)
await screen.findByRole('alertdialog', { name: '发现新版本 v2.1.0' })
})
it('persists the ignored version and closes the prompt immediately', async () => {
const user = userEvent.setup()
api.getAppUpdateState.mockResolvedValue({
status: 'available',
currentVersion: '1.9.0',
delivery: 'automatic',
version: '2.0.0',
source: 'startup',
isSimulation: true
})
const onNotice = vi.fn()
render(<AppUpdatePrompt onDownloadStart={vi.fn()} onNotice={onNotice} />)
await screen.findByRole('alertdialog', { name: '发现新版本 v2.0.0' })
await user.click(screen.getByRole('button', { name: '忽略此版本' }))
expect(api.setIgnoredUpdateVersion).toHaveBeenCalledWith('2.0.0')
await waitFor(() =>
expect(
screen.queryByRole('alertdialog', { name: '发现新版本 v2.0.0' })
).not.toBeInTheDocument()
)
expect(onNotice).toHaveBeenCalledWith(expect.stringContaining('v2.0.0'))
expect(api.downloadAppUpdate).not.toHaveBeenCalled()
})
it('restores the startup prompt from About', async () => {
const user = userEvent.setup()
api.getAppUpdateState.mockResolvedValue({
status: 'up-to-date',
currentVersion: '2.2.2',
delivery: 'release-page',
message: '已是最新版本'
})
api.getIgnoredUpdateVersion.mockResolvedValue('2.2.3')
api.setIgnoredUpdateVersion.mockResolvedValue('')
const onNotice = vi.fn()
render(<AboutPage onNotice={onNotice} />)
await screen.findByText('已忽略 v2.2.3 的更新提示')
await user.click(screen.getByRole('button', { name: '恢复提示' }))
expect(api.setIgnoredUpdateVersion).toHaveBeenCalledWith(null)
expect(onNotice).toHaveBeenCalledWith('已恢复启动时的更新提示')
await waitFor(() =>
expect(screen.queryByText('已忽略 v2.2.3 的更新提示')).not.toBeInTheDocument()
)
})
it('renders live transfer details and keeps simulated install inside the app', async () => {
const user = userEvent.setup()
api.getAppUpdateState.mockResolvedValue({
@@ -0,0 +1,92 @@
import { render, screen } from '@testing-library/react'
import { describe, expect, it, vi } from 'vitest'
import { DatabaseKeyAutoDetect } from '../../src/renderer/src/features/settings/database-key/DatabaseKeyAutoDetect'
import type { DatabaseKeyState } from '../../src/renderer/src/features/settings/database-key/types'
import type { DatabaseKeyEnvironment } from '../../src/shared/database-key'
import type { MacKeyFlow } from '../../src/shared/macos-arch'
function environment(macKeyFlow: MacKeyFlow, hardwareArchitecture: 'arm64' | 'x64'): DatabaseKeyEnvironment {
return {
platform: 'darwin',
architecture: macKeyFlow === 'intel' ? 'x64' : 'x64',
hardwareArchitecture,
underARM64Translation: macKeyFlow === 'arch-mismatch',
macKeyFlow,
archAnomalies: [],
osVersion: 'macOS 15.7.7 (x64)',
appVersion: 'v2.5.3',
wechatVersion: '4.1.13',
dataStructureVersion: 'v4',
dataDirectoryDetected: true,
diagnosticSummary: 'fixture',
autoDetectSupported: true,
wechatRunning: true,
accountIdentified: true,
dbConnected: false,
encryptionAvailable: true
}
}
function state(macKeyFlow: MacKeyFlow): DatabaseKeyState {
return {
status: 'idle',
saved: false,
encryptionAvailable: true,
autoPhase: 0,
environment: environment(macKeyFlow, macKeyFlow === 'intel' ? 'x64' : 'arm64')
}
}
describe('DatabaseKeyAutoDetect arch mismatch', () => {
it('explains the mismatch and disables auto detection', () => {
render(
<DatabaseKeyAutoDetect
state={state('arch-mismatch')}
disabled={false}
onDetect={vi.fn()}
onRefresh={vi.fn()}
/>
)
expect(
screen.getByText('当前电脑使用 Apple 芯片,但你正在运行 Intel 版 TraceMemo。')
).toBeTruthy()
expect(screen.getByText('已保存的微信数据库密钥无需重新获取。')).toBeTruthy()
expect(screen.getByText('架构不匹配')).toBeTruthy()
expect(screen.queryByText('Intel Mac 自动获取')).toBeNull()
expect((screen.getByRole('button', { name: '自动获取密钥' }) as HTMLButtonElement).disabled).toBe(
true
)
})
it('keeps the Apple Silicon copy when the flow matches the hardware', () => {
render(
<DatabaseKeyAutoDetect
state={state('apple-silicon')}
disabled={false}
onDetect={vi.fn()}
onRefresh={vi.fn()}
/>
)
expect(screen.getByText('macOS 自动获取')).toBeTruthy()
expect(screen.queryByText('当前电脑使用 Apple 芯片,但你正在运行 Intel 版 TraceMemo。')).toBeNull()
expect((screen.getByRole('button', { name: '自动获取密钥' }) as HTMLButtonElement).disabled).toBe(
false
)
})
it('still labels a genuine Intel Mac as Intel', () => {
render(
<DatabaseKeyAutoDetect
state={state('intel')}
disabled={false}
onDetect={vi.fn()}
onRefresh={vi.fn()}
/>
)
expect(screen.getByText('Intel Mac 自动获取')).toBeTruthy()
expect(screen.queryByText('架构不匹配')).toBeNull()
})
})
@@ -0,0 +1,123 @@
import { render, screen, waitFor } from '@testing-library/react'
import { describe, expect, it, vi } from 'vitest'
import type { MsgInsertSwitchesSnapshot } from '../../src/shared/msg-insert-switch'
vi.mock('../../src/renderer/src/components/ui', async (importOriginal) => {
const actual = await importOriginal<Record<string, unknown>>()
return { ...actual, useToast: () => ({ toast: () => undefined }) }
})
import { MessageInsertSwitches } from '../../src/renderer/src/features/automation/MessageInsertSwitches'
/**
* 开关的门禁语义:
* 开启 → 看 capability.canEnable
* 关闭 → 永远可点(授权失效也不能把用户锁死在开启状态)
*/
function baseStatus(
desiredEnabled: boolean,
overrides: Record<string, unknown> = {}
): Record<string, unknown> {
return {
switch: 'recall_notice',
scope: 'all_sessions',
mode: 'rules',
desiredEnabled,
effectiveEnabled: desiredEnabled,
operationOk: true,
totalInstallableRooms: 0,
readyInstallableRooms: 0,
roomsWithoutTable: 0,
totalShards: 0,
targetShards: 0,
configuredShards: 0,
readyShards: 0,
notReadyShards: 0,
failedShards: 0,
...overrides
}
}
function snapshotOf(
canEnable: boolean,
desired: { recall: boolean; exit: boolean },
reasonCode = canEnable ? 'CAPABILITY_READY' : 'LICENSE_REQUIRED',
message = canEnable ? '授权与组件均已就绪' : '未检测到有效授权'
): MsgInsertSwitchesSnapshot {
return {
success: true,
helperAvailable: true,
capability: {
entitlementState: canEnable ? 'valid' : 'invalid',
nativeComponentState: 'ready',
databaseReady: true,
canEnable,
canDisable: true,
reasonCode: reasonCode as never,
message
},
switches: {
recall_notice: baseStatus(desired.recall) as never,
group_exit_notice: baseStatus(desired.exit, {
switch: 'group_exit_notice',
mode: 'event',
effectiveEnabled: canEnable ? desired.exit : false
}) as never
}
}
}
function installApi(snapshot: MsgInsertSwitchesSnapshot): void {
;(window as unknown as { api: Record<string, unknown> }).api = {
getMsgInsertSwitches: async () => snapshot,
setMsgInsertSwitch: async () => ({ success: true })
}
}
describe('MessageInsertSwitches 能力门禁', () => {
it('没有授权时两个未开启的开关都不可操作,并给出激活引导', async () => {
installApi(snapshotOf(false, { recall: false, exit: false }))
render(<MessageInsertSwitches />)
await waitFor(() => expect(screen.getAllByRole('switch').length).toBe(2))
const switches = screen.getAllByRole('switch')
expect(switches[0]).toBeDisabled()
expect(switches[1]).toBeDisabled()
expect(screen.getByText(/需要有效授权才能开启/)).toBeTruthy()
})
it('已开启的开关在授权失效时仍可点击关闭(不能被锁死)', async () => {
installApi(snapshotOf(false, { recall: true, exit: true }))
render(<MessageInsertSwitches />)
await waitFor(() => expect(screen.getAllByRole('switch').length).toBe(2))
const switches = screen.getAllByRole('switch')
expect(switches[0]).not.toBeDisabled()
expect(switches[1]).not.toBeDisabled()
})
it('授权有效时允许开启', async () => {
installApi(snapshotOf(true, { recall: false, exit: false }))
render(<MessageInsertSwitches />)
await waitFor(() => expect(screen.getAllByRole('switch').length).toBe(2))
const switches = screen.getAllByRole('switch')
expect(switches[0]).not.toBeDisabled()
expect(switches[1]).not.toBeDisabled()
})
it('缺组件时提示组件缺失,而不是「没授权」', async () => {
const snapshot = snapshotOf(
false,
{ recall: false, exit: false },
'COMPONENT_MISSING',
'未安装发送能力组件'
)
installApi(snapshot)
render(<MessageInsertSwitches />)
await waitFor(() => expect(screen.getByText(/发送能力组件/)).toBeTruthy())
})
})
@@ -41,7 +41,6 @@ const readyStatus = {
boundWechatPid: 4668,
endpoint: '127.0.0.1:4290',
endpointReady: true,
wechatVersion: '4.1.11.53',
runtimeReady: true,
attachReady: true,
baseAddress: '0x114ef8000',
@@ -1,4 +1,4 @@
import { render, screen } from '@testing-library/react'
import { fireEvent, render, screen, waitFor } from '@testing-library/react'
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { PersonalWechatSendPage } from '../../src/renderer/src/features/settings/pages/PersonalWechatSendPage'
@@ -12,6 +12,10 @@ vi.mock('../../src/renderer/src/utils/runtime-environment', () => ({
const getCapability = vi.fn()
const getSenderStatus = vi.fn()
const rebindSender = vi.fn()
const listResidualProcesses = vi.fn()
const cleanupResidualProcesses = vi.fn()
const startMacRuntime = vi.fn()
const getMacLicenseStatus = vi.fn()
const senderStatus = {
state: 'online' as const,
@@ -21,9 +25,8 @@ const senderStatus = {
wechatRunning: true,
wechatPid: 4668,
boundWechatPid: 4668,
endpoint: '127.0.0.1:4290',
endpoint: 'http://127.0.0.1:4290',
endpointReady: true,
wechatVersion: '4.1.11.53',
runtimeReady: true,
attachReady: true,
baseAddress: '0x114ef8000',
@@ -54,12 +57,55 @@ describe('PersonalWechatSendPage on macOS', () => {
getCapability.mockReset().mockResolvedValue(capability)
getSenderStatus.mockReset().mockResolvedValue(senderStatus)
rebindSender.mockReset().mockResolvedValue(senderStatus)
listResidualProcesses.mockReset().mockResolvedValue([
{
pid: 202,
name: 'tm-wechat-host',
targets: ['port_4290'],
confirmationToken: 'process-identity-202'
}
])
cleanupResidualProcesses.mockReset().mockResolvedValue({
stopped: [
{
pid: 202,
name: 'tm-wechat-host',
targets: ['port_4290'],
confirmationToken: 'process-identity-202'
}
],
remaining: [],
runtimeStopped: true
})
startMacRuntime.mockReset().mockResolvedValue({ lifecycle: 'online' })
getMacLicenseStatus.mockReset().mockResolvedValue({
deviceId: null,
state: 'unlicensed',
authorized: false,
source: 'none',
features: [],
lastCheckedAt: null,
licenseExpiresAt: null,
tokenExpiresAt: null,
message: '当前设备暂无发送能力授权'
})
Object.defineProperty(window, 'api', {
configurable: true,
value: {
getPersonalWechatSendCapability: getCapability,
getPersonalWechatSenderStatus: getSenderStatus,
rebindPersonalWechatSender: rebindSender
rebindPersonalWechatSender: rebindSender,
listMacWechatResidualProcesses: listResidualProcesses,
cleanupMacWechatResidualProcesses: cleanupResidualProcesses,
startMacSendRuntime: startMacRuntime,
// 发送能力授权卡所需的两个入口。页面在 Native 档位会调用它们,
// 缺 mock 会让 refresh 抛错、整页停在错误态。
getMacSendRuntimeAvailability: vi.fn(async () => ({
state: 'available',
message: '微信发送组件可用'
})),
getMacLicenseStatus,
refreshMacLicense: vi.fn()
}
})
})
@@ -67,9 +113,145 @@ describe('PersonalWechatSendPage on macOS', () => {
it('shows the native runtime readiness', async () => {
render(<PersonalWechatSendPage onNotice={vi.fn()} />)
expect(await screen.findByText('微信消息发送已配置完成')).toBeVisible()
// 页面重构后「就绪」的落点从 SetupGuide 尾部文案变成了「微信发送环境」卡片的状态标签;
// 断言改到新位置,语义仍是“运行时准备好了”。
expect(await screen.findByText('运行环境已就绪')).toBeVisible()
expect(
screen.getByText('当前发送能力占用端口为 4290(TM_WECHAT_HOST_PORT)。')
).toBeVisible()
expect(await screen.findByText('已被占用:tm-wechat-host(PID 202)')).toBeVisible()
expect(screen.getAllByText('已就绪')).not.toHaveLength(0)
expect(screen.queryByText('查看支持的微信版本')).not.toBeInTheDocument()
expect(screen.queryByText('高级诊断')).not.toBeInTheDocument()
})
it('shows the actual runtime port when it uses a configured fallback instead of 4290', async () => {
const fallbackPortStatus = { ...senderStatus, endpoint: 'http://127.0.0.1:4291' }
getCapability.mockResolvedValueOnce({ ...capability, senderStatus: fallbackPortStatus })
getSenderStatus.mockResolvedValueOnce(fallbackPortStatus)
listResidualProcesses.mockResolvedValueOnce([])
render(<PersonalWechatSendPage onNotice={vi.fn()} />)
expect(
await screen.findByText(
'当前发送能力占用端口为 4291(TM_WECHAT_HOST_PORT)。'
)
).toBeVisible()
expect(screen.getByText('未被占用')).toBeVisible()
})
it('shows confirmed cleanup targets before ending processes', async () => {
const onNotice = vi.fn()
render(<PersonalWechatSendPage onNotice={onNotice} />)
await screen.findByText('运行环境已就绪')
fireEvent.click(screen.getByRole('button', { name: '清理残留以及微信进程' }))
expect(await screen.findByRole('heading', { name: '清理微信残留进程?' })).toBeVisible()
expect(screen.getByText('tm-wechat-host')).toBeVisible()
expect(screen.getByText(/PID 202.*4290 端口/)).toBeVisible()
expect(cleanupResidualProcesses).not.toHaveBeenCalled()
})
it('cleans only the process the user confirmed and refreshes the runtime state', async () => {
const onNotice = vi.fn()
render(<PersonalWechatSendPage onNotice={onNotice} />)
await screen.findByText('运行环境已就绪')
fireEvent.click(screen.getByRole('button', { name: '清理残留以及微信进程' }))
fireEvent.click(await screen.findByRole('button', { name: '确认结束进程' }))
await waitFor(() => {
expect(cleanupResidualProcesses).toHaveBeenCalledWith([
{ pid: 202, confirmationToken: 'process-identity-202' }
])
})
expect(onNotice).toHaveBeenCalledWith('已结束 1 个残留进程;发送环境状态已刷新。')
expect(await screen.findByRole('button', { name: '重新启动发送组件' })).toBeVisible()
fireEvent.click(screen.getByRole('button', { name: '重新启动发送组件' }))
await waitFor(() => expect(startMacRuntime).toHaveBeenCalledOnce())
})
it('shows that WeChat must be reopened and rebound after its process is cleaned', async () => {
listResidualProcesses.mockResolvedValueOnce([
{
pid: 4668,
name: 'WeChat',
targets: ['wechat'],
confirmationToken: 'wechat-process-4668'
}
])
cleanupResidualProcesses.mockResolvedValueOnce({
stopped: [
{
pid: 4668,
name: 'WeChat',
targets: ['wechat'],
confirmationToken: 'wechat-process-4668'
}
],
remaining: [],
runtimeStopped: false
})
rebindSender.mockResolvedValueOnce({
...senderStatus,
state: 'stopped',
wechatRunning: true,
wechatPid: undefined,
boundWechatPid: undefined,
canSend: false
})
const stoppedStatus = {
...senderStatus,
state: 'stopped',
wechatRunning: false,
wechatPid: undefined,
boundWechatPid: undefined,
attachReady: false,
baseAddressReady: false,
canSend: false,
canSendText: false,
canSendImage: false,
canSendVoice: false
}
getSenderStatus.mockReset().mockResolvedValueOnce(senderStatus).mockResolvedValue(stoppedStatus)
getMacLicenseStatus.mockResolvedValue({
deviceId: 'mac_test',
state: 'valid',
authorized: true,
source: 'online',
features: ['wechat'],
lastCheckedAt: new Date().toISOString(),
licenseExpiresAt: null,
tokenExpiresAt: new Date(Date.now() + 60_000).toISOString(),
message: '设备已授权'
})
const onNotice = vi.fn()
render(<PersonalWechatSendPage onNotice={onNotice} />)
await screen.findByText('运行环境已就绪')
fireEvent.click(screen.getByRole('button', { name: '清理残留以及微信进程' }))
fireEvent.click(await screen.findByRole('button', { name: '确认结束进程' }))
expect(
await screen.findByText(
'微信进程已清理。请重新打开微信,然后点击“绑定微信”;绑定完成后此提示会自动消失。'
)
).toBeVisible()
fireEvent.click(screen.getByRole('button', { name: '绑定微信' }))
await waitFor(() => expect(rebindSender).toHaveBeenCalledOnce())
expect(
screen.getByText(
'微信进程已清理。请重新打开微信,然后点击“绑定微信”;绑定完成后此提示会自动消失。'
)
).toBeVisible()
fireEvent.click(screen.getByRole('button', { name: '绑定微信' }))
await waitFor(() => expect(rebindSender).toHaveBeenCalledTimes(2))
expect(
screen.queryByText(
'微信进程已清理。请重新打开微信,然后点击“绑定微信”;绑定完成后此提示会自动消失。'
)
).not.toBeInTheDocument()
})
})
@@ -1,4 +1,4 @@
import { render, screen } from '@testing-library/react'
import { fireEvent, render, screen, waitFor } from '@testing-library/react'
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { PersonalWechatSetupGuide } from '../../src/renderer/src/components/chat/PersonalWechatSetupGuide'
@@ -41,6 +41,10 @@ describe('personal WeChat unavailable product state', () => {
Object.defineProperty(window, 'api', {
configurable: true,
value: {
getMacSendRuntimeAvailability: vi.fn(async () => ({
state: 'available',
message: '微信发送组件可用'
})),
getPersonalWechatSendCapability: vi.fn(async () => ({
supported: true,
ready: false,
@@ -50,7 +54,19 @@ describe('personal WeChat unavailable product state', () => {
message: '暂无发送能力',
error: '暂无发送能力'
})),
getPersonalWechatSenderStatus: vi.fn(async () => unavailableStatus)
getPersonalWechatSenderStatus: vi.fn(async () => unavailableStatus),
getMacLicenseStatus: vi.fn(async () => ({
deviceId: `mac_${'c'.repeat(64)}`,
state: 'unlicensed',
authorized: false,
source: 'none',
features: [],
lastCheckedAt: null,
licenseExpiresAt: null,
tokenExpiresAt: null,
message: '当前设备暂无发送能力授权'
})),
refreshMacLicense: vi.fn()
}
})
})
@@ -81,16 +97,261 @@ describe('personal WeChat unavailable product state', () => {
expect(screen.queryByText(/manifest|dylib|runtime missing|文件缺失/i)).not.toBeInTheDocument()
})
it('describes a ready runtime separately from pending send capability initialization', () => {
const boundStatus: PersonalWechatSenderStatus = {
...unavailableStatus,
state: 'hook_not_ready',
wechatRunning: true,
wechatPid: 4668,
boundWechatPid: 4668,
endpointReady: true,
runtimeReady: true,
attachReady: true,
baseAddressReady: true,
message: '已绑定,等待发送 hook 就绪'
}
render(
<PersonalWechatSetupGuide
senderStatus={boundStatus}
binding={false}
detecting={false}
sessionBound
showBindAction={false}
/>
)
expect(screen.getByText('微信已绑定,正在等待发送能力完成初始化…')).toBeVisible()
expect(screen.queryByText('正在等待发送运行时完成初始化…')).not.toBeInTheDocument()
})
it('does not say the runtime is still initializing when it is ready but message capabilities are pending', () => {
const boundButInitializing: PersonalWechatSenderStatus = {
...unavailableStatus,
state: 'hook_not_ready',
wechatRunning: true,
wechatPid: 4668,
boundWechatPid: 4668,
endpointReady: true,
runtimeReady: true,
attachReady: true,
baseAddressReady: true,
message: '已绑定,等待发送 hook 就绪'
}
render(
<PersonalWechatSetupGuide
senderStatus={boundButInitializing}
binding={false}
detecting={false}
sessionBound
showBindAction={false}
showBindingInstructionsInInitialization
/>
)
expect(screen.getByText('微信已绑定,正在等待发送能力完成初始化…')).toBeVisible()
expect(screen.queryByText('正在等待发送运行时完成初始化…')).not.toBeInTheDocument()
})
it('shows the disabled binding flow on the settings page', async () => {
render(<PersonalWechatSendPage onNotice={vi.fn()} />)
expect(await screen.findByRole('heading', { name: '先准备好微信消息功能' })).toBeVisible()
expect(screen.getByRole('button', { name: '绑定微信' })).toBeDisabled()
expect(screen.getByRole('button', { name: '授权后可绑定微信' })).toBeDisabled()
expect(screen.getByRole('region', { name: '微信发送环境' })).toBeVisible()
expect(screen.getByText('运行时正常')).toBeVisible()
expect(screen.getByText('微信已绑定')).toBeVisible()
expect(screen.getByText('发送组件正常')).toBeVisible()
expect(screen.getByRole('button', { name: '首次使用配置' })).toHaveAttribute(
'aria-expanded',
'true'
)
expect(await screen.findByRole('region', { name: '发送能力授权' })).toBeVisible()
expect(screen.queryByText(/发送能力属授权制,需要联系群主/)).not.toBeInTheDocument()
expect(screen.queryByRole('link', { name: '这里' })).not.toBeInTheDocument()
expect(screen.queryByText(/manifest|dylib|runtime missing|文件缺失/i)).not.toBeInTheDocument()
})
it('shows real environment status and keeps first-use details collapsed when ready', async () => {
Object.defineProperty(window, 'api', {
configurable: true,
value: {
getMacSendRuntimeAvailability: vi.fn(async () => ({
state: 'available',
message: '微信发送组件可用'
})),
getPersonalWechatSendCapability: vi.fn(async () => ({
supported: true,
ready: true,
status: 'ready',
capabilities: { text: true, image: true, voice: true },
senderStatus: readyStatus,
message: '已就绪'
})),
getPersonalWechatSenderStatus: vi.fn(async () => readyStatus),
getMacLicenseStatus: vi.fn(async () => ({
...licenseStatus,
state: 'revoked',
authorized: false
})),
refreshMacLicense: vi.fn()
}
})
render(<PersonalWechatSendPage onNotice={vi.fn()} />)
expect(await screen.findByText('运行环境已就绪')).toBeVisible()
expect(screen.getAllByText('正常')).toHaveLength(3)
expect(screen.getByRole('button', { name: '授权后可开始发送' })).toBeDisabled()
expect(screen.getByRole('button', { name: '首次使用配置' })).toHaveAttribute(
'aria-expanded',
'false'
)
expect(screen.queryByRole('button', { name: '绑定微信' })).not.toBeInTheDocument()
expect(await screen.findByText('授权已撤销')).toBeVisible()
fireEvent.click(screen.getByRole('button', { name: '首次使用配置' }))
expect(screen.getByRole('button', { name: '首次使用配置' })).toHaveAttribute(
'aria-expanded',
'true'
)
expect(screen.queryByRole('button', { name: '绑定微信' })).not.toBeInTheDocument()
expect(screen.queryByRole('button', { name: '开始发送' })).not.toBeInTheDocument()
expect(screen.getAllByRole('listitem')).toHaveLength(2)
expect(screen.getByText('每个微信进程只能绑定一次')).toBeVisible()
expect(screen.getByText(/4\.1\.13以下请保持微信未登录窗口状态/)).toBeVisible()
expect(screen.getByText('4.1.13以上登录状态微信直接点击“绑定微信”')).toBeVisible()
expect(screen.queryByText('能力检测')).not.toBeInTheDocument()
expect(screen.queryByText('文字消息')).not.toBeInTheDocument()
expect(screen.queryByText('图片消息')).not.toBeInTheDocument()
expect(screen.queryByText('语音消息')).not.toBeInTheDocument()
})
it('copies the full device id and shows refresh loading without disabling copy', async () => {
const deviceId = `mac_${'a'.repeat(64)}`
let resolveRefresh: ((value: typeof licenseStatus) => void) | undefined
const refreshMacLicense = vi.fn(
() => new Promise<typeof licenseStatus>((resolve) => (resolveRefresh = resolve))
)
Object.defineProperty(navigator, 'clipboard', {
configurable: true,
value: { writeText: vi.fn(async () => undefined) }
})
Object.defineProperty(window, 'api', {
configurable: true,
value: {
getMacSendRuntimeAvailability: vi.fn(async () => ({
state: 'available',
message: '微信发送组件可用'
})),
getPersonalWechatSendCapability: vi.fn(async () => ({
supported: true,
ready: false,
status: 'unconfigured',
capabilities: { text: false, image: false, voice: false },
senderStatus: readyStatus,
message: '未配置'
})),
getPersonalWechatSenderStatus: vi.fn(async () => readyStatus),
getMacLicenseStatus: vi.fn(async () => ({ ...licenseStatus, deviceId, state: 'expired' })),
refreshMacLicense
}
})
render(<PersonalWechatSendPage onNotice={vi.fn()} />)
const copyButton = await screen.findByRole('button', { name: '复制完整设备 ID' })
fireEvent.click(copyButton)
await waitFor(() => expect(navigator.clipboard.writeText).toHaveBeenCalledWith(deviceId))
expect(await screen.findByText('授权状态需刷新')).toBeVisible()
expect(
screen.getByText('当前授权状态与到期日不一致,请点击「重新检测授权」更新状态。')
).toBeVisible()
fireEvent.click(screen.getByRole('button', { name: '重新检测授权' }))
expect(await screen.findByRole('button', { name: '检测中…' })).toBeDisabled()
expect(copyButton).toBeEnabled()
resolveRefresh?.({ ...licenseStatus, deviceId, state: 'valid', authorized: true })
expect(await screen.findByText('设备已授权')).toBeVisible()
expect(screen.queryByText('授权状态需刷新')).not.toBeInTheDocument()
})
it('does not query or render License when the send runtime is unavailable', async () => {
const getMacLicenseStatus = vi.fn()
Object.defineProperty(window, 'api', {
configurable: true,
value: {
getMacSendRuntimeAvailability: vi.fn(async () => ({
state: 'unavailable',
message: '当前版本没有微信发送能力'
})),
getMacLicenseStatus,
getPersonalWechatSendCapability: vi.fn(),
getPersonalWechatSenderStatus: vi.fn()
}
})
render(<PersonalWechatSendPage onNotice={vi.fn()} />)
expect(await screen.findByRole('button', { name: '当前版本没有微信发送能力' })).toBeDisabled()
expect(screen.getByText(/发送能力属授权制,需要联系群主/)).toBeVisible()
expect(screen.getByRole('link', { name: '这里' })).toHaveAttribute(
'href',
'https://github.com/Wxw-Gu/TraceMemo#-交流与反馈'
)
expect(screen.queryByText(/manifest|dylib|runtime missing|文件缺失/i)).not.toBeInTheDocument()
expect(screen.queryByRole('region', { name: '发送能力授权' })).not.toBeInTheDocument()
expect(getMacLicenseStatus).not.toHaveBeenCalled()
})
it('shows component failure without querying License when send runtime files are damaged', async () => {
const getMacLicenseStatus = vi.fn()
Object.defineProperty(window, 'api', {
configurable: true,
value: {
getMacSendRuntimeAvailability: vi.fn(async () => ({
state: 'component_error',
message: '发送组件缺失或异常:manifest missing'
})),
getMacLicenseStatus,
getPersonalWechatSendCapability: vi.fn(),
getPersonalWechatSenderStatus: vi.fn()
}
})
render(<PersonalWechatSendPage onNotice={vi.fn()} />)
expect(await screen.findByRole('button', { name: '发送组件缺失或异常' })).toBeDisabled()
expect(screen.getAllByText('发送组件缺失或异常').length).toBeGreaterThan(0)
expect(screen.queryByText(/发送能力属授权制,需要联系群主/)).not.toBeInTheDocument()
expect(getMacLicenseStatus).not.toHaveBeenCalled()
expect(screen.queryByRole('region', { name: '发送能力授权' })).not.toBeInTheDocument()
})
})
const readyStatus: PersonalWechatSenderStatus = {
...unavailableStatus,
state: 'online',
wechatRunning: true,
wechatPid: 1234,
boundWechatPid: 1234,
endpointReady: true,
runtimeReady: true,
attachReady: true,
baseAddressReady: true,
canSend: true,
canSendText: true,
canSendImage: true,
canSendVoice: true
}
const licenseStatus = {
deviceId: `mac_${'b'.repeat(64)}`,
state: 'valid' as const,
authorized: true,
source: 'online' as const,
features: ['wechat', 'api'],
lastCheckedAt: '2026-11-04T09:44:00+08:00',
licenseExpiresAt: '2027-11-03T00:00:00+08:00',
tokenExpiresAt: null,
message: '已授权'
}
-1
View File
@@ -663,7 +663,6 @@ handle('wechat-personal:getStatus', () => ({
boundWechatPid: 4668,
endpoint: '127.0.0.1:4290',
endpointReady: true,
wechatVersion: '4.1.11.53',
runtimeReady: true,
attachReady: true,
baseAddress: '0x114ef8000',
+221
View File
@@ -0,0 +1,221 @@
import crypto from 'node:crypto'
import fs from 'node:fs'
import os from 'node:os'
import path from 'node:path'
import { afterEach, beforeEach, describe, expect, it } from 'vitest'
import {
MessageInsertCapabilityService,
mapLicenseStatus
} from '../../src/main/services/msg-insert-capability-service'
import {
resetComponentCache,
resolveExternalComponent
} from '../../src/main/services/external-component-locator'
/**
* 组件发现与能力判定的验收:真实文件与 PE 头,只替换 4290 探测。
*/
const HELPER = 'tm-wcdb-config-helper.exe'
const API = 'wcdb_api.dll'
const CORE = 'WCDB.dll'
/** 造一个「PE 头合法、体积够大」的假组件,专门喂给 inspectNativeComponent。 */
function fakePe(machine = 0x8664, total = 2048): Buffer {
const buf = Buffer.alloc(total)
buf.write('MZ', 0, 'latin1')
buf.writeUInt32LE(0x80, 0x3c)
buf.write('PE\0\0', 0x80, 'latin1')
buf.writeUInt16LE(machine, 0x84)
return buf
}
function sha256(buf: Buffer): string {
return crypto.createHash('sha256').update(buf).digest('hex')
}
interface Fixture {
root: string
versionDir: string
localAppData: string
pointerPath: string
}
function buildFixture(): Fixture {
const root = fs.mkdtempSync(path.join(os.tmpdir(), 'tm-cap-'))
const localAppData = path.join(root, 'LocalAppData')
const versionDir = path.join(localAppData, 'TraceMemo', 'Pro', 'windows-x64', '1.0.0')
fs.mkdirSync(versionDir, { recursive: true })
const files: Array<{ path: string; size: number; sha256: string }> = []
for (const name of [API, CORE, HELPER]) {
const buf = fakePe()
fs.writeFileSync(path.join(versionDir, name), buf)
files.push({ path: name, size: buf.length, sha256: sha256(buf) })
}
fs.writeFileSync(
path.join(versionDir, 'manifest.json'),
JSON.stringify(
{
schemaVersion: 1,
product: 'TraceMemo',
edition: 'oss',
platform: 'windows-x64',
componentVersion: '1.0.0',
wchookCommit: 'test',
dllCommit: 'test',
worktreeDirty: false,
installedAt: new Date().toISOString(),
files
},
null,
2
)
)
const pointerPath = path.join(localAppData, 'TraceMemo', 'Pro', 'windows-x64', 'current.json')
fs.writeFileSync(pointerPath, JSON.stringify({ version: '1.0.0', dir: versionDir }))
return { root, versionDir, localAppData, pointerPath }
}
/**
* 组一个和生产同构的服务实例。
* 定位器显式传 LOCALAPPDATA(不去改 process.env,避免用例之间互相污染),
* 其余依赖保持生产实现。
*/
function makeService(
localAppData: string | null,
probe: { ok: true; status: string } | { ok: false; error: string }
): MessageInsertCapabilityService {
return new MessageInsertCapabilityService({
platform: 'win32',
hasMacNativeBundle: () => true,
isMacRuntimeUnavailable: () => false,
resolveNativeComponent: () =>
localAppData
? (resolveExternalComponent({ LOCALAPPDATA: localAppData } as never, 'win32')?.helperPath ??
null)
: null,
probeLicense: async () => probe
})
}
const located = (localAppData: string): ReturnType<typeof resolveExternalComponent> =>
resolveExternalComponent({ LOCALAPPDATA: localAppData } as never, 'win32')
describe('能力验收矩阵(真实文件 + 真实 PE 嗅探)', () => {
let fixture: Fixture
beforeEach(() => {
fixture = buildFixture()
resetComponentCache()
})
afterEach(() => {
resetComponentCache()
fs.rmSync(fixture.root, { recursive: true, force: true })
})
it('定位到外置 bundle 时返回 helper 绝对路径与版本', () => {
const found = located(fixture.localAppData)
expect(found).not.toBeNull()
expect(found!.version).toBe('1.0.0')
expect(found!.helperPath).toBe(path.join(fixture.versionDir, HELPER))
expect(fs.existsSync(found!.helperPath)).toBe(true)
})
it('1. 未安装组件:没有 current.json → 组件缺失,不支持开启', async () => {
fs.rmSync(fixture.pointerPath)
resetComponentCache()
const cap = await makeService(fixture.localAppData, {
ok: true,
status: 'LICENSE_OK'
}).refresh({ databaseReady: true })
expect(cap.nativeComponentState).toBe('missing')
expect(cap.canEnable).toBe(false)
expect(cap.reasonCode).toBe('COMPONENT_MISSING')
})
it('2. 装了组件但授权不可达 → 不许开启,原因指向授权', async () => {
const cap = await makeService(fixture.localAppData, {
ok: false,
error: 'ECONNREFUSED'
}).refresh({ databaseReady: true })
expect(cap.nativeComponentState).toBe('ready')
expect(cap.entitlementState).toBe('unavailable')
expect(cap.canEnable).toBe(false)
expect(cap.reasonCode).toBe('LICENSE_UNAVAILABLE')
})
it('3. 授权有效 + 组件就绪 + 库已连接 → 允许开启', async () => {
const cap = await makeService(fixture.localAppData, {
ok: true,
status: 'LICENSE_OK'
}).refresh({ databaseReady: true })
expect(cap.entitlementState).toBe('valid')
expect(cap.nativeComponentState).toBe('ready')
expect(cap.canEnable).toBe(true)
expect(cap.reasonCode).toBe('CAPABILITY_READY')
})
it('4. 授权过期 → 不许开启', async () => {
const cap = await makeService(fixture.localAppData, {
ok: true,
status: 'LICENSE_EXPIRED'
}).refresh({ databaseReady: true })
expect(cap.entitlementState).toBe('invalid')
expect(cap.canEnable).toBe(false)
expect(cap.reasonCode).toBe('LICENSE_EXPIRED')
})
it('5. 组件文件缺失 → 定位失败,按未安装处理', () => {
fs.rmSync(path.join(fixture.versionDir, HELPER))
resetComponentCache()
expect(located(fixture.localAppData)).toBeNull()
})
it('6. 组件被篡改(大小不同)→ manifest 校验失败,按未安装处理', () => {
fs.writeFileSync(path.join(fixture.versionDir, API), fakePe(0x8664, 4096))
resetComponentCache()
expect(located(fixture.localAppData)).toBeNull()
})
it('7. 关闭永远不被授权拦住(授权过期 + 组件缺失也能关)', async () => {
const svc = new MessageInsertCapabilityService({
platform: 'win32',
hasMacNativeBundle: () => true,
isMacRuntimeUnavailable: () => false,
resolveNativeComponent: () => null,
probeLicense: async () => ({ ok: true, status: 'LICENSE_EXPIRED' })
})
const cap = await svc.refresh({ databaseReady: false })
expect(cap.canEnable).toBe(false)
expect(cap.canDisable).toBe(true)
})
it('8. 微信库未连接 → 不许开启', async () => {
const cap = await makeService(fixture.localAppData, {
ok: true,
status: 'LICENSE_OK'
}).refresh({ databaseReady: false })
expect(cap.canEnable).toBe(false)
expect(cap.reasonCode).toBe('DATABASE_UNAVAILABLE')
})
it('9. 授权状态映射:只有 LICENSE_OK 算 valid', () => {
for (const status of [
'LICENSE_EXPIRED',
'LICENSE_MACHINE_MISMATCH',
'LICENSE_REVOKED',
'LICENSE_INVALID',
'LICENSE_SERVICE_DOWN',
'LICENSE_CHECKING',
''
]) {
expect(mapLicenseStatus(status).entitlement).not.toBe('valid')
}
expect(mapLicenseStatus('LICENSE_OK').entitlement).toBe('valid')
})
})
@@ -186,7 +186,7 @@ describe('派生库句柄的账号身份缓存', () => {
h.service.resetAccount()
})
it('identity resolution cost is paid once per pass, not per image', async () => {
it('identity resolution cost is consumed once per pass, not per image', async () => {
const RESOLVE_MS = 30
const OCR_MS = 5
const slow = createHarness({
@@ -0,0 +1,82 @@
import { createRequire } from 'module'
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'fs'
import { tmpdir } from 'os'
import { join } from 'path'
import { afterAll, describe, expect, it } from 'vitest'
const nodeRequire = createRequire(import.meta.url)
const { validateElectronMainBinary } = nodeRequire('../../scripts/after-pack.cjs') as {
validateElectronMainBinary: (
appOutDir: string,
productName: string,
platform: string,
arch: string
) => void
}
const root = mkdtempSync(join(tmpdir(), 'tm-electron-arch-'))
/** 最小 64 位 Mach-O 头;cputype 决定被判成哪种架构。 */
function macho(cpuType: number): Buffer {
const buffer = Buffer.alloc(32)
buffer.writeUInt32LE(0xfeedfacf, 0)
buffer.writeUInt32LE(cpuType, 4)
return buffer
}
const CPU_X86_64 = 0x01000007
const CPU_ARM64 = 0x0100000c
function bundle(name: string, binary: Buffer | string): { appOutDir: string; productName: string } {
const appOutDir = join(root, name)
const macosDir = join(appOutDir, 'TraceMemo.app', 'Contents', 'MacOS')
mkdirSync(macosDir, { recursive: true })
writeFileSync(join(macosDir, 'TraceMemo'), binary)
return { appOutDir, productName: 'TraceMemo' }
}
afterAll(() => rmSync(root, { recursive: true, force: true }))
describe('validateElectronMainBinary', () => {
it('accepts an arm64 main binary for an arm64 bundle', () => {
const context = bundle('arm64-ok', macho(CPU_ARM64))
expect(() =>
validateElectronMainBinary(context.appOutDir, context.productName, 'darwin', 'arm64')
).not.toThrow()
})
it('rejects an x64 Electron binary in an arm64 bundle', () => {
const context = bundle('arm64-with-x64', macho(CPU_X86_64))
expect(() =>
validateElectronMainBinary(context.appOutDir, context.productName, 'darwin', 'arm64')
).toThrow(/is x64 but this bundle targets arm64/)
})
it('accepts either slice for a universal bundle', () => {
const context = bundle('universal', macho(CPU_X86_64))
expect(() =>
validateElectronMainBinary(context.appOutDir, context.productName, 'darwin', 'universal')
).not.toThrow()
})
it('fails when the main binary is missing', () => {
const appOutDir = join(root, 'missing')
mkdirSync(join(appOutDir, 'TraceMemo.app', 'Contents', 'MacOS'), { recursive: true })
expect(() =>
validateElectronMainBinary(appOutDir, 'TraceMemo', 'darwin', 'arm64')
).toThrow(/Missing Electron main binary/)
})
it('fails when the main binary is not a Mach-O executable', () => {
const context = bundle('not-macho', '#!/bin/sh\necho hi\n')
expect(() =>
validateElectronMainBinary(context.appOutDir, context.productName, 'darwin', 'arm64')
).toThrow(/not a Mach-O executable/)
})
it('ignores non-darwin targets', () => {
expect(() =>
validateElectronMainBinary(join(root, 'nowhere'), 'TraceMemo', 'win32', 'x64')
).not.toThrow()
})
})
+190
View File
@@ -0,0 +1,190 @@
import { describe, expect, it } from 'vitest'
import {
isDefinitelyBlocked,
isEntitlementBlocked,
resolveExitNoticeGate,
resolveSwitchPresentation
} from '../../src/main/services/exit-notice-gate'
import type { MessageInsertCapability } from '../../src/main/services/msg-insert-capability-service'
/** 开关呈现:授权不成立时,两个开关必须同时显示关闭。 */
function capability(over: Partial<MessageInsertCapability>): MessageInsertCapability {
return {
entitlementState: 'valid',
nativeComponentState: 'ready',
databaseReady: true,
canEnable: true,
canDisable: true,
reasonCode: 'CAPABILITY_READY',
message: '授权与组件均已就绪',
checkedAt: 0,
...over
}
}
describe('退群内提示开关判定', () => {
it('授权有效 + 组件就绪 + 库已连接 + 用户开着 → 显示开、确实在跑', () => {
const d = resolveExitNoticeGate(capability({}), true)
expect(d).toEqual({ desiredEnabled: true, effectiveEnabled: true, persistDisable: false })
})
it('用户本来关着 → 显示关,不落盘', () => {
const d = resolveExitNoticeGate(capability({}), false)
expect(d).toEqual({ desiredEnabled: false, effectiveEnabled: false, persistDisable: false })
})
it('授权过期(invalid)→ 显示关闭,并把本地开关落盘关掉', () => {
const cap = capability({
entitlementState: 'invalid',
canEnable: false,
reasonCode: 'LICENSE_EXPIRED',
message: '授权已过期,请重新激活后再开启'
})
const d = resolveExitNoticeGate(cap, true)
expect(d.desiredEnabled).toBe(false)
expect(d.effectiveEnabled).toBe(false)
expect(d.persistDisable).toBe(true)
})
it('授权服务探测失败(unavailable)→ 显示关闭,但不改写用户设置', () => {
const cap = capability({
entitlementState: 'unavailable',
canEnable: false,
reasonCode: 'LICENSE_UNAVAILABLE',
message: '暂时无法确认授权状态'
})
const d = resolveExitNoticeGate(cap, true)
expect(d.desiredEnabled).toBe(false)
expect(d.effectiveEnabled).toBe(false)
/* 微信刚启动时 4290 还没起来,这时落盘会把正常正常用户的开关误关 */
expect(d.persistDisable).toBe(false)
expect(isDefinitelyBlocked(cap)).toBe(false)
expect(isEntitlementBlocked(cap)).toBe(true)
})
it('组件缺失 → 显示关闭,落盘关掉(OSS 包的典型状态)', () => {
const cap = capability({
nativeComponentState: 'missing',
canEnable: false,
reasonCode: 'COMPONENT_MISSING',
message: '未安装发送能力组件'
})
const d = resolveExitNoticeGate(cap, true)
expect(d.desiredEnabled).toBe(false)
expect(d.persistDisable).toBe(true)
})
it('组件架构不匹配 → 显示关闭并落盘', () => {
const cap = capability({
nativeComponentState: 'incompatible',
canEnable: false,
reasonCode: 'COMPONENT_INVALID'
})
expect(resolveExitNoticeGate(cap, true).persistDisable).toBe(true)
})
it('授权与组件都就绪、只是微信库没连 → 保留用户意愿,不显示成已生效', () => {
const cap = capability({
databaseReady: false,
canEnable: false,
reasonCode: 'DATABASE_UNAVAILABLE',
message: '微信数据库尚未连接'
})
const d = resolveExitNoticeGate(cap, true)
expect(d.desiredEnabled).toBe(true)
expect(d.effectiveEnabled).toBe(false)
/* 库连上是暂时的,不能因此把人家的开关关掉 */
expect(d.persistDisable).toBe(false)
})
it('平台不支持(公开版/非 Windows-mac 包)→ 显示关闭并落盘', () => {
const cap = capability({
entitlementState: 'unsupported',
canEnable: false,
reasonCode: 'UNSUPPORTED_PLATFORM',
databaseReady: false
})
const d = resolveExitNoticeGate(cap, true)
expect(d.desiredEnabled).toBe(false)
expect(d.persistDisable).toBe(true)
})
it('授权正在验证(pending)→ 先按关闭显示,不改写设置', () => {
const cap = capability({
entitlementState: 'pending',
canEnable: false,
reasonCode: 'LICENSE_PENDING'
})
const d = resolveExitNoticeGate(cap, true)
expect(d.desiredEnabled).toBe(false)
expect(d.persistDisable).toBe(false)
})
})
describe('两个微信内开关的呈现(防撤回 / 退群提示必须一致)', () => {
const expired = capability({
entitlementState: 'invalid',
canEnable: false,
reasonCode: 'LICENSE_EXPIRED'
})
const unavailable = capability({
entitlementState: 'unavailable',
canEnable: false,
reasonCode: 'LICENSE_UNAVAILABLE'
})
const noComponent = capability({
nativeComponentState: 'missing',
canEnable: false,
reasonCode: 'COMPONENT_MISSING'
})
it('报障场景:库里 recall=1 且本地退群=true,没有授权 → 两个都显示关闭', () => {
for (const cap of [expired, unavailable, noComponent]) {
expect(resolveSwitchPresentation('recall_notice', true, cap)).toEqual({
desiredEnabled: false,
effectiveEnabled: false
})
expect(resolveSwitchPresentation('group_exit_notice', true, cap)).toEqual({
desiredEnabled: false,
effectiveEnabled: false
})
}
})
it('授权与组件都就绪、库已连接 → 两个都保持用户设置', () => {
const ok = capability({})
expect(resolveSwitchPresentation('recall_notice', true, ok)).toEqual({
desiredEnabled: true,
effectiveEnabled: true
})
expect(resolveSwitchPresentation('group_exit_notice', true, ok)).toEqual({
desiredEnabled: true,
effectiveEnabled: true
})
})
it('只是微信库没连 → 保留用户意愿但 effective 为 false', () => {
const noDb = capability({
databaseReady: false,
canEnable: false,
reasonCode: 'DATABASE_UNAVAILABLE'
})
expect(resolveSwitchPresentation('recall_notice', true, noDb)).toEqual({
desiredEnabled: true,
effectiveEnabled: false
})
expect(resolveSwitchPresentation('group_exit_notice', true, noDb)).toEqual({
desiredEnabled: true,
effectiveEnabled: false
})
})
it('用户本来就关着 + 无授权 → 依然是关闭,不会被"授权没问题"之外的逻辑打开', () => {
expect(resolveSwitchPresentation('recall_notice', false, expired).desiredEnabled).toBe(false)
expect(resolveSwitchPresentation('group_exit_notice', false, expired).desiredEnabled).toBe(
false
)
})
})
@@ -0,0 +1,134 @@
import crypto from 'node:crypto'
import fs from 'node:fs'
import os from 'node:os'
import path from 'node:path'
import { afterEach, beforeEach, describe, expect, it } from 'vitest'
import {
resetComponentCache,
resolveExternalComponent
} from '../../src/main/services/external-component-locator'
/** 组件发现必须 fail-closed:指针/目录/哈希任一不对都当没装。 */
let tmpRoot = ''
let localAppData = ''
function writeFile(filePath: string, content: Buffer | string): Buffer {
fs.mkdirSync(path.dirname(filePath), { recursive: true })
const buf = Buffer.isBuffer(content) ? content : Buffer.from(content)
fs.writeFileSync(filePath, buf)
return buf
}
function sha256(buf: Buffer): string {
return crypto.createHash('sha256').update(buf).digest('hex')
}
function buildBundle(options: { dirty?: boolean; corruptHash?: boolean } = {}): string {
const versionDir = path.join(localAppData, 'TraceMemo', 'Pro', 'windows-x64', '1.0.0')
const wcdbApi = writeFile(path.join(versionDir, 'wcdb_api.dll'), Buffer.alloc(2048, 0x11))
const wcdb = writeFile(path.join(versionDir, 'WCDB.dll'), Buffer.alloc(4096, 0x22))
const helper = writeFile(path.join(versionDir, 'tm-wcdb-config-helper.exe'), Buffer.alloc(1024, 0x33))
const manifest = {
schemaVersion: 1,
componentVersion: '1.0.0',
worktreeDirty: options.dirty === true,
files: [
{ path: 'wcdb_api.dll', size: wcdbApi.length, sha256: sha256(wcdbApi) },
{ path: 'WCDB.dll', size: wcdb.length, sha256: sha256(wcdb) },
{
path: 'tm-wcdb-config-helper.exe',
size: helper.length,
sha256: options.corruptHash ? 'a'.repeat(64) : sha256(helper)
}
]
}
writeFile(path.join(versionDir, 'manifest.json'), JSON.stringify(manifest, null, 2))
writeFile(
path.join(localAppData, 'TraceMemo', 'Pro', 'windows-x64', 'current.json'),
JSON.stringify({ version: '1.0.0', dir: versionDir }, null, 2)
)
return versionDir
}
beforeEach(() => {
tmpRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'tm-locator-'))
localAppData = path.join(tmpRoot, 'LocalAppData')
fs.mkdirSync(localAppData, { recursive: true })
resetComponentCache()
})
afterEach(() => {
fs.rmSync(tmpRoot, { recursive: true, force: true })
resetComponentCache()
})
const env = (): NodeJS.ProcessEnv => ({ LOCALAPPDATA: localAppData })
describe('resolveExternalComponent', () => {
it('没有 current.json 时返回 null(= 组件没装)', () => {
expect(resolveExternalComponent(env(), 'win32')).toBeNull()
})
it('非 Windows 直接返回 null', () => {
buildBundle()
expect(resolveExternalComponent(env(), 'darwin')).toBeNull()
})
it('校验通过时返回 helper 路径与版本', () => {
const dir = buildBundle()
const found = resolveExternalComponent(env(), 'win32')
expect(found).not.toBeNull()
expect(found?.helperPath).toBe(path.join(dir, 'tm-wcdb-config-helper.exe'))
expect(found?.version).toBe('1.0.0')
expect(found?.dirty).toBe(false)
})
it('dirty 标记透传(内部调试构建)', () => {
buildBundle({ dirty: true })
expect(resolveExternalComponent(env(), 'win32')?.dirty).toBe(true)
})
it('哈希不符时当作没装(不能返回可疑路径)', () => {
buildBundle({ corruptHash: true })
expect(resolveExternalComponent(env(), 'win32')).toBeNull()
})
it('指针指向的目录不存在时返回 null', () => {
writeFile(
path.join(localAppData, 'TraceMemo', 'Pro', 'windows-x64', 'current.json'),
JSON.stringify({ version: '1.0.0', dir: path.join(tmpRoot, 'gone') })
)
expect(resolveExternalComponent(env(), 'win32')).toBeNull()
})
it('manifest 缺失时返回 null', () => {
const dir = buildBundle()
fs.rmSync(path.join(dir, 'manifest.json'))
expect(resolveExternalComponent(env(), 'win32')).toBeNull()
})
it('helper 缺失时返回 null', () => {
const dir = buildBundle()
fs.rmSync(path.join(dir, 'tm-wcdb-config-helper.exe'))
resetComponentCache()
expect(resolveExternalComponent(env(), 'win32')).toBeNull()
})
it('文件被替换后校验会重新计算(不吃旧缓存)', () => {
const dir = buildBundle()
expect(resolveExternalComponent(env(), 'win32')).not.toBeNull()
/* 篡改 WCDB.dll 内容但不改 mtime 之外的东西:manifest mtime 变了就要重算 */
const target = path.join(dir, 'WCDB.dll')
fs.writeFileSync(target, Buffer.alloc(4096, 0x99))
const manifestPath = path.join(dir, 'manifest.json')
const stat = fs.statSync(manifestPath)
fs.utimesSync(manifestPath, stat.atime, new Date(stat.mtimeMs + 5000))
expect(resolveExternalComponent(env(), 'win32')).toBeNull()
})
})
@@ -0,0 +1,70 @@
import { describe, expect, it } from 'vitest'
import { resolveLicenseRefreshFailure } from '../../src/main/services/mac-wechat-runtime-manager'
import type { MacLicenseStatus } from '../../src/shared/personal-wechat-mac-license'
const DEVICE_ID = `mac_${'a'.repeat(64)}`
function status(overrides: Partial<MacLicenseStatus> = {}): MacLicenseStatus {
return {
deviceId: DEVICE_ID,
state: 'cached',
authorized: true,
source: 'cache',
features: ['wechat'],
lastCheckedAt: '2026-11-04T07:00:00Z',
licenseExpiresAt: null,
tokenExpiresAt: '2026-11-05T07:00:00Z',
message: '授权有效(本地缓存)',
...overrides
}
}
const DIAGNOSTIC = '无法连接授权服务器,请检查网络后重试'
describe('resolveLicenseRefreshFailure', () => {
it('有效缓存时保留授权,并把本次失败写进诊断信息', () => {
const result = resolveLicenseRefreshFailure(status(), DIAGNOSTIC)
// 授权状态不变 —— 网络故障不能让已授权设备变成未授权。
expect(result.authorized).toBe(true)
expect(result.state).toBe('cached')
expect(result.deviceId).toBe(DEVICE_ID)
expect(result.features).toEqual(['wechat'])
// 但这次失败必须可见,不能被快照整个盖掉。
expect(result.message).toContain('本次刷新失败')
expect(result.message).toContain(DIAGNOSTIC)
expect(result.message).toContain('本地缓存授权')
})
it('无有效缓存时明确报 server_unavailable,而不是未授权或已撤销', () => {
const result = resolveLicenseRefreshFailure(null, DIAGNOSTIC)
expect(result.state).toBe('server_unavailable')
expect(result.authorized).toBe(false)
expect(result.state).not.toBe('revoked')
expect(result.state).not.toBe('unlicensed')
expect(result.message).toBe(DIAGNOSTIC)
})
it('快照存在但未授权时同样按网络故障处理', () => {
const result = resolveLicenseRefreshFailure(
status({ state: 'unlicensed', authorized: false, message: '当前设备暂无发送能力授权' }),
DIAGNOSTIC
)
expect(result.state).toBe('server_unavailable')
expect(result.authorized).toBe(false)
expect(result.message).toBe(DIAGNOSTIC)
})
it('不把 revoked 快照改写成授权有效', () => {
const result = resolveLicenseRefreshFailure(
status({ state: 'revoked', authorized: false, message: '授权已被撤销' }),
DIAGNOSTIC
)
expect(result.authorized).toBe(false)
expect(result.state).toBe('server_unavailable')
})
})
@@ -1,127 +0,0 @@
import { createRequire } from 'module'
import { existsSync, mkdirSync, mkdtempSync, writeFileSync } from 'fs'
import { tmpdir } from 'os'
import { join } from 'path'
import { describe, expect, it } from 'vitest'
import {
bindingMatchesRuntimeManifest,
readMacWechatRuntimeManifest
} from '../../src/main/services/mac-wechat-runtime-artifact'
const nodeRequire = createRequire(import.meta.url)
const { readAndValidateArtifact, syncArtifact } = nodeRequire(
'../../scripts/prepare-wechat-native-runtime.cjs'
) as {
readAndValidateArtifact: (sourceDir: string) => { manifest: { tmSendSourceSha256: string } }
syncArtifact: (sourceDir: string, targetDir: string) => unknown
}
const AGENT_HASH = 'a'.repeat(64)
const ADDRESS_PROFILE_HASH = 'b'.repeat(64)
function writeMachOArm64(filePath: string, suffix = Buffer.alloc(0)): void {
const header = Buffer.alloc(32)
header.writeUInt32LE(0xfeedfacf, 0)
header.writeUInt32LE(0x0100000c, 4)
writeFileSync(filePath, Buffer.concat([header, suffix]))
}
function createArtifact(root: string): void {
writeMachOArm64(join(root, 'tm-wechat-host'))
writeMachOArm64(
join(root, 'libtmwechat.dylib'),
Buffer.from(`${AGENT_HASH}${ADDRESS_PROFILE_HASH}`)
)
writeFileSync(
join(root, 'runtime-manifest.json'),
JSON.stringify({
runtime: 'tm-wechat-native',
version: '0.1.0',
platform: 'darwin-arm64',
architecture: 'arm64',
protocolVersion: 1,
buildCommit: 'test',
tmSendSourceSha256: AGENT_HASH,
addressProfileSha256: ADDRESS_PROFILE_HASH,
supportedWechatVersions: ['4.1.11.53'],
capabilities: ['text', 'image', 'voice']
})
)
}
describe('macOS self-contained WeChat runtime artifact', () => {
it('validates the manifest, architecture, capabilities and embedded agent identity', () => {
const root = mkdtempSync(join(tmpdir(), 'tm-native-runtime-'))
createArtifact(root)
const manifest = readMacWechatRuntimeManifest(root, 'arm64')
expect(manifest.tmSendSourceSha256).toBe(AGENT_HASH)
expect(
bindingMatchesRuntimeManifest(
{
hostPid: 123,
runtimeVersion: 'tm-wechat-runtime/0.1.0',
embeddedAgentSha256: AGENT_HASH,
embeddedAddressProfileSha256: ADDRESS_PROFILE_HASH
},
manifest
)
).toBe(true)
expect(
bindingMatchesRuntimeManifest(
{ hostPid: 123, runtimeVersion: 'tm-wechat-runtime/0.1.0' },
manifest
)
).toBe(false)
expect(
bindingMatchesRuntimeManifest(
{
runtimeVersion: 'tm-wechat-runtime/0.1.0',
embeddedAgentSha256: AGENT_HASH
},
manifest
)
).toBe(false)
})
it('rejects a manifest whose embedded address profile hash is absent from the dylib', () => {
const root = mkdtempSync(join(tmpdir(), 'tm-native-runtime-profile-mismatch-'))
createArtifact(root)
writeFileSync(
join(root, 'runtime-manifest.json'),
JSON.stringify({
runtime: 'tm-wechat-native',
version: '0.1.0',
platform: 'darwin-arm64',
architecture: 'arm64',
protocolVersion: 1,
buildCommit: 'test',
tmSendSourceSha256: AGENT_HASH,
addressProfileSha256: 'c'.repeat(64),
supportedWechatVersions: ['4.1.11.53'],
capabilities: ['text', 'image', 'voice']
})
)
expect(() => readMacWechatRuntimeManifest(root, 'arm64')).toThrow(/address profile hash/)
})
it('prepares an exact runtime tree and removes old external agent and table directories', () => {
const source = mkdtempSync(join(tmpdir(), 'tm-native-source-'))
const target = mkdtempSync(join(tmpdir(), 'tm-native-target-parent-'))
const targetRuntime = join(target, 'darwin-arm64')
createArtifact(source)
mkdirSync(join(targetRuntime, 'scripts'), { recursive: true })
writeFileSync(join(targetRuntime, 'scripts', 'tm_send.js'), 'old external agent')
mkdirSync(join(targetRuntime, 'wechat_version'), { recursive: true })
writeFileSync(join(targetRuntime, 'wechat_version', '4_1_11_53_mac.json'), '{}')
expect(readAndValidateArtifact(source).manifest.tmSendSourceSha256).toBe(AGENT_HASH)
syncArtifact(source, targetRuntime)
expect(existsSync(join(targetRuntime, 'scripts'))).toBe(false)
expect(existsSync(join(targetRuntime, 'wechat_version'))).toBe(false)
expect(existsSync(join(targetRuntime, 'runtime-manifest.json'))).toBe(true)
expect(readAndValidateArtifact(targetRuntime).manifest.tmSendSourceSha256).toBe(AGENT_HASH)
})
})
@@ -0,0 +1,165 @@
import { describe, expect, it, vi } from 'vitest'
import {
cleanupMacWechatResidualProcesses,
inspectMacWechatResidualProcesses,
readPids,
type MacWechatResidualCleanupDependencies
} from '../../src/main/services/mac-wechat-residual-cleanup'
function createDependencies(
overrides: Partial<MacWechatResidualCleanupDependencies> = {}
): MacWechatResidualCleanupDependencies {
return {
platform: 'darwin',
listWechatPids: vi.fn(async () => [101]),
listPortPids: vi.fn(async () => [202]),
processName: vi.fn(async (pid) => (pid === 101 ? 'WeChat' : 'tm-wechat-host')),
processIdentity: vi.fn(async (pid) => 'identity-' + pid),
signal: vi.fn(),
wait: vi.fn(async () => undefined),
...overrides
}
}
describe('macOS WeChat residual cleanup', () => {
it('treats pgrep exit code 1 as no matching process', async () => {
const run = vi.fn(async () => {
throw Object.assign(new Error('Command failed: /usr/bin/pgrep -x Weixin'), { code: 1 })
})
await expect(readPids('/usr/bin/pgrep', ['-x', 'Weixin'], run)).resolves.toEqual([])
})
it('lists only WeChat processes and port 4290 listeners', async () => {
const dependencies = createDependencies()
await expect(inspectMacWechatResidualProcesses(dependencies)).resolves.toEqual([
{ pid: 101, name: 'WeChat', targets: ['wechat'], confirmationToken: 'identity-101' },
{
pid: 202,
name: 'tm-wechat-host',
targets: ['port_4290'],
confirmationToken: 'identity-202'
}
])
expect(dependencies.processName).toHaveBeenCalledTimes(2)
})
it('does not signal a PID whose process identity changed after confirmation', async () => {
const dependencies = createDependencies({
listWechatPids: vi.fn(async () => []),
listPortPids: vi.fn(async () => [202]),
processIdentity: vi.fn(async () => 'changed-process')
})
const result = await cleanupMacWechatResidualProcesses(
[{ pid: 202, confirmationToken: 'old-process' }],
dependencies
)
expect(dependencies.signal).not.toHaveBeenCalled()
expect(result.remaining).toEqual([
{
pid: 202,
name: 'tm-wechat-host',
targets: ['port_4290'],
confirmationToken: 'changed-process'
}
])
})
it('uses graceful termination first and only escalates confirmed targets', async () => {
const signalled: Array<[number, NodeJS.Signals]> = []
const dependencies = createDependencies({
listWechatPids: vi.fn(async () => []),
listPortPids: vi.fn(async () => [202]),
signal: vi.fn((pid, signal) => signalled.push([pid, signal]))
})
const targets = await inspectMacWechatResidualProcesses(dependencies)
const result = await cleanupMacWechatResidualProcesses(
[{ pid: 202, confirmationToken: targets[0].confirmationToken }],
dependencies
)
expect(signalled).toEqual([
[202, 'SIGTERM'],
[202, 'SIGKILL']
])
expect(result.remaining.map((target) => target.pid)).toEqual([202])
})
it('reports only identity-matched targets before signaling so the caller can stop its own runtime safely', async () => {
const dependencies = createDependencies({
listWechatPids: vi.fn(async () => []),
listPortPids: vi.fn(async () => [202, 303]),
processIdentity: vi.fn(async (pid) =>
pid === 202 ? 'identity-202' : 'stale-confirmation-303'
),
processName: vi.fn(async (pid) => 'process-' + pid),
signal: vi.fn()
})
const onTargetsConfirmed = vi.fn()
await cleanupMacWechatResidualProcesses(
[{ pid: 202, confirmationToken: 'identity-202' }],
dependencies,
onTargetsConfirmed
)
expect(onTargetsConfirmed).toHaveBeenCalledWith([
{
pid: 202,
name: 'process-202',
targets: ['port_4290'],
confirmationToken: 'identity-202'
}
])
expect(dependencies.signal).toHaveBeenCalledWith(202, 'SIGTERM')
expect(dependencies.signal).not.toHaveBeenCalledWith(303, expect.any(String))
})
it('does not signal a process after its PID identity changes', async () => {
let identityReads = 0
const dependencies = createDependencies({
listWechatPids: vi.fn(async () => []),
listPortPids: vi.fn(async () => [202]),
processIdentity: vi.fn(async () => {
identityReads += 1
return identityReads === 1 ? 'confirmed-process' : 'reused-pid-process'
}),
signal: vi.fn()
})
const onTargetsConfirmed = vi.fn()
const result = await cleanupMacWechatResidualProcesses(
[{ pid: 202, confirmationToken: 'confirmed-process' }],
dependencies,
onTargetsConfirmed
)
expect(dependencies.signal).not.toHaveBeenCalled()
expect(onTargetsConfirmed).not.toHaveBeenCalled()
expect(result.stopped).toEqual([])
expect(result.remaining[0]).toMatchObject({
pid: 202,
confirmationToken: 'reused-pid-process'
})
})
it('does nothing outside macOS', async () => {
const dependencies = createDependencies({ platform: 'win32' })
await expect(inspectMacWechatResidualProcesses(dependencies)).resolves.toEqual([])
await expect(
cleanupMacWechatResidualProcesses(
[{ pid: 101, confirmationToken: 'identity-101' }],
dependencies
)
).resolves.toEqual({
stopped: [],
remaining: []
})
expect(dependencies.signal).not.toHaveBeenCalled()
})
})
@@ -1,138 +0,0 @@
import { describe, expect, it, vi } from 'vitest'
vi.mock('electron', () => ({
app: {
getAppPath: () => '/fixture/app',
isPackaged: false
}
}))
import {
deriveMacWechatSenderStatus,
shouldClearWechatRestartRequired
} from '../../src/main/services/mac-wechat-runtime-manager'
import type {
MacWechatBindingStatus,
MacWechatRuntimeManifest,
MacWechatRuntimeSnapshot
} from '../../src/shared/personal-wechat-mac-runtime'
const AGENT_HASH = 'a'.repeat(64)
const ADDRESS_PROFILE_HASH = 'b'.repeat(64)
const manifest: MacWechatRuntimeManifest = {
runtime: 'tm-wechat-native',
version: '0.1.0',
platform: 'darwin-arm64',
architecture: 'arm64',
protocolVersion: 1,
buildCommit: 'test',
tmSendSourceSha256: AGENT_HASH,
addressProfileSha256: ADDRESS_PROFILE_HASH,
supportedWechatVersions: ['4.1.11.53'],
capabilities: ['text', 'image', 'voice']
}
function snapshot(overrides: Partial<MacWechatRuntimeSnapshot> = {}): MacWechatRuntimeSnapshot {
return {
lifecycle: 'online',
wechatRestartRequired: false,
endpoint: 'http://127.0.0.1:4290',
port: 4290,
manifest,
...overrides
}
}
function binding(overrides: Partial<MacWechatBindingStatus> = {}): MacWechatBindingStatus {
return {
runtime: true,
hostPid: 123,
runtimeState: 'ready',
runtimeVersion: 'tm-wechat-runtime/0.1.0',
embeddedAgentSha256: AGENT_HASH,
embeddedAddressProfileSha256: ADDRESS_PROFILE_HASH,
wechatRunning: true,
wechatPid: 456,
wechatVersion: '4.1.11.53',
supported: true,
bindingState: 'ready',
bound: true,
boundWechatPid: 456,
sessionAttached: true,
scriptLoaded: true,
sendContextReady: true,
canSendText: true,
canSendImage: true,
canSendVoice: true,
attachCount: 1,
...overrides
}
}
describe('macOS native runtime sender status mapping', () => {
it('exposes capabilities only for a ready binding with matching runtime identity', () => {
expect(
deriveMacWechatSenderStatus({ snapshot: snapshot(), binding: binding(), manifest })
).toMatchObject({
state: 'online',
runtimeReady: true,
attachReady: true,
baseAddressReady: true,
messageListenerReady: true,
canSend: true,
canSendText: true,
canSendImage: true,
canSendVoice: true
})
})
it('rejects a live host whose embedded runtime identity does not match the manifest', () => {
const status = deriveMacWechatSenderStatus({
snapshot: snapshot(),
binding: binding({ embeddedAgentSha256: 'b'.repeat(64) }),
manifest
})
expect(status).toMatchObject({
state: 'error',
runtimeReady: false,
canSend: false,
canSendText: false,
canSendImage: false,
canSendVoice: false
})
expect(status.error).toContain('Native Runtime 不一致')
})
it('maps a stale binding to a rebind-required stopped state', () => {
expect(
deriveMacWechatSenderStatus({
snapshot: snapshot(),
binding: binding({ bindingState: 'stale', sendContextReady: false }),
manifest
})
).toMatchObject({
state: 'stopped',
message: '检测到微信已重启,请重新绑定',
canSend: false
})
})
it('keeps restart-required errors above otherwise ready binding state', () => {
expect(
deriveMacWechatSenderStatus({
snapshot: snapshot({ wechatRestartRequired: true }),
binding: binding(),
manifest
})
).toMatchObject({ state: 'error', canSend: false })
})
it('clears restart-required only after WeChat has a different positive pid', () => {
expect(shouldClearWechatRestartRequired(100, 200)).toBe(true)
expect(shouldClearWechatRestartRequired(100, 100)).toBe(false)
expect(shouldClearWechatRestartRequired(0, 200)).toBe(false)
expect(shouldClearWechatRestartRequired(100, 0)).toBe(false)
})
})
+247
View File
@@ -0,0 +1,247 @@
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { KeyServiceMac } from '../../src/main/key-service-mac'
import {
ARCH_MISMATCH_X64_ON_ARM_ERROR,
buildMacArchSnapshot,
resolveMacKeyFlow,
shouldProbeIntelEnvironment,
type MacArchInput
} from '../../src/shared/macos-arch'
/**
* 密钥流程的选择依据是「硬件 + 运行架构 + 转译状态」三者组合,
* 不是单一的 `process.arch`。这组用例把组合表钉死,
* 避免以后有人把判定简化回 `process.arch === 'x64'`。
*/
function input(overrides: Partial<MacArchInput>): MacArchInput {
return {
platform: 'darwin',
hardwareArch: 'arm64',
runtimeArch: 'arm64',
underARM64Translation: false,
...overrides
}
}
describe('resolveMacKeyFlow', () => {
it('runs the Apple Silicon flow on native arm64', () => {
expect(resolveMacKeyFlow(input({}))).toBe('apple-silicon')
})
it('blocks the Intel flow when Rosetta is reported, even if hardware is unknown', () => {
expect(
resolveMacKeyFlow(input({ hardwareArch: 'unknown', runtimeArch: 'x64', underARM64Translation: true }))
).toBe('arch-mismatch')
})
it('blocks the Intel flow when hardware is arm64 but the translation flag is missing', () => {
expect(
resolveMacKeyFlow(input({ hardwareArch: 'arm64', runtimeArch: 'x64', underARM64Translation: false }))
).toBe('arch-mismatch')
})
it('keeps the Intel flow on a real Intel Mac', () => {
expect(
resolveMacKeyFlow(input({ hardwareArch: 'x64', runtimeArch: 'x64', underARM64Translation: false }))
).toBe('intel')
})
it('falls back to the Intel flow when hardware cannot be read but nothing looks translated', () => {
expect(
resolveMacKeyFlow(input({ hardwareArch: 'unknown', runtimeArch: 'x64', underARM64Translation: false }))
).toBe('intel')
})
it('treats other platforms as unsupported', () => {
expect(
resolveMacKeyFlow(input({ platform: 'win32', hardwareArch: 'x64', runtimeArch: 'x64' }))
).toBe('unsupported')
})
it('treats an unexpected runtime architecture as unsupported', () => {
expect(resolveMacKeyFlow(input({ runtimeArch: 'ia32' }))).toBe('unsupported')
})
})
describe('buildMacArchSnapshot', () => {
it('records the unknown hardware signal without changing the Intel flow', () => {
const snapshot = buildMacArchSnapshot(
input({ hardwareArch: 'unknown', runtimeArch: 'x64', underARM64Translation: false })
)
expect(snapshot.macKeyFlow).toBe('intel')
expect(snapshot.anomalies).toContain('hardware_arch_unknown')
})
it('records a translated process whose hardware probe disagreed', () => {
const snapshot = buildMacArchSnapshot(
input({ hardwareArch: 'x64', runtimeArch: 'x64', underARM64Translation: true })
)
expect(snapshot.macKeyFlow).toBe('arch-mismatch')
expect(snapshot.anomalies).toContain('translation_flag_without_arm_hardware')
})
it('records a translation flag on a native arm64 process', () => {
const snapshot = buildMacArchSnapshot(input({ underARM64Translation: true }))
expect(snapshot.macKeyFlow).toBe('apple-silicon')
expect(snapshot.anomalies).toContain('translation_flag_with_native_arm64')
})
it('flags an x64 runtime on Apple silicon that reports no translation', () => {
const snapshot = buildMacArchSnapshot(
input({ hardwareArch: 'arm64', runtimeArch: 'x64', underARM64Translation: false })
)
expect(snapshot.macKeyFlow).toBe('arch-mismatch')
expect(snapshot.anomalies).toContain('x64_runtime_on_arm_without_translation_flag')
})
})
describe('ARCH_MISMATCH_X64_ON_ARM_ERROR', () => {
it('tells the user to install the arm64 build', () => {
expect(ARCH_MISMATCH_X64_ON_ARM_ERROR).toContain('Apple Silicon')
expect(ARCH_MISMATCH_X64_ON_ARM_ERROR).toContain('arm64')
})
})
describe('shouldProbeIntelEnvironment', () => {
it('only probes on a genuine Intel Mac', () => {
expect(shouldProbeIntelEnvironment('intel')).toBe(true)
expect(shouldProbeIntelEnvironment('apple-silicon')).toBe(false)
expect(shouldProbeIntelEnvironment('arch-mismatch')).toBe(false)
expect(shouldProbeIntelEnvironment('unsupported')).toBe(false)
})
})
const { spawnMock, execFileMock, flowState } = vi.hoisted(() => ({
spawnMock: vi.fn(),
execFileMock: vi.fn(),
flowState: { flow: 'arch-mismatch' as 'apple-silicon' | 'intel' | 'arch-mismatch' | 'unsupported' }
}))
vi.mock('child_process', () => ({
spawn: (...args: unknown[]) => spawnMock(...args),
execFile: (...args: unknown[]) => execFileMock(...args)
}))
vi.mock('electron', () => ({
app: {
getPath: () => '/tmp/tracememo-fixture-userdata',
getVersion: () => '0.0.0',
isPackaged: false
},
safeStorage: {
isEncryptionAvailable: () => false,
encryptString: () => Buffer.from(''),
decryptString: () => ''
}
}))
vi.mock('../../src/main/macos-arch', () => ({
getMacArchSnapshot: () => ({
platform: 'darwin',
hardwareArch: flowState.flow === 'intel' ? 'x64' : 'arm64',
runtimeArch: flowState.flow === 'intel' ? 'x64' : 'x64',
underARM64Translation: flowState.flow === 'arch-mismatch',
macKeyFlow: flowState.flow,
anomalies: []
}),
resetMacArchSnapshotCache: () => undefined
}))
describe('KeyServiceMac arch guard', () => {
beforeEach(() => {
spawnMock.mockReset()
execFileMock.mockReset()
flowState.flow = 'arch-mismatch'
})
/** 列出所有被 spawn/execFile 触达的可执行文件,用于断言「什么也没启动」。 */
const execFileCommands = (): string[] => execFileMock.mock.calls.map((call) => String(call[0]))
it('returns ARCH_MISMATCH_X64_ON_ARM without spawning anything', async () => {
const service = new KeyServiceMac()
const result = await service.autoGetDbKey(undefined, 60_000, '/tmp/fixture-account')
expect(result.success).toBe(false)
expect(result.code).toBe('ARCH_MISMATCH_X64_ON_ARM')
expect(result.error).toBe(ARCH_MISMATCH_X64_ON_ARM_ERROR)
expect(spawnMock).not.toHaveBeenCalled()
expect(execFileMock).not.toHaveBeenCalled()
})
it('never touches csrutil, pgrep or osascript on a mismatched machine', async () => {
const service = new KeyServiceMac()
await service.autoGetDbKey(undefined, 60_000, '/tmp/fixture-account')
const commands = execFileCommands()
// csrutil = SIP 探测,pgrep = 查找微信进程,osascript = 请求管理员授权执行 helper
expect(commands).not.toContain('/usr/bin/csrutil')
expect(commands).not.toContain('/usr/bin/pgrep')
expect(commands).not.toContain('/usr/bin/osascript')
expect(spawnMock).not.toHaveBeenCalled()
})
it('checks the architecture before SIP, so a mismatch never reports SIP_ENABLED', async () => {
execFileMock.mockImplementation((_cmd, _args, _options, callback) => {
callback(null, { stdout: 'System Integrity Protection status: enabled.' }, '')
})
const service = new KeyServiceMac()
const result = await service.autoGetDbKey(undefined, 60_000, '/tmp/fixture-account')
expect(result.code).toBe('ARCH_MISMATCH_X64_ON_ARM')
expect(result.code).not.toBe('SIP_ENABLED')
expect(execFileMock).not.toHaveBeenCalled()
})
it('refuses to install the Intel runtime on a mismatched machine', async () => {
const service = new KeyServiceMac()
const result = await service.installIntelKeyRuntime()
expect(result.success).toBe(false)
expect(result.code).toBe('ARCH_MISMATCH_X64_ON_ARM')
expect(spawnMock).not.toHaveBeenCalled()
})
it('does not spawn the Intel helper when refreshing the environment', async () => {
const service = new KeyServiceMac()
const status = await service.getIntelEnvironmentStatus()
expect(status).toEqual({
sipDisabled: false,
pythonAvailable: false,
fridaAvailable: false,
wechatAdhocSigned: false
})
expect(spawnMock).not.toHaveBeenCalled()
})
it('still reports SIP_ENABLED on a genuine Intel Mac', async () => {
flowState.flow = 'intel'
// promisify(execFile) 在只传两个参数时把 callback 放在第三个位置。
execFileMock.mockImplementation((_cmd, _args, options, callback) => {
const done = typeof options === 'function' ? options : callback
done(null, { stdout: 'System Integrity Protection status: enabled.' }, '')
})
const service = new KeyServiceMac()
const result = await service.autoGetDbKey(undefined, 60_000, '/tmp/fixture-account')
expect(result.code).toBe('SIP_ENABLED')
expect(spawnMock).not.toHaveBeenCalled()
})
it('never reaches the Intel helper on the Apple Silicon flow', async () => {
flowState.flow = 'apple-silicon'
execFileMock.mockImplementation((_cmd, _args, options, callback) => {
const done = typeof options === 'function' ? options : callback
done(null, { stdout: '' }, '')
})
const service = new KeyServiceMac()
const result = await service.autoGetDbKey(undefined, 60_000, '/tmp/fixture-account')
expect(result.code).not.toBe('ARCH_MISMATCH_X64_ON_ARM')
// Intel helper 是唯一的 spawn 调用点;arm64 流程走 osascript + xkey_helper,不会经过它。
expect(spawnMock).not.toHaveBeenCalled()
})
})
+269
View File
@@ -0,0 +1,269 @@
import fs from 'node:fs'
import os from 'node:os'
import path from 'node:path'
import { afterEach, describe, expect, it, vi } from 'vitest'
import {
MessageInsertCapabilityService,
inspectNativeComponent,
mapLicenseStatus,
type CapabilityInput,
type LicenseProbeResult,
type CapabilityDeps
} from '../../src/main/services/msg-insert-capability-service'
/** 判定矩阵:不确定即拒、三种原因可区分、关闭不受授权影响。 */
const tmpDirs: string[] = []
function makeTempDir(): string {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'tm-cap-'))
tmpDirs.push(dir)
return dir
}
/** 造一个最小的合法 PE:MZ + e_lfanew + PE 签名 + machine */
function writeFakePe(
machine = process.arch === 'arm64' ? 0xaa64 : 0x8664,
size = 4096
): string {
const dir = makeTempDir()
const file = path.join(dir, 'tm-wcdb-config-helper.exe')
const buf = Buffer.alloc(size)
buf.write('MZ', 0, 'ascii')
buf.writeUInt32LE(0x80, 0x3c)
buf.write('PE\0\0', 0x80, 'ascii')
buf.writeUInt16LE(machine, 0x80 + 4)
fs.writeFileSync(file, buf)
return file
}
afterEach(() => {
for (const dir of tmpDirs.splice(0)) fs.rmSync(dir, { recursive: true, force: true })
vi.restoreAllMocks()
})
function makeService(options: {
platform?: NodeJS.Platform
probe?: () => Promise<LicenseProbeResult>
component?: string | null
macBundle?: boolean
now?: () => number
}): { service: MessageInsertCapabilityService; probeCalls: () => number } {
let calls = 0
const deps: CapabilityDeps = {
platform: options.platform ?? 'win32',
hasMacNativeBundle: () => options.macBundle === true,
isMacRuntimeUnavailable: () => options.macBundle !== true,
resolveNativeComponent: () => (options.component === undefined ? null : options.component),
probeLicense: async () => {
calls += 1
if (options.probe) return options.probe()
return { ok: true, status: 'LICENSE_OK' }
},
now: options.now
}
return { service: new MessageInsertCapabilityService(deps), probeCalls: () => calls }
}
const dbReady: CapabilityInput = { databaseReady: true }
const dbDown: CapabilityInput = { databaseReady: false }
describe('mapLicenseStatus', () => {
it('只有 LICENSE_OK 算有效', () => {
expect(mapLicenseStatus('LICENSE_OK').entitlement).toBe('valid')
for (const status of [
'LICENSE_EXPIRED',
'LICENSE_MACHINE_MISMATCH',
'LICENSE_REVOKED',
'LICENSE_INVALID',
'LICENSE_TAMPERED',
'LICENSE_NOT_FOUND'
]) {
expect(mapLicenseStatus(status).entitlement).toBe('invalid')
}
})
it('校验中与网络错误都不算有效,也不能算「没买」', () => {
expect(mapLicenseStatus('LICENSE_CHECKING').entitlement).toBe('pending')
expect(mapLicenseStatus('LICENSE_NETWORK_ERROR').entitlement).toBe('unavailable')
expect(mapLicenseStatus('LICENSE_SERVER_ERROR').entitlement).toBe('unavailable')
expect(mapLicenseStatus(undefined).entitlement).toBe('unavailable')
expect(mapLicenseStatus('SOMETHING_NEW').entitlement).toBe('unavailable')
})
})
describe('inspectNativeComponent', () => {
it('缺失与空文件都算 missing', () => {
expect(inspectNativeComponent(null, 'x64', () => null)).toBe('missing')
const dir = makeTempDir()
const empty = path.join(dir, 'empty.exe')
fs.writeFileSync(empty, Buffer.alloc(16))
expect(inspectNativeComponent(empty, 'x64', (p) => ({ size: fs.statSync(p).size }))).toBe('missing')
})
it('不是 PE 的算 invalid', () => {
const dir = makeTempDir()
const junk = path.join(dir, 'junk.exe')
fs.writeFileSync(junk, Buffer.alloc(4096, 0x41))
expect(inspectNativeComponent(junk, 'x64', (p) => ({ size: fs.statSync(p).size }))).toBe('invalid')
})
it('架构不符算 incompatible', () => {
const arm = writeFakePe(0xaa64)
expect(inspectNativeComponent(arm, 'x64', (p) => ({ size: fs.statSync(p).size }))).toBe('incompatible')
const x64 = writeFakePe(0x8664)
expect(inspectNativeComponent(x64, 'x64', (p) => ({ size: fs.statSync(p).size }))).toBe('ready')
})
})
describe('Windows 能力判定', () => {
it('Hook 无响应:不可开启,原因是有界失败而不是「未授权」', async () => {
const { service } = makeService({ probe: async () => ({ ok: false, error: 'ECONNREFUSED' }) })
const cap = await service.refresh(dbReady)
expect(cap.canEnable).toBe(false)
expect(cap.entitlementState).toBe('unavailable')
expect(cap.reasonCode).toBe('LICENSE_UNAVAILABLE')
})
it('没有授权文件:要求先激活', async () => {
const { service } = makeService({ probe: async () => ({ ok: true, status: 'LICENSE_NOT_FOUND' }) })
const cap = await service.refresh(dbReady)
expect(cap.reasonCode).toBe('LICENSE_REQUIRED')
expect(cap.canEnable).toBe(false)
})
it('LICENSE_CHECKING 不能当有效', async () => {
const { service } = makeService({ probe: async () => ({ ok: true, status: 'LICENSE_CHECKING' }) })
const cap = await service.refresh(dbReady)
expect(cap.entitlementState).toBe('pending')
expect(cap.reasonCode).toBe('LICENSE_PENDING')
expect(cap.canEnable).toBe(false)
})
it('过期 / 设备不匹配 / 吊销 各自有专属原因', async () => {
const cases: Array<[string, string]> = [
['LICENSE_EXPIRED', 'LICENSE_EXPIRED'],
['LICENSE_MACHINE_MISMATCH', 'LICENSE_MACHINE_MISMATCH'],
['LICENSE_REVOKED', 'LICENSE_REVOKED'],
['LICENSE_INVALID', 'LICENSE_INVALID']
]
for (const [status, reason] of cases) {
const { service } = makeService({ probe: async () => ({ ok: true, status }) })
const cap = await service.refresh(dbReady)
expect(cap.reasonCode).toBe(reason)
expect(cap.canEnable).toBe(false)
}
})
it('有授权但缺组件:不能开,且原因不是授权问题', async () => {
const { service } = makeService({ component: null })
const cap = await service.refresh(dbReady)
expect(cap.entitlementState).toBe('valid')
expect(cap.nativeComponentState).toBe('missing')
expect(cap.reasonCode).toBe('COMPONENT_MISSING')
expect(cap.canEnable).toBe(false)
})
it('组件损坏:不能开', async () => {
const dir = makeTempDir()
const junk = path.join(dir, 'broken.exe')
fs.writeFileSync(junk, Buffer.alloc(4096, 0x00))
const { service } = makeService({ component: junk })
const cap = await service.refresh(dbReady)
expect(cap.nativeComponentState).toBe('invalid')
expect(cap.reasonCode).toBe('COMPONENT_INVALID')
expect(cap.canEnable).toBe(false)
})
it('数据库没连:不能开', async () => {
const { service } = makeService({ component: writeFakePe() })
const cap = await service.refresh(dbDown)
expect(cap.reasonCode).toBe('DATABASE_UNAVAILABLE')
expect(cap.canEnable).toBe(false)
})
it('授权 + 组件 + 数据库齐了才允许开', async () => {
const { service } = makeService({ component: writeFakePe() })
const cap = await service.refresh(dbReady)
expect(cap.canEnable).toBe(true)
expect(cap.reasonCode).toBe('CAPABILITY_READY')
})
it('关闭永远不受授权限制', async () => {
const { service } = makeService({
probe: async () => ({ ok: true, status: 'LICENSE_EXPIRED' }),
component: null
})
const cap = await service.refresh(dbReady)
expect(cap.canEnable).toBe(false)
expect(cap.canDisable).toBe(true)
})
})
describe('macOS 双版本策略', () => {
it('OSS 包:不支持,且不能说成「未授权」', async () => {
const { service } = makeService({ platform: 'darwin', macBundle: false })
const cap = await service.refresh(dbReady)
expect(cap.entitlementState).toBe('unsupported')
expect(cap.reasonCode).toBe('UNSUPPORTED_PLATFORM')
expect(cap.canEnable).toBe(false)
})
it('Native 包:组件与数据库就绪即可开,不看发送 ready', async () => {
const { service } = makeService({ platform: 'darwin', macBundle: true, component: writeFakePe() })
const cap = await service.refresh(dbReady)
expect(cap.canEnable).toBe(true)
expect(cap.entitlementState).toBe('valid')
})
it('Native 包但缺组件:仍然不能开', async () => {
const { service } = makeService({ platform: 'darwin', macBundle: true, component: null })
const cap = await service.refresh(dbReady)
expect(cap.canEnable).toBe(false)
expect(cap.reasonCode).toBe('COMPONENT_MISSING')
})
})
describe('缓存与并发', () => {
it('TTL 内复用结果,refresh 强制重查', async () => {
let now = 1_000
let status = 'LICENSE_REQUIRED'
const { service, probeCalls } = makeService({
component: writeFakePe(),
now: () => now,
probe: async () => ({ ok: true, status: status === 'LICENSE_REQUIRED' ? 'LICENSE_NOT_FOUND' : status })
})
await service.getCapability(dbReady)
const first = probeCalls()
await service.getCapability(dbReady)
expect(probeCalls()).toBe(first)
status = 'LICENSE_OK'
const cached = await service.getCapability(dbReady)
expect(cached.canEnable).toBe(false)
const fresh = await service.refresh(dbReady)
expect(fresh.canEnable).toBe(true)
expect(probeCalls()).toBeGreaterThan(first)
now += 31_000
await service.getCapability(dbReady)
expect(probeCalls()).toBeGreaterThan(first + 1)
})
it('并发刷新只探一次', async () => {
const { service, probeCalls } = makeService({ component: writeFakePe() })
await Promise.all([service.refresh(dbReady), service.refresh(dbReady), service.refresh(dbReady)])
expect(probeCalls()).toBe(1)
})
it('数据库状态变化不受授权缓存影响', async () => {
const { service } = makeService({ component: writeFakePe() })
expect((await service.getCapability(dbReady)).canEnable).toBe(true)
expect((await service.getCapability(dbDown)).canEnable).toBe(false)
expect((await service.getCapability(dbReady)).canEnable).toBe(true)
})
})
+98 -1
View File
@@ -19,6 +19,26 @@ const asar = nodeRequire('@electron/asar') as {
const { hasWindowsSherpaRuntime } = nodeRequire('../../scripts/prepare-win-runtime.cjs') as {
hasWindowsSherpaRuntime: (runtimeRoot: string) => boolean
}
const { createBuilderConfig } = nodeRequire('../../scripts/build-macos-edition.cjs') as {
createBuilderConfig: (options: {
edition: 'public' | 'native'
stageRoot: string
buildOutput: string
outputRoot: string
appVersion: string
}) => {
files: Array<string | { from?: string; to?: string }>
extraResources: Array<{ from: string; to: string }>
dmg: { artifactName: string }
}
}
const { resolveEditionRoots, validateLicenseStatusRoute } = nodeRequire('../../scripts/prepare-macos-edition.cjs') as {
resolveEditionRoots: (projectRoot?: string, env?: NodeJS.ProcessEnv) => {
stageRoot: string
outputRoot: string
}
validateLicenseStatusRoute: (hostPath: string) => void
}
const {
validateAsarRuntimeDependencies,
validateFfmpegRuntime,
@@ -32,7 +52,11 @@ const {
signMacosAppBundle
} = nodeRequire('../../scripts/after-pack.cjs') as {
validateAsarRuntimeDependencies: (runtimeResources: string) => void
validateFfmpegRuntime: (runtimeResources: string, platform?: NodeJS.Platform) => void
validateFfmpegRuntime: (
runtimeResources: string,
platform?: NodeJS.Platform,
edition?: string
) => string
validateKoffiRuntime: (runtimeResources: string, platform: NodeJS.Platform, arch: string) => void
validateReaderSkillRuntime: (runtimeResources: string) => string
validateSherpaRuntime: (runtimeResources: string, platform: NodeJS.Platform, arch: string) => void
@@ -246,6 +270,72 @@ describe('production runtime packaging', () => {
expect(config).toContain('node_modules/ffmpeg-static/**')
})
it('requires staged arm64 edition ffmpeg before removing the shared binary', () => {
const resources = join(root, 'edition-ffmpeg-resources')
const shared = join(resources, 'app.asar.unpacked', 'node_modules', 'ffmpeg-static', 'ffmpeg')
mkdirSync(dirname(shared), { recursive: true })
writeFileSync(shared, 'existing shared binary')
expect(() => validateFfmpegRuntime(resources, 'darwin', 'public')).toThrow(/staged macOS ffmpeg/)
expect(readFileSync(shared, 'utf8')).toBe('existing shared binary')
})
it('builds each edition from an isolated native resource allowlist', () => {
const stageRoot = join(root, 'mac-staging', 'public')
const config = createBuilderConfig({
edition: 'public',
stageRoot,
buildOutput: join(stageRoot, 'out'),
outputRoot: join(root, 'dist', 'mac', 'public'),
appVersion: '2.5.2'
})
expect(config.extraResources.map((item) => item.to)).toEqual([
'resources',
'app-update.yml',
'skill/tracememo-reader'
])
expect(config.extraResources[0].from).toBe(join(stageRoot, 'resources'))
expect(config.files).toContainEqual({ from: join(stageRoot, 'out'), to: 'out', filter: ['**/*'] })
expect(config.files).toContain('package.json')
expect(
config.files.some(
(item) => typeof item === 'string' && !item.startsWith('!') && item.includes('resources')
)
).toBe(false)
expect(config.dmg.artifactName).toBe('TraceMemo-2.5.2-mac-arm64-oss.dmg')
const nativeConfig = createBuilderConfig({
edition: 'native',
stageRoot: join(root, 'mac-staging', 'native'),
buildOutput: join(root, 'mac-staging', 'native', 'out'),
outputRoot: join(root, 'dist', 'mac', 'native'),
appVersion: '2.5.2'
})
expect(nativeConfig.dmg.artifactName).toBe('TraceMemo-2.5.2-mac-arm64-native.dmg')
})
it('supports isolated macOS staging and output roots without changing defaults', () => {
expect(resolveEditionRoots('/repo', {})).toEqual({
stageRoot: '/repo/build/mac-staging',
outputRoot: '/repo/dist/mac'
})
expect(
resolveEditionRoots('/repo', {
TRACEMEMO_MAC_STAGE_ROOT: '/tmp/candidate/staging',
TRACEMEMO_MAC_OUTPUT_ROOT: '/tmp/candidate/output'
})
).toEqual({
stageRoot: '/tmp/candidate/staging',
outputRoot: '/tmp/candidate/output'
})
})
it('rejects a native Host that cannot serve the license status route', () => {
const host = join(root, 'license-route-host')
writeFileSync(host, 'GET /healthz')
expect(() => validateLicenseStatusRoute(host)).toThrow(/GET \/license\/status/)
writeFileSync(host, 'GET /healthz GET /license/status')
expect(() => validateLicenseStatusRoute(host)).not.toThrow()
})
it('requires the matching Windows and macOS sherpa native runtime', () => {
const resources = join(root, 'sherpa-resources')
const unpacked = join(resources, 'app.asar.unpacked', 'node_modules')
@@ -624,6 +714,13 @@ describe('send runtime packaging boundary', () => {
expect(command).not.toContain('electron-builder.send-runtime.yml')
expect(command).not.toContain('TM_SEND_RUNTIME_BUILD')
}
expect(pkg.scripts['release:mac:arm64']).toContain(
'--config.directories.output=dist/release/mac-arm64'
)
expect(pkg.scripts['release:mac:x64']).toContain(
'--config.directories.output=dist/release/mac-x64'
)
})
it('excludes the send runtime in the default builder config', () => {
+147
View File
@@ -0,0 +1,147 @@
import { createHash } from 'crypto'
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'fs'
import { tmpdir } from 'os'
import { basename, join } from 'path'
import { DatabaseSync } from 'node:sqlite'
import { afterEach, describe, expect, it, vi } from 'vitest'
import { Wcdb4Client } from '../../src/main/wcdb4-client'
import { readMsgInsertSwitches } from '../../src/main/services/msg-insert-switch-service'
vi.mock('../../src/main/resource-paths', () => ({
getResourceRoots: () => [],
findResource: () => null
}))
// wcdb4-client 现在通过 native-runtime-paths 解析 dylib 路径,那条链路读 electron.app。
vi.mock('electron', () => ({
app: { isPackaged: false, getPath: () => '/tmp' }
}))
describe('message insert shard catalog', () => {
const roots: string[] = []
const room = 'fixture-group@chatroom'
const hash = createHash('md5').update(room).digest('hex')
const table = `Msg_${hash}`
const capture = `_tm_msg_insert_capture_${hash}`
afterEach(() => {
roots.splice(0).forEach((root) => rmSync(root, { recursive: true, force: true }))
})
function fixture() {
const root = mkdtempSync(join(tmpdir(), 'wcdb-insert-catalog-'))
roots.push(root)
const messageRoot = join(root, 'message')
mkdirSync(messageRoot)
for (const name of ['message_0.db', 'message_1.db']) {
const db = new DatabaseSync(join(messageRoot, name))
try {
db.exec(`CREATE TABLE ${table}(content TEXT);`)
if (name === 'message_0.db') {
db.exec(`
CREATE TABLE _tm_config(key TEXT PRIMARY KEY, value INTEGER);
CREATE TRIGGER ${capture} AFTER INSERT ON ${table} BEGIN SELECT 1; END;
`)
}
} finally {
db.close()
}
}
for (const name of ['media_0.db', 'message_0 (SFConflict).db', 'message_0.db-wal']) {
writeFileSync(join(messageRoot, name), '')
}
const nativeCatalog = vi.fn(() => {
throw new Error('unsafe native catalog called')
})
const query = vi.fn((_handle, kind, dbPath: string, sql: string, out: unknown[]) => {
expect(kind).toBe('message')
const db = new DatabaseSync(dbPath, { readOnly: true })
try {
out[0] = db.prepare(sql).all()
} finally {
db.close()
}
return 0
})
const client = Object.assign(Object.create(Wcdb4Client.prototype), {
dbStoragePath: root,
wcdbMsgInsertListShardCatalog: nativeCatalog,
wcdbExecQuery: query,
callJson: (call: (handle: number, out: unknown[]) => number) => {
const out: unknown[] = [null]
call(1, out)
return out[0]
},
getSessions: () => [{ username: room }],
getMsgInsertSwitches: () => ({ success: true, switches: { recall_notice: true } })
}) as Wcdb4Client
return { client, nativeCatalog, query, messageRoot }
}
it('reads tables and trigger attachments through read-only SQL without the crashing native API', () => {
const { client, nativeCatalog, query, messageRoot } = fixture()
expect(client.listMsgInsertShardCatalog()).toEqual({
success: true,
catalog: {
shardCount: 2,
shards: [
{
shard: 'message_0.db',
dbPath: join(messageRoot, 'message_0.db'),
configTable: true,
tables: [table, '_tm_config'],
rules: [{ name: capture, table }]
},
{
shard: 'message_1.db',
dbPath: join(messageRoot, 'message_1.db'),
configTable: false,
tables: [table],
rules: []
}
]
}
})
expect(nativeCatalog).not.toHaveBeenCalled()
expect(query.mock.calls.map((call) => basename(call[2]))).toEqual([
'message_0.db',
'message_1.db'
])
})
it('preserves the rule coverage calculation across shards', () => {
const { client } = fixture()
const snapshot = readMsgInsertSwitches({ client, monitoredRoomIds: [] })
expect(snapshot.success).toBe(true)
expect(snapshot.switches.recall_notice).toMatchObject({
desiredEnabled: true,
effectiveEnabled: false,
totalShards: 2,
totalInstallableRooms: 1,
readyInstallableRooms: 0,
notReadyRooms: [{ roomId: room, notReadyShards: ['message_1.db'] }]
})
})
it('reports a query failure instead of returning a partial catalog', () => {
const { client, query } = fixture()
query.mockImplementationOnce(() => {
throw new Error('fixture shard unavailable')
})
expect(client.listMsgInsertShardCatalog()).toEqual({
success: false,
error: 'fixture shard unavailable'
})
})
it('reports an unsupported SQL channel without calling the unsafe native API', () => {
const { client, nativeCatalog } = fixture()
Reflect.set(client, 'wcdbExecQuery', null)
expect(client.listMsgInsertShardCatalog()).toMatchObject({ success: false })
expect(nativeCatalog).not.toHaveBeenCalled()
})
})
+136
View File
@@ -0,0 +1,136 @@
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'fs'
import { tmpdir } from 'os'
import { join } from 'path'
import { DatabaseSync } from 'node:sqlite'
import { afterEach, describe, expect, it, vi } from 'vitest'
import { Wcdb4Client } from '../../src/main/wcdb4-client'
describe('WCDB voice media shards', () => {
const roots: string[] = []
const databases: DatabaseSync[] = []
const session = "wxid_fixture'peer"
const serverId = '1234567890123456789'
const createTime = 1_790_000_000
const localId = 42
const audio = Buffer.from('02532345', 'hex')
afterEach(() => {
databases.splice(0).forEach((db) => db.close())
roots.splice(0).forEach((root) => rmSync(root, { recursive: true, force: true }))
})
function fixture(nativeHex = '', nativeCode = 0) {
const root = mkdtempSync(join(tmpdir(), 'wcdb-voice-shards-'))
roots.push(root)
const messageRoot = join(root, 'message')
mkdirSync(messageRoot)
const stores = new Map<string, DatabaseSync>()
for (const name of ['media_0.db', 'media_1.db']) {
const dbPath = join(messageRoot, name)
const db = new DatabaseSync(dbPath)
databases.push(db)
db.exec(`
CREATE TABLE Name2Id(user_name TEXT PRIMARY KEY);
CREATE TABLE VoiceInfo(chat_name_id INTEGER, create_time INTEGER, local_id INTEGER, svr_id INTEGER, voice_data BLOB);
`)
db.prepare('INSERT INTO Name2Id VALUES (?)').run(session)
db.prepare('INSERT INTO Name2Id VALUES (?)').run('other-session')
stores.set(dbPath, db)
}
writeFileSync(join(messageRoot, 'media_0 (SFConflict).db'), '')
const query = vi.fn(async (_fn, _kind, dbPath: string, sql: string) => {
const db = stores.get(dbPath)
if (!db) throw new Error('Unexpected media shard')
return db.prepare(sql).all()
})
const freeString = vi.fn()
const client = Object.assign(Object.create(Wcdb4Client.prototype), {
dbStoragePath: root,
wcdbGetVoiceData: {
async: (...args: unknown[]) => {
;(args.at(-2) as [unknown])[0] = {}
;(args.at(-1) as (error: unknown, code: number) => void)(null, nativeCode)
}
},
wcdbExecQuery: vi.fn(),
wcdbFreeString: freeString,
callJsonAsync: query,
decodeHexPtr: () => nativeHex,
handle: 1,
closing: false,
nativeCallsInFlight: new Set()
}) as Wcdb4Client
const insert = (shard: number, chat: number, id: number, svr: string, bytes = audio) => {
stores
.get(join(messageRoot, `media_${shard}.db`))!
.prepare('INSERT INTO VoiceInfo VALUES (?, ?, ?, ?, ?)')
.run(chat, createTime, id, BigInt(svr), bytes)
}
return { client, query, freeString, insert }
}
it.each([0, -3003])(
'reads a later shard when native lookup returns empty data or fails (%s)',
async (code) => {
const { client, query, freeString, insert } = fixture('', code)
insert(0, 1, localId, '1234567890123456790', Buffer.from('bad1', 'hex'))
insert(0, 2, localId, serverId, Buffer.from('bad2', 'hex'))
insert(0, 1, localId, serverId, Buffer.alloc(0))
insert(1, 1, localId, serverId)
await expect(
client.getVoiceData(session, createTime, [session], localId, serverId)
).resolves.toEqual({ success: true, hex: audio.toString('hex'), error: '' })
expect(query).toHaveBeenCalledTimes(2)
expect(freeString).toHaveBeenCalledOnce()
}
)
it('uses both local id and time within the session when no server id is available', async () => {
const { client, insert } = fixture()
insert(0, 1, localId + 1, '123')
insert(0, 2, localId, '456')
insert(1, 1, localId, '789')
await expect(
client.getVoiceData(session, createTime, [session], localId)
).resolves.toMatchObject({ success: true, hex: audio.toString('hex') })
await expect(
client.getVoiceData(session, createTime + 1, [session], localId)
).resolves.toMatchObject({ success: false })
})
it('does not substitute another message when the known server id is missing', async () => {
const { client, insert } = fixture()
insert(0, 1, localId, '1234567890123456790')
await expect(
client.getVoiceData(session, createTime, [session], localId, serverId)
).resolves.toEqual({ success: false, error: '语音数据为空' })
})
it('continues after an unreadable shard', async () => {
const { client, query, insert } = fixture()
vi.spyOn(console, 'warn').mockImplementation(() => {})
query.mockRejectedValueOnce(new Error('unreadable shard'))
insert(1, 1, localId, serverId)
await expect(
client.getVoiceData(session, createTime, [session], localId, serverId)
).resolves.toMatchObject({ success: true, hex: audio.toString('hex') })
})
it('skips SQL when native lookup succeeds or the message identity is incomplete', async () => {
const successful = fixture('aabb')
await expect(
successful.client.getVoiceData(session, createTime, [], localId, serverId)
).resolves.toMatchObject({ success: true, hex: 'aabb' })
expect(successful.query).not.toHaveBeenCalled()
const missing = fixture()
await expect(missing.client.getVoiceData(session, createTime, [])).resolves.toMatchObject({
success: false
})
expect(missing.query).not.toHaveBeenCalled()
})
})