mirror of
https://wget.la/https://github.com/Wxw-Gu/WechatExplorer
synced 2026-11-30 16:02:58 +08:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c398691792 | ||
|
|
804466aad8 | ||
|
|
d1ee3bbd30 | ||
|
|
7dcda8554e | ||
|
|
6cadcb9a5a | ||
|
|
f47af8024f | ||
|
|
4a4c0eb520 | ||
|
|
05b881d79e | ||
|
|
80e0f43529 | ||
|
|
39753d7784 | ||
|
|
f95e9d491c | ||
|
|
780a19900b | ||
|
|
7e9997cc06 | ||
|
|
8c162969ff | ||
|
|
51c373501a | ||
|
|
9db08dba1a | ||
|
|
49e3fcfb20 | ||
|
|
450668f5e6 | ||
|
|
8804a16ad9 | ||
|
|
d9d0672072 | ||
|
|
a328db687d | ||
|
|
915ee73f95 | ||
|
|
df6388a86d | ||
|
|
695afd7c3e | ||
|
|
049b5a9495 | ||
|
|
43c917a070 | ||
|
|
84737a7407 | ||
|
|
d6d837e6f6 | ||
|
|
443bbc866c | ||
|
|
e17e2d908e | ||
|
|
a0c729374f | ||
|
|
b36311e276 | ||
|
|
9608077b90 | ||
|
|
9ab71bf730 | ||
|
|
52c89bf0c7 | ||
|
|
a799fc1490 | ||
|
|
c366dd1187 | ||
|
|
0d78ad3f54 | ||
|
|
de9f4d311a | ||
|
|
67e4e8f31e | ||
|
|
958dab1ddd | ||
|
|
694d5041bd | ||
|
|
7f3ea4ae6d | ||
|
|
ae0afa65d9 | ||
|
|
72812447fd | ||
|
|
eaa25cd29e | ||
|
|
fd7d5016a8 | ||
|
|
028e8b6553 | ||
|
|
7ce0475b3f | ||
|
|
9564fde04d | ||
|
|
632ec9ee13 | ||
|
|
4d9af4a193 | ||
|
|
e5f0aa59f4 | ||
|
|
108d04f901 | ||
|
|
713232bd62 | ||
|
|
e83e85fe64 | ||
|
|
e5a1656644 |
No files matched your search
@@ -15,6 +15,9 @@ jobs:
|
|||||||
|
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v4
|
- uses: actions/checkout@v4
|
||||||
|
with:
|
||||||
|
# 版本漂移检查需要与基准分支比较 SKILL.md,浅克隆拿不到基准。
|
||||||
|
fetch-depth: 0
|
||||||
|
|
||||||
- uses: pnpm/action-setup@v4
|
- uses: pnpm/action-setup@v4
|
||||||
with:
|
with:
|
||||||
@@ -46,6 +49,9 @@ jobs:
|
|||||||
- name: Skill installation instruction tests
|
- name: Skill installation instruction tests
|
||||||
run: pnpm test:skill-install
|
run: pnpm test:skill-install
|
||||||
|
|
||||||
|
- name: Reader Skill version drift check
|
||||||
|
run: pnpm check:skill-version
|
||||||
|
|
||||||
- name: Build Electron test application
|
- name: Build Electron test application
|
||||||
run: pnpm test:e2e:build
|
run: pnpm test:e2e:build
|
||||||
|
|
||||||
|
|||||||
@@ -26,3 +26,8 @@ skills-lock.json
|
|||||||
findings.md
|
findings.md
|
||||||
progress.md
|
progress.md
|
||||||
task_plan.md
|
task_plan.md
|
||||||
|
|
||||||
|
*tm-wcdb-config-helper*
|
||||||
|
*libtmlicense*
|
||||||
|
debug-originals
|
||||||
|
/build/mac-staging/
|
||||||
@@ -79,7 +79,7 @@ TraceMemo(迹忆)原名 **WechatExplorer** 是一款本地优先的微信数
|
|||||||
|
|
||||||
## 💻 平台支持
|
## 💻 平台支持
|
||||||
|
|
||||||
TraceMemo 2.5.0 支持:
|
TraceMemo 2.5.1 支持:
|
||||||
|
|
||||||
- **Windows x64**
|
- **Windows x64**
|
||||||
- **macOS Apple Silicon(M 系列 / arm64)**
|
- **macOS Apple Silicon(M 系列 / arm64)**
|
||||||
|
|||||||
@@ -45,6 +45,7 @@ Agent Hub 让微信机器人调用本机 TraceMemo;Reader Skill / Local HTTP A
|
|||||||
- [导出聊天](./user-guide/export.md):导出 HTML、Markdown、CSV 或 JSON 档案。
|
- [导出聊天](./user-guide/export.md):导出 HTML、Markdown、CSV 或 JSON 档案。
|
||||||
- [数据、隐私与安全](./user-guide/privacy.md):本地处理、Provider、媒体和 Token 的数据边界。
|
- [数据、隐私与安全](./user-guide/privacy.md):本地处理、Provider、媒体和 Token 的数据边界。
|
||||||
- [常见问题与排查](./user-guide/troubleshooting.md):按安装、连接、AI、媒体和 Agent 现象排查。
|
- [常见问题与排查](./user-guide/troubleshooting.md):按安装、连接、AI、媒体和 Agent 现象排查。
|
||||||
|
- [macOS 更新27后读不到微信数据](./user-guide/macos27-permission-recovery.md):升级 macOS 或更新应用后失去微信数据访问权限的恢复步骤。
|
||||||
|
|
||||||
## 开发文档
|
## 开发文档
|
||||||
|
|
||||||
|
|||||||
+305
-2
@@ -8,7 +8,9 @@
|
|||||||
- API 前缀:`/api/v1`
|
- API 前缀:`/api/v1`
|
||||||
- 默认只监听 loopback;不要把它当作公网服务。
|
- 默认只监听 loopback;不要把它当作公网服务。
|
||||||
- `/api/v1/health` 无需 Token;其他端点需要 `Authorization: Bearer <TOKEN>`。
|
- `/api/v1/health` 无需 Token;其他端点需要 `Authorization: Bearer <TOKEN>`。
|
||||||
- 请求体使用 JSON;响应为 JSON。
|
- 请求体使用 JSON,单个请求体最大 `1 MiB`;超限返回 `413`。
|
||||||
|
- 错误响应包含 `requestId`,响应头包含 `X-Request-Id`。客户端可传入 1-128 位的 `[A-Za-z0-9._:-]` 标识,否则服务端会生成 UUID。
|
||||||
|
- 不支持的 HTTP method 返回 `405` 和 `Allow` 响应头。
|
||||||
|
|
||||||
## 最小请求
|
## 最小请求
|
||||||
|
|
||||||
@@ -33,6 +35,7 @@ Token 由应用生成并保存在本机,**不接受用环境变量覆盖**:A
|
|||||||
| 方法 | 路径 | 作用 | 参数/请求体 |
|
| 方法 | 路径 | 作用 | 参数/请求体 |
|
||||||
| ------ | --------------------------------------------------------------- | -------------------------------------- | --------------------------------------------------------------- |
|
| ------ | --------------------------------------------------------------- | -------------------------------------- | --------------------------------------------------------------- |
|
||||||
| GET | `/api/v1/health` | 服务与数据库健康状态 | 无 |
|
| GET | `/api/v1/health` | 服务与数据库健康状态 | 无 |
|
||||||
|
| GET | `/api/v1/skill/tracememo-reader` | 当前 Reader Skill 的版本与全文 | 无(需 Token) |
|
||||||
| GET | `/api/v1/current_time` | 本机时间、时区和 Unix 时间戳 | 无 |
|
| GET | `/api/v1/current_time` | 本机时间、时区和 Unix 时间戳 | 无 |
|
||||||
| GET | `/api/v1/contact` | 联系人和群聊列表 | `filter`、`type=user\|group` |
|
| GET | `/api/v1/contact` | 联系人和群聊列表 | `filter`、`type=user\|group` |
|
||||||
| GET | `/api/v1/chatroom` | 群聊列表 | `keyword` |
|
| GET | `/api/v1/chatroom` | 群聊列表 | `keyword` |
|
||||||
@@ -45,6 +48,7 @@ Token 由应用生成并保存在本机,**不接受用环境变量覆盖**:A
|
|||||||
| GET | `/api/v1/agent/status` | Agent Hub、连接器和数据库状态 | 无 |
|
| GET | `/api/v1/agent/status` | Agent Hub、连接器和数据库状态 | 无 |
|
||||||
| POST | `/api/v1/agent/group-report` | 读取群聊并生成总结图片 | `{ "group": "群名或标识", "range": "today\|yesterday\|7days" }` |
|
| POST | `/api/v1/agent/group-report` | 读取群聊并生成总结图片 | `{ "group": "群名或标识", "range": "today\|yesterday\|7days" }` |
|
||||||
| POST | `/api/v1/agent/send` | 通过已连接机器人测试发送文字或本地图片 | `{ "to": "接收者", "text": "...", "media_url": "..." }` |
|
| POST | `/api/v1/agent/send` | 通过已连接机器人测试发送文字或本地图片 | `{ "to": "接收者", "text": "...", "media_url": "..." }` |
|
||||||
|
| POST | `/api/v1/wechat/send` | 用本机微信账号把消息发给别人 | `{ "to": "wxid 或 filehelper", "type": "text\|image\|voice", "text": "..." }` |
|
||||||
| GET | `/api/v1/wechat-personal/send-capability` | 个人微信发送能力状态 | 无 |
|
| GET | `/api/v1/wechat-personal/send-capability` | 个人微信发送能力状态 | 无 |
|
||||||
| GET | `/api/v1/scheduled-reports` | 定时日报任务列表 | 无 |
|
| GET | `/api/v1/scheduled-reports` | 定时日报任务列表 | 无 |
|
||||||
| POST | `/api/v1/scheduled-reports` | 创建定时日报任务 | `ScheduledReportApiCreateRequest` JSON |
|
| POST | `/api/v1/scheduled-reports` | 创建定时日报任务 | `ScheduledReportApiCreateRequest` JSON |
|
||||||
@@ -55,10 +59,210 @@ Token 由应用生成并保存在本机,**不接受用环境变量覆盖**:A
|
|||||||
| POST | `/api/v1/scheduled-reports/{id}/disable` | 暂停定时日报任务 | 无 |
|
| POST | `/api/v1/scheduled-reports/{id}/disable` | 暂停定时日报任务 | 无 |
|
||||||
| POST | `/api/v1/scheduled-reports/{id}/run` | 立即执行一次并返回 execution | 无 |
|
| POST | `/api/v1/scheduled-reports/{id}/run` | 立即执行一次并返回 execution | 无 |
|
||||||
| GET | `/api/v1/scheduled-reports/{id}/executions` | 查询某个任务的执行记录 | 无 |
|
| GET | `/api/v1/scheduled-reports/{id}/executions` | 查询某个任务的执行记录 | 无 |
|
||||||
| POST | `/api/v1/scheduled-reports/executions/{executionId}/retry-send` | 复用已有 PNG 重试发送 | 无 |
|
| POST | `/api/v1/scheduled-reports/executions/{executionId}/retry-send` | 兼容占位路由;当前返回 `501 not_supported` | 无 |
|
||||||
|
| GET | `/api/v1/capabilities` | TraceMemo 应用能力和可用状态 | 无 |
|
||||||
|
| GET | `/api/v1/automations` | 自动化规则列表 | 可选 `type`、`enabled` |
|
||||||
|
| POST | `/api/v1/automations` | 创建默认停用的自动化规则 | Automation draft JSON |
|
||||||
|
| POST | `/api/v1/automations/validate` | 校验规则,不保存、不执行 | Automation draft JSON |
|
||||||
|
| GET | `/api/v1/automations/{id}` | 查询单条自动化规则 | 无 |
|
||||||
|
| PATCH | `/api/v1/automations/{id}` | 更新规则配置 | 可变配置字段 JSON |
|
||||||
|
| DELETE | `/api/v1/automations/{id}` | 删除自定义规则 | 系统内置规则受保护 |
|
||||||
|
| POST | `/api/v1/automations/{id}/enable` | 校验并启用规则 | 无 |
|
||||||
|
| POST | `/api/v1/automations/{id}/disable` | 停用规则 | 无 |
|
||||||
|
| GET | `/api/v1/automations/executions` | 查询自动化执行记录 | `ruleId`、`status`、`since`、`until`、`limit` |
|
||||||
|
| GET | `/api/v1/monitors/group-exits` | 查看退群监控状态 | 无 |
|
||||||
|
| PATCH | `/api/v1/monitors/group-exits` | 配置监控群范围或启停 | `enabled`、`monitoredConversationIds` |
|
||||||
|
| GET | `/api/v1/monitors/group-exits/events` | 查询退群事件历史 | `conversationId`、`since`、`until`、`limit` |
|
||||||
|
| GET | `/api/v1/groups/{conversationId}/member-stats` | 查询群成员活跃统计 | 必填 `conversationId`、`start`、`end` |
|
||||||
|
|
||||||
`/api/v1/query/*` 是一组结构化的 Query 端点,见下方[LLM-friendly Query Tool API](#llm-friendly-query-tool-api)。
|
`/api/v1/query/*` 是一组结构化的 Query 端点,见下方[LLM-friendly Query Tool API](#llm-friendly-query-tool-api)。
|
||||||
|
|
||||||
|
## 发送消息 API
|
||||||
|
|
||||||
|
两个发送端点走**完全不同的通道**,用途也不同,不要混用。
|
||||||
|
|
||||||
|
| | `POST /api/v1/wechat/send` | `POST /api/v1/agent/send` |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| 通道 | 本机微信(macOS native runtime / Windows hook) | Agent Hub 机器人(iLink) |
|
||||||
|
| 身份 | 你本人当前登录的微信账号 | 已扫码接入的机器人 |
|
||||||
|
| 用途 | **以你的身份把消息发给别人**(好友 / 群 / 文件传输助手) | **机器人给自己发通知**(测试连通性) |
|
||||||
|
| 前置条件 | 本机微信已启动,发送能力为 `ready` | 连接器为 `online` |
|
||||||
|
| 内容类型 | `text` / `image` / `voice`,媒体只接受本地文件 | `text` / `image`(URL 或本地路径) |
|
||||||
|
| 典型失败 | 能力未就绪 `503`、发送失败 `502` | 连接器离线 `503`、凭证过期 `401` |
|
||||||
|
|
||||||
|
### 本地发送:`POST /api/v1/wechat/send`
|
||||||
|
|
||||||
|
用你正在登录的微信账号发消息。**这是唯一能把消息发给别人(而不是发给机器人自己)的端点。**
|
||||||
|
|
||||||
|
```bash
|
||||||
|
: "${TRACEMEMO_API_TOKEN:?Set TRACEMEMO_API_TOKEN from API Center}"
|
||||||
|
curl -X POST http://127.0.0.1:6131/api/v1/wechat/send \
|
||||||
|
-H "Authorization: Bearer $TRACEMEMO_API_TOKEN" \
|
||||||
|
-H "Content-Type: application/json" \
|
||||||
|
-d '{"to":"filehelper","type":"text","text":"来自 Agent 的一条消息"}'
|
||||||
|
```
|
||||||
|
|
||||||
|
请求体:
|
||||||
|
|
||||||
|
| 字段 | 必填 | 说明 |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| `to` | 是 | 接收者:好友 wxid、群 id(以 `@chatroom` 结尾),或 `filehelper`(文件传输助手)。**不做昵称解析**,先调 `/api/v1/resolve?q=张三` 换 wxid |
|
||||||
|
| `type` | 否 | `text`(默认)/ `image` / `voice` |
|
||||||
|
| `text` | `type=text` 时必填 | **最长 2000 字符**,超限返回 `400`,不会截断 |
|
||||||
|
| `filePath` | `type=image\|voice` 时必填 | 本机**绝对路径**,必须已存在。不接受 URL —— 需要发网络图片时先落盘 |
|
||||||
|
| `isGroup` | 否 | 通常可省略;`to` 以 `@chatroom` 结尾时自动判为群 |
|
||||||
|
| `idempotencyKey` | 否 | 幂等键。**重试时请原样带上**,避免 Agent 超时重发导致重复消息 |
|
||||||
|
|
||||||
|
发送前会先校验当前发送能力(等价于 `GET /api/v1/wechat-personal/send-capability`):`ready=false` 时直接返回 `503`,不会进入投递;`capabilities[type]=false` 时返回 `503 SEND_NOT_READY`。
|
||||||
|
|
||||||
|
> **没有 3 秒节流。** 自动化规则(定时日报、退群通知)之间共享 3 秒发送间隔,但本端点属于手动发送,**不受该队列约束**:连续调用会连续投递。Agent 需要自行控制频率,不要用它循环刷消息。
|
||||||
|
|
||||||
|
响应:
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"success": true,
|
||||||
|
"status": "sent",
|
||||||
|
"actionId": "5f0c…",
|
||||||
|
"recipient": { "type": "contact", "id": "filehelper" },
|
||||||
|
"contentType": "text",
|
||||||
|
"durationMs": 842
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
| HTTP | `errorCode` | 含义 |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| `400` | `INVALID_REQUEST` / `INVALID_RECIPIENT` | 字段缺失、`text` 超长、`filePath` 不存在 |
|
||||||
|
| `403` | `POLICY_BLOCKED` / `ACTION_NOT_ALLOWED` / `RECIPIENT_SCOPE_VIOLATION` | 发送策略拒绝 |
|
||||||
|
| `502` | `SEND_FAILED` | 已进入投递,底层发送失败(看 `error`) |
|
||||||
|
| `503` | `SEND_CAPABILITY_UNAVAILABLE` | 微信未启动 / 未绑定 / 未初始化 |
|
||||||
|
| `503` | `SEND_NOT_READY` | 能力在,但不支持该内容类型(例如语音 hook 未就绪) |
|
||||||
|
| `503` | `UNSUPPORTED_PLATFORM` | 非 macOS / Windows |
|
||||||
|
| `500` | `INTERNAL_ERROR` | 网关执行抛出未预期异常 |
|
||||||
|
|
||||||
|
> **`status: "sent"` 只代表投递成功,不等于消息已写入本地数据库。** TraceMemo 读的是微信本地库,自己发出的消息可能延迟落库,也可能根本不会写入。因此不要用 `/api/v1/chatlog` 回查自己刚发的消息来判断是否发送成功 —— 查不到是正常现象;也**不要**因为本地库没有就重发,那会产生真实的重复消息。需要人工确认时,让对方用手机微信或另一个账号查看会话。
|
||||||
|
|
||||||
|
每一次发送都会写入 `actions/wechat-actions.json` 审计记录(`origin` 为 `http_api`),可在 Send Log 中核对。这份记录证明的是「调用过并成功投递」,**不能**证明对方已收到或本地库已落库。
|
||||||
|
|
||||||
|
### 机器人通知:`POST /api/v1/agent/send`
|
||||||
|
|
||||||
|
走已扫码的 Agent Hub 连接器,给**自己**发一条测试消息,用于确认机器人链路是否通畅。它不适合「通知某人」这类场景 —— 那要用上面的 `/api/v1/wechat/send`。
|
||||||
|
|
||||||
|
```bash
|
||||||
|
curl -X POST http://127.0.0.1:6131/api/v1/agent/send \
|
||||||
|
-H "Authorization: Bearer $TRACEMEMO_API_TOKEN" \
|
||||||
|
-H "Content-Type: application/json" \
|
||||||
|
-d '{"to":"<你的 wxid>","text":"connector ok"}'
|
||||||
|
```
|
||||||
|
|
||||||
|
`to` 省略时回落到当前登录账号自己。`media_url` 可传 URL。连接器离线返回 `503`,凭证过期返回 `401`。
|
||||||
|
|
||||||
|
## Application Capabilities
|
||||||
|
|
||||||
|
`GET /api/v1/capabilities` 描述 TraceMemo 应用级能力和当前运行环境;`GET /api/v1/query/capabilities` 只描述结构化 Query primitive,两者不是同一份目录。应用能力使用 `supported` 和 `available` 分开表示“代码支持”与“当前可用”;运行时原因使用稳定的简短 code,不返回 Token、数据库路径、微信密钥或 sender 诊断路径。
|
||||||
|
|
||||||
|
响应包含应用版本、数据库 readiness、Query、Automation、退群监控、群统计,以及个人微信/iLink 的能力状态。`groupExitMonitor.operations` 当前声明 `read_state`、`configure_scope`、`enable`、`disable`、`list_events`;`groupStats.operations` 当前声明 `member_stats`。能力声明不会触发监控扫描或群统计查询。
|
||||||
|
|
||||||
|
```bash
|
||||||
|
: "${TRACEMEMO_API_TOKEN:?Set TRACEMEMO_API_TOKEN from API Center}"
|
||||||
|
BASE="http://127.0.0.1:6131/api/v1"
|
||||||
|
AUTH="Authorization: Bearer $TRACEMEMO_API_TOKEN"
|
||||||
|
curl -H "$AUTH" "$BASE/capabilities"
|
||||||
|
```
|
||||||
|
|
||||||
|
## Group Exit Monitor API
|
||||||
|
|
||||||
|
退群监控只负责“监测哪些群、发现了哪些退群事实”。退群后是否通知、通知到哪里以及通知模板,仍由 `leave_notification` Automation singleton 负责;修改监控范围不会隐式修改该 Automation。
|
||||||
|
|
||||||
|
### 查看和配置监控
|
||||||
|
|
||||||
|
```bash
|
||||||
|
curl -H "$AUTH" "$BASE/monitors/group-exits"
|
||||||
|
|
||||||
|
curl -X PATCH -H "$AUTH" -H 'Content-Type: application/json' \
|
||||||
|
"$BASE/monitors/group-exits" \
|
||||||
|
-d '{"enabled":true,"monitoredConversationIds":["123@chatroom"]}'
|
||||||
|
```
|
||||||
|
|
||||||
|
`monitoredConversationIds` 只接受当前联系人列表中精确存在的群 `roomId`(例如 `xxx@chatroom`),不接受群名、md5、个人联系人、重复或空 ID。请求至少提供 `enabled` 或 `monitoredConversationIds` 其中一个;传空数组表示清空监控范围。服务会先校验全部群,再执行一次原子配置。PATCH 返回最终完整状态。
|
||||||
|
|
||||||
|
状态中的 `eventCount` 是持久化退群事件总数,`lastCheckedAt`/`lastReadAt` 为空时返回 `null`。GET 不会调用 `checkNow()`,也不会触发通知发送。
|
||||||
|
|
||||||
|
### 查询退群事件
|
||||||
|
|
||||||
|
```bash
|
||||||
|
curl -G -H "$AUTH" "$BASE/monitors/group-exits/events" \
|
||||||
|
--data-urlencode 'conversationId=123@chatroom' \
|
||||||
|
--data-urlencode 'since=2026-10-01T00:00:00+07:00' \
|
||||||
|
--data-urlencode 'until=2026-10-02T23:59:59+07:00' \
|
||||||
|
--data-urlencode 'limit=50'
|
||||||
|
```
|
||||||
|
|
||||||
|
时间参数必须是带 offset 的 ISO-8601;默认 `limit=50`,最大 200。事件按 `detectedAt` 升序返回。事件 DTO 使用 `eventId`、稳定的 `conversationId` 和 `memberId`,并把时间输出为 ISO-8601;当前整体已读状态不会伪造成 event-level `read` 字段。当前未开放 clear events、markRead 或 checkNow HTTP 路由。
|
||||||
|
|
||||||
|
一个典型 Agent 工作流是:先通过 `/resolve` 或 `/contact` 找到稳定群 ID,再 PATCH monitor scope;如需通知,再单独 PATCH `leave_notification` Automation,调用 `/automations/validate`,最后启用规则。
|
||||||
|
|
||||||
|
## Group Member Stats API
|
||||||
|
|
||||||
|
```bash
|
||||||
|
curl -G -H "$AUTH" "$BASE/groups/123%40chatroom/member-stats" \
|
||||||
|
--data-urlencode 'start=2026-09-01T00:00:00+07:00' \
|
||||||
|
--data-urlencode 'end=2026-10-01T00:00:00+07:00'
|
||||||
|
```
|
||||||
|
|
||||||
|
`conversationId` 必须是当前联系人列表中精确存在的群 `roomId`;不存在返回 `NOT_FOUND`,个人联系人返回 `NOT_GROUP_CONVERSATION`。`start` 和 `end` 必须同时提供,且使用带 offset 的 ISO-8601,`start` 不能晚于 `end`。HTTP adapter 只负责把稳定群 ID 解析为内部 md5 并调用现有 `GroupStatsService`,不会在 HTTP 层重新统计消息。
|
||||||
|
|
||||||
|
响应中的 `activeMembers` 和 `silentMembers` 都只描述当前成员名单;成员使用 `memberId`,活跃成员的 `lastMessageAt` 和 `range` 时间均为 ISO-8601。`freshness`、`complete`、`limitations` 必须原样保留,`unattributedMessages` 与 `excludedSystemMessages` 用于诊断,`firstMessageAt` 没有消息时为 `null`。当前成员统计不等于完整历史成员统计,`limitations` 表达的退群成员或未归档时段不能从文本中推导成额外的 `formerMembers`,也不会伪造 `totalMessageCount`。
|
||||||
|
|
||||||
|
## Automation API
|
||||||
|
|
||||||
|
`/api/v1/automations*` 是 Automation 的 canonical HTTP API,读写唯一的 `AutomationRuleStore`。它支持当前真实规则类型:`daily_report`、`scheduled_report`、`leave_notification`。本 API 不提供立即执行、重试或清理执行记录。
|
||||||
|
|
||||||
|
旧 `/api/v1/scheduled-reports*` 保持兼容,不设移除日期;它是面向旧 DTO 的受限 compatibility API,不是第二份存储,也不能表示所有新的定时日报目标和配置。新的 Agent 集成应使用 `/automations`。
|
||||||
|
|
||||||
|
创建和校验规则时 `enabled` 只能缺省或为 `false`。创建成功后必须调用 `/automations/{id}/enable` 才会启用。启用会重新校验当前规则;数据库未就绪、目标无法解析或配置无效时不会启用。`PATCH` 只接受规则配置字段,不可改 `ruleType`、`id`、创建/更新时间或 `enabled`;启停必须使用独立 endpoint。未知字段和未知枚举会被拒绝。
|
||||||
|
|
||||||
|
会话范围优先传 `wxid`、`roomId`(如 `xxx@chatroom`)或 canonical conversation ID。唯一匹配的联系人名可被解析为稳定 ID;重名会返回 `ambiguous_contact`,不会猜测。`daily_report.conditions.conversationIds` 在对外 API 中使用稳定 ID,Store 内部仍沿用既有 md5 口径。
|
||||||
|
|
||||||
|
校验请求不落盘、不发消息,也不执行规则。`valid: false` 时查看 `issues`;有效时 `normalized` 是经 ID 解析后的草稿,`effects` 描述启用后的动作,定时日报另外返回按本机时区计算的 `nextRunAt`。
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"name": "产品群每日日报",
|
||||||
|
"ruleType": "scheduled_report",
|
||||||
|
"scheduledReport": {
|
||||||
|
"schedule": { "time": "20:00" },
|
||||||
|
"report": {
|
||||||
|
"sourceConversationId": "wxid_product@chatroom",
|
||||||
|
"range": "today",
|
||||||
|
"messageTypes": ["text", "image"],
|
||||||
|
"templateId": "v1",
|
||||||
|
"memberNameMode": "groupNickname",
|
||||||
|
"timeoutSeconds": 300
|
||||||
|
},
|
||||||
|
"target": { "type": "file_transfer" },
|
||||||
|
"postfixText": ""
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
执行历史只读,默认最多返回 50 条,`limit` 范围是 1-200。`since` 和 `until` 接受带时区的 ISO-8601 时间;execution 本身最多留存 200 条。`running` 记录的 `finishedAt` 为 `null`。
|
||||||
|
|
||||||
|
新 Agent API 的错误格式:
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"error": {
|
||||||
|
"code": "VALIDATION_FAILED",
|
||||||
|
"message": "自动化规则校验失败",
|
||||||
|
"details": []
|
||||||
|
},
|
||||||
|
"requestId": "..."
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
常见错误码包括 `UNAUTHORIZED`、`METHOD_NOT_ALLOWED`、`PAYLOAD_TOO_LARGE`、`INVALID_ARGUMENT`、`NOT_FOUND`、`NOT_GROUP_CONVERSATION`、`DATABASE_NOT_READY`、`VALIDATION_FAILED`、`SINGLETON_RULE`、`PROTECTED_RULE` 和 `PERSISTENCE_FAILED`。`leave_notification` 是固定单例:可读取、修改和启停,但不能创建第二条或删除。内置 `@我生成日报` 同样不能通过 HTTP 删除。
|
||||||
|
|
||||||
### 这些端点与实时机器人有什么关系
|
### 这些端点与实时机器人有什么关系
|
||||||
|
|
||||||
- `/api/v1/agent/status` 只用于查询 Agent Hub、微信连接器和数据库状态;
|
- `/api/v1/agent/status` 只用于查询 Agent Hub、微信连接器和数据库状态;
|
||||||
@@ -215,3 +419,102 @@ curl -X POST -H "$AUTH" -H 'Content-Type: application/json' "$BASE/query/convers
|
|||||||
调用方**必须**把 `coverage` 当真:`coverage.state` 不是 `complete` 且 `evidence` 为空时,只能说明"这段范围暂时无法确认",**不能**下"没有找到"的结论。索引落后时服务端会自动请求一次追赶同步,但不会让请求无限等待;`freshness.catchUp` 为 `pending` 表示追赶仍在后台进行,稍后重试即可拿到更新的覆盖。
|
调用方**必须**把 `coverage` 当真:`coverage.state` 不是 `complete` 且 `evidence` 为空时,只能说明"这段范围暂时无法确认",**不能**下"没有找到"的结论。索引落后时服务端会自动请求一次追赶同步,但不会让请求无限等待;`freshness.catchUp` 为 `pending` 表示追赶仍在后台进行,稍后重试即可拿到更新的覆盖。
|
||||||
|
|
||||||
`query/messages` 与 `query/conversation-overview` 直读聊天数据库,不受索引新鲜度影响。
|
`query/messages` 与 `query/conversation-overview` 直读聊天数据库,不受索引新鲜度影响。
|
||||||
|
|
||||||
|
### 语音转文字(voice-transcribe)
|
||||||
|
|
||||||
|
语音消息的正文固定是 `[语音消息]`。本机已转写过的语音,读取时会直接带上转写结果(只读缓存,不触发识别):
|
||||||
|
|
||||||
|
- `query/messages`、`query/message-context`:`voiceTranscriptState` 与 `voiceTranscript`,`derivedSource` 为 `voice_transcript`;
|
||||||
|
- `/chatlog`:语音消息额外带 `messageRef`、`voiceTranscriptState` 与 `voiceTranscript`。
|
||||||
|
|
||||||
|
`voiceTranscriptState` 为 `pending` 表示**还没转写**,不能当成"语音里没说话"。需要内容时,把这些语音的 `messageRef` 交给 `POST /api/v1/query/voice-transcribe`:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
curl -X POST -H "$AUTH" -H 'Content-Type: application/json' "$BASE/query/voice-transcribe" \
|
||||||
|
-d '{"messageRefs":["<语音消息的 messageRef>"],"waitMs":15000}'
|
||||||
|
```
|
||||||
|
|
||||||
|
| 字段 | 含义 |
|
||||||
|
| ------------- | --------------------------------------------------------------------------------------- |
|
||||||
|
| `messageRefs` | 必填,1~20 条;重复的引用会合并 |
|
||||||
|
| `waitMs` | 可选,最多同步等待的毫秒数,默认 15000,上限 60000;`0` 表示只排队、不等待 |
|
||||||
|
| `force` | 可选,`true` 时忽略已有转写和失败记录、重新识别;只在用户明确要求重试时使用 |
|
||||||
|
|
||||||
|
识别在本机离线进行(需要先在 TraceMemo 设置里下载语音识别模型),和界面共用同一份缓存与同一条串行队列:界面上点开语音会优先处理,API 的任务随后继续。等待超时的条目返回 `pending`,识别会在后台继续;稍后用同样的 `messageRefs` 再调用即可取回结果,不会重复排队。
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"status": "completed",
|
||||||
|
"items": [
|
||||||
|
{ "messageRef": "…", "state": "transcribed", "transcript": "…", "cached": false },
|
||||||
|
{ "messageRef": "…", "state": "pending", "code": "still_processing", "hint": "…" }
|
||||||
|
],
|
||||||
|
"summary": { "transcribed": 1, "pending": 1, "failed": 0 }
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
每个未成功的条目都带 `code` 与 `hint`(下一步该怎么做):
|
||||||
|
|
||||||
|
| `code` | 含义 |
|
||||||
|
| ----------------------- | ------------------------------------------ |
|
||||||
|
| `still_processing` | 仍在后台转写,稍后原样重试 |
|
||||||
|
| `previously_failed` | 之前识别失败,默认不自动重跑 |
|
||||||
|
| `recognition_failed` | 本次识别失败(音频损坏、过短或没有人声) |
|
||||||
|
| `recognition_timeout` | 识别超时 |
|
||||||
|
| `not_voice_message` | 不是语音消息 |
|
||||||
|
| `message_not_found` | 找不到消息(可能已切换账号) |
|
||||||
|
| `invalid_message_ref` | `messageRef` 无法解析 |
|
||||||
|
|
||||||
|
整次请求的状态:`200 completed`;`400 invalid_tool_arguments`(带 `field`、`constraint`、`hint`);`503 voice_model_not_ready`(模型未下载)或 `knowledge_unavailable`(数据库未连接);`429 busy`(队列已满,带 `retryAfterSeconds` 与 `Retry-After` 头)。
|
||||||
|
|
||||||
|
## Reader Skill 的版本与更新
|
||||||
|
|
||||||
|
Reader Skill 是随应用分发的说明文件。它被安装到 Agent 自己的 Skill 目录之后就与 TraceMemo 分离了,不再随应用升级自动变化,所以它必须能自己证明版本:
|
||||||
|
|
||||||
|
- `SKILL.md` frontmatter 的 `version` 是**唯一真源**(形如 `1.4.0`);
|
||||||
|
- `/api/v1/health` 的 `skill.version` 回报当前应用内置的版本;
|
||||||
|
- 两者不一致,就说明 Agent 手里那份已经过期,接口契约可能已经变化。
|
||||||
|
|
||||||
|
### 检查更新
|
||||||
|
|
||||||
|
```bash
|
||||||
|
curl http://127.0.0.1:6131/api/v1/health
|
||||||
|
```
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"ok": true,
|
||||||
|
"ready": true,
|
||||||
|
"service": "TraceMemo Reader",
|
||||||
|
"version": "2.5.1",
|
||||||
|
"skill": { "name": "tracememo-reader", "version": "1.4.0", "available": true },
|
||||||
|
"timestamp": "2026-10-13T08:43:52.863Z"
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
注意区分两个版本号:`version` 是应用版本,`skill.version` 才是 Reader Skill 的版本。Skill 文件读不到时 `available` 为 `false`、`skill.version` 为 `null`,此时 health 仍然返回 `200`——外部 Agent 靠它做自检,这个接口不允许因为 Skill 缺失而失败。
|
||||||
|
|
||||||
|
### 拉取最新 Skill
|
||||||
|
|
||||||
|
```bash
|
||||||
|
curl -H "Authorization: Bearer $TRACEMEMO_API_TOKEN" \
|
||||||
|
"http://127.0.0.1:6131/api/v1/skill/tracememo-reader"
|
||||||
|
```
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"name": "tracememo-reader",
|
||||||
|
"version": "1.4.0",
|
||||||
|
"contentHash": "<sha256 hex>",
|
||||||
|
"modifiedAt": "2026-10-13T08:37:30.000Z",
|
||||||
|
"markdown": "---\nname: tracememo-reader\nversion: 1.4.0\n…"
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
`markdown` 就是可以直接落盘的 SKILL.md 全文,`contentHash` 是它的 SHA-256,可用来核对写入结果。响应**不包含**任何本地文件路径。`503 skill_unavailable` 表示应用侧也没找到 Skill 文件,需要重新安装 TraceMemo。
|
||||||
|
|
||||||
|
### Agent 侧的自检义务
|
||||||
|
|
||||||
|
`docs/skill/tracememo-reader/SKILL.md` 中的「版本自检」要求 Agent 在每次会话开始时比对一次版本:不一致就停止读取数据并提醒用户重新安装;用户同意后,Agent 可以直接调用上面的接口自助覆盖本地文件,不需要用户重新复制安装指令。
|
||||||
|
|
||||||
|
修改 `SKILL.md` 内容时必须同步提升 `version`。CI 中的 `pnpm check:skill-version` 会在"只改文档、不升版本"时失败,避免再次出现"文档改了两轮、版本号纹丝不动"的情况。
|
||||||
@@ -26,6 +26,21 @@ Reader Skill 只负责“外部 Agent 主动查询历史微信数据”。它不
|
|||||||
|
|
||||||
TraceMemo 不会自动把 Token 写进 Agent 配置。重新生成 Token 后,必须同步更新 Agent 环境。
|
TraceMemo 不会自动把 Token 写进 Agent 配置。重新生成 Token 后,必须同步更新 Agent 环境。
|
||||||
|
|
||||||
|
## 更新已安装的 Skill
|
||||||
|
|
||||||
|
Reader Skill 在 Agent 那边是独立副本,**不会随 TraceMemo 升级自动更新**。判断是否需要更新:
|
||||||
|
|
||||||
|
1. 在 API Center 的「Skill 详情」里看到的是 TraceMemo 内置的版本;
|
||||||
|
2. Agent 调用 `/api/v1/health` 拿到 `skill.version`;
|
||||||
|
3. 再和 Agent 手里 SKILL.md frontmatter 的 `version` 比对——不一致就是过期了。
|
||||||
|
|
||||||
|
更新有两种方式,任选其一:
|
||||||
|
|
||||||
|
- **让 Agent 自己更新**:直接告诉 Agent「你的 Reader Skill 过期了,请从本机 TraceMemo 拉最新版覆盖」。它会调用 `/api/v1/skill/tracememo-reader` 取回最新全文并落盘,不需要你重新复制安装指令。
|
||||||
|
- **手工重新安装**:回到 API Center → 快速接入,重新点一次「复制安装指令」交给 Agent 覆盖安装。
|
||||||
|
|
||||||
|
新版 Skill 里带有「版本自检」条款,要求 Agent 每次会话开始时比对一次版本。**如果它从来没提醒过你版本不一致,很可能你手里那份还是旧版**——旧版没有这条自检。
|
||||||
|
|
||||||
## Agent 的读取顺序
|
## Agent 的读取顺序
|
||||||
|
|
||||||
当用户使用“今天”“昨天”“本周”等相对时间时:
|
当用户使用“今天”“昨天”“本周”等相对时间时:
|
||||||
@@ -55,7 +70,8 @@ Reader Skill 可以指导 Agent 使用:
|
|||||||
- 结构化日报渲染和按群聊生成总结图片;
|
- 结构化日报渲染和按群聊生成总结图片;
|
||||||
- 定时日报任务的查询、创建、修改、启停、删除、立即执行和执行记录;删除不可逆,Skill 要求先列出唯一任务并取得用户明确确认;
|
- 定时日报任务的查询、创建、修改、启停、删除、立即执行和执行记录;删除不可逆,Skill 要求先列出唯一任务并取得用户明确确认;
|
||||||
- 个人微信发送能力状态查询(`/wechat-personal/send-capability`);
|
- 个人微信发送能力状态查询(`/wechat-personal/send-capability`);
|
||||||
- `query/*` 一组结构化 Query 端点:`messages`、`search`、`message-context`、`conversation-overview`;
|
- `query/*` 一组结构化 Query 端点:`messages`、`search`、`message-context`、`conversation-overview`、`voice-transcribe`;
|
||||||
|
- 自身版本查询(`/skill/tracememo-reader`),用于判断是否需要更新;
|
||||||
- Agent Hub 状态检查与已连接机器人发送测试。这里的发送接口是开发者/测试用途,不是实时机器人入口,也不会让 Reader Skill 自动监听微信消息。
|
- Agent Hub 状态检查与已连接机器人发送测试。这里的发送接口是开发者/测试用途,不是实时机器人入口,也不会让 Reader Skill 自动监听微信消息。
|
||||||
|
|
||||||
注意这个 API 不只是只读的:`/report`、`/agent/send` 和 `/scheduled-reports*` 会写入状态或真的发出微信消息。
|
注意这个 API 不只是只读的:`/report`、`/agent/send` 和 `/scheduled-reports*` 会写入状态或真的发出微信消息。
|
||||||
|
|||||||
@@ -0,0 +1,308 @@
|
|||||||
|
# TraceMemo Local HTTP API / Agent API 能力审计
|
||||||
|
|
||||||
|
本报告基于当前代码、文档、IPC、Renderer 调用和相关测试做静态审计,对应当前发布应用版本 `2.5.0`;不连接真实微信数据库,也不修改生产代码、API Center 或测试。
|
||||||
|
|
||||||
|
主要代码入口:[http-server.ts](../../src/main/http-server.ts)、[automation-rule-store.ts](../../src/main/services/automation-rule-store.ts)、[group-exit-monitor-service.ts](../../src/main/services/group-exit-monitor-service.ts)、[group-stats-service.ts](../../src/main/services/group-stats-service.ts)、[api.md](../agent/api.md)。
|
||||||
|
|
||||||
|
## 1. Executive Summary
|
||||||
|
|
||||||
|
当前 HTTP 层声明了 **30 个 Method + Path 模板**:15 个 GET、12 个 POST、1 个 PATCH、1 个 DELETE、1 个 HEAD。共享 `LOCAL_API_ENDPOINTS` 定义 **14 个测试项**,但 Renderer 的 `API_ENDPOINTS` 实际只展示 **12 项**;个人微信能力和 `GET /scheduled-reports` 虽有共享定义,界面没有展示。界面也没有结构化 Query、媒体读取、定时日报写操作、退群监控、群统计、Automation 通用资源或执行日志查询。
|
||||||
|
|
||||||
|
当前不缺成熟的 Query primitive:结构化读取消息、Knowledge 搜索、消息前后文、会话概览和图片 OCR 搜索已经有 HTTP 契约。真正的能力缺口集中在 **监控配置、自动化规则通用管理、群员统计、执行历史、全局能力发现、发送状态和报告历史**。
|
||||||
|
|
||||||
|
几个影响后续设计的代码事实:
|
||||||
|
|
||||||
|
1. 定时日报已迁入 `AutomationRuleStore`。当前 `/scheduled-reports` 是旧 HTTP 契约的兼容投影,不是第二份活动规则存储;但它只表达“生成后发回来源群”,其他当前合法目标不会出现在该兼容 API 列表中。
|
||||||
|
2. 退群监控只负责监测范围、快照和事件历史;退群后如何通知由唯一的 `leave_notification` Automation 规则负责。二者应分别建资源。
|
||||||
|
3. 群统计 Service 足以提供活跃成员、当前沉默成员、时间范围、新鲜度和限制说明;它没有结构化的 former member 列表,也没有覆盖所有发言者的群总消息数。
|
||||||
|
4. 现有微信 Action Gateway 有策略、审计和幂等骨架,但策略目前主要校验收件人,以及 Automation purpose allowlist;手动用户 purpose 默认可放行。它只发个人微信,现有 `/agent/send` 则走 iLink 的 `WechatSendGateway`。两者不能直接视为统一的 Agent 安全边界。
|
||||||
|
5. HTTP 静态 GET handler 大多没有 method guard;对这些路径发 POST、PATCH 或 DELETE 仍会执行读处理。Automation store 的规则落盘失败会记录日志,但仍将内存中的规则返回为成功。
|
||||||
|
|
||||||
|
建议先做应用级能力发现、退群监控资源、严格校验后的 Automation CRUD/执行查询;发送和“立即执行”放到有 dry-run、明确确认、幂等键和 Action 审计的后续阶段。
|
||||||
|
|
||||||
|
## 2. Current API Inventory
|
||||||
|
|
||||||
|
以下按 `http-server.ts` 的路由分派和动态 route factory 盘点。静态读路由的 `Method` 是当前文档和产品语义的预期方法;实际接受方法的差异见本节末尾。
|
||||||
|
|
||||||
|
| Method | Path | 能力 | Read/Write/Execute | Service | API Center | 文档 | Agent 价值 |
|
||||||
|
|---|---|---|---|---|---|---|---|
|
||||||
|
| GET | `/api/v1/health` | HTTP 与数据库 ready 状态;唯一免 Token 路径 | Read | `isReady()` | 是 | 是 | 高:连通性 |
|
||||||
|
| GET | `/api/v1/current_time` | 本机时间、时区、日期 | Read | JavaScript `Date` | 是 | 是 | 中:相对日期换算 |
|
||||||
|
| GET | `/api/v1/contact` | 联系人和群列表;`filter`、`type`;使用异步 hydration | Read | `chat-service.listContactsAsync` | 是 | 是 | 高:标识发现与 resolve 前置 |
|
||||||
|
| GET | `/api/v1/chatroom` | 群聊列表;`keyword`;使用异步 hydration | Read | `chat-service.listContactsAsync` | 是 | 是 | 高:群标识发现 |
|
||||||
|
| GET | `/api/v1/recent_chat` | 最近会话;`limit` 默认 50 | Read | `chat-service.listRecentChat` | 是 | 是 | 高:导航/摘要 |
|
||||||
|
| GET | `/api/v1/chatlog` | 按 talker 和时间读取原始消息;移除 `contentData.aeskey` | Read | `chat-service.listMessages`、`resolveMd5` | 是 | 是 | 高,但旧式、未做结构化分页 |
|
||||||
|
| GET | `/api/v1/group_snapshot` | 群成员快照;必填 `md5` | Read | `chat-service.getGroupSnapshot` | 是 | 是 | 高:成员身份解析 |
|
||||||
|
| GET | `/api/v1/resolve` | 昵称、wxid、md5 解析为会话 | Read | `chat-service.resolveMd5` | 是 | 是 | 高;新资源宜返回稳定 ID 和歧义候选 |
|
||||||
|
| POST | `/api/v1/report` | 接收完整结构化日报并导出 HTML/PNG;当前拒绝外部 `templateRef` | Write:本地文件 | `group-report-service.exportGroupReport` | 是 | 是 | 低/中:低层渲染契约,Agent 须先拼完整结构 |
|
||||||
|
| POST | `/api/v1/agent/group-report` | 读群消息、调用 AI 生成群总结、导出 HTML/PNG | Execute:AI/本地文件 | `agent-group-report-service.generateAgentGroupReport` | 是 | 是 | 高但有模型费用/数据出站;结果不等同于报告历史记录 |
|
||||||
|
| GET | `/api/v1/agent/status` | Agent Hub、connector、数据 API、数据库状态 | Read | `agentHubService.getStatus` | 是 | 是 | 中:只覆盖 Agent Hub,不是应用总能力 |
|
||||||
|
| POST | `/api/v1/agent/send` | 通过 Agent Hub 连接器发送文字或媒体 | Execute:微信发送 | `agentHubService.testSend` → `WechatSendGateway`/iLink | 是 | 是 | 高但 R2;是测试入口,不含统一 Action policy/幂等确认 |
|
||||||
|
| GET | `/api/v1/wechat-personal/send-capability` | 个人微信 text/image/voice 能力状态 | Read | `PersonalWechatCapabilityService`,由 `ScheduledReportApiService` 包装 | 否(共享定义有,界面未展示) | 是 | 高但只代表 personal,不代表 iLink |
|
||||||
|
| GET | `/api/v1/scheduled-reports` | 列出旧 DTO 可表达的定时日报规则 | Read | `ScheduledReportApiService.list` → 规则投影 | 否(共享定义有,界面未展示) | 是 | 高但不完整:仅 `source_chat` 目标 |
|
||||||
|
| POST | `/api/v1/scheduled-reports` | 创建旧型定时日报,来源群即发送目标 | Write:规则配置 | `ScheduledReportApiService.create` → `AutomationRuleStore` | 否 | 是 | 高;功能受旧 DTO 限制 |
|
||||||
|
| GET | `/api/v1/scheduled-reports/{id}` | 单条旧型日报规则投影 | Read | `ScheduledReportApiService.get` → `AutomationRuleStore` | 否 | 是 | 中/高:只支持兼容投影规则 |
|
||||||
|
| PATCH | `/api/v1/scheduled-reports/{id}` | 修改旧型日报规则 | Write:规则配置 | `ScheduledReportApiService.update` → `AutomationRuleStore` | 否 | 是 | 高但只能改旧字段/目标 |
|
||||||
|
| DELETE | `/api/v1/scheduled-reports/{id}` | 删除旧型日报规则 | Write:删除配置 | `ScheduledReportApiService.delete` → `AutomationRuleStore` | 否 | 是 | 中;新 API 应标 R3 并防护系统规则 |
|
||||||
|
| POST | `/api/v1/scheduled-reports/{id}/enable` | 启用规则 | Write:配置/未来执行 | `ScheduledReportApiService.setEnabled` → `AutomationRuleStore` | 否 | 是 | 高;启用后未来可能发送微信 |
|
||||||
|
| POST | `/api/v1/scheduled-reports/{id}/disable` | 暂停规则 | Write:配置 | `ScheduledReportApiService.setEnabled` → `AutomationRuleStore` | 否 | 是 | 高 |
|
||||||
|
| POST | `/api/v1/scheduled-reports/{id}/run` | 手动触发完整日报规则 | Execute:可能调用 AI、保存历史、发微信 | `ScheduledReportService.runScheduledReportNow` → `AutomationService` | 否 | 是 | 高但 R2;当前无 HTTP 幂等键/确认 |
|
||||||
|
| GET | `/api/v1/scheduled-reports/{id}/executions` | 旧型 execution 历史和新 Automation execution 投影 | Read | `ScheduledReportService.listExecutions` | 否 | 是 | 高但旧响应模型/有限留存 |
|
||||||
|
| POST | `/api/v1/scheduled-reports/executions/{executionId}/retry-send` | 旧文档称复用 PNG 重发 | Execute 路由存在但当前固定 `501 not_supported` | `ScheduledReportApiService.retrySend` | 否 | **路径有,语义已失效** | 无:不能重发 |
|
||||||
|
| GET | `/api/v1/media/{mediaId}` | 读取消息关联的图片二进制 | Read | `http-media-service.readImageMedia` | 否 | 是 | 高:图像证据 |
|
||||||
|
| HEAD | `/api/v1/media/{mediaId}` | 图片资源存在性/响应头 | Read | `http-media-service.readImageMedia` | 否 | 否 | 低/中 |
|
||||||
|
| GET | `/api/v1/query/capabilities` | Query Tool 支持的结构化操作、范围和上限 | Read | `LocalQueryApiService.capabilities` | 否 | 是(独立章节) | 高,但不是 TraceMemo 应用能力清单 |
|
||||||
|
| POST | `/api/v1/query/messages` | 单会话、范围、时间、方向、类型等确定性消息读取 | Read | `LocalQueryApiService.messages` | 否 | 是 | 高:推荐 Query primitive |
|
||||||
|
| POST | `/api/v1/query/search` | Knowledge 关键词检索,返回覆盖、新鲜度和 OCR 命中 | Read | `LocalQueryApiService.search` + `KnowledgeSearchService` | 否 | 是 | 高:必须读取 coverage/freshness |
|
||||||
|
| POST | `/api/v1/query/message-context` | 通过 opaque `messageRef` 读取前后文 | Read | `LocalQueryApiService.context` | 否 | 是 | 高:稳定消息引用 |
|
||||||
|
| POST | `/api/v1/query/conversation-overview` | 单会话范围的概览证据和 source coverage | Read | `LocalQueryApiService.overview` | 否 | 是 | 高:broad summary |
|
||||||
|
|
||||||
|
路由来源:[http-server.ts](../../src/main/http-server.ts#L212)、scheduled/query/media route factory(同文件 L404-L670)。总数是代码中声明的业务方法模板,不代表静态 handler 都正确拒绝其他动词:`/health`、`/current_time`、`/contact`、`/chatroom`、`/recent_chat`、`/chatlog`、`/group_snapshot`、`/resolve`、`/agent/status` 没有检查 `req.method`。这些路径携带错误动词仍会走同一 handler;特别是 `POST /health` 也绕过 Token 检查,因为鉴权例外按 pathname 判断。新/旧路由都应 fail closed 并对不支持的方法返回 405。
|
||||||
|
|
||||||
|
全局 `OPTIONS` 在路由和鉴权前处理;媒体额外支持 HEAD。非 health 路径要求 `Authorization: Bearer …`,但 `readBody` 没有大小上限。路由外层目前没有统一请求 schema、统一错误 envelope 或 request id。
|
||||||
|
|
||||||
|
## 3. Internal Capability Inventory
|
||||||
|
|
||||||
|
这里按产品能力追 Service → IPC/Renderer → HTTP → 外部 Agent,而不是按当前 API 名字扩展。
|
||||||
|
|
||||||
|
| 业务域 | 已有能力及实现 | IPC / Renderer | HTTP 现状 | Agent 结论 |
|
||||||
|
|---|---|---|---|---|
|
||||||
|
| Chat / Contact | 联系人、群聊、最近会话、解析、历史消息、群快照、消息周边上下文、媒体定位;`contact-resolution-service` 可精确匹配别名并返回歧义候选 | `db:getContacts`、`db:getGroupSnapshot`、消息查询/around 等,Chat/Contact/档案 UI | 旧 Reader routes + `/query/*` + 图片 `/media/{id}` | 已有 Read API 基础完整。新配置应使用 `m_nsUsrName` 对应的 wxid/roomId 等稳定 ID,不应把昵称当长期键 |
|
||||||
|
| Query / Knowledge | `messages`、`search`、`message-context`、`conversation-overview`;Knowledge 索引覆盖/新鲜度;Image OCR 可进入 Knowledge 搜索和证据 | `knowledge:search/getStatus/startIndex/cancelIndex`、AI Search UI、`LocalQueryToolExecutor` | 四个 Query 操作均已 HTTP 化;`query/capabilities` 只描述 Query Tool | 没有需要重做的基础 Query primitive。缺的是统一应用 capability/status、更多外层筛选和 API Center 展示 |
|
||||||
|
| Group Analytics | 活跃/沉默当前成员、每人 messageCount/lastMessageTime、窗口时间、memberCount、unattributed/system 消息、firstMessageTime、freshness/complete/limitations;索引未新鲜时最多等待 2 秒并如实降级 | `group-stats:getMemberStats`;聊天页群统计 UI | 无 | P1 候选。当前 query 要求群 `userMd5` + epoch 毫秒。former sender 只以限制文案给出数量,没有 formerMembers 数组/结构化计数;没有覆盖 former sender 的群总消息数字段,需扩 DTO 后再承诺 |
|
||||||
|
| Group Exit Monitor | enabled/running/nativeMonitor 状态、监控 roomId 集合、lastChecked、unread、事件历史;每次回传最多 500 条,但完整事件历史 append-only 长期保存;可立即 check、改范围、启停、筛事件、清历史、mark read | `group-exit-monitor:*`;`GroupExitMonitorWorkspace` | 无 | P0。拆成 monitor state/config、events、check。`checkNow` 可能发现事件并触发自动通知,不是纯读操作;重启监控会重建快照基线,暂停期成员变化不会补报 |
|
||||||
|
| Automation | 实际规则类型:`daily_report`、`scheduled_report`、`leave_notification`。`daily_report` 是现有消息触发条件/动作链,不是任意流程引擎;退群通知为固定 ID singleton。规则 CRUD、enable、执行记录读写均已有 Service/Store | `automation:*`;AutomationWorkspace 有规则、日志、定时执行、启停、删除和状态 UI | 没有通用 Automation API;仅 scheduled-report 兼容映射 | P0。使用 typed rule union;不要把内部任意 draft 原样开放。规则创建当前缺省 enabled=true,未知值会被归一化成默认;需 HTTP 严格校验,先 disabled + validate,再显式 enable |
|
||||||
|
| WeChat Send / Action | `WechatSendGateway` 有 personal/iLink transport resolution、text/image/voice/file 统一类型及 Send Log;`WechatActionGateway` 做 capability preflight、Automation purpose allowlist、Action audit、幂等和 Automation 3 秒间隔 | `wechat-personal:send`、`sendGeneratedTtsVoice`、`wechat-action-log:list`、Agent Hub connector 相关 IPC/UI | `/agent/send` 只走 Agent Hub/iLink 测试发送;个人 capability 有独立 GET;两类日志没有 HTTP | 分 transport 公布 capability;R2 send 通过经审计的业务门面,不直接暴露底层 gateway。现有 Action Gateway 还不是普适安全策略:`triggerType=user` 不按 purpose 限制;普通 `/agent/send` 没传 idempotency key,也没有 Action audit |
|
||||||
|
| Agent Hub | status、connector login/reconnect/disconnect、notification recipient/send、logs、conversation list/detail/clear、入站 inbox retry | `agent-hub:*`;Agent Hub UI | 仅 `/agent/status` 和 `/agent/send`;无 conversation/log HTTP | status 有只读价值。对话记录包含完整收发正文;inbox 包含 context token/raw items。Connector 生命周期、登录 QR/验证码、收件箱和通知 recipient 应保持 internal |
|
||||||
|
| Reports / Templates | 手动 report render/export;AI group report;本地 Report History list/save/update template/delete;内置/已安装模板和市场 catalog/install/uninstall | `report:*`、`report-template:*`、`report-template-market:*`;Reports 与 Template Market UI | `/report` 低层 export,`/agent/group-report` AI 生成;没有 history/template API | P1:只读 Report History 元数据/资产可分离设计。现有 `listGeneratedReports` 会读取每张 PNG 为 base64,并返回结构快照和本机绝对路径,不可原样直出。模板目录可读列入 P2;安装/卸载涉及网络与本地包写入,不宜第一批开放 |
|
||||||
|
| Recall Archive | 后台监听撤回变化,最多按会话存归档消息/撤回记录;chat-service 将 archive merge 到历史读结果 | 没有独立 CRUD IPC;设置开关和消息渲染 | 没有独立 archive API;旧 `/chatlog` 可能随底层消息返回 `recalled` 标记;Query DTO 未声明 recalled 字段 | 不开放原始 archive 管理。后续 Query 应明确返回 `recalled`/来源,避免把已撤回归档当普通消息证据 |
|
||||||
|
| OCR / Image Insight | System OCR 本地识别;image-text-index status/count/start/pause/resume/cancel/clear/repair;Image Insight 读/解密图片并可调用 AI Provider | `system-ocr:*`、`image-text-index:*`、`image:*` IPC;Search/Report UI | OCR 派生文本可通过 `/query/search` 得到;索引管理、单图 AI 分析无 HTTP | 已有搜索能力可用。状态可纳入 capability/status;索引删除、key/decoder 配置、任意图像 AI 分析涉及成本、私密图片和索引破坏,不列第一批 |
|
||||||
|
| 系统 / 数据 / 其他 | account discovery、DB key 管理、数据库 connect/root 重开、设置写入、cache summary/clear、app update、voice/TTS、export/import、Reader Skill 本地安装信息 | 多组 IPC;Settings、Cache、Export、Update、Voice UI | 无相应 HTTP API | 只读脱敏运行状态可按需求列 P2;DB key/root、通用 settings patch、cache 清理、任意文件路径、更新安装、TTS synthesis 等保持 internal |
|
||||||
|
|
||||||
|
### A. Chat / Contact 与 ID 语义
|
||||||
|
|
||||||
|
- `/contact`、`/chatroom` 改用 `listContactsAsync`,因为 macOS Session 可能只有原始 wxid/chatroom id,需要 hydrate 显示名;`ScheduledReportApiService` 却使用同步 `listContacts()` 解析群名。稳定 `talker` 可直接解析,但名称输入在需要 hydration 的运行时可能失败/退化。这是可复用 adapter 应统一异步解析的理由。
|
||||||
|
- ID 现在不是一个口径:旧 Query 的 `scope.conversationId`/`target` 解析为 `Contact.md5`;`group-stats` 传 `userMd5`;监控用 `roomId`(`xxx@chatroom`);新的 scheduled automation 用 `sourceConversationId`(wxid/roomId);老 HTTP 路由混用昵称、wxid、md5。保持已有 Reader 契约不动,新 API facade 应统一对外 canonical `conversationId`(底层当前联系人的稳定 username/wxid 或 roomId),并在 main adapter 转为服务所需 md5。名称只做 resolve,不持久化到规则。
|
||||||
|
- `chatlog` 时间边界是 Unix 秒,Query `absolute` 内部也是秒,而 group stats IPC 是 epoch 毫秒;新 Agent 资源建议用带时区 ISO-8601 输入/输出,并在 facade 单点转换。
|
||||||
|
- `/query/messages` 有 200 上限,`messageRef` 是 opaque 稳定引用;图片 OCR 文字和 Coverage 分开呈现。`/chatlog` 则支持旧 talker/time 风格但读取结果没有同等结构边界;作为兼容 Reader 保留,不作为新 Agent 配置/分析的默认接口。
|
||||||
|
|
||||||
|
### B. Group Exit Monitor 与 Leave Notification
|
||||||
|
|
||||||
|
`GroupExitMonitorService` 的真实 IPC 有 `getState`、`setEnabled`、`setGroups`、`checkNow`、`listEvents`、`clearEvents`、`markRead`。事件是群成员差异事实,包含 roomId、member wxid/name、previous/current count、detectedAt;monitor state 中 `events` 只是最近 500 条快照,`totalEventCount` 对应完整内存历史。
|
||||||
|
|
||||||
|
`AutomationService.handleGroupExit` 只处理 `BUILTIN_LEAVE_NOTIFICATION_RULE_ID` 对应的 singleton 规则。规则另有 `notifyScope` / `notifyRoomIds` 二次范围、target、template。Agent 配“监控 A/B/C”需改 monitor 范围;配置通知目标/通知哪些被监控群则另改这条 leave notification automation。两者不能合并为 `/monitors/{id}/notify`。
|
||||||
|
|
||||||
|
### C. Automation 与 Scheduled Report
|
||||||
|
|
||||||
|
`AutomationRuleStore` 的真实方法有 `listRules/getRule/createRule/updateRule/saveLeaveNotificationRule/deleteRule/setRuleEnabled`;`AutomationExecutionLogService` 提供 `list/record/clear/countSince`。执行日志最多留存 200 条,clear 属于破坏性操作。规则在 `{userData}/automation/rules.json` 中 JSON 持久化。
|
||||||
|
|
||||||
|
`scheduled-report-service.ts` 的调度来源是 `automationRuleStore.listRules()`,执行交给 `AutomationService.executeScheduledRule()`,execution 从 Automation Log 投影。迁移后的旧 `tasks.json`/`executions.json` 是只读历史存档。旧 HTTP API 通过 `ScheduledReportApiService` 转换旧 DTO;创建、修改、删除、启停最终也是读写 `AutomationRuleStore`。所以正确方案是保留兼容 facade,并建立 Automation canonical API,不要继续增加第二个 scheduled-report store。
|
||||||
|
|
||||||
|
旧 facade 的限制:只列/操作可投影为 `target.type === 'wechat_group'`、且目标等于来源群的规则。如今 scheduled automation 支持 source_chat/self/file_transfer/contact,故通过新 UI 创建为文件传输助手或联系人目标的规则,会从旧 `/scheduled-reports` 列表隐藏。旧 API 输入 schema 也不能表示完整 scheduled config(成员名、消息类型、模板、timeout、postfix 等)。
|
||||||
|
|
||||||
|
写 API 前还需处理 `AutomationRuleStore` 的归一化和持久化契约:未知 ruleType 会降成 `daily_report`,大部分错误枚举会静默落安全默认;缺省 enabled 是 true;`persist()` catch 写盘错误后只记 warning,Store 仍返回创建/更新后的对象。HTTP adapter 必须先 strict validate,且 Store 需要可观察的持久化结果,不能把内存态冒充成功。
|
||||||
|
|
||||||
|
### D. Group Analytics 确认项
|
||||||
|
|
||||||
|
`GroupStatsService.getMemberStats` 已有可直接复用的核心计算;接口具体有:
|
||||||
|
|
||||||
|
- 当前群成员:`memberCount`、`activeMembers`、`silentMembers`、各活跃成员 `messageCount`/`lastMessageTime`;
|
||||||
|
- 查询窗口:`startTime`、`endTime`(epoch ms)、`firstMessageTime`;
|
||||||
|
- 数据完整性:`freshness = fresh|stale|unknown`、`complete`、`limitations`;
|
||||||
|
- 诊断:`unattributedMessages`、`excludedSystemMessages`。
|
||||||
|
|
||||||
|
成员名单是当前成员集合;知识库统计的 sender 不在当前集合时被排除,只在 `limitations` 中增加“另有 N 位窗口内发言者已不在当前群成员名单”。Service 不返回其身份/每人消息数,也没有 `totalMessageCount`。若 Agent 需要“前成员榜”或全群消息数,需要先扩展 Service/shared type;不能由 API adapter 从 limitation 文案反解析。
|
||||||
|
|
||||||
|
## 4. API / Docs / API Center Drift
|
||||||
|
|
||||||
|
| 项目 | 代码事实 | 漂移/影响 |
|
||||||
|
|---|---|---|
|
||||||
|
| HTTP、共享定义与界面列表 | HTTP 有 30 个 method/path 模板;`LOCAL_API_ENDPOINTS` 定义 14 项,Renderer `API_ENDPOINTS` 实际展示 12 项 | 16 个 HTTP 操作模板没有共享定义;另有 2 个已定义项(个人微信能力、定时日报列表)没有展示。界面仅呈现 12/30 项,不能作为完整 API catalog |
|
||||||
|
| Scheduled Report 展示 | 共享定义只有 `GET /scheduled-reports`;该项本身也未进入 Renderer 列表 | POST 和 task action 不显示,GET 列表也不显示;Agent 在 API Center 里无法发现这组 API |
|
||||||
|
| WeChat Capability 展示 | 共享定义有 `GET /wechat-personal/send-capability`;Renderer 列表未包含它 | API Center 看不到个人微信发送能力状态,用户可能误把 Agent Hub 状态当成完整发送能力 |
|
||||||
|
| Query 展示 | Query 文档在 `api.md` 的独立 LLM-friendly 章节,Service/HTTP 实现完整 | API Center 看不到;用户可能误认为 Reader API 仍只有旧 chatlog |
|
||||||
|
| Media 方法 | `/media/{mediaId}` 支持 GET、HEAD | 文档仅列 GET;API Center 都未列 |
|
||||||
|
| Retry Send | 文档表称 retry-send“复用已有 PNG 重试发送” | `ScheduledReportApiService.retrySend()` 当前无条件抛 `501 not_supported`;integration/unit tests 也未覆盖 retry 路由的这项现状 |
|
||||||
|
| Scheduled Report 完整性 | 旧 facade 只 project `source_chat` | UI 可保存的其他 scheduled target 会从旧 API list/get 隐藏;不是两份存储,但旧 API 不是 Automation API 的完整别名 |
|
||||||
|
| Health 版本 | `/health` 固定返回 `version: "1.0.0"` | 与当前 package version `2.5.0` 不同,Agent 无法据此判断应用版本 |
|
||||||
|
| HTTP 动词 | 九个静态 GET 语义路由无 method guard | POST/PATCH/DELETE 等也可能调用读取逻辑;`/health` 任意 method 均免 Token。测试目前未锁定统一 405 契约 |
|
||||||
|
| 请求/错误 schema | JSON parsing 和错误形状分散:通用 `sendError`、ScheduledReport 专用 error、Query status body、业务自身 result | Agent 要写多套解析逻辑;共享 API schema 和统一错误 code 不存在 |
|
||||||
|
| 命名 | `/contact`、`/chatroom`、`/recent_chat`、`/group_snapshot` 与 `/scheduled-reports`、`/query/*`、`/agent/*`、`/wechat-personal/*` 并存 | snake_case 旧路径、资源路径和“Agent 为业务 owner”的命名混杂;新接口不能继续沿用此漂移 |
|
||||||
|
|
||||||
|
文档 [api.md](../agent/api.md#L35) 基本列出当前 HTTP 路径,Query 在后续单独说明;除 HEAD 外没有发现漏写的当前业务路径,但 retry-send 的成功语义过期。API Center 的来源是单独的 [local-api-test.ts](../../src/shared/local-api-test.ts) 和 [apiEndpoints.ts](../../src/renderer/src/features/api-center/model/apiEndpoints.ts),没有从 HTTP route/schema 派生。测试现有 `local-api-auth` 覆盖鉴权、媒体、部分 Query 和 Agent send;`scheduled-report-api` 覆盖旧生命周期;`local-api-contact-search` 覆盖 hydrate。它们没有自动比对 HTTP route、文档、Catalog 三者,也没有覆盖全部 method guard 和 retry-send。
|
||||||
|
|
||||||
|
## 5. Candidate API Matrix
|
||||||
|
|
||||||
|
风险按本任务口径:R0 只读;R1 本地配置/应用状态修改;R2 微信发送、AI/provider 调用等外部副作用;R3 删除或清空不可轻易恢复的数据。R1 不代表没有后续行为:enable 一条定时规则会武装未来的 R2 执行。
|
||||||
|
|
||||||
|
| Capability | 当前实现 | 当前 API | 建议 | Agent 用例 | Risk | Priority |
|
||||||
|
|---|---|---|---|---|---|---|
|
||||||
|
| 联系人/群/会话 resolve | Chat Service + Contact Resolution | 有旧 routes;Query 内 resolve | 保留旧路由;新 resource 返回稳定 ID、歧义候选 | 查找群并取得 roomId | R0 | P0(复用) |
|
||||||
|
| 结构化消息/搜索/上下文/概览 | LocalQueryApiService + Knowledge | `/query/*` | 保持契约;加 route schema/catalog,后续可升级稳定 ID | 查聊天、关键词/OCR、补上下文 | R0 | P0(复用) |
|
||||||
|
| 应用 capability discovery | 各 Service 能回答局部状态 | 无;`query/capabilities` 仅 Query Tools | 新 `GET /capabilities`,区分 supported/available/reason/operations | 发现自动化、监控、统计、发送 transport | R0 | P0 |
|
||||||
|
| Group Exit Monitor 状态/范围 | GroupExitMonitorService | 仅 IPC | GET state + PATCH enabled/roomIds | 查看监控、监控/停止一个群 | R0/R1 | P0 |
|
||||||
|
| Group Exit events | Monitor JSONL + listEvents | 仅 IPC | GET 带 stable roomId/time/cursor/limit | 最近 7 天谁退群 | R0 | P0 |
|
||||||
|
| 手动检查退群 | checkNow 会扫描并触发事件 handler | 仅 IPC | 有外部通知时按 R2 操作开放,先 validate effects + confirm | 立即检查一次 | R2 | P1 |
|
||||||
|
| Automation 规则 CRUD | AutomationRuleStore | 通用 IPC;HTTP 仅旧 scheduled facade | typed union CRUD;create disabled;validate 再 enable;保护 singleton/system rules | 创建、列出、修改、暂停自动化 | R1/R3(delete) | P0 |
|
||||||
|
| Automation validation/dry-run | 现有编辑器 preview 分散;无通用 validator API | 无 | `POST /automations/validate`;不落盘、不发送 | 确认群、目标、模板、下次运行和能力 | R0 | P0 |
|
||||||
|
| Automation execution history | AutomationExecutionLogService,最多 200 条 | schedule 专属旧投影 | 规范化 Automation execution 读接口;清日志不开放第一批 | 查看失败、按 rule 过滤 | R0/R3(clear) | P0 |
|
||||||
|
| Group member stats | GroupStatsService | 仅 IPC | 按稳定 group ID + ISO window 读统计;先补 former/total 语义 | 近 30 天活跃榜 | R0 | P1 |
|
||||||
|
| WeChat capability | personal capability service;Agent Hub status | personal GET + Agent status | 新全局 capability 含 personal/iLink 和内容能力;旧路由保留 | 检查发送当前是否可用 | R0 | P0 |
|
||||||
|
| 手动微信发送 | WechatSendGateway + Action Gateway | `/agent/send` iLink test send | 新 send command 经受限 Action facade,强制 stable recipient、confirm、idempotency | 文件助手测试消息 | R2 | P1 |
|
||||||
|
| Send Log / Action audit | Send Log 500 条;Action audit 500 条;IPC action-log | 无 HTTP | 分层只读分页,preview 脱敏;按 executionId/requestId 关联 | 查最近发送失败、审计规则动作 | R0 | P1 |
|
||||||
|
| Agent Hub status | AgentHubService.getStatus | `/agent/status` + IPC | 保留 alias,新资源名归 `/agent-hub/status`,与 app capabilities 分开 | 查 Hub/connector online | R0 | P1(复用) |
|
||||||
|
| Agent Hub 对话内容 | Conversation Store,最多 50 会话×500 条 | 仅 IPC | 默认为 Internal;若产品确认需要,另做显式 opt-in、分页/时间过滤 | 查看机器人与某人的对话 | R0(高隐私) | 不建议第一批 |
|
||||||
|
| AI 群日报 | AgentGroupReportService + export | `/agent/group-report` | 保留兼容;未来先 validate model/range/group/data egress,再异步 job | 生成临时总结图片 | R2(provider/本地文件) | P1 |
|
||||||
|
| 日报历史 | ReportHistory Service,IPC CRUD | 无 | 分页 metadata DTO;图片 asset 单独下载;不返回 base64/路径/完整 snapshot | 昨天生成过哪些日报 | R0 | P1 |
|
||||||
|
| 模板列表 | Template Service + market catalog | 仅 IPC | 仅已安装模板只读列表列 P2 | 有哪些日报模板 | R0 | P2 |
|
||||||
|
| 模板安装/删除/历史改版 | Template Service/Market + Report History | 仅 IPC | 不开放通用 HTML/路径写入;将来单独授权且保留校验 | 安装或修改模板 | R1/R3 | Maybe/P2 |
|
||||||
|
| Recall archive 查询 | 内部 archive merge 到历史消息 | 无独立 API | 不单独开放磁盘 Archive;给 Query 增 `recalled` 来源标记 | 找被撤回消息 | R0(敏感/语义风险) | P2 |
|
||||||
|
| Image OCR index 操作 | image-text-index service | IPC(含 clear/repair) | coverage 状态可汇入 capabilities/status;不让 Agent 操作 clear/reset | 查 OCR 覆盖 | R0/R1/R3 | P2 |
|
||||||
|
| AI image insight | ImageInsightService 读/解密图片并调 vision provider | IPC | 不暴露任意 hash/message AI 分析,除非有成本/隐私授权 | 理解群图片 | R2 | 不建议第一批 |
|
||||||
|
| DB key、根目录、settings、cache | 多个设置/DB/cache Service | IPC/UI | 禁止通用 settings patch / 文件路径 / DB key API;只加白名单状态字段 | 修改本机数据库、安全设置 | R1/R3 | 不建议开放 |
|
||||||
|
| Connector 生命周期/inbox | AgentHubService + WechatInboundInbox | 仅 IPC/内部 | connector 登录、验证码、QR、inbox、context token 不对 Agent 暴露 | 重连或直接拿入站 token | R1/R2 | 不建议开放 |
|
||||||
|
|
||||||
|
## 6. P0 Recommendation
|
||||||
|
|
||||||
|
第一批目标是“让 Agent 能配置和核验 TraceMemo,但不意外发消息”。建议只包括:
|
||||||
|
|
||||||
|
1. `GET /api/v1/capabilities`:应用级 capability,不与现有 `/query/capabilities` 合并。返回版本、DB/readiness、supported vs available、不可用原因和依赖;发送分 personal/iLink 与 text/image/voice 能力。
|
||||||
|
2. Group Exit Monitor:读取状态、显式配置 monitored roomIds、读取历史事件。`PATCH` 只接 canonical 群 ID,拒绝不存在/非群 ID;修改范围响应明确显示后台 baseline/check 状态。`check` 先列 P1,因为它可能启动退群通知发送。
|
||||||
|
3. Automation typed CRUD:列/读规则、创建 disabled 规则、更新、显式启停、执行历史读取。Leave Notification 仍使用固定 singleton id,不允许创建重复规则;拒绝未知字段/未知 enum,而不是靠 `normalizeRuleDraft` 静默修正。
|
||||||
|
4. `POST /automations/validate`:验证目标群、稳定通知 recipient、模板变量、report/template 配置、send capability 和 nextRunAt;只返回 plan,不落盘、不发送。
|
||||||
|
5. 运行状态与错误契约:一致的 405、最大 body、请求 ID、错误 envelope;这是任何新 Agent 写接口前的 foundation,不是大规模权限系统。
|
||||||
|
|
||||||
|
Agent 实现示例(概念流程):
|
||||||
|
|
||||||
|
- “监控 A/B/C 退群”:resolve 三个群为 roomId → validate scope → PATCH monitor group IDs。
|
||||||
|
- “A 群有人退出就通知文件助手”:读取 monitor scope 和 singleton leave rule → validate 类型/notify scope/target → 更新规则但保持 disabled → 用户/Agent 明确 enable。监控与 leave-notification 是两份正交配置。
|
||||||
|
- “每天 20:00 生成产品群日报”:resolve sourceConversationId → validate scheduled rule(包含 target/transport/模板/时区/next run)→ 创建 disabled → 显式 enable。旧 `/scheduled-reports` 无法表达所有当前 config,不承担新 Agent CRUD。
|
||||||
|
- “昨天哪些自动化失败”:读 automation executions,按本机 timezone/UTC offset 和 status 查询,不清理日志。
|
||||||
|
|
||||||
|
## 7. Proposed Resource Model
|
||||||
|
|
||||||
|
采用业务 capability 资源,HTTP server 只负责 transport、auth、body、统一错误;每个 domain route 调用独立的 main-process API facade/Service adapter。Facade 复用当前 Service/Store,不把 UI IPC 当 HTTP RPC 转发层。
|
||||||
|
|
||||||
|
| Resource | 职责 | 现有路径的处理 |
|
||||||
|
|---|---|---|
|
||||||
|
| `system` | health、版本、应用级 capabilities、运行状态 | `/health` 保留;新增 `/capabilities`;`query/capabilities` 不改语义 |
|
||||||
|
| `contacts` / `groups` | 稳定 ID 列表、resolve、群成员快照/统计 | `/contact`、`/chatroom`、`/resolve`、`/group_snapshot` 保留兼容 |
|
||||||
|
| `query` | 消息/搜索/上下文/概览证据 | 现有 `/query/*` 保持;query ID 口径升级需兼容 reader skill |
|
||||||
|
| `monitors` | 退群监控范围、启停、事件、显式 check | 新 `/monitors/group-exits`,与通知规则分离 |
|
||||||
|
| `automations` | 规则 typed CRUD、validate、启停和运行 | 新 `/automations` 是 canonical HTTP resource;底层仍由 `AutomationRuleStore` 存储 |
|
||||||
|
| `executions` | 跨 Automation/Action/Send 的只读运行视图 | 新 `/executions` read model,不合并各自写存储 |
|
||||||
|
| `wechat` | transport capabilities、受控 send command、Send Log/Action audit | `/agent/send` 与 `/wechat-personal/send-capability` 保留兼容 |
|
||||||
|
| `reports` | report history 元数据/asset;installed templates read-only | `/report` 与 `/agent/group-report` 保留为不同兼容操作 |
|
||||||
|
| `agent-hub` | Hub/connector 状态;conversation API 默认 internal | `/agent/status` 保留 alias,不复用 app capability |
|
||||||
|
| `developer` | 高级 raw request tester 与诊断 | API Center 的 tester;不作为 Agent 业务 API |
|
||||||
|
|
||||||
|
共享资源原则:新 API 输入以 stable id 为主、名字只用于 resolve;所有写请求 strict validate;时间对新资源用 offset ISO-8601;分页使用 `limit` + `cursor`;成功/失败使用一个 typed envelope;不直接返回 app userData path、token、context token、AES key 或原始 transport payload。
|
||||||
|
|
||||||
|
## 8. Safety Model
|
||||||
|
|
||||||
|
### 当前边界
|
||||||
|
|
||||||
|
- 默认监听 `127.0.0.1:6131`,但 host/port 由设置和 `api:start` 调用传入,API Center 会警告非 loopback。CORS 只允许 loopback Origin,但不带 Origin 的 curl/Agent 请求仍可用 Token;CORS 不是本地进程授权边界。
|
||||||
|
- `/health` 公开,其余 endpoint 共用单一 Bearer Token。Token 为 32 random bytes、safeStorage 加密存储并设 `0600`,没有 read/config/send scope。拿到 token 即可读取聊天,也能建/删/启停规则、立即发送。
|
||||||
|
- HTTP `/agent/send` 的消息进入 `WechatSendGateway`,因此有低层 Send Log;但没有 `WechatActionGateway` 的业务 Action audit/策略决策,也没有调用方 Idempotency-Key。Personal capability 路由只报告个人微信状态。
|
||||||
|
- `WechatActionGateway` 的请求包含 `purpose`、`triggerType`、recipient、content、`idempotencyKey`、`executionId`;Automation trigger 有 purpose allowlist,sender capability 会先检查,审计记录会保存 content preview/hash。当前 `evaluateWechatActionPolicy` 对 `triggerType=user` 不做 purpose allowlist,`shouldUseAiPolicy` 固定 false;幂等只对显式 key 或历史特定 scheduled request 生效。它目前只发个人微信,不能直接替换 iLink send。
|
||||||
|
- Action Audit 和 Send Log 各自上限 500;Automation Execution Log 上限 200。三类日志粒度不同,不是重复的同一事实。
|
||||||
|
|
||||||
|
### 分级建议
|
||||||
|
|
||||||
|
| 风险 | 操作 | 建议控制 |
|
||||||
|
|---|---|---|
|
||||||
|
| R0 | 查询聊天/成员/事件/状态/统计/日志/报告元数据 | 保留本地 Token;响应明确 scope、coverage、freshness、隐私字段 |
|
||||||
|
| R1 | 修改监控群、Automation 配置、启停、模板设置 | typed validation、dry-run plan、显示持久化成功;enable 需确认它武装未来发送 |
|
||||||
|
| R2 | 微信发送、立即执行日报/退群通知 check、调用 AI Provider 生成报告 | 明确 recipient 和内容/规则;`Idempotency-Key` 必填;统一 Action policy + Action audit + Send Log;重复请求回放原结果;返回发送状态 |
|
||||||
|
| R3 | 清理退群事件、删除 report、清空执行/发送/Action 日志、清 cache/index、删规则 | 初始不开放;如以后开放,独立权限、预览计数、可恢复备份/本地确认,不接受批量 wildcard |
|
||||||
|
|
||||||
|
现有 Bearer Token 不足以支撑“查询、配置、发送、清理”都对一个不受信 Agent 开放。近期不必造完整账户系统,但应先修路由 method/body/validation,提供默认只读或 disabled 配置工作流;后续可加入多个 named token + scope(`read`, `configure`, `send`, `destructive`),R2 请求确认和 durable idempotency。风险分类也需承认本地 artifact write(如 `/report` 导出)不是配置本身,可先按 R1 local-write 处理。
|
||||||
|
|
||||||
|
## 9. Compatibility Plan
|
||||||
|
|
||||||
|
1. 不 rename/remove 任何现有 route。Reader Skill 依赖旧 contacts/chatlog/media 路径;新 structured query 已经是更合适的 Agent query,但两者并行。
|
||||||
|
2. 新 `/automations` 读写同一 `AutomationRuleStore`。旧 `/scheduled-reports*` 改为明确标注 Deprecated 的 compatibility adapter;维持现有 request/response shape 和 source_chat 子集,不维护第二个任务存储。响应可加 `Deprecation` header/文档说明,未定 sunset 前不返回 breaking error。
|
||||||
|
3. `/scheduled-reports` 的投影不能假装覆盖所有 scheduled automation。旧 list/get 只反映 source_chat;新 clients 必须迁到 `/automations?type=scheduled_report`。旧 `retry-send` 保留返回 501,文档明确废弃;不能伪造已发送成功。
|
||||||
|
4. `/agent/send` 继续表示现有 iLink/Agent Hub 测试发送。新 `/wechat/send` 必须先明确 transport/recipient schema,再通过能统一 personal+iLink 的受控 Action facade;如果不能保留旧发送语义,就将旧路径作为 adapter 而不是简单 alias。
|
||||||
|
5. `/wechat-personal/send-capability` 保持 personal-only 兼容 view;新全局 capability 返回 transport map。应用能力 `/capabilities` 和 Query Tool 的 `/query/capabilities` 各自有清晰不同的契约。
|
||||||
|
6. 同一 shared contract/catalog 应供 HTTP 验证、API Center、文档和 route contract tests 使用;把实际路由、文档和 API Center 三者 drift 变成测试失败,而不是发布后人工发现。
|
||||||
|
|
||||||
|
## 10. Proposed Phase Plan
|
||||||
|
|
||||||
|
### Phase A — HTTP Contract / Facade
|
||||||
|
|
||||||
|
给现有 routes 加明确 method guard、body size limit、严格 shared request schema、统一错误 envelope/request id;补 `AutomationRuleStore` 写盘成功/失败结果;建立稳定 conversation ID adapter 和 route contract tests。保留 raw Node HTTP,不需要为第一阶段换 web framework。
|
||||||
|
|
||||||
|
### Phase B — Read + Validation P0
|
||||||
|
|
||||||
|
增加应用 `/capabilities`、monitor state/events、automation rules/executions 读取、`/automations/validate`、group stats adapter。monitor `check` 因可能触发 notification 暂留 P1 或先加 side-effect confirmation。把新资源路径、schema、风险元数据接进 EndpointCatalog/生成文档。
|
||||||
|
|
||||||
|
### Phase C — Automation Configuration
|
||||||
|
|
||||||
|
开放 disabled create、PATCH、启停和 DELETE 防护;退群通知专用 singleton upsert 接入同一规则资源;scheduled report 使用真实完整 config;旧 scheduled API 只做 compatibility projection。先做 dry-run 再允许 enable。
|
||||||
|
|
||||||
|
### Phase D — Side Effects / Execution Read Model
|
||||||
|
|
||||||
|
扩展一层统一 `Action` facade 支持 iLink + personal transports,并有 per-purpose policy、recipient allowlist/validation、确认语义、强幂等、Action audit 到 Send Log correlation。再开放 send/check/run;按需增加 `/executions` read projection,不合并底层日志存储。
|
||||||
|
|
||||||
|
### Phase E — API Center
|
||||||
|
|
||||||
|
Overview、Query、Monitors、Automations、WeChat Actions、Reports、Developer 分区;按业务任务做 schema-aware 表单/效果预览,Raw Request Tester 留在 Developer。展示 Token scope/host 范围/transport capability,而不只是固定 URL 测试器。
|
||||||
|
|
||||||
|
## 11. Concrete Endpoint Proposal
|
||||||
|
|
||||||
|
下表是下一阶段建议契约,不表示当前已实现。新写 API 应统一错误:`{"error":{"code":"...","message":"...","details":{...}},"requestId":"..."}`。时间使用带 offset 的 ISO-8601;接口只接受 stable IDs。
|
||||||
|
|
||||||
|
| Method | Path | Request → Response | Risk | Underlying Service |
|
||||||
|
|---|---|---|---|---|
|
||||||
|
| GET | `/api/v1/capabilities` | 无 → app version/readiness + `query`,`groups.memberStats`,`groupExitMonitor`,`automations`、每种 `wechat.transport/content` 的 `supported/available/reason` | R0 | 新薄 facade 汇总 LocalQuery、GroupStats、Monitor、AutomationStore、personal capability、AgentHub status |
|
||||||
|
| GET | `/api/v1/monitors/group-exits` | 无 → `{enabled,running,monitoredConversationIds,lastCheckedAt,eventCount}` | R0 | `GroupExitMonitorService.getState` |
|
||||||
|
| PATCH | `/api/v1/monitors/group-exits` | `{enabled?,monitoredConversationIds?}` → 保存后的 state;监控 ID 必须 resolve 到现有群 | R1 | `setEnabled` / `setMonitoredRoomIds` |
|
||||||
|
| GET | `/api/v1/monitors/group-exits/events?conversationId=&since=&until=&limit=&cursor=` | ISO 时间和稳定群 ID → `{events,nextCursor}`,事件显式 `eventId`、group/member、counts、detectedAt | R0 | `GroupExitMonitorService.listEvents`;为无 cursor 的现有 list 加稳定分页 adapter |
|
||||||
|
| POST | `/api/v1/monitors/group-exits/check` | `{confirmSideEffects:true}` + `Idempotency-Key` → checkedAt、新事件数、notification execution refs | R2 | `checkNow`;因检查可发现事件并调用 leave-notification Automation,不应标成纯读 |
|
||||||
|
| GET | `/api/v1/automations?type=&enabled=` | 无 → typed rules page;包括 singleton leave rule | R0 | `AutomationRuleStore.listRules` |
|
||||||
|
| POST | `/api/v1/automations` | typed `AutomationRuleDraft`,create 默认 `enabled:false` → `{rule}` | R1 | `AutomationRuleStore.createRule`(需先强化 strict validation/persist result) |
|
||||||
|
| GET | `/api/v1/automations/{ruleId}` | 无 → `{rule}` | R0 | `AutomationRuleStore.getRule` |
|
||||||
|
| PATCH | `/api/v1/automations/{ruleId}` | typed partial config → `{rule}`;`ruleType` 不可变 | R1 | `AutomationRuleStore.updateRule` |
|
||||||
|
| DELETE | `/api/v1/automations/{ruleId}` | 无 → `{deletedId}`;默认拒绝 builtin/system singleton 删除 | R3 | `AutomationRuleStore.deleteRule` + protected-id policy |
|
||||||
|
| POST | `/api/v1/automations/validate` | typed draft → `{valid,normalizedDraft,issues,effects,resolvedTargets,nextRunAt,capabilities,validationId}`;不保存、不发送 | R0 | 新 validator adapter:contact resolve、template validator、capability services、schedule pure functions |
|
||||||
|
| POST | `/api/v1/automations/{ruleId}/enable` | `{validationId,confirmFutureEffects:true}` → `{rule}`;validation hash 必须匹配当前规则 | R1(武装未来 R2) | `AutomationRuleStore.setRuleEnabled` + validator |
|
||||||
|
| POST | `/api/v1/automations/{ruleId}/disable` | 无 → `{rule}` | R1 | `AutomationRuleStore.setRuleEnabled` |
|
||||||
|
| POST | `/api/v1/automations/{ruleId}/run` | `{confirmSideEffects:true}` + `Idempotency-Key` → `{execution}` | R2 | `AutomationService.executeScheduledRule`;只对具有 `run` 语义的 rule type 开放 |
|
||||||
|
| GET | `/api/v1/automations/executions?ruleId=&status=&trigger=&since=&until=&limit=&cursor=` | 无 → `{executions,nextCursor}` | R0 | `AutomationExecutionLogService.list`;需加 timestamp/filter/cursor adapter |
|
||||||
|
| GET | `/api/v1/groups/{conversationId}/member-stats?start=&end=` | ISO 时间窗口 → active/silent/counts/freshness/complete/limitations;未来要 former members 则先扩 shared result | R0 | `GroupStatsService.getMemberStats`;adapter 把 canonical roomId 转 md5 |
|
||||||
|
| GET | `/api/v1/wechat/capabilities` | 无 → personal/iLink 分 transport 状态与内容能力 | R0 | `PersonalWechatCapabilityService` + `WechatSendGateway.hasIlinkSender`/Agent Hub connector health |
|
||||||
|
| POST | `/api/v1/wechat/send` | `{recipient:{type,id},content:{type:"text",text},confirm:true}` + 必填 `Idempotency-Key` → `{actionId,status,transport,sendLogRef}` | R2 | 扩展后的 `WechatActionGateway`/统一 Action facade;不得裸调 `WechatSendGateway.send` |
|
||||||
|
| GET | `/api/v1/wechat/send-logs?status=&since=&limit=&cursor=` | 无 → 只读、脱敏 Send Log page | R0 | `WechatSendGateway.listSendLog` / `WechatSendLogService.list` |
|
||||||
|
| GET | `/api/v1/wechat/action-logs?executionId=&status=&since=&limit=&cursor=` | 无 → 业务 Action 审计 page;preview 默认截短/可省略 | R0 | `WechatActionLogService.list` / `WechatActionGateway.listAuditRecords` |
|
||||||
|
| GET | `/api/v1/executions?source=&status=&since=&until=&limit=&cursor=` | 无 → 统一只读 projection,每项保留 source/executionId/trigger/action/status/error/times/correlation IDs | R0 | 组合 `AutomationExecutionLogService`、Action audit、Send Log;不合并其存储 |
|
||||||
|
| GET | `/api/v1/reports/history?groupId=&since=&until=&limit=&cursor=` | 无 → 仅元数据分页,不带 `generatedImage`、本地绝对路径或完整 report snapshot | R0 | `listGeneratedReports` 经 summary adapter,最好先让 Service 支持 metadata-only |
|
||||||
|
| GET | `/api/v1/reports/history/{reportId}/image` | 无 → PNG binary | R0 | Report History 的 file resolver;仅按内部 report id 解析,不接收任意路径 |
|
||||||
|
| GET | `/api/v1/report-templates` | 无 → 已安装模板的 stable id/name/version/available 列表 | R0 | `reportTemplateService.list` |
|
||||||
|
| GET | `/api/v1/agent-hub/status` | 无 → hub/connector/dataApi/dbReady 的脱敏状态 | R0 | `AgentHubService.getStatus`;`/api/v1/agent/status` 保留 alias |
|
||||||
|
|
||||||
|
`POST /wechat/send` 建议先只开放 text + 明确目标;image path/url、voice 和 file 类型各自扩大本机文件/外传风险,需独立 validation/permission,不从现有任意 `msg` 输入自动继承。
|
||||||
|
|
||||||
|
## 12. Do Not Expose
|
||||||
|
|
||||||
|
- 任意数据库 key、图片 AES key、微信登录凭据、iLink `context_token`/bot token、inbound inbox raw items;这些是密钥或未处理消息,不是业务 API。
|
||||||
|
- 通用 `settings:set`、任意 `dbRoot`、数据库 disconnect/reopen、cache 全清、Knowledge/OCR 索引 clear/reset;配置或 destructive blast radius 远高于 Agent automation 管理需求。
|
||||||
|
- Agent Hub QR/login/verify-code/reconnect/disconnect/connector lifecycle。它会影响进程状态/账户登录,也会暴露登录材料。
|
||||||
|
- `WechatInboundInbox` pending/clear/complete/recordFailure 等队列控制。它是 at-least-once 消息交付内部机制,外部 ack 会破坏不丢消息语义。
|
||||||
|
- Agent Hub 完整对话正文默认不暴露。若明确产品需要,独立设计用户授权、最小时间窗口、分页、清理和脱敏;现有 Conversation Store 为本机完整收发留档。
|
||||||
|
- 任意本地 file path、path traversal 类导出/报告资产操作;不要把 IPC 的 file chooser、reveal、delete path 形状直接变 HTTP 参数。
|
||||||
|
- 单图 AI insight/任意 Vision analyze、批量 TTS synthesis、AI Provider 配置/测试和 app update download/install;它们具有费用、敏感图片/文本上传或应用安装影响。
|
||||||
|
- 清除退群、Automation、发送/Action、报告历史或批量发送接口作为 P0。清理类不是“管理配置”的必要前提,应使用 R3 独立权限及本地可恢复流程。
|
||||||
|
- 通用“任意 Automation DAG/任意脚本/任意 purpose”的创建。当前实现只有明确的三类规则和固定动作,不是 workflow engine;扩展功能应有显式 ruleType/schema,而不是暴露内存对象。
|
||||||
|
|
||||||
|
## 13. Open Questions
|
||||||
|
|
||||||
|
以下属于产品边界选择,无法只从代码决定:
|
||||||
|
|
||||||
|
1. 新 Agent API 是否允许同时操作个人微信和 Agent Hub/iLink,还是第一版限定一个 transport?现有 capability 与 send endpoint 分属两套连接状态。
|
||||||
|
2. Agent 是否默认只拿只读 scope;配置和 R2 send 是否要求独立 token/用户确认?当前只有单一 Bearer Token。
|
||||||
|
3. 多账号是否属于本阶段?当前 Query/GroupExit 绑定当前活动数据库账号,Agent Hub 有自己的 connector accountId;没有统一 account-scoped API model。
|
||||||
|
4. Agent Hub 完整对话是否要作为 API capability?它含完整消息正文,和从微信数据库按 query 搜历史是不同隐私边界。
|
||||||
|
|
||||||
|
真实微信 runtime 可用性、平台 hydration 和 transport 能力需在后续实现集成测试中验证;静态代码审计无法替代真实数据库/微信连接的运行时验证。
|
||||||
@@ -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 开发环境,在「设置 → 微信发送」中查看发送能力与授权状态。
|
||||||
|
|
||||||
|
**注意:** 发送能力组件不包含授权。开发环境仍需使用有效的设备授权才能绑定微信和发送消息。
|
||||||
+57
-1
@@ -13,6 +13,39 @@ TraceMemo 需要读取微信本地数据。macOS 会根据系统版本、微信
|
|||||||
|
|
||||||
不要直接复制网上针对其他微信版本的命令。系统授权失败时,记录 macOS 版本、微信版本和页面错误,再按[排障文档](../user-guide/troubleshooting.md#连接微信失败)处理。
|
不要直接复制网上针对其他微信版本的命令。系统授权失败时,记录 macOS 版本、微信版本和页面错误,再按[排障文档](../user-guide/troubleshooting.md#连接微信失败)处理。
|
||||||
|
|
||||||
|
## 提示「无法读取微信数据库」时
|
||||||
|
|
||||||
|
**这是故障恢复步骤,不是安装前置条件。** 能正常连接的用户不需要做任何权限设置。
|
||||||
|
|
||||||
|
如果你在连接页看到「最近验证结果:无法读取微信数据库」(错误码 `DATABASE_PERMISSION_DENIED`),并且已经确认微信数据目录**实际存在**(例如在终端里能列出 `db_storage/session/session.db`),那说明是 **TraceMemo 这个进程**读不到,而不是文件缺失。
|
||||||
|
|
||||||
|
微信数据放在另一个应用的沙盒容器里,macOS 会对这种跨应用访问单独做校验。先看「完全磁盘访问权限」里 TraceMemo 的状态,再按情况处理:
|
||||||
|
|
||||||
|
- **不在列表里,或开关是关的**:按下面的步骤授权。
|
||||||
|
- **开关已经是开的,但仍然读不到**:这不是「没授权」,而是旧授权记录对不上当前版本的应用,需要先清掉旧记录再重新授权。完整步骤见[macOS 更新后读不到微信数据:权限恢复](../user-guide/macos27-permission-recovery.md)。
|
||||||
|
|
||||||
|
首次授权的步骤:
|
||||||
|
|
||||||
|
1. 打开 **系统设置 → 隐私与安全性 → 完全磁盘访问权限**
|
||||||
|
2. 找到 **TraceMemo**,打开开关
|
||||||
|
3. **重新启动 TraceMemo**(该授权只在进程下次启动时生效)
|
||||||
|
4. 回到连接页重试
|
||||||
|
|
||||||
|
### 为什么终端能读、TraceMemo 读不了
|
||||||
|
|
||||||
|
macOS 的隐私权限按**应用进程的身份**判定,而不是按文件系统的用户身份。同一个用户在终端里能读到文件内容,不代表 TraceMemo 进程也有权限 —— 两者走的是不同的授权判定。所以「终端能读」不能用来排除权限问题。
|
||||||
|
|
||||||
|
### 不要做的事
|
||||||
|
|
||||||
|
上面这条路径**只涉及给 TraceMemo 授权**。以下做法都不需要,而且有风险:
|
||||||
|
|
||||||
|
- 关闭 SIP
|
||||||
|
- `chmod` / `chown` 整个微信目录
|
||||||
|
- 用 `sudo` 启动 TraceMemo
|
||||||
|
- 修改微信数据库文件权限
|
||||||
|
|
||||||
|
「无法读取微信数据库」与 SIP 不是同一个问题;改动微信数据目录的权限还可能影响微信自身的正常运行。
|
||||||
|
|
||||||
## SIP 风险
|
## SIP 风险
|
||||||
|
|
||||||
关闭 System Integrity Protection 会降低 macOS 对系统文件和进程的保护。它不是日常使用 TraceMemo 的功能开关,也不应长期保持关闭。只有在你理解风险、确认页面要求且完成必要操作时才处理;完成后按 Apple 官方方式重新启用。
|
关闭 System Integrity Protection 会降低 macOS 对系统文件和进程的保护。它不是日常使用 TraceMemo 的功能开关,也不应长期保持关闭。只有在你理解风险、确认页面要求且完成必要操作时才处理;完成后按 Apple 官方方式重新启用。
|
||||||
@@ -33,6 +66,29 @@ TraceMemo 同时支持两种 Mac 架构:
|
|||||||
- Apple Silicon:`tracememo-<版本号>-arm64.dmg`
|
- Apple Silicon:`tracememo-<版本号>-arm64.dmg`
|
||||||
- Intel:`tracememo-<版本号>-x64.dmg`
|
- Intel:`tracememo-<版本号>-x64.dmg`
|
||||||
|
|
||||||
两种架构都可以通过应用内的连接流程自动获取微信数据库密钥。首次连接时,TraceMemo 会根据当前机器架构进入对应的流程,按连接页面提示操作即可。
|
两种架构都可以通过应用内的连接流程自动获取微信数据库密钥。首次连接时,TraceMemo 会按**当前运行的这个版本**进入对应流程,按连接页面提示操作即可。
|
||||||
|
|
||||||
|
### 提示「Intel Mac 自动获取」,但电脑是 Apple 芯片
|
||||||
|
|
||||||
|
如果在 M 系列 Mac 上看到「Intel Mac 自动获取」,或页面要求准备 Intel 连接环境,多数是**正在运行 Intel(x64)版 TraceMemo**。macOS 允许 Intel 版应用在 Apple 芯片上通过 Rosetta 运行,应用本身不会报错,但会如实把自己识别成 Intel 版本,于是走了 Intel 的密钥获取方式。
|
||||||
|
|
||||||
|
判断当前跑的是哪个版本:
|
||||||
|
|
||||||
|
- 打开「活动监视器」,选中 TraceMemo,看「种类」一列 —— 显示「Apple」是 arm64 版,显示「Intel」是 x64 版;
|
||||||
|
- 或点连接页的「复制脱敏诊断摘要」,看「处理器架构」和「硬件架构」两行。
|
||||||
|
|
||||||
|
**启动方式不会改变架构。** Finder、Dock、桌面文件夹、`open` 命令打开的都是同一个 `.app`。但如果电脑上存在多个 TraceMemo 副本(例如「应用程序」里一个、下载文件夹里一个),不同入口可能打开不同副本,表现出来就像「有时是 Intel、有时不是」。列出所有副本及架构:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
mdfind "kMDItemCFBundleIdentifier == 'com.tracememo.app'" | while read -r p; do
|
||||||
|
[ -f "$p/Contents/MacOS/TraceMemo" ] && printf '%s -> ' "$p" && file -b "$p/Contents/MacOS/TraceMemo"
|
||||||
|
done
|
||||||
|
```
|
||||||
|
|
||||||
|
输出里带 `arm64` 的是 Apple 芯片版,带 `x86_64` 的是 Intel 版。
|
||||||
|
|
||||||
|
解决办法是从 [Releases](https://github.com/Wxw-Gu/TraceMemo/releases) 下载文件名带 `arm64` 的包,替换现有应用后重启。已保存的数据库密钥和连接配置不需要重新设置。
|
||||||
|
|
||||||
|
这与[提示「无法读取微信数据库」](#提示无法读取微信数据库时)不是同一个问题:那边是系统授权失效,这里是装错了版本。两种情况的处理方式不同,都不需要关闭 SIP。
|
||||||
|
|
||||||
Apple Silicon 和 Intel 已适配微信 macOS `4.1.13`。不同架构、微信版本和系统授权状态可能导致连接结果不同;文档不对所有组合做兼容性保证。
|
Apple Silicon 和 Intel 已适配微信 macOS `4.1.13`。不同架构、微信版本和系统授权状态可能导致连接结果不同;文档不对所有组合做兼容性保证。
|
||||||
@@ -1,6 +1,7 @@
|
|||||||
---
|
---
|
||||||
name: tracememo-reader
|
name: tracememo-reader
|
||||||
description: 通过 TraceMemo 本地 HTTP API 按需读取用户有权访问的微信聊天数据和图片媒体,并管理定时日报任务。当用户要求查看微信消息、查找联系人或群聊、总结聊天、查看或理解图片、生成群聊总结、查询或修改定时日报时使用。此 Skill 由本机 TraceMemo 提供数据,不是 MCP Server。
|
version: 1.4.0
|
||||||
|
description: 通过 TraceMemo 本地 HTTP API 按需读取用户有权访问的微信聊天数据和图片媒体、管理定时日报任务,并用用户本机登录的微信账号发送消息。当用户要求查看微信消息、查找联系人或群聊、总结聊天、查看或理解图片、生成群聊总结、查询或修改定时日报、给好友或群发送微信消息、代发消息、查看发送记录时使用。此 Skill 由本机 TraceMemo 提供数据,不是 MCP Server。
|
||||||
---
|
---
|
||||||
|
|
||||||
# TraceMemo Reader
|
# TraceMemo Reader
|
||||||
@@ -17,6 +18,35 @@ description: 通过 TraceMemo 本地 HTTP API 按需读取用户有权访问的
|
|||||||
- 不要把 Token 放到 URL、回答、日志、Skill 文件或仓库。
|
- 不要把 Token 放到 URL、回答、日志、Skill 文件或仓库。
|
||||||
- 6131 是普通 Local HTTP API,不是 MCP Server;不要生成 `mcpServers` 配置。
|
- 6131 是普通 Local HTTP API,不是 MCP Server;不要生成 `mcpServers` 配置。
|
||||||
|
|
||||||
|
## 版本自检(每次会话开始时执行一次)
|
||||||
|
|
||||||
|
这份 Skill 随 TraceMemo 一起更新,接口会随版本变化。本文件 frontmatter 里的 `version` 是它的唯一版本标识,服务端在 `/health` 回报当前版本。
|
||||||
|
|
||||||
|
1. 读取本文件 frontmatter 的 `version`。
|
||||||
|
2. 调用 `GET /health`,取返回的 `skill.version`。
|
||||||
|
3. 两者一致 → 正常继续。
|
||||||
|
4. 两者不一致(本文件更旧)→ **先停止,不要继续读取数据**,并原样告知用户:
|
||||||
|
|
||||||
|
> 本机 TraceMemo Reader Skill 是 {本地版本},而 TraceMemo 当前是 {服务端版本},接口契约可能已经过期。
|
||||||
|
> 请打开 TraceMemo → API Center → 快速接入 → 选择目标 Agent → 复制安装指令,把新指令发给我重新安装。
|
||||||
|
|
||||||
|
5. `/health` 没有返回 `skill.version`(说明 TraceMemo 版本较旧)→ 无法比对,正常继续,但要在回答中提醒用户升级 TraceMemo。
|
||||||
|
|
||||||
|
自检只做一次,不要每个任务都执行。**不要**因为版本不一致就自行猜测新接口的用法。
|
||||||
|
|
||||||
|
### 自助更新
|
||||||
|
|
||||||
|
用户同意更新时,不必让他手动复制安装指令,Agent 可以自己完成:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
curl -H "Authorization: Bearer $TRACEMEMO_API_TOKEN" \
|
||||||
|
"http://127.0.0.1:6131/api/v1/skill/tracememo-reader"
|
||||||
|
```
|
||||||
|
|
||||||
|
响应的 `markdown` 就是最新 SKILL.md 全文,`version` 是它的版本,`contentHash` 可用于核对写入结果。先取得用户同意,再用它覆盖本机这份 SKILL.md(连同 frontmatter 一起写),然后重新读取本文件,并告知用户已更新到哪个版本。
|
||||||
|
|
||||||
|
覆盖前先确认目标文件路径并留一份备份;**不要**改动本目录里的其他文件,也不要把 `markdown` 内容写进回答或日志。
|
||||||
|
|
||||||
## 每次任务前
|
## 每次任务前
|
||||||
|
|
||||||
1. 调用 `/health`,确认服务和数据库状态。
|
1. 调用 `/health`,确认服务和数据库状态。
|
||||||
@@ -29,7 +59,8 @@ description: 通过 TraceMemo 本地 HTTP API 按需读取用户有权访问的
|
|||||||
|
|
||||||
| 方法 | 路径 | 用途 |
|
| 方法 | 路径 | 用途 |
|
||||||
| ------ | ------------------------------------------------------- | ------------------------------------------------- |
|
| ------ | ------------------------------------------------------- | ------------------------------------------------- |
|
||||||
| GET | `/health` | 健康和数据库状态 |
|
| GET | `/health` | 健康和数据库状态 + 当前 Skill 版本 |
|
||||||
|
| GET | `/skill/tracememo-reader` | 当前 SKILL.md 全文与版本号(自助更新用) |
|
||||||
| GET | `/current_time` | 本机时间与时区 |
|
| GET | `/current_time` | 本机时间与时区 |
|
||||||
| GET | `/contact` | 联系人/群聊列表;可传 `filter`、`type` |
|
| GET | `/contact` | 联系人/群聊列表;可传 `filter`、`type` |
|
||||||
| GET | `/chatroom` | 群聊列表;可传 `keyword` |
|
| GET | `/chatroom` | 群聊列表;可传 `keyword` |
|
||||||
@@ -42,8 +73,10 @@ description: 通过 TraceMemo 本地 HTTP API 按需读取用户有权访问的
|
|||||||
| POST | `/query/search` | 受限语义关键词检索(依赖本地索引,见 freshness) |
|
| POST | `/query/search` | 受限语义关键词检索(依赖本地索引,见 freshness) |
|
||||||
| POST | `/query/message-context` | 用 `messageRef` 取某条消息的前后文 |
|
| POST | `/query/message-context` | 用 `messageRef` 取某条消息的前后文 |
|
||||||
| POST | `/query/conversation-overview` | 按会话与时间范围提取可总结的证据 |
|
| POST | `/query/conversation-overview` | 按会话与时间范围提取可总结的证据 |
|
||||||
|
| POST | `/query/voice-transcribe` | 把指定语音消息转成文字(本机离线识别) |
|
||||||
| GET | `/query/capabilities` | Query 端点能力目录 |
|
| GET | `/query/capabilities` | Query 端点能力目录 |
|
||||||
| GET | `/wechat-personal/send-capability` | 个人微信发送能力状态(文字 / 图片 / 语音) |
|
| GET | `/wechat-personal/send-capability` | 个人微信发送能力状态(文字 / 图片 / 语音) |
|
||||||
|
| POST | `/wechat/send` | 用本机微信账号发消息给他人(文字/图片/语音) |
|
||||||
| GET | `/scheduled-reports` | 查询全部定时日报任务 |
|
| GET | `/scheduled-reports` | 查询全部定时日报任务 |
|
||||||
| GET | `/scheduled-reports/:id` | 查询单个定时日报任务 |
|
| GET | `/scheduled-reports/:id` | 查询单个定时日报任务 |
|
||||||
| POST | `/scheduled-reports` | 创建定时日报任务 |
|
| POST | `/scheduled-reports` | 创建定时日报任务 |
|
||||||
@@ -59,7 +92,68 @@ description: 通过 TraceMemo 本地 HTTP API 按需读取用户有权访问的
|
|||||||
| POST | `/agent/group-report` | 按群和 `today`/`yesterday`/`7days` 生成总结图片 |
|
| POST | `/agent/group-report` | 按群和 `today`/`yesterday`/`7days` 生成总结图片 |
|
||||||
| POST | `/agent/send` | 已连接机器人发送测试(文字或本地图片) |
|
| POST | `/agent/send` | 已连接机器人发送测试(文字或本地图片) |
|
||||||
|
|
||||||
这个 API **不只是只读的**:`/report` 会渲染并写文件,`/agent/send` 会真的发出微信消息,`/scheduled-reports*` 会创建、修改、删除或立刻执行定时任务。这些调用都要先确认用户意图;`DELETE` 与 `/agent/send` 尤其需要用户明确确认。
|
这个 API **不只是只读的**:`/report` 会渲染并写文件,`/wechat/send` 会以用户本人的微信账号把消息真的发给别人,`/agent/send` 会通过机器人发出消息,`/scheduled-reports*` 会创建、修改、删除或立刻执行定时任务。这些调用都要先确认用户意图;`DELETE`、`/wechat/send` 与 `/agent/send` 尤其需要用户明确确认。
|
||||||
|
|
||||||
|
## 发送微信消息
|
||||||
|
|
||||||
|
两个发送端点的**身份和通道完全不同**,不要混用:
|
||||||
|
|
||||||
|
| | `/wechat/send` | `/agent/send` |
|
||||||
|
| -------- | ------------------------------ | -------------------------------- |
|
||||||
|
| 发送身份 | 用户本机正在登录的微信账号 | 已扫码接入的 TraceMemo 机器人 |
|
||||||
|
| 收件人 | 好友 / 群 / 文件传输助手 | 一般是自己,用于测试连接器连通性 |
|
||||||
|
| 前置条件 | 本机微信已启动,发送能力 ready | Agent Hub 连接器 online |
|
||||||
|
|
||||||
|
用户说“发消息给某人 / 某个群 / 文件传输助手”时,**只能用 `/wechat/send`**。`/agent/send` 不是用来通知别人的。
|
||||||
|
|
||||||
|
### 调用前必须做
|
||||||
|
|
||||||
|
1. 调用 `GET /wechat-personal/send-capability`,只有 `capability.ready === true` 且 `capability.capabilities[type] === true` 才继续。否则停下来说明需要先在 TraceMemo「设置 → 发送能力」里完成绑定,**不要**直接调用再解释失败。
|
||||||
|
2. 通过 `/resolve` 把用户说的昵称换成 wxid;`to` 只接受 wxid、`xxx@chatroom` 群 id,或 `filehelper`。**不要猜 wxid,也不要把昵称直接写进 `to`。**
|
||||||
|
3. 把「发给谁 + 发什么」复述给用户并得到确认后再发。这是不可撤回的外部操作。
|
||||||
|
|
||||||
|
### 请求
|
||||||
|
|
||||||
|
```json
|
||||||
|
{ "to": "wxid_xxx", "type": "text", "text": "消息内容", "idempotencyKey": "可选" }
|
||||||
|
```
|
||||||
|
|
||||||
|
| 字段 | 必填 | 说明 |
|
||||||
|
| ---------------- | ------------------ | ------------------------------------------------------------------- |
|
||||||
|
| `to` | 是 | wxid / `xxx@chatroom` / `filehelper`;以 `@chatroom` 结尾自动判为群 |
|
||||||
|
| `type` | 否 | `text`(默认)/ `image` / `voice` |
|
||||||
|
| `text` | `type=text` 时必填 | **最多 2000 字符**,超限返回 `400`,不会自动截断 |
|
||||||
|
| `filePath` | `type=image/voice` | 本机**绝对路径**且文件必须存在;**不接受 URL** |
|
||||||
|
| `idempotencyKey` | 否 | 重试时原样带回,避免超时重发产生重复消息 |
|
||||||
|
|
||||||
|
几个必须遵守的限制:
|
||||||
|
|
||||||
|
- **超过 2000 字符不要硬发**。先告诉用户内容过长,征得同意后再拆成多条依次发送;不要静默截断。
|
||||||
|
- **媒体只收本地文件**。用户给的是聊天里的图片时,先用 `/chatlog` 拿到 `media.url` 下载成临时文件,再把该路径传给 `filePath`;网络图片同样需要先落盘。不要试图传 URL。
|
||||||
|
- **本端点没有节流**。automation 的 3 秒间隔对它不生效,连续调用就会连续投递。单个任务里连续发送超过 3 条前,先和用户确认节奏。
|
||||||
|
|
||||||
|
### 结果
|
||||||
|
|
||||||
|
成功返回 `success: true`、`status: "sent"`、`actionId`。失败时读 `errorCode`:
|
||||||
|
|
||||||
|
- `400 INVALID_REQUEST` / `INVALID_RECIPIENT`:字段不合法,按 `error` 里的说明修正;
|
||||||
|
- `403 POLICY_BLOCKED`:被发送策略拒绝,如实告知用户;
|
||||||
|
- `502 SEND_FAILED`:已进入投递但微信侧失败,不要说成“已发送”;
|
||||||
|
- `503 SEND_CAPABILITY_UNAVAILABLE` / `SEND_NOT_READY`:能力未就绪,引导用户去绑定;
|
||||||
|
- `503 UNSUPPORTED_PLATFORM`:当前系统不支持。
|
||||||
|
|
||||||
|
只有 `status === "sent"` 才能告诉用户发送成功。不要凭 `actionId` 或 HTTP 200 之外的任何信息推断结果。
|
||||||
|
|
||||||
|
### 发送成功后不要用 `/chatlog` 自证
|
||||||
|
|
||||||
|
`status: "sent"` 只表示消息已经交给微信完成投递,**不代表它会出现在本地聊天数据库里**。TraceMemo 读的是微信本地库,自己发出的消息可能延迟落库,也可能根本不写入。
|
||||||
|
|
||||||
|
因此:
|
||||||
|
|
||||||
|
- **不要**用 `/chatlog` 查自己刚发出的那条消息来确认发送成功。查不到是正常现象,不等于发送失败。
|
||||||
|
- **不要**因为本地库没有这条消息就重发 —— 那会产生真实的重复消息。
|
||||||
|
- 需要人工确认时,请用户用**手机微信**或**另一个微信号**查看该会话;这是唯一可靠的确认方式。
|
||||||
|
- Send Log 与 `actions/wechat-actions.json` 记录的是 TraceMemo 自己的发送动作与结果,能证明“调用过并成功投递”,**不能**证明对方收到或本地库已落库。不要把它们混为一谈。
|
||||||
|
|
||||||
## 定时日报管理
|
## 定时日报管理
|
||||||
|
|
||||||
@@ -118,6 +212,7 @@ description: 通过 TraceMemo 本地 HTTP API 按需读取用户有权访问的
|
|||||||
- `query/search`:受限语义关键词检索,依赖本地索引;
|
- `query/search`:受限语义关键词检索,依赖本地索引;
|
||||||
- `query/message-context`:用返回的 `messageRef` 取前后文;
|
- `query/message-context`:用返回的 `messageRef` 取前后文;
|
||||||
- `query/conversation-overview`:按会话与时间范围提取可总结的证据。
|
- `query/conversation-overview`:按会话与时间范围提取可总结的证据。
|
||||||
|
- `query/voice-transcribe`:把指定语音消息的 `messageRef` 转成文字。
|
||||||
|
|
||||||
两个要点:
|
两个要点:
|
||||||
|
|
||||||
@@ -147,6 +242,18 @@ description: 通过 TraceMemo 本地 HTTP API 按需读取用户有权访问的
|
|||||||
|
|
||||||
不要只根据 `[图片]` 猜测内容,不要把一次 OCR 当作完整图片理解,也不要直接读取任意本地图片路径。
|
不要只根据 `[图片]` 猜测内容,不要把一次 OCR 当作完整图片理解,也不要直接读取任意本地图片路径。
|
||||||
|
|
||||||
|
### 语音消息
|
||||||
|
|
||||||
|
语音消息的正文固定是 `[语音消息]`,转写结果在 `voiceTranscript`,状态在 `voiceTranscriptState`(`/chatlog` 与 `query/*` 都会返回)。
|
||||||
|
|
||||||
|
1. `transcribed`:直接使用 `voiceTranscript`。
|
||||||
|
2. `pending`:还没转写,**不能**说成“语音里没内容”。回答需要它时,把这些语音的 `messageRef` 批量(每次最多 20 条)交给 `POST /query/voice-transcribe`。
|
||||||
|
3. 返回 `pending`(`still_processing`)时,稍后用同样的 `messageRefs` 再调用一次;不要换参数反复重试。
|
||||||
|
4. 返回 `failed` 时按 `hint` 处理;`previously_failed` 只有用户明确要求才传 `force: true` 重试。
|
||||||
|
5. `503 voice_model_not_ready`:告诉用户先在 TraceMemo 设置中下载语音识别模型,在此之前不要重试。
|
||||||
|
6. `429 busy`:等待 `retryAfterSeconds` 后再调用。
|
||||||
|
7. 只转写回答问题所需的语音,不要一次把整个会话的语音都提交。
|
||||||
|
|
||||||
## 隐私和安全
|
## 隐私和安全
|
||||||
|
|
||||||
只读取用户请求所需的会话和时间范围。不要把完整聊天数据库、密钥或 Token 暴露给用户。Reader API 本身不自动把聊天转发到外部服务器,但当前 Agent 可能会把工具结果交给其配置的模型;如有疑问,提醒用户检查 Agent 的数据策略。
|
只读取用户请求所需的会话和时间范围。不要把完整聊天数据库、密钥或 Token 暴露给用户。Reader API 本身不自动把聊天转发到外部服务器,但当前 Agent 可能会把工具结果交给其配置的模型;如有疑问,提醒用户检查 Agent 的数据策略。
|
||||||
@@ -154,8 +261,8 @@ description: 通过 TraceMemo 本地 HTTP API 按需读取用户有权访问的
|
|||||||
## 常见错误
|
## 常见错误
|
||||||
|
|
||||||
- `401`:Token 缺失、错误或被轮换;请用户回 API Center 复制最新 Token。
|
- `401`:Token 缺失、错误或被轮换;请用户回 API Center 复制最新 Token。
|
||||||
- `403`:浏览器 Origin 不在 loopback 允许列表;CLI/Agent 通常不带 Origin。
|
- `403`:浏览器 Origin 不在 loopback 允许列表;CLI/Agent 通常不带 Origin。注意 `/wechat/send` 的 `403 POLICY_BLOCKED` 是被发送策略拒绝,含义不同。
|
||||||
- `404`:会话查询失败时先用 `/resolve` 确认会话标识;媒体请求表示标识未登记、已过期、有歧义,或图片文件不存在(`NOT_FOUND`)。先重新读取 `/chatlog` 并使用新的 `media.url`;若仍失败,再检查本地图片文件是否存在。
|
- `404`:会话查询失败时先用 `/resolve` 确认会话标识;媒体请求表示标识未登记、已过期、有歧义,或图片文件不存在(`NOT_FOUND`)。先重新读取 `/chatlog` 并使用新的 `media.url`;若仍失败,再检查本地图片文件是否存在。
|
||||||
- `422`:媒体标识格式错误,或消息不是可读取的图片(`NOT_IMAGE`)。
|
- `422`:媒体标识格式错误,或消息不是可读取的图片(`NOT_IMAGE`)。
|
||||||
- `503`:用户还没有完成数据库连接或对应服务未就绪。
|
- `503`:用户还没有完成数据库连接或对应服务未就绪。发送端点返回 `503` 时先查 `/wechat-personal/send-capability`,不要反复重试。
|
||||||
- 空结果:缩小/扩大时间范围,确认账号和会话,再检查媒体或语音是否可读。
|
- 空结果:缩小/扩大时间范围,确认账号和会话,再检查媒体或语音是否可读。
|
||||||
@@ -24,6 +24,12 @@ ZIP 是 HTML 资源包的压缩选项,不是第五种内容格式。
|
|||||||
5. 设置文件名并开始导出。
|
5. 设置文件名并开始导出。
|
||||||
6. 在导出任务中心查看读取、解析、媒体处理、转写、写入和压缩进度;完成后打开文件位置。
|
6. 在导出任务中心查看读取、解析、媒体处理、转写、写入和压缩进度;完成后打开文件位置。
|
||||||
|
|
||||||
|
## 导出设置会被记住
|
||||||
|
|
||||||
|
TraceMemo 会记住上一次使用的导出设置,下次打开导出页面时自动恢复,减少重复选择。包括格式、时间范围、消息类型、名称显示方式、媒体选项(原图/缩略图、头像)、语音转写、缺失资源处理、ZIP、文件名和输出目录。
|
||||||
|
|
||||||
|
这些偏好保存在本机,不会随账号同步到其他设备。
|
||||||
|
|
||||||
## 多会话和增量导出
|
## 多会话和增量导出
|
||||||
|
|
||||||
HTML 支持把最多五个会话合并到一个档案中;选择多个会话后,其他格式会不可用。再次使用相同名称导出 HTML 时,可以把新消息增量合并到已有档案;这不会删除之前已导出的消息。
|
HTML 支持把最多五个会话合并到一个档案中;选择多个会话后,其他格式会不可用。再次使用相同名称导出 HTML 时,可以把新消息增量合并到已有档案;这不会删除之前已导出的消息。
|
||||||
|
|||||||
@@ -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 节即可,通常不需要重装、不需要重新取密钥。
|
||||||
|
- 彻底解决需要发布端改用稳定的开发者签名并完成公证,这属于打包流程的改动,不在用户侧。
|
||||||
|
|
||||||
|
正常使用、没有出现问题的用户,不需要提前做任何权限设置。授权不是安装前置条件。
|
||||||
@@ -25,13 +25,25 @@
|
|||||||
1. 数据目录是否指向当前登录账号,而不是旧备份或迁移前目录;
|
1. 数据目录是否指向当前登录账号,而不是旧备份或迁移前目录;
|
||||||
2. 微信版本是否属于当前代码面向的 4.x 数据结构;
|
2. 微信版本是否属于当前代码面向的 4.x 数据结构;
|
||||||
3. 微信是否处于页面要求的登录/退出状态;
|
3. 微信是否处于页面要求的登录/退出状态;
|
||||||
4. macOS 是否完成页面要求的授权;
|
4. macOS 是否完成页面要求的授权;如果是升级 macOS 或更新 TraceMemo 之后才失败的,按[权限恢复文档](./macos27-permission-recovery.md)处理,只打开开关通常不够;
|
||||||
5. 连接页面的诊断项是否明确指出密钥、账号或数据库问题;
|
5. 连接页面的诊断项是否明确指出密钥、账号或数据库问题;
|
||||||
6. macOS 上 Apple Silicon 与 Intel 使用不同的连接流程,按连接页面提示操作;两者都可以自动获取数据库密钥。
|
6. macOS 上 Apple Silicon 与 Intel 使用不同的连接流程,按连接页面提示操作;两者都可以自动获取数据库密钥。
|
||||||
|
7. 页面显示「Intel Mac 自动获取」但电脑是 Apple 芯片时,多半是装了 Intel 版,见[架构不匹配说明](../platform/macos.md#提示intel-mac-自动获取但电脑是-apple-芯片)。
|
||||||
|
|
||||||
重新输入密钥或断开连接不会删除微信原始数据库。macOS 的 SIP 和授权说明见[平台说明](../platform/macos.md)。
|
重新输入密钥或断开连接不会删除微信原始数据库。macOS 的 SIP 和授权说明见[平台说明](../platform/macos.md)。
|
||||||
|
|
||||||
仍然失败时,记录 **macOS 版本、CPU 架构(Apple Silicon / Intel)、微信版本、TraceMemo 版本和页面错误提示**后 扫码 README 文档二维码进群提交消息, 或者提交 Issue。
|
### 提示「无法读取微信数据库」但文件确实存在
|
||||||
|
|
||||||
|
这是**权限问题,不是文件缺失** —— 如果你在终端里能列出 `db_storage/session/session.db`,说明数据目录是完整的,只是 TraceMemo 这个进程读不到。
|
||||||
|
|
||||||
|
注意:**终端能读到文件不代表 TraceMemo 有权限** —— macOS 的隐私权限按应用进程的身份判定,两者走的是不同的授权。
|
||||||
|
|
||||||
|
按出现时机分两种情况:
|
||||||
|
|
||||||
|
- **首次连接就没成功**:给 TraceMemo 授予「完全磁盘访问权限」即可,步骤见 [macOS 数据访问与系统权限 → 提示「无法读取微信数据库」时](../platform/macos.md#提示无法读取微信数据库时)。
|
||||||
|
- **之前能用,升级 macOS 或更新 TraceMemo 之后才失败**:多数是旧授权记录对不上新版本的应用,只打开开关不够,需要先清掉旧记录再重新授权。完整步骤见[macOS 更新后读不到微信数据:权限恢复](./macos27-permission-recovery.md)。
|
||||||
|
|
||||||
|
仍然失败时,记录 **macOS 版本、CPU 架构(Apple Silicon / Intel)、微信版本、TraceMemo 版本和页面错误提示** 后,扫码 README 文档二维码进群反馈,或提交 Issue。连接页的「复制脱敏诊断摘要」可以直接提供这些环境信息。
|
||||||
|
|
||||||
## 连接成功但没有联系人或消息
|
## 连接成功但没有联系人或消息
|
||||||
|
|
||||||
@@ -92,3 +104,15 @@ Agent Hub 和外部 Agent 是两条路径。机器人异常时依次确认:
|
|||||||
5. 需要总结或自然语言理解时,AI Provider 是否可用。
|
5. 需要总结或自然语言理解时,AI Provider 是否可用。
|
||||||
|
|
||||||
当前机器人不支持群发、定时任务或与文字同等的图片、语音、文件和视频理解。详细边界见[Agent Hub](../agent/agent-hub.md)。
|
当前机器人不支持群发、定时任务或与文字同等的图片、语音、文件和视频理解。详细边界见[Agent Hub](../agent/agent-hub.md)。
|
||||||
|
|
||||||
|
## 点击关闭后应用没有退出
|
||||||
|
|
||||||
|
「关闭窗口时」可能被配置为**最小化到托盘** —— 窗口隐藏,应用仍在后台运行。
|
||||||
|
|
||||||
|
到「设置 → 外观与行为 → 关闭窗口时」可以改成:
|
||||||
|
|
||||||
|
- **每次询问**:每次关闭都弹窗确认;
|
||||||
|
- **最小化到托盘**:窗口隐藏,应用继续在后台运行;
|
||||||
|
- **退出应用**:直接结束 TraceMemo 进程。
|
||||||
|
|
||||||
|
选择「每次询问」时,在关闭弹窗里勾选「记住我的选择,下次不再询问」会自动切换到这里对应的项。
|
||||||
@@ -6,6 +6,10 @@ extraResources:
|
|||||||
to: resources
|
to: resources
|
||||||
filter:
|
filter:
|
||||||
- '**/*'
|
- '**/*'
|
||||||
|
- from: resources/wcdb/macos/arm64
|
||||||
|
to: resources/wcdb/macos/arm64
|
||||||
|
filter:
|
||||||
|
- 'tm-wcdb-config-helper'
|
||||||
- from: docs/skill/tracememo-reader
|
- from: docs/skill/tracememo-reader
|
||||||
to: skill/tracememo-reader
|
to: skill/tracememo-reader
|
||||||
filter:
|
filter:
|
||||||
|
|||||||
@@ -38,6 +38,12 @@ extraResources:
|
|||||||
- key/win32/x64/**
|
- key/win32/x64/**
|
||||||
- runtime/win32/**
|
- runtime/win32/**
|
||||||
- wcdb/win32/x64/**
|
- wcdb/win32/x64/**
|
||||||
|
- '!wcdb/**/tm-wcdb-config-helper*'
|
||||||
|
# 默认不打包helper
|
||||||
|
# - from: resources/wcdb/win32/x64
|
||||||
|
# to: resources/wcdb/win32/x64
|
||||||
|
# filter:
|
||||||
|
# - 'tm-wcdb-config-helper.exe'
|
||||||
- from: docs/skill/tracememo-reader
|
- from: docs/skill/tracememo-reader
|
||||||
to: skill/tracememo-reader
|
to: skill/tracememo-reader
|
||||||
filter:
|
filter:
|
||||||
|
|||||||
@@ -35,6 +35,7 @@ extraResources:
|
|||||||
filter:
|
filter:
|
||||||
- '**/*'
|
- '**/*'
|
||||||
- '!runtime/darwin-arm64/**'
|
- '!runtime/darwin-arm64/**'
|
||||||
|
- '!wcdb/**/tm-wcdb-config-helper*'
|
||||||
- from: docs/skill/tracememo-reader
|
- from: docs/skill/tracememo-reader
|
||||||
to: skill/tracememo-reader
|
to: skill/tracememo-reader
|
||||||
filter:
|
filter:
|
||||||
|
|||||||
@@ -2,9 +2,12 @@ import { resolve } from 'path'
|
|||||||
import { defineConfig } from 'electron-vite'
|
import { defineConfig } from 'electron-vite'
|
||||||
import react from '@vitejs/plugin-react'
|
import react from '@vitejs/plugin-react'
|
||||||
|
|
||||||
|
const editionOutDir = process.env.TRACEMEMO_EDITION_OUT_DIR
|
||||||
|
|
||||||
export default defineConfig({
|
export default defineConfig({
|
||||||
main: {
|
main: {
|
||||||
build: {
|
build: {
|
||||||
|
...(editionOutDir ? { outDir: editionOutDir } : {}),
|
||||||
rollupOptions: {
|
rollupOptions: {
|
||||||
input: {
|
input: {
|
||||||
index: resolve('src/main/index.ts'),
|
index: resolve('src/main/index.ts'),
|
||||||
@@ -20,8 +23,9 @@ export default defineConfig({
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
preload: {},
|
preload: editionOutDir ? { build: { outDir: editionOutDir } } : {},
|
||||||
renderer: {
|
renderer: {
|
||||||
|
...(editionOutDir ? { build: { outDir: editionOutDir } } : {}),
|
||||||
resolve: {
|
resolve: {
|
||||||
alias: {
|
alias: {
|
||||||
'@renderer': resolve('src/renderer/src')
|
'@renderer': resolve('src/renderer/src')
|
||||||
|
|||||||
+6
-3
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "tracememo",
|
"name": "tracememo",
|
||||||
"version": "2.5.0",
|
"version": "2.6.0",
|
||||||
"packageManager": "pnpm@7.33.7",
|
"packageManager": "pnpm@7.33.7",
|
||||||
"description": "TraceMemo(迹忆)是一款本地优先、可追溯的 AI 微信知识与分析工作台。 原名 WechatExplorer,支持聊天记录搜索、知识库、微信群聊总结和 Agent 助手。",
|
"description": "TraceMemo(迹忆)是一款本地优先、可追溯的 AI 微信知识与分析工作台。 原名 WechatExplorer,支持聊天记录搜索、知识库、微信群聊总结和 Agent 助手。",
|
||||||
"keywords": [
|
"keywords": [
|
||||||
@@ -33,6 +33,7 @@
|
|||||||
"typecheck": "npm run typecheck:node && npm run typecheck:web && npm run typecheck:test",
|
"typecheck": "npm run typecheck:node && npm run typecheck:web && npm run typecheck:test",
|
||||||
"typecheck:test": "node scripts/typecheck-tests.cjs",
|
"typecheck:test": "node scripts/typecheck-tests.cjs",
|
||||||
"test:skill-install": "node scripts/test-skill-install-instruction.cjs",
|
"test:skill-install": "node scripts/test-skill-install-instruction.cjs",
|
||||||
|
"check:skill-version": "node scripts/check-skill-version-drift.cjs",
|
||||||
"cp:env": "node scripts/ensure-env.cjs",
|
"cp:env": "node scripts/ensure-env.cjs",
|
||||||
"prepare:env": "node scripts/ensure-env.cjs",
|
"prepare:env": "node scripts/ensure-env.cjs",
|
||||||
"prepare:ffmpeg:win": "node scripts/prepare-electron-runtime.cjs --platform win32 --arch x64",
|
"prepare:ffmpeg:win": "node scripts/prepare-electron-runtime.cjs --platform win32 --arch x64",
|
||||||
@@ -62,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: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": "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: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",
|
"build:mac:x64": "npm run typecheck && npm run prepare:ffmpeg:mac:x64 && electron-vite build && electron-builder --config electron-builder.yml --mac --x64",
|
||||||
"release": "npm run release:mac && npm run release:win",
|
"release": "npm run release:mac && npm run release:win",
|
||||||
"release:mac": "npm run typecheck && electron-vite build && npm run release:mac:arm64 && npm run release:mac:x64",
|
"release:mac": "npm run typecheck && electron-vite build && npm run release:mac:arm64 && npm run release:mac:x64",
|
||||||
"release:mac:arm64": "npm run prepare:ffmpeg:mac:arm64 && electron-builder --config electron-builder.yml --mac --arm64 --publish always",
|
"release:mac:arm64": "npm run prepare:ffmpeg:mac:arm64 && electron-builder --config electron-builder.yml --mac --arm64 --publish always --config.directories.output=dist/release/mac-arm64",
|
||||||
"release:mac:x64": "npm run prepare:ffmpeg:mac:x64 && electron-builder --config electron-builder.yml --mac --x64 --publish always",
|
"release:mac:x64": "npm run prepare:ffmpeg:mac:x64 && electron-builder --config electron-builder.yml --mac --x64 --publish always --config.directories.output=dist/release/mac-x64",
|
||||||
"release:win": "npm run typecheck && npm run prepare:win-runtime && electron-vite build && electron-builder --config electron-builder.win.yml --win --x64 --publish always",
|
"release:win": "npm run typecheck && npm run prepare:win-runtime && electron-vite build && electron-builder --config electron-builder.win.yml --win --x64 --publish always",
|
||||||
"release:beta": "cross-env EP_PRE_RELEASE=true npm run release",
|
"release:beta": "cross-env EP_PRE_RELEASE=true npm run release",
|
||||||
"release:stable": "npm run release",
|
"release:stable": "npm run release",
|
||||||
|
|||||||
Binary file not shown.
|
Before Width: | Height: | Size: 156 KiB After Width: | Height: | Size: 153 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 417 B |
@@ -0,0 +1,13 @@
|
|||||||
|
<svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 18 18">
|
||||||
|
<rect
|
||||||
|
x="1.5"
|
||||||
|
y="1.5"
|
||||||
|
width="15"
|
||||||
|
height="15"
|
||||||
|
rx="3.5"
|
||||||
|
fill="none"
|
||||||
|
stroke="#000"
|
||||||
|
stroke-width="1.75"
|
||||||
|
/>
|
||||||
|
<circle cx="9" cy="9" r="2.3" fill="#000" />
|
||||||
|
</svg>
|
||||||
|
After Width: | Height: | Size: 277 B |
Binary file not shown.
|
After Width: | Height: | Size: 702 B |
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
+293
-8
@@ -1,5 +1,6 @@
|
|||||||
/* eslint-disable @typescript-eslint/no-require-imports, @typescript-eslint/explicit-function-return-type */
|
/* eslint-disable @typescript-eslint/no-require-imports, @typescript-eslint/explicit-function-return-type */
|
||||||
const { chmodSync, existsSync, readdirSync, rmSync } = require('node:fs')
|
const { chmodSync, existsSync, readFileSync, readdirSync, rmSync } = require('node:fs')
|
||||||
|
const { createHash } = require('node:crypto')
|
||||||
const { execFileSync } = require('node:child_process')
|
const { execFileSync } = require('node:child_process')
|
||||||
const path = require('node:path')
|
const path = require('node:path')
|
||||||
const asar = require('@electron/asar')
|
const asar = require('@electron/asar')
|
||||||
@@ -24,6 +25,14 @@ const REQUIRED_RUNTIME_PACKAGES = [
|
|||||||
// every Mach-O verifies strictly; spctl still rejects ad-hoc code, which is
|
// every Mach-O verifies strictly; spctl still rejects ad-hoc code, which is
|
||||||
// acceptable for the SIP-disabled customer workflow.
|
// acceptable for the SIP-disabled customer workflow.
|
||||||
const MACOS_HELPER_NAMES = ['xkey_helper', 'xkey_helper_4_1_13']
|
const MACOS_HELPER_NAMES = ['xkey_helper', 'xkey_helper_4_1_13']
|
||||||
|
const MACOS_EDITION_CODE_PATHS = [
|
||||||
|
['wcdb', 'macos', 'arm64', 'libwcdb_api.dylib'],
|
||||||
|
['wcdb', 'macos', 'arm64', 'libWCDB.dylib'],
|
||||||
|
['wcdb', 'macos', 'arm64', 'tm-wcdb-config-helper'],
|
||||||
|
['wcdb', 'macos', 'arm64', 'libtmlicense.dylib'],
|
||||||
|
['runtime', 'darwin-arm64', 'tm-wechat-host'],
|
||||||
|
['runtime', 'darwin-arm64', 'libtmwechat.dylib']
|
||||||
|
]
|
||||||
|
|
||||||
function getRuntimeResources(context) {
|
function getRuntimeResources(context) {
|
||||||
const productName = context.packager.appInfo.productFilename
|
const productName = context.packager.appInfo.productFilename
|
||||||
@@ -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 executable = platform === 'win32' ? 'ffmpeg.exe' : 'ffmpeg'
|
||||||
const ffmpegPath = path.join(
|
const ffmpegPath = path.join(
|
||||||
runtimeResources,
|
runtimeResources,
|
||||||
@@ -61,6 +88,202 @@ function validateFfmpegRuntime(runtimeResources, platform = process.platform) {
|
|||||||
return ffmpegPath
|
return ffmpegPath
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function validateMacEditionResources(runtimeResources, edition, platform) {
|
||||||
|
if (platform !== 'darwin') return
|
||||||
|
const resources = path.join(runtimeResources, 'resources')
|
||||||
|
const markerPath = path.join(resources, 'tracememo-build.json')
|
||||||
|
if (!existsSync(markerPath)) throw new Error(`Missing macOS edition marker: ${markerPath}`)
|
||||||
|
const marker = JSON.parse(readFileSync(markerPath, 'utf8'))
|
||||||
|
if (marker.profile !== edition) throw new Error(`Expected ${edition} bundle, found ${String(marker.profile)}`)
|
||||||
|
const wcdb = path.join(resources, 'wcdb', 'macos', 'arm64')
|
||||||
|
const api = path.join(wcdb, 'libwcdb_api.dylib')
|
||||||
|
const companion = path.join(wcdb, 'libWCDB.dylib')
|
||||||
|
const helper = path.join(wcdb, 'tm-wcdb-config-helper')
|
||||||
|
const runtime = path.join(resources, 'runtime', 'darwin-arm64')
|
||||||
|
const host = path.join(runtime, 'tm-wechat-host')
|
||||||
|
const runtimeDylib = path.join(runtime, 'libtmwechat.dylib')
|
||||||
|
const runtimeManifest = path.join(runtime, 'runtime-manifest.json')
|
||||||
|
const nativeArtifacts = [helper, host, runtimeDylib, runtimeManifest]
|
||||||
|
const presentNativeArtifacts = nativeArtifacts.filter(existsSync)
|
||||||
|
if (edition === 'public' && presentNativeArtifacts.length) {
|
||||||
|
throw new Error(`Public bundle contains native artifacts: ${presentNativeArtifacts.join(', ')}`)
|
||||||
|
}
|
||||||
|
if (edition === 'native' && presentNativeArtifacts.length !== nativeArtifacts.length) {
|
||||||
|
throw new Error('Native bundle is missing WCDB helper or WeChat runtime files')
|
||||||
|
}
|
||||||
|
for (const protectedPath of [path.join(resources, '1.txt'), path.join(resources, 'runtime', 'runtime.zip')]) {
|
||||||
|
if (existsSync(protectedPath)) throw new Error(`Protected file leaked into macOS bundle: ${protectedPath}`)
|
||||||
|
}
|
||||||
|
if (!existsSync(api) || !existsSync(companion)) throw new Error('macOS bundle is missing WCDB files')
|
||||||
|
if (!readBinaryArchitectures(api).includes('arm64')) throw new Error('Bundled WCDB API is not arm64')
|
||||||
|
if (!readBinaryArchitectures(companion).includes('arm64')) throw new Error('Bundled WCDB companion is not arm64')
|
||||||
|
const apiDependencies = execFileSync('/usr/bin/otool', ['-L', api], { encoding: 'utf8' })
|
||||||
|
if (!apiDependencies.includes('@loader_path/libWCDB.dylib')) {
|
||||||
|
throw new Error('Bundled WCDB API is missing its @loader_path companion dependency')
|
||||||
|
}
|
||||||
|
const symbols = execFileSync('/usr/bin/nm', ['-gU', api], { encoding: 'utf8' })
|
||||||
|
.split(/\r?\n/)
|
||||||
|
.map((line) => line.trim().split(/\s+/).pop() || '')
|
||||||
|
.map((symbol) => symbol.replace(/^_/, ''))
|
||||||
|
// OSS 合法保留的只读消息插入状态查询符号;其余 wcdb_msg_insert_* 都是写入入口。
|
||||||
|
const PUBLIC_READONLY_MSG_INSERT = new Set([
|
||||||
|
'wcdb_msg_insert_get_switches',
|
||||||
|
'wcdb_msg_insert_inspect_shard',
|
||||||
|
'wcdb_msg_insert_list_shard_catalog',
|
||||||
|
'wcdb_msg_insert_get_rooms_status'
|
||||||
|
])
|
||||||
|
const msgInsertSymbols = symbols.filter((symbol) => symbol.startsWith('wcdb_msg_insert_'))
|
||||||
|
if (edition === 'public') {
|
||||||
|
const leaked = msgInsertSymbols.filter((symbol) => !PUBLIC_READONLY_MSG_INSERT.has(symbol))
|
||||||
|
if (leaked.length) {
|
||||||
|
throw new Error(`Bundled public WCDB API leaks write ABI: ${leaked.join(', ')}`)
|
||||||
|
}
|
||||||
|
} else if (msgInsertSymbols.length === 0) {
|
||||||
|
throw new Error('Bundled native WCDB API is missing message-insert ABI')
|
||||||
|
}
|
||||||
|
const nativeInput = marker.nativeInput || {}
|
||||||
|
if (edition === 'public') {
|
||||||
|
if (nativeInput.libwcdbApiSha256 && createHash('sha256').update(readFileSync(api)).digest('hex') !== nativeInput.libwcdbApiSha256) {
|
||||||
|
throw new Error('Packaged public WCDB API does not match the recorded WCDB input hash')
|
||||||
|
}
|
||||||
|
if (nativeInput.libWCDBSha256 && createHash('sha256').update(readFileSync(companion)).digest('hex') !== nativeInput.libWCDBSha256) {
|
||||||
|
throw new Error('Packaged public WCDB companion does not match the recorded WCDB input hash')
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const requiredSymbols = [
|
||||||
|
'wcdb_get_messages',
|
||||||
|
'wcdb_get_group_members_batch',
|
||||||
|
'wcdb_start_monitor_pipe',
|
||||||
|
...(edition === 'native'
|
||||||
|
? [
|
||||||
|
'wcdb_msg_insert_set_switch',
|
||||||
|
'wcdb_msg_insert_get_switches',
|
||||||
|
'wcdb_msg_insert_list_shard_catalog',
|
||||||
|
'wcdb_msg_insert_ensure_rooms_rules',
|
||||||
|
'wcdb_msg_insert_get_rooms_status',
|
||||||
|
'wcdb_msg_insert_inspect_shard',
|
||||||
|
'wcdb_msg_insert_insert_local_notice',
|
||||||
|
'wcdb_msg_insert_insert_local_notice_ex',
|
||||||
|
'wcdb_msg_insert_sync_display_names'
|
||||||
|
]
|
||||||
|
: [])
|
||||||
|
]
|
||||||
|
const missingSymbols = requiredSymbols.filter((symbol) => !symbols.includes(symbol))
|
||||||
|
if (missingSymbols.length) throw new Error(`${edition} WCDB API is missing exports: ${missingSymbols.join(', ')}`)
|
||||||
|
const ffmpeg = path.join(resources, 'ffmpeg', 'ffmpeg')
|
||||||
|
if (!existsSync(ffmpeg) || !readBinaryArchitectures(ffmpeg).includes('arm64')) {
|
||||||
|
throw new Error(`macOS arm64 FFmpeg is missing or wrong architecture: ${ffmpeg}`)
|
||||||
|
}
|
||||||
|
if (marker.ffmpegSha256 && createHash('sha256').update(readFileSync(ffmpeg)).digest('hex') !== marker.ffmpegSha256) {
|
||||||
|
throw new Error('Packaged FFmpeg does not match its recorded staged hash')
|
||||||
|
}
|
||||||
|
for (const relative of [
|
||||||
|
'licenses/ffmpeg-static/LICENSE',
|
||||||
|
'licenses/ffmpeg-static/FFMPEG-LICENSE.txt',
|
||||||
|
'licenses/ffmpeg-static/FFMPEG-BUILD-INFO.txt'
|
||||||
|
]) {
|
||||||
|
if (!existsSync(path.join(resources, relative))) {
|
||||||
|
throw new Error(`Missing FFmpeg license/build notice: ${relative}`)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const ffmpegLicenseHashes = marker.ffmpegLicenseSha256
|
||||||
|
if (!ffmpegLicenseHashes || typeof ffmpegLicenseHashes !== 'object') {
|
||||||
|
throw new Error('Mac build marker is missing FFmpeg license/source notice hashes')
|
||||||
|
}
|
||||||
|
for (const [relative, expected] of Object.entries(ffmpegLicenseHashes)) {
|
||||||
|
const notice = path.join(resources, relative)
|
||||||
|
if (!/^[a-f0-9]{64}$/.test(expected) || !existsSync(notice) ||
|
||||||
|
createHash('sha256').update(readFileSync(notice)).digest('hex') !== expected) {
|
||||||
|
throw new Error(`Packaged FFmpeg license/source notice hash mismatch: ${relative}`)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (edition === 'native') {
|
||||||
|
if (!readFileSync(host).includes(Buffer.from('/license/status'))) {
|
||||||
|
throw new Error('Native Host does not implement GET /license/status')
|
||||||
|
}
|
||||||
|
for (const binary of [helper, host, runtimeDylib]) {
|
||||||
|
if (!readBinaryArchitectures(binary).includes('arm64')) {
|
||||||
|
throw new Error(`Native binary lacks arm64 architecture: ${binary}`)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const manifest = JSON.parse(readFileSync(runtimeManifest, 'utf8'))
|
||||||
|
if (manifest.runtime !== 'tm-wechat-native') throw new Error('Runtime Manifest runtime name is invalid')
|
||||||
|
if (manifest.platform !== 'darwin-arm64' || manifest.architecture !== 'arm64' || manifest.protocolVersion !== 1) {
|
||||||
|
throw new Error('Runtime Manifest platform, architecture, or protocol is invalid')
|
||||||
|
}
|
||||||
|
for (const capability of ['text', 'image', 'voice']) {
|
||||||
|
if (!Array.isArray(manifest.capabilities) || !manifest.capabilities.includes(capability)) {
|
||||||
|
throw new Error(`Runtime Manifest is missing capability: ${capability}`)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (!Array.isArray(manifest.supportedWechatVersions) || manifest.supportedWechatVersions.length === 0) {
|
||||||
|
throw new Error('Runtime Manifest has no supported WeChat versions')
|
||||||
|
}
|
||||||
|
const dylib = readFileSync(runtimeDylib)
|
||||||
|
for (const key of ['tmSendSourceSha256', 'addressProfileSha256']) {
|
||||||
|
if (!/^[a-f0-9]{64}$/.test(manifest[key] || '') || !dylib.includes(Buffer.from(manifest[key]))) {
|
||||||
|
throw new Error(`Runtime embedded hash mismatch: ${key}`)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (!execFileSync('/usr/bin/otool', ['-L', helper], { encoding: 'utf8' }).includes('@loader_path/libwcdb_api.dylib')) {
|
||||||
|
throw new Error('Native helper is missing its @loader_path WCDB API dependency')
|
||||||
|
}
|
||||||
|
const actualRuntimeManifest = JSON.parse(readFileSync(runtimeManifest, 'utf8'))
|
||||||
|
if (actualRuntimeManifest.runtime !== 'tm-wechat-native' ||
|
||||||
|
actualRuntimeManifest.platform !== 'darwin-arm64' ||
|
||||||
|
actualRuntimeManifest.architecture !== 'arm64' ||
|
||||||
|
actualRuntimeManifest.protocolVersion !== 1 ||
|
||||||
|
!Array.isArray(actualRuntimeManifest.supportedWechatVersions) ||
|
||||||
|
actualRuntimeManifest.supportedWechatVersions.length === 0) {
|
||||||
|
throw new Error('Runtime Manifest failed application compatibility checks')
|
||||||
|
}
|
||||||
|
for (const key of ['tmSendSourceSha256', 'addressProfileSha256']) {
|
||||||
|
if (!/^[a-f0-9]{64}$/.test(actualRuntimeManifest[key] || '')) {
|
||||||
|
throw new Error(`Runtime Manifest has invalid ${key}`)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const stagedFiles = marker.nativeInput?.files
|
||||||
|
if (!Array.isArray(stagedFiles) || stagedFiles.length !== 7) {
|
||||||
|
throw new Error('Native build marker is missing its source Bundle file hashes')
|
||||||
|
}
|
||||||
|
for (const entry of stagedFiles) {
|
||||||
|
const remainder = entry.path.replace(/^tracememo\//, '')
|
||||||
|
let relative
|
||||||
|
if (remainder === 'runtime/libtmlicense.dylib') {
|
||||||
|
relative = path.join('wcdb', 'macos', 'arm64', 'libtmlicense.dylib')
|
||||||
|
} else if (remainder.startsWith('runtime/')) {
|
||||||
|
relative = remainder.replace(/^runtime\//, 'runtime/darwin-arm64/')
|
||||||
|
} else {
|
||||||
|
relative = path.join('wcdb', 'macos', 'arm64', remainder.replace(/^wcdb\//, ''))
|
||||||
|
}
|
||||||
|
const binary = path.join(resources, relative)
|
||||||
|
if (!existsSync(binary) || readFileSync(binary).length !== entry.bytes) {
|
||||||
|
throw new Error(`Native packaged artifact size mismatch: ${entry.path}`)
|
||||||
|
}
|
||||||
|
const digest = createHash('sha256').update(readFileSync(binary)).digest('hex')
|
||||||
|
if (digest !== entry.sha256) throw new Error(`Native packaged artifact SHA-256 mismatch: ${entry.path}`)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function validateMacEditionProtectedFiles(runtimeResources) {
|
||||||
|
const asarPath = path.join(runtimeResources, 'app.asar')
|
||||||
|
if (!existsSync(asarPath)) throw new Error(`Missing packaged application archive: ${asarPath}`)
|
||||||
|
const entries = asar.listPackage(asarPath).map((entry) => entry.replaceAll('\\', '/'))
|
||||||
|
const leaked = entries.filter((entry) =>
|
||||||
|
/(^|\/)1\.txt$/i.test(entry) ||
|
||||||
|
/(^|\/)runtime\.zip$/i.test(entry) ||
|
||||||
|
/(^|\/)\.env(?:\.|$)/i.test(entry) ||
|
||||||
|
/\.(?:db|sqlite)(?:3)?$/i.test(entry) ||
|
||||||
|
/\.log$/i.test(entry)
|
||||||
|
)
|
||||||
|
if (leaked.length) throw new Error(`Sensitive file(s) leaked into app.asar: ${leaked.join(', ')}`)
|
||||||
|
for (const relative of ['1.txt', 'runtime/runtime.zip']) {
|
||||||
|
const candidate = path.join(runtimeResources, 'resources', relative)
|
||||||
|
if (existsSync(candidate)) throw new Error(`Protected file leaked into packaged resources: ${candidate}`)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
function validateSherpaRuntime(runtimeResources, platform, arch) {
|
function validateSherpaRuntime(runtimeResources, platform, arch) {
|
||||||
const platformName = platform === 'win32' ? 'win' : platform
|
const platformName = platform === 'win32' ? 'win' : platform
|
||||||
const basePath = path.join(
|
const basePath = path.join(
|
||||||
@@ -193,19 +416,28 @@ function isMacosCodeValid(targetPath, run = runCodesign) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
function findMacosHelperPaths(runtimeResources) {
|
function findMacosHelperPaths(runtimeResources) {
|
||||||
return MACOS_HELPER_NAMES.map((name) => path.join(runtimeResources, 'resources', name)).filter(
|
const paths = MACOS_HELPER_NAMES.map((name) => path.join(runtimeResources, 'resources', name))
|
||||||
(helperPath) => existsSync(helperPath)
|
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) {
|
function signMacosHelpers(runtimeResources, run = runCodesign) {
|
||||||
const helperPaths = findMacosHelperPaths(runtimeResources)
|
const helperPaths = findMacosHelperPaths(runtimeResources)
|
||||||
for (const helperPath of helperPaths) {
|
for (const helperPath of helperPaths) {
|
||||||
chmodSync(helperPath, 0o755)
|
if (!helperPath.endsWith('.dylib')) chmodSync(helperPath, 0o755)
|
||||||
if (!isMacosCodeValid(helperPath, run)) {
|
if (!isMacosCodeValid(helperPath, run)) {
|
||||||
run(['--force', '--sign', '-', helperPath])
|
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 {
|
try {
|
||||||
run(['--verify', '--strict', '--arch', arch, helperPath])
|
run(['--verify', '--strict', '--arch', arch, helperPath])
|
||||||
} catch (error) {
|
} 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
|
* The Intel Mac key helper is an x86_64 executable that only the x64 (or
|
||||||
* universal) macOS bundle can run. Every other target — Apple Silicon macOS,
|
* universal) macOS bundle can run. Every other target — Apple Silicon macOS,
|
||||||
@@ -483,7 +737,12 @@ function isSendRuntimeBuild() {
|
|||||||
function enforceSendRuntimeBoundary(
|
function enforceSendRuntimeBoundary(
|
||||||
runtimeResources,
|
runtimeResources,
|
||||||
platform,
|
platform,
|
||||||
bundlesSendRuntime = isSendRuntimeBuild()
|
bundlesSendRuntime =
|
||||||
|
process.env.TRACEMEMO_EDITION === 'native'
|
||||||
|
? true
|
||||||
|
: process.env.TRACEMEMO_EDITION === 'public'
|
||||||
|
? false
|
||||||
|
: isSendRuntimeBuild()
|
||||||
) {
|
) {
|
||||||
if (platform !== 'darwin') return null
|
if (platform !== 'darwin') return null
|
||||||
const found = findSendRuntime(runtimeResources)
|
const found = findSendRuntime(runtimeResources)
|
||||||
@@ -523,6 +782,12 @@ exports.default = async function afterPack(context) {
|
|||||||
validateReaderSkillRuntime(runtimeResources)
|
validateReaderSkillRuntime(runtimeResources)
|
||||||
validateSilkWasmRuntime(runtimeResources)
|
validateSilkWasmRuntime(runtimeResources)
|
||||||
const ffmpegPath = validateFfmpegRuntime(runtimeResources, context.electronPlatformName)
|
const ffmpegPath = validateFfmpegRuntime(runtimeResources, context.electronPlatformName)
|
||||||
|
validateElectronMainBinary(
|
||||||
|
context.appOutDir,
|
||||||
|
context.packager.appInfo.productFilename,
|
||||||
|
context.electronPlatformName,
|
||||||
|
arch
|
||||||
|
)
|
||||||
validateRuntimeBinaryArchitecture(
|
validateRuntimeBinaryArchitecture(
|
||||||
ffmpegPath,
|
ffmpegPath,
|
||||||
context.electronPlatformName,
|
context.electronPlatformName,
|
||||||
@@ -532,6 +797,23 @@ exports.default = async function afterPack(context) {
|
|||||||
validateSherpaRuntime(runtimeResources, context.electronPlatformName, arch)
|
validateSherpaRuntime(runtimeResources, context.electronPlatformName, arch)
|
||||||
validateSystemOcrRuntime(runtimeResources, context.electronPlatformName, arch)
|
validateSystemOcrRuntime(runtimeResources, context.electronPlatformName, arch)
|
||||||
validateKoffiRuntime(runtimeResources, context.electronPlatformName, arch)
|
validateKoffiRuntime(runtimeResources, context.electronPlatformName, arch)
|
||||||
|
if (context.electronPlatformName === 'darwin' && process.env.TRACEMEMO_EDITION) {
|
||||||
|
validateMacEditionResources(runtimeResources, process.env.TRACEMEMO_EDITION, context.electronPlatformName)
|
||||||
|
validateMacEditionProtectedFiles(runtimeResources)
|
||||||
|
if (process.env.TRACEMEMO_EDITION === 'public' && sendRuntime) {
|
||||||
|
throw new Error('Public edition unexpectedly includes a WeChat Runtime')
|
||||||
|
}
|
||||||
|
if (process.env.TRACEMEMO_EDITION === 'native' && !sendRuntime) {
|
||||||
|
throw new Error('Native edition is missing its WeChat Runtime')
|
||||||
|
}
|
||||||
|
if (sendRuntime) {
|
||||||
|
for (const runtimeFile of ['tm-wechat-host', 'libtmwechat.dylib', 'runtime-manifest.json']) {
|
||||||
|
if (!existsSync(path.join(sendRuntime, runtimeFile))) {
|
||||||
|
throw new Error(`Runtime file missing after packaging: ${runtimeFile}`)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
pruneIntelMacKeyTool(runtimeResources, context.electronPlatformName, arch)
|
pruneIntelMacKeyTool(runtimeResources, context.electronPlatformName, arch)
|
||||||
pruneForeignArchConnectors(runtimeResources, context.electronPlatformName, arch)
|
pruneForeignArchConnectors(runtimeResources, context.electronPlatformName, arch)
|
||||||
pruneForeignArchNativeRuntimes(runtimeResources, context.electronPlatformName, arch)
|
pruneForeignArchNativeRuntimes(runtimeResources, context.electronPlatformName, arch)
|
||||||
@@ -554,10 +836,13 @@ exports.validateSilkWasmRuntime = validateSilkWasmRuntime
|
|||||||
exports.validateSherpaRuntime = validateSherpaRuntime
|
exports.validateSherpaRuntime = validateSherpaRuntime
|
||||||
exports.validateSystemOcrRuntime = validateSystemOcrRuntime
|
exports.validateSystemOcrRuntime = validateSystemOcrRuntime
|
||||||
exports.validateKoffiRuntime = validateKoffiRuntime
|
exports.validateKoffiRuntime = validateKoffiRuntime
|
||||||
|
exports.validateMacEditionResources = validateMacEditionResources
|
||||||
|
exports.validateMacEditionProtectedFiles = validateMacEditionProtectedFiles
|
||||||
exports.pruneIntelMacKeyTool = pruneIntelMacKeyTool
|
exports.pruneIntelMacKeyTool = pruneIntelMacKeyTool
|
||||||
exports.pruneForeignArchConnectors = pruneForeignArchConnectors
|
exports.pruneForeignArchConnectors = pruneForeignArchConnectors
|
||||||
exports.pruneForeignArchNativeRuntimes = pruneForeignArchNativeRuntimes
|
exports.pruneForeignArchNativeRuntimes = pruneForeignArchNativeRuntimes
|
||||||
exports.validateRuntimeBinaryArchitecture = validateRuntimeBinaryArchitecture
|
exports.validateRuntimeBinaryArchitecture = validateRuntimeBinaryArchitecture
|
||||||
|
exports.validateElectronMainBinary = validateElectronMainBinary
|
||||||
exports.findMacosHelperPaths = findMacosHelperPaths
|
exports.findMacosHelperPaths = findMacosHelperPaths
|
||||||
exports.isMacosCodeValid = isMacosCodeValid
|
exports.isMacosCodeValid = isMacosCodeValid
|
||||||
exports.signMacosHelpers = signMacosHelpers
|
exports.signMacosHelpers = signMacosHelpers
|
||||||
|
|||||||
@@ -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 }
|
||||||
@@ -0,0 +1,121 @@
|
|||||||
|
#!/usr/bin/env node
|
||||||
|
/**
|
||||||
|
* 防漂移检查:Reader Skill 的版本号只有一个真源 —— SKILL.md frontmatter 的 `version`。
|
||||||
|
*
|
||||||
|
* 只要本次变更动了 SKILL.md 的内容,就必须同时提升 version,否则外部 Agent
|
||||||
|
* 无法通过 /health 上的 skill.version 发现自己手里的 Skill 已经过期,
|
||||||
|
* 会继续按旧契约调用接口(历史上真实发生过:文档改了两轮,版本号没动)。
|
||||||
|
*
|
||||||
|
* 比较基准依次尝试 SKILL_VERSION_BASE / origin/main / origin/develop / HEAD~1;
|
||||||
|
* 找不到基准(例如浅克隆)时只提示并跳过,不阻塞构建。
|
||||||
|
*/
|
||||||
|
const { execFileSync } = require('node:child_process')
|
||||||
|
const { readFileSync, existsSync } = require('node:fs')
|
||||||
|
const path = require('node:path')
|
||||||
|
|
||||||
|
const REQUESTED_BASE = 'SKILL_VERSION_BASE'
|
||||||
|
const SKILL_PATH = 'docs/skill/tracememo-reader/SKILL.md'
|
||||||
|
const SEMVER = /^\d+\.\d+\.\d+$/
|
||||||
|
|
||||||
|
function git(args) {
|
||||||
|
return execFileSync('git', args, {
|
||||||
|
cwd: process.cwd(),
|
||||||
|
encoding: 'utf8',
|
||||||
|
stdio: ['ignore', 'pipe', 'pipe']
|
||||||
|
}).trim()
|
||||||
|
}
|
||||||
|
|
||||||
|
function resolveBase() {
|
||||||
|
const candidates = []
|
||||||
|
if (process.env[REQUESTED_BASE]) candidates.push(process.env[REQUESTED_BASE])
|
||||||
|
candidates.push('origin/main', 'origin/develop', 'HEAD~1')
|
||||||
|
|
||||||
|
for (const candidate of candidates) {
|
||||||
|
try {
|
||||||
|
git(['rev-parse', '--verify', '--quiet', `${candidate}^{commit}`])
|
||||||
|
return candidate
|
||||||
|
} catch {
|
||||||
|
// 该基准不存在,继续尝试下一个
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
|
||||||
|
function versionOf(markdown) {
|
||||||
|
if (!markdown) return null
|
||||||
|
const match = /^version:[ \t]*(\S+)[ \t]*$/m.exec(markdown)
|
||||||
|
return match ? match[1] : null
|
||||||
|
}
|
||||||
|
|
||||||
|
function skip(reason) {
|
||||||
|
console.log(`[skill-version] 跳过版本漂移检查:${reason}`)
|
||||||
|
process.exit(0)
|
||||||
|
}
|
||||||
|
|
||||||
|
function fail(message) {
|
||||||
|
console.error(`[skill-version] FAIL:${message}`)
|
||||||
|
process.exit(1)
|
||||||
|
}
|
||||||
|
|
||||||
|
const root = process.cwd()
|
||||||
|
const skillFile = path.join(root, SKILL_PATH)
|
||||||
|
|
||||||
|
if (!existsSync(skillFile)) fail(`找不到 ${SKILL_PATH}。`)
|
||||||
|
|
||||||
|
const current = readFileSync(skillFile, 'utf8')
|
||||||
|
const currentVersion = versionOf(current)
|
||||||
|
|
||||||
|
if (!currentVersion) {
|
||||||
|
fail(`${SKILL_PATH} 的 frontmatter 缺少 version 字段。外部 Agent 依赖它做版本自检。`)
|
||||||
|
}
|
||||||
|
if (!SEMVER.test(currentVersion)) {
|
||||||
|
fail(`${SKILL_PATH} 的 version "${currentVersion}" 不是 x.y.z 形式。`)
|
||||||
|
}
|
||||||
|
|
||||||
|
const base = resolveBase()
|
||||||
|
if (!base) skip('找不到可用的 git 比较基准(可能是浅克隆)。')
|
||||||
|
|
||||||
|
// 已提交的改动 + 工作区未提交的改动都要看,否则本地预检会漏掉。
|
||||||
|
let changedFiles = new Set()
|
||||||
|
try {
|
||||||
|
for (const args of [
|
||||||
|
['diff', '--name-only', `${base}...HEAD`],
|
||||||
|
['diff', '--name-only', 'HEAD']
|
||||||
|
]) {
|
||||||
|
for (const file of git(args).split('\n')) if (file) changedFiles.add(file)
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
skip(`无法计算与 ${base} 的差异(${error.message.split('\n')[0]})。`)
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!changedFiles.has(SKILL_PATH)) {
|
||||||
|
console.log(`[skill-version] OK:与 ${base} 相比 ${SKILL_PATH} 未变更,无需提升版本。`)
|
||||||
|
process.exit(0)
|
||||||
|
}
|
||||||
|
|
||||||
|
let previous = null
|
||||||
|
try {
|
||||||
|
previous = git(['show', `${base}:${SKILL_PATH}`])
|
||||||
|
} catch {
|
||||||
|
previous = null
|
||||||
|
}
|
||||||
|
|
||||||
|
const previousVersion = versionOf(previous)
|
||||||
|
|
||||||
|
if (previousVersion === null) {
|
||||||
|
console.log(
|
||||||
|
`[skill-version] OK:${base} 上没有可比较的 version,当前为 ${currentVersion}。`
|
||||||
|
)
|
||||||
|
process.exit(0)
|
||||||
|
}
|
||||||
|
|
||||||
|
if (previousVersion === currentVersion) {
|
||||||
|
fail(
|
||||||
|
`${SKILL_PATH} 内容已变更,但 version 仍是 ${currentVersion}(基准 ${base})。\n` +
|
||||||
|
' 外部 Agent 只能通过 version 判断自己是否过期,请提升该版本号(例如 1.3.0 → 1.4.0)。'
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
console.log(
|
||||||
|
`[skill-version] OK:版本随文档一起提升 ${previousVersion} → ${currentVersion}(基准 ${base})。`
|
||||||
|
)
|
||||||
@@ -0,0 +1,660 @@
|
|||||||
|
const fs = require('node:fs')
|
||||||
|
const path = require('node:path')
|
||||||
|
const { createHash } = require('node:crypto')
|
||||||
|
const { execFileSync } = require('node:child_process')
|
||||||
|
const { createGunzip } = require('node:zlib')
|
||||||
|
const https = require('node:https')
|
||||||
|
const { pipeline } = require('node:stream/promises')
|
||||||
|
const { readBinaryArchitectures } = require('./binary-arch.cjs')
|
||||||
|
|
||||||
|
const ROOT = path.resolve(__dirname, '..')
|
||||||
|
function resolveEditionRoots(projectRoot = ROOT, env = process.env) {
|
||||||
|
return {
|
||||||
|
stageRoot: path.resolve(env.TRACEMEMO_MAC_STAGE_ROOT || path.join(projectRoot, 'build', 'mac-staging')),
|
||||||
|
outputRoot: path.resolve(env.TRACEMEMO_MAC_OUTPUT_ROOT || path.join(projectRoot, 'dist', 'mac'))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const WCDB_DIST_ROOT = resolveWcdbDistRoot()
|
||||||
|
const NATIVE_DIST_ROOT =
|
||||||
|
process.env.TRACEMEMO_NATIVE_DIST_ROOT || path.resolve(ROOT, '..', 'native-runtime-dist')
|
||||||
|
const NATIVE_BUNDLE_ROOT = findNativeBundleRoot(NATIVE_DIST_ROOT)
|
||||||
|
const PUBLIC_FILES = [
|
||||||
|
'icon.png',
|
||||||
|
'trayTemplate.png',
|
||||||
|
'trayTemplate@2x.png',
|
||||||
|
'daily_report_templates.html',
|
||||||
|
'mobile_daily_report.html',
|
||||||
|
'mobile_daily_report_v1.html',
|
||||||
|
'mobile_daily_report_v2.html',
|
||||||
|
'xkey_helper',
|
||||||
|
'xkey_helper_4_1_13'
|
||||||
|
]
|
||||||
|
const FFMPEG_LICENSE_FILES = [
|
||||||
|
['LICENSE', 'licenses/ffmpeg-static/LICENSE'],
|
||||||
|
['ffmpeg.LICENSE', 'licenses/ffmpeg-static/FFMPEG-LICENSE.txt'],
|
||||||
|
['ffmpeg.README', 'licenses/ffmpeg-static/FFMPEG-BUILD-INFO.txt']
|
||||||
|
]
|
||||||
|
const REQUIRED_NATIVE_SYMBOLS = [
|
||||||
|
'wcdb_msg_insert_set_switch',
|
||||||
|
'wcdb_msg_insert_get_switches',
|
||||||
|
'wcdb_msg_insert_list_shard_catalog',
|
||||||
|
'wcdb_msg_insert_ensure_rooms_rules',
|
||||||
|
'wcdb_msg_insert_get_rooms_status',
|
||||||
|
'wcdb_msg_insert_inspect_shard',
|
||||||
|
'wcdb_msg_insert_insert_local_notice',
|
||||||
|
'wcdb_msg_insert_insert_local_notice_ex',
|
||||||
|
'wcdb_msg_insert_sync_display_names'
|
||||||
|
]
|
||||||
|
const REQUIRED_PUBLIC_SYMBOLS = [
|
||||||
|
'wcdb_get_messages',
|
||||||
|
'wcdb_get_group_members_batch',
|
||||||
|
'wcdb_start_monitor_pipe',
|
||||||
|
'wcdb_msg_insert_get_switches',
|
||||||
|
'wcdb_msg_insert_inspect_shard',
|
||||||
|
'wcdb_msg_insert_list_shard_catalog',
|
||||||
|
'wcdb_msg_insert_get_rooms_status'
|
||||||
|
]
|
||||||
|
const PUBLIC_ALLOWED_MSG_INSERT = new Set([
|
||||||
|
'wcdb_msg_insert_get_switches',
|
||||||
|
'wcdb_msg_insert_inspect_shard',
|
||||||
|
'wcdb_msg_insert_list_shard_catalog',
|
||||||
|
'wcdb_msg_insert_get_rooms_status'
|
||||||
|
])
|
||||||
|
const PROTECTED_RESOURCE_PATHS = ['runtime/runtime.zip']
|
||||||
|
|
||||||
|
function sha256(filePath) {
|
||||||
|
return createHash('sha256').update(fs.readFileSync(filePath)).digest('hex')
|
||||||
|
}
|
||||||
|
|
||||||
|
function resolveWcdbDistRoot() {
|
||||||
|
const configured = process.env.TRACEMEMO_WCDB_DIST_ROOT
|
||||||
|
const candidates = [
|
||||||
|
configured,
|
||||||
|
path.resolve(ROOT, '..', 'wcdb-dist', 'build', 'macos-package-universal'),
|
||||||
|
path.resolve(ROOT, '..', '..', 'workspace', 'wcdb-dist', 'build', 'macos-package-universal')
|
||||||
|
].filter(Boolean)
|
||||||
|
return candidates.find((candidate) => fs.existsSync(candidate)) || candidates[0]
|
||||||
|
}
|
||||||
|
|
||||||
|
function findNativeBundleRoot(root) {
|
||||||
|
if (!fs.existsSync(root)) return root
|
||||||
|
const pending = [{ directory: root, depth: 0 }]
|
||||||
|
while (pending.length) {
|
||||||
|
const { directory, depth } = pending.shift()
|
||||||
|
const manifest = path.join(directory, 'manifest.json')
|
||||||
|
if (fs.existsSync(manifest)) {
|
||||||
|
try {
|
||||||
|
const parsed = JSON.parse(fs.readFileSync(manifest, 'utf8'))
|
||||||
|
if (
|
||||||
|
parsed.platform === 'macos' &&
|
||||||
|
parsed.architecture === 'arm64' &&
|
||||||
|
Array.isArray(parsed.files)
|
||||||
|
) {
|
||||||
|
return directory
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
// Ignore unrelated manifests while locating the native runtime bundle.
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (depth >= 3) continue
|
||||||
|
for (const entry of fs.readdirSync(directory, { withFileTypes: true })) {
|
||||||
|
if (entry.isDirectory())
|
||||||
|
pending.push({ directory: path.join(directory, entry.name), depth: depth + 1 })
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return root
|
||||||
|
}
|
||||||
|
|
||||||
|
function run(command, args) {
|
||||||
|
return execFileSync(command, args, { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] })
|
||||||
|
}
|
||||||
|
|
||||||
|
function binaryArchitectures(filePath) {
|
||||||
|
return readBinaryArchitectures(filePath)
|
||||||
|
}
|
||||||
|
|
||||||
|
function exportedSymbols(filePath) {
|
||||||
|
return run('/usr/bin/nm', ['-gU', filePath])
|
||||||
|
.split(/\r?\n/)
|
||||||
|
.map((line) => line.trim().split(/\s+/).pop())
|
||||||
|
.filter(Boolean)
|
||||||
|
.map((symbol) => symbol.replace(/^_/, ''))
|
||||||
|
}
|
||||||
|
|
||||||
|
function assertArm64(filePath, label) {
|
||||||
|
if (!binaryArchitectures(filePath).includes('arm64')) {
|
||||||
|
throw new Error(`${label} does not contain arm64: ${filePath}`)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function validateLicenseStatusRoute(hostPath) {
|
||||||
|
if (!fs.readFileSync(hostPath).includes(Buffer.from('/license/status'))) {
|
||||||
|
throw new Error(`Native Host does not implement GET /license/status: ${hostPath}`)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function validateWcdbPair(apiPath, dependencyPath, profile) {
|
||||||
|
if (!fs.existsSync(apiPath) || !fs.existsSync(dependencyPath)) {
|
||||||
|
throw new Error(`Missing ${profile} WCDB library pair: ${apiPath}`)
|
||||||
|
}
|
||||||
|
assertArm64(apiPath, `${profile} WCDB API`)
|
||||||
|
assertArm64(dependencyPath, `${profile} WCDB companion`)
|
||||||
|
const symbols = exportedSymbols(apiPath)
|
||||||
|
const missing = (profile === 'public' ? REQUIRED_PUBLIC_SYMBOLS : REQUIRED_NATIVE_SYMBOLS).filter(
|
||||||
|
(symbol) => !symbols.includes(symbol)
|
||||||
|
)
|
||||||
|
if (missing.length)
|
||||||
|
throw new Error(`${profile} WCDB API is missing exports: ${missing.join(', ')}`)
|
||||||
|
if (profile === 'public') {
|
||||||
|
const leaked = symbols.filter(
|
||||||
|
(symbol) => symbol.startsWith('wcdb_msg_insert_') && !PUBLIC_ALLOWED_MSG_INSERT.has(symbol)
|
||||||
|
)
|
||||||
|
if (leaked.length) {
|
||||||
|
throw new Error(
|
||||||
|
`Public WCDB API contains forbidden message-insert exports: ${leaked.join(', ')}`
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const dependencies = run('/usr/bin/otool', ['-L', apiPath])
|
||||||
|
if (!dependencies.includes('@loader_path/libWCDB.dylib')) {
|
||||||
|
throw new Error(`${profile} WCDB API does not resolve libWCDB.dylib via @loader_path`)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function readAndValidateNativeManifest(bundleRoot) {
|
||||||
|
const manifestPath = path.join(bundleRoot, 'manifest.json')
|
||||||
|
const manifest = JSON.parse(fs.readFileSync(manifestPath, 'utf8'))
|
||||||
|
if (manifest.platform !== 'macos' || manifest.architecture !== 'arm64') {
|
||||||
|
throw new Error('Native bundle manifest must target macos-arm64')
|
||||||
|
}
|
||||||
|
if (!Array.isArray(manifest.files) || manifest.files.length !== 7) {
|
||||||
|
throw new Error(
|
||||||
|
'Native bundle manifest must list exactly seven files (six runtime/wcdb artifacts plus libtmlicense.dylib)'
|
||||||
|
)
|
||||||
|
}
|
||||||
|
const normalized = new Set()
|
||||||
|
const listedNativePaths = new Set()
|
||||||
|
for (const entry of manifest.files) {
|
||||||
|
if (
|
||||||
|
!entry ||
|
||||||
|
typeof entry.path !== 'string' ||
|
||||||
|
!/^tracememo\/(runtime|wcdb)\//.test(entry.path)
|
||||||
|
) {
|
||||||
|
throw new Error('Native bundle manifest contains an unexpected resource path')
|
||||||
|
}
|
||||||
|
if (normalized.has(entry.path) || !/^[a-f0-9]{64}$/.test(entry.sha256 || '')) {
|
||||||
|
throw new Error(`Invalid native bundle manifest entry: ${String(entry.path)}`)
|
||||||
|
}
|
||||||
|
normalized.add(entry.path)
|
||||||
|
const source = path.join(bundleRoot, entry.path)
|
||||||
|
const stat = fs.statSync(source)
|
||||||
|
if (!stat.isFile() || stat.size !== entry.bytes || sha256(source) !== entry.sha256) {
|
||||||
|
throw new Error(`Native bundle manifest verification failed: ${entry.path}`)
|
||||||
|
}
|
||||||
|
listedNativePaths.add(entry.path)
|
||||||
|
if (/\/runtime\/(tm-wechat-host|libtmwechat\.dylib|libtmlicense\.dylib)$/.test(entry.path)) {
|
||||||
|
if (!binaryArchitectures(source).includes('arm64')) {
|
||||||
|
throw new Error(`Native runtime binary is not arm64: ${entry.path}`)
|
||||||
|
}
|
||||||
|
if (entry.path.endsWith('libtmlicense.dylib')) {
|
||||||
|
const signature = run('/usr/bin/codesign', ['--verify', '--strict', source])
|
||||||
|
if (signature.trim() !== '') {
|
||||||
|
throw new Error(`libtmlicense.dylib code signature is invalid: ${signature.trim()}`)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (/\/wcdb\/(libwcdb_api\.dylib|tm-wcdb-config-helper)$/.test(entry.path)) {
|
||||||
|
if (!binaryArchitectures(source).includes('arm64')) {
|
||||||
|
throw new Error(`Native WCDB binary is not arm64: ${entry.path}`)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const expected = [
|
||||||
|
'tracememo/runtime/libtmlicense.dylib',
|
||||||
|
'tracememo/runtime/libtmwechat.dylib',
|
||||||
|
'tracememo/runtime/runtime-manifest.json',
|
||||||
|
'tracememo/runtime/tm-wechat-host',
|
||||||
|
'tracememo/wcdb/libWCDB.dylib',
|
||||||
|
'tracememo/wcdb/libwcdb_api.dylib',
|
||||||
|
'tracememo/wcdb/tm-wcdb-config-helper'
|
||||||
|
]
|
||||||
|
if (expected.some((entry) => !normalized.has(entry))) {
|
||||||
|
throw new Error('Native bundle manifest file list is incomplete')
|
||||||
|
}
|
||||||
|
if (listedNativePaths.size !== expected.length)
|
||||||
|
throw new Error('Native bundle manifest has unexpected files')
|
||||||
|
return { manifest, files: manifest.files }
|
||||||
|
}
|
||||||
|
|
||||||
|
function validateNativeBundle(bundleRoot, files) {
|
||||||
|
const bySuffix = (suffix) => {
|
||||||
|
const entry = files.find((file) => file.path.endsWith(suffix))
|
||||||
|
if (!entry) throw new Error(`Missing native bundle manifest path: ${suffix}`)
|
||||||
|
return path.join(bundleRoot, entry.path)
|
||||||
|
}
|
||||||
|
const api = bySuffix('/wcdb/libwcdb_api.dylib')
|
||||||
|
const companion = bySuffix('/wcdb/libWCDB.dylib')
|
||||||
|
const helper = bySuffix('/wcdb/tm-wcdb-config-helper')
|
||||||
|
const host = bySuffix('/runtime/tm-wechat-host')
|
||||||
|
const runtimeDylib = bySuffix('/runtime/libtmwechat.dylib')
|
||||||
|
const runtimeManifestPath = bySuffix('/runtime/runtime-manifest.json')
|
||||||
|
const licenseDylib = bySuffix('/runtime/libtmlicense.dylib')
|
||||||
|
validateLicenseStatusRoute(host)
|
||||||
|
validateWcdbPair(api, companion, 'native')
|
||||||
|
for (const [binary, label] of [
|
||||||
|
[helper, 'WCDB helper'],
|
||||||
|
[host, 'WeChat host'],
|
||||||
|
[runtimeDylib, 'WeChat runtime'],
|
||||||
|
[licenseDylib, 'License core']
|
||||||
|
]) {
|
||||||
|
assertArm64(binary, label)
|
||||||
|
}
|
||||||
|
// libtmlicense must carry a valid ad-hoc signature; it is dlopen'd at runtime.
|
||||||
|
const licenseSignature = run('/usr/bin/codesign', ['--verify', '--strict', licenseDylib])
|
||||||
|
if (licenseSignature.trim() !== '') {
|
||||||
|
throw new Error(`libtmlicense.dylib code signature is invalid: ${licenseSignature.trim()}`)
|
||||||
|
}
|
||||||
|
if (!run('/usr/bin/otool', ['-L', helper]).includes('@loader_path/libwcdb_api.dylib')) {
|
||||||
|
throw new Error('WCDB helper does not resolve its API dylib via @loader_path')
|
||||||
|
}
|
||||||
|
const bundleManifest = JSON.parse(fs.readFileSync(path.join(bundleRoot, 'manifest.json'), 'utf8'))
|
||||||
|
const runtimeDependencies = run('/usr/bin/otool', ['-L', runtimeDylib])
|
||||||
|
if (!bundleManifest.compatibility || bundleManifest.proWcdbAbiVersion !== 1) {
|
||||||
|
throw new Error('Native bundle manifest does not declare the expected WCDB ABI')
|
||||||
|
}
|
||||||
|
const runtimeManifest = JSON.parse(fs.readFileSync(runtimeManifestPath, 'utf8'))
|
||||||
|
if (
|
||||||
|
runtimeManifest.platform !== 'darwin-arm64' ||
|
||||||
|
runtimeManifest.architecture !== 'arm64' ||
|
||||||
|
runtimeManifest.protocolVersion !== 1
|
||||||
|
) {
|
||||||
|
throw new Error('Runtime manifest platform, architecture, or protocol is invalid')
|
||||||
|
}
|
||||||
|
if (runtimeManifest.runtime !== 'tm-wechat-native') throw new Error('Runtime name is invalid')
|
||||||
|
if (
|
||||||
|
!Array.isArray(runtimeManifest.supportedWechatVersions) ||
|
||||||
|
runtimeManifest.supportedWechatVersions.length === 0
|
||||||
|
) {
|
||||||
|
throw new Error('Runtime manifest has no supported WeChat versions')
|
||||||
|
}
|
||||||
|
for (const capability of ['text', 'image', 'voice']) {
|
||||||
|
if (
|
||||||
|
!Array.isArray(runtimeManifest.capabilities) ||
|
||||||
|
!runtimeManifest.capabilities.includes(capability)
|
||||||
|
) {
|
||||||
|
throw new Error(`Runtime manifest is missing capability: ${capability}`)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const runtimeBytes = fs.readFileSync(runtimeDylib)
|
||||||
|
for (const key of ['tmSendSourceSha256', 'addressProfileSha256']) {
|
||||||
|
if (
|
||||||
|
!/^[a-f0-9]{64}$/.test(runtimeManifest[key] || '') ||
|
||||||
|
!runtimeBytes.includes(Buffer.from(runtimeManifest[key]))
|
||||||
|
) {
|
||||||
|
throw new Error(`Runtime dylib does not contain the manifest ${key}`)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const apiDependencies = run('/usr/bin/otool', ['-L', api])
|
||||||
|
if (!apiDependencies.includes('@loader_path/libWCDB.dylib'))
|
||||||
|
throw new Error('WCDB companion dependency missing')
|
||||||
|
if (!run('/usr/bin/otool', ['-L', host]).includes('libSystem')) {
|
||||||
|
throw new Error('Host is missing its system runtime dependency')
|
||||||
|
}
|
||||||
|
if (
|
||||||
|
runtimeDependencies.includes('@rpath/libtmwechat.dylib') &&
|
||||||
|
!runtimeDependencies.includes('/usr/lib/libSystem')
|
||||||
|
) {
|
||||||
|
throw new Error('Runtime dylib is missing required system dependencies')
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function assertStagingTargetDoesNotExist(stageRoot, outputRoot) {
|
||||||
|
for (const target of [stageRoot, outputRoot]) {
|
||||||
|
if (fs.existsSync(target))
|
||||||
|
throw new Error(`Refusing to overwrite existing build target: ${target}`)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function copyPublicResources(sourceResources, destination) {
|
||||||
|
for (const relative of PUBLIC_FILES) {
|
||||||
|
const source = path.join(sourceResources, relative)
|
||||||
|
if (!fs.existsSync(source)) throw new Error(`Missing public resource: ${source}`)
|
||||||
|
fs.mkdirSync(path.dirname(path.join(destination, relative)), { recursive: true })
|
||||||
|
fs.copyFileSync(source, path.join(destination, relative), fs.constants.COPYFILE_EXCL)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function copyFfmpegLicenses(destination) {
|
||||||
|
const suppliedLicenseRoot = String(process.env.TRACEMEMO_FFMPEG_LICENSE_DIR || '').trim()
|
||||||
|
const packageRoot = suppliedLicenseRoot || path.dirname(require.resolve('ffmpeg-static/package.json'))
|
||||||
|
const files = suppliedLicenseRoot
|
||||||
|
? [
|
||||||
|
['LICENSE', 'LICENSE', 'licenses/ffmpeg-static/LICENSE'],
|
||||||
|
['FFMPEG-LICENSE.txt', 'FFMPEG-LICENSE.txt', 'licenses/ffmpeg-static/FFMPEG-LICENSE.txt'],
|
||||||
|
['FFMPEG-BUILD-INFO.txt', 'FFMPEG-BUILD-INFO.txt', 'licenses/ffmpeg-static/FFMPEG-BUILD-INFO.txt']
|
||||||
|
]
|
||||||
|
: FFMPEG_LICENSE_FILES.map(([source, relative]) => [source, source, relative])
|
||||||
|
for (const [sourceName, inputName, destinationRelative] of files) {
|
||||||
|
const source = path.join(packageRoot, inputName)
|
||||||
|
if (!fs.existsSync(source)) throw new Error(`Missing FFmpeg license/source notice: ${source}`)
|
||||||
|
const target = path.join(destination, destinationRelative)
|
||||||
|
fs.mkdirSync(path.dirname(target), { recursive: true })
|
||||||
|
fs.copyFileSync(source, target, fs.constants.COPYFILE_EXCL)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function copyNative(source, destination) {
|
||||||
|
fs.mkdirSync(path.dirname(destination), { recursive: true })
|
||||||
|
fs.copyFileSync(source, destination, fs.constants.COPYFILE_EXCL)
|
||||||
|
}
|
||||||
|
|
||||||
|
async function downloadFfmpegArm64(destination) {
|
||||||
|
const url =
|
||||||
|
'https://github.com/eugeneware/ffmpeg-static/releases/download/b6.1.1/ffmpeg-darwin-arm64.gz'
|
||||||
|
const archivePath = `${destination}.gz`
|
||||||
|
await new Promise((resolve, reject) => {
|
||||||
|
const request = (target) =>
|
||||||
|
https.get(target, (response) => {
|
||||||
|
if (response.statusCode >= 300 && response.statusCode < 400 && response.headers.location) {
|
||||||
|
response.resume()
|
||||||
|
request(response.headers.location)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if (response.statusCode !== 200) {
|
||||||
|
response.resume()
|
||||||
|
reject(new Error(`FFmpeg download failed with HTTP ${response.statusCode}`))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
const output = fs.createWriteStream(archivePath, { flags: 'wx' })
|
||||||
|
pipeline(response, output).then(resolve, reject)
|
||||||
|
})
|
||||||
|
request(url).on('error', reject)
|
||||||
|
})
|
||||||
|
await pipeline(
|
||||||
|
fs.createReadStream(archivePath),
|
||||||
|
createGunzip(),
|
||||||
|
fs.createWriteStream(destination, { flags: 'wx' })
|
||||||
|
)
|
||||||
|
fs.unlinkSync(archivePath)
|
||||||
|
fs.chmodSync(destination, 0o755)
|
||||||
|
assertArm64(destination, 'Staged FFmpeg')
|
||||||
|
}
|
||||||
|
|
||||||
|
async function prepareFfmpeg(stagedResources) {
|
||||||
|
const destination = path.join(stagedResources, 'ffmpeg', 'ffmpeg')
|
||||||
|
fs.mkdirSync(path.dirname(destination), { recursive: true })
|
||||||
|
const supplied = process.env.TRACEMEMO_FFMPEG_ARM64_PATH
|
||||||
|
if (supplied) {
|
||||||
|
assertArm64(supplied, 'Provided FFmpeg')
|
||||||
|
copyNative(supplied, destination)
|
||||||
|
fs.chmodSync(destination, 0o755)
|
||||||
|
return sha256(destination)
|
||||||
|
}
|
||||||
|
await downloadFfmpegArm64(destination)
|
||||||
|
return sha256(destination)
|
||||||
|
}
|
||||||
|
|
||||||
|
function assertNoProtectedInputs(root) {
|
||||||
|
for (const relative of ['1.txt']) {
|
||||||
|
if (fs.existsSync(path.join(ROOT, relative))) {
|
||||||
|
throw new Error(`Protected file must not be used as a build input: ${relative}`)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for (const relative of PROTECTED_RESOURCE_PATHS) {
|
||||||
|
if (fs.existsSync(path.join(root, relative))) {
|
||||||
|
throw new Error(`Protected file must not be used as a build input: ${relative}`)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function prepareEdition(edition) {
|
||||||
|
if (edition !== 'public' && edition !== 'native')
|
||||||
|
throw new Error('Usage: prepare-macos-edition.cjs <public|native>')
|
||||||
|
const roots = resolveEditionRoots()
|
||||||
|
const stageRoot = path.join(roots.stageRoot, edition)
|
||||||
|
const outputRoot = path.join(roots.outputRoot, edition)
|
||||||
|
assertStagingTargetDoesNotExist(stageRoot, outputRoot)
|
||||||
|
|
||||||
|
const sourceResources = path.join(ROOT, 'resources')
|
||||||
|
assertNoProtectedInputs(sourceResources)
|
||||||
|
fs.mkdirSync(path.dirname(stageRoot), { recursive: true })
|
||||||
|
fs.mkdirSync(stageRoot)
|
||||||
|
try {
|
||||||
|
const stagedResources = path.join(stageRoot, 'resources')
|
||||||
|
fs.mkdirSync(stagedResources, { recursive: true })
|
||||||
|
copyPublicResources(sourceResources, stagedResources)
|
||||||
|
copyFfmpegLicenses(stagedResources)
|
||||||
|
const ffmpegSha256 = await prepareFfmpeg(stagedResources)
|
||||||
|
|
||||||
|
const marker = {
|
||||||
|
profile: edition,
|
||||||
|
appVersion: require(path.join(ROOT, 'package.json')).version,
|
||||||
|
ffmpegSha256,
|
||||||
|
ffmpegLicenseSource: process.env.TRACEMEMO_FFMPEG_LICENSE_DIR
|
||||||
|
? 'provided verified license files'
|
||||||
|
: 'ffmpeg-static package',
|
||||||
|
ffmpegLicenseSha256: Object.fromEntries(
|
||||||
|
FFMPEG_LICENSE_FILES.map(([, relative]) => [relative, sha256(path.join(stagedResources, relative))])
|
||||||
|
)
|
||||||
|
}
|
||||||
|
if (edition === 'public') {
|
||||||
|
const api = path.join(WCDB_DIST_ROOT, 'libwcdb_api.dylib')
|
||||||
|
const companion = path.join(WCDB_DIST_ROOT, 'libWCDB.dylib')
|
||||||
|
validateWcdbPair(api, companion, 'public')
|
||||||
|
copyNative(api, path.join(stagedResources, 'wcdb', 'macos', 'arm64', 'libwcdb_api.dylib'))
|
||||||
|
copyNative(companion, path.join(stagedResources, 'wcdb', 'macos', 'arm64', 'libWCDB.dylib'))
|
||||||
|
marker.nativeInput = {
|
||||||
|
source: path.relative(ROOT, WCDB_DIST_ROOT),
|
||||||
|
libwcdbApiSha256: sha256(api),
|
||||||
|
libWCDBSha256: sha256(companion)
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
const { manifest, files } = readAndValidateNativeManifest(NATIVE_BUNDLE_ROOT)
|
||||||
|
validateNativeBundle(NATIVE_BUNDLE_ROOT, files)
|
||||||
|
for (const entry of files) {
|
||||||
|
const remainder = entry.path.replace(/^tracememo\//, '')
|
||||||
|
let relative
|
||||||
|
if (remainder === 'runtime/libtmlicense.dylib') {
|
||||||
|
// libtmlicense 只给 WCDB helper 用(main 进程的内嵌授权核是静态编译进
|
||||||
|
// libtmwechat.dylib 的)。放到 helper 同目录,helper 的 dlopen 候选路径
|
||||||
|
// <exe dir>/libtmlicense.dylib 才能命中;放 runtime/ 子目录会让
|
||||||
|
// helper 找不到它而 fail-closed。
|
||||||
|
relative = path.join('wcdb', 'macos', 'arm64', 'libtmlicense.dylib')
|
||||||
|
} else if (remainder.startsWith('runtime/')) {
|
||||||
|
relative = path.join(remainder.replace(/^runtime\//, 'runtime/darwin-arm64/'))
|
||||||
|
} else {
|
||||||
|
relative = path.join('wcdb', 'macos', 'arm64', remainder.replace(/^wcdb\//, ''))
|
||||||
|
}
|
||||||
|
copyNative(path.join(NATIVE_BUNDLE_ROOT, entry.path), path.join(stagedResources, relative))
|
||||||
|
}
|
||||||
|
marker.nativeInput = {
|
||||||
|
bundleVersion: manifest.bundleVersion,
|
||||||
|
manifestSha256: sha256(path.join(NATIVE_BUNDLE_ROOT, 'manifest.json')),
|
||||||
|
files: files.map(({ path: relative, sha256: digest, bytes }) => ({
|
||||||
|
path: relative,
|
||||||
|
sha256: digest,
|
||||||
|
bytes
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
for (const relative of ['1.txt', 'runtime/runtime.zip']) {
|
||||||
|
if (fs.existsSync(path.join(stagedResources, relative))) {
|
||||||
|
throw new Error(`Protected file leaked into ${edition} staging: ${relative}`)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
fs.writeFileSync(
|
||||||
|
path.join(stagedResources, 'tracememo-build.json'),
|
||||||
|
`${JSON.stringify(marker, null, 2)}\n`,
|
||||||
|
{ flag: 'wx' }
|
||||||
|
)
|
||||||
|
console.log(`[prepare-macos-edition] ${edition} resources staged at ${stagedResources}`)
|
||||||
|
} catch (error) {
|
||||||
|
fs.rmSync(stageRoot, { recursive: true, force: true })
|
||||||
|
throw error
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function validateStagedEdition(edition) {
|
||||||
|
if (edition !== 'public' && edition !== 'native')
|
||||||
|
throw new Error('Usage: validate staged edition <public|native>')
|
||||||
|
const resources = path.join(resolveEditionRoots().stageRoot, edition, 'resources')
|
||||||
|
const markerPath = path.join(resources, 'tracememo-build.json')
|
||||||
|
if (!fs.existsSync(markerPath)) throw new Error(`Missing staged edition marker: ${markerPath}`)
|
||||||
|
const marker = JSON.parse(fs.readFileSync(markerPath, 'utf8'))
|
||||||
|
if (
|
||||||
|
marker.profile !== edition ||
|
||||||
|
marker.appVersion !== require(path.join(ROOT, 'package.json')).version
|
||||||
|
) {
|
||||||
|
throw new Error('Staged edition marker does not match the expected edition/version')
|
||||||
|
}
|
||||||
|
if (!/^[a-f0-9]{64}$/.test(marker.ffmpegSha256 || ''))
|
||||||
|
throw new Error('Staged FFmpeg hash is invalid')
|
||||||
|
const ffmpeg = path.join(resources, 'ffmpeg', 'ffmpeg')
|
||||||
|
if (!fs.existsSync(ffmpeg) || sha256(ffmpeg) !== marker.ffmpegSha256) {
|
||||||
|
throw new Error('Staged FFmpeg SHA-256 does not match the edition marker')
|
||||||
|
}
|
||||||
|
assertArm64(ffmpeg, 'Staged FFmpeg')
|
||||||
|
for (const [, relative] of FFMPEG_LICENSE_FILES) {
|
||||||
|
const licensePath = path.join(resources, relative)
|
||||||
|
const expected = marker.ffmpegLicenseSha256?.[relative]
|
||||||
|
if (!fs.existsSync(licensePath) || !/^[a-f0-9]{64}$/.test(expected || '') || sha256(licensePath) !== expected) {
|
||||||
|
throw new Error(`Staged FFmpeg license/source notice hash mismatch: ${relative}`)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const api = path.join(resources, 'wcdb', 'macos', 'arm64', 'libwcdb_api.dylib')
|
||||||
|
const companion = path.join(resources, 'wcdb', 'macos', 'arm64', 'libWCDB.dylib')
|
||||||
|
validateWcdbPair(api, companion, edition)
|
||||||
|
if (marker.nativeInput?.libwcdbApiSha256 && sha256(api) !== marker.nativeInput.libwcdbApiSha256) {
|
||||||
|
throw new Error('Staged public WCDB API does not match the recorded input hash')
|
||||||
|
}
|
||||||
|
if (marker.nativeInput?.libWCDBSha256 && sha256(companion) !== marker.nativeInput.libWCDBSha256) {
|
||||||
|
throw new Error('Staged public WCDB companion does not match the recorded input hash')
|
||||||
|
}
|
||||||
|
if (edition === 'native') {
|
||||||
|
const nativeManifest = marker.nativeInput?.files
|
||||||
|
if (!Array.isArray(nativeManifest) || nativeManifest.length !== 7) {
|
||||||
|
throw new Error(
|
||||||
|
'Staged native bundle is missing its verified source manifest (expected seven files)'
|
||||||
|
)
|
||||||
|
}
|
||||||
|
for (const item of nativeManifest) {
|
||||||
|
const relative = item.path.replace(/^tracememo\//, '')
|
||||||
|
let stagedRelative
|
||||||
|
if (relative === 'runtime/libtmlicense.dylib') {
|
||||||
|
stagedRelative = path.join('wcdb', 'macos', 'arm64', 'libtmlicense.dylib')
|
||||||
|
} else if (relative.startsWith('runtime/')) {
|
||||||
|
stagedRelative = relative.replace(/^runtime\//, 'runtime/darwin-arm64/')
|
||||||
|
} else {
|
||||||
|
stagedRelative = path.join('wcdb', 'macos', 'arm64', relative.replace(/^wcdb\//, ''))
|
||||||
|
}
|
||||||
|
const staged = path.join(resources, stagedRelative)
|
||||||
|
if (
|
||||||
|
!fs.existsSync(staged) ||
|
||||||
|
fs.statSync(staged).size !== item.bytes ||
|
||||||
|
sha256(staged) !== item.sha256
|
||||||
|
) {
|
||||||
|
throw new Error(`Staged native artifact hash mismatch: ${item.path}`)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
validateNativeBundleFromStaging(resources)
|
||||||
|
}
|
||||||
|
for (const relative of ['1.txt', 'runtime/runtime.zip']) {
|
||||||
|
if (fs.existsSync(path.join(resources, relative)))
|
||||||
|
throw new Error(`Protected file leaked into staging: ${relative}`)
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
edition,
|
||||||
|
appVersion: marker.appVersion,
|
||||||
|
apiSha256: sha256(api),
|
||||||
|
companionSha256: sha256(companion),
|
||||||
|
ffmpegSha256: sha256(ffmpeg)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function validateNativeBundleFromStaging(resources) {
|
||||||
|
const api = path.join(resources, 'wcdb', 'macos', 'arm64', 'libwcdb_api.dylib')
|
||||||
|
const companion = path.join(resources, 'wcdb', 'macos', 'arm64', 'libWCDB.dylib')
|
||||||
|
const helper = path.join(resources, 'wcdb', 'macos', 'arm64', 'tm-wcdb-config-helper')
|
||||||
|
const licenseDylib = path.join(resources, 'wcdb', 'macos', 'arm64', 'libtmlicense.dylib')
|
||||||
|
const host = path.join(resources, 'runtime', 'darwin-arm64', 'tm-wechat-host')
|
||||||
|
const runtimeDylib = path.join(resources, 'runtime', 'darwin-arm64', 'libtmwechat.dylib')
|
||||||
|
const runtimeManifestPath = path.join(
|
||||||
|
resources,
|
||||||
|
'runtime',
|
||||||
|
'darwin-arm64',
|
||||||
|
'runtime-manifest.json'
|
||||||
|
)
|
||||||
|
if (!fs.existsSync(licenseDylib)) {
|
||||||
|
throw new Error('Staged native edition is missing libtmlicense.dylib next to the WCDB helper')
|
||||||
|
}
|
||||||
|
const symbols = exportedSymbols(api)
|
||||||
|
const missing = REQUIRED_NATIVE_SYMBOLS.filter((symbol) => !symbols.includes(symbol))
|
||||||
|
if (missing.length) throw new Error(`Staged native WCDB ABI is missing: ${missing.join(', ')}`)
|
||||||
|
for (const [binary, label] of [
|
||||||
|
[companion, 'WCDB companion'],
|
||||||
|
[helper, 'WCDB helper'],
|
||||||
|
[licenseDylib, 'License core'],
|
||||||
|
[host, 'Host'],
|
||||||
|
[runtimeDylib, 'Runtime dylib']
|
||||||
|
]) {
|
||||||
|
assertArm64(binary, label)
|
||||||
|
}
|
||||||
|
// helper must be able to dlopen libtmlicense.dylib: it must sit in the same directory.
|
||||||
|
const licenseSignature = run('/usr/bin/codesign', ['--verify', '--strict', licenseDylib])
|
||||||
|
if (licenseSignature.trim() !== '') {
|
||||||
|
throw new Error(
|
||||||
|
`Staged libtmlicense.dylib code signature is invalid: ${licenseSignature.trim()}`
|
||||||
|
)
|
||||||
|
}
|
||||||
|
if (!run('/usr/bin/otool', ['-L', helper]).includes('@loader_path/libwcdb_api.dylib')) {
|
||||||
|
throw new Error('Staged helper lost its @loader_path WCDB dependency')
|
||||||
|
}
|
||||||
|
const runtimeManifest = JSON.parse(fs.readFileSync(runtimeManifestPath, 'utf8'))
|
||||||
|
const runtimeBytes = fs.readFileSync(runtimeDylib)
|
||||||
|
if (
|
||||||
|
runtimeManifest.runtime !== 'tm-wechat-native' ||
|
||||||
|
runtimeManifest.platform !== 'darwin-arm64' ||
|
||||||
|
runtimeManifest.architecture !== 'arm64' ||
|
||||||
|
runtimeManifest.protocolVersion !== 1
|
||||||
|
) {
|
||||||
|
throw new Error('Staged Runtime Manifest identity is invalid')
|
||||||
|
}
|
||||||
|
for (const key of ['tmSendSourceSha256', 'addressProfileSha256']) {
|
||||||
|
if (
|
||||||
|
!/^[a-f0-9]{64}$/.test(runtimeManifest[key] || '') ||
|
||||||
|
!runtimeBytes.includes(Buffer.from(runtimeManifest[key]))
|
||||||
|
) {
|
||||||
|
throw new Error(`Staged runtime hash verification failed: ${key}`)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (require.main === module) {
|
||||||
|
try {
|
||||||
|
prepareEdition(process.argv[2]).catch((error) => {
|
||||||
|
console.error(error instanceof Error ? error.message : String(error))
|
||||||
|
process.exitCode = 1
|
||||||
|
})
|
||||||
|
} catch (error) {
|
||||||
|
console.error(error instanceof Error ? error.message : String(error))
|
||||||
|
process.exitCode = 1
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = {
|
||||||
|
resolveEditionRoots,
|
||||||
|
validateLicenseStatusRoute,
|
||||||
|
assertNoProtectedInputs,
|
||||||
|
assertStagingTargetDoesNotExist,
|
||||||
|
copyPublicResources,
|
||||||
|
copyFfmpegLicenses,
|
||||||
|
downloadFfmpegArm64,
|
||||||
|
prepareFfmpeg,
|
||||||
|
prepareEdition,
|
||||||
|
validateNativeBundleFromStaging,
|
||||||
|
validateStagedEdition,
|
||||||
|
readAndValidateNativeManifest,
|
||||||
|
validateNativeBundle,
|
||||||
|
validateWcdbPair
|
||||||
|
}
|
||||||
@@ -67,4 +67,34 @@ assert.match(
|
|||||||
/https:\/\/example\.com\/skill/
|
/https:\/\/example\.com\/skill/
|
||||||
)
|
)
|
||||||
|
|
||||||
|
// source.version 曾经是死字段:传进来却被模板丢掉,于是安装指令不携带任何版本信息。
|
||||||
|
for (const target of ['codex', 'claude-code', 'openclaw', 'generic']) {
|
||||||
|
const text = buildSkillInstallInstruction({
|
||||||
|
target,
|
||||||
|
source: { ...local, version: '9.9.9' },
|
||||||
|
apiBaseUrl: { host: '127.0.0.1', port: 6131 }
|
||||||
|
})
|
||||||
|
assert.match(text, /Skill 版本是 9\.9\.9/, `${target} 指令应携带 source.version`)
|
||||||
|
assert.doesNotMatch(text, /v1\.0/, `${target} 不应残留 fixture 的旧版本号`)
|
||||||
|
assert.match(text, /覆盖/, `${target} 指令应说明用新版本覆盖旧版本`)
|
||||||
|
}
|
||||||
|
|
||||||
|
// 指令要同时提醒 Agent 做版本自检,否则更新机制又只能靠人记得。
|
||||||
|
const selfCheckText = buildSkillInstallInstruction({
|
||||||
|
target: 'codex',
|
||||||
|
source: local,
|
||||||
|
apiBaseUrl: { host: '127.0.0.1', port: 6131 }
|
||||||
|
})
|
||||||
|
assert.match(selfCheckText, /版本自检/)
|
||||||
|
assert.match(selfCheckText, /skill\.version/)
|
||||||
|
|
||||||
|
// 没有版本号时不编造:不输出版本段,其余指令保持可用。
|
||||||
|
const withoutVersion = buildSkillInstallInstruction({
|
||||||
|
target: 'codex',
|
||||||
|
source: { type: 'local', directoryPath: 'C:/skill/tracememo-reader', skillPath: 'x' },
|
||||||
|
apiBaseUrl: { host: '127.0.0.1', port: 6131 }
|
||||||
|
})
|
||||||
|
assert.doesNotMatch(withoutVersion, /Skill 版本是/)
|
||||||
|
assert.match(withoutVersion, /TRACEMEMO_API_TOKEN/)
|
||||||
|
|
||||||
console.log('skill install instruction tests passed')
|
console.log('skill install instruction tests passed')
|
||||||
@@ -0,0 +1,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()
|
||||||
|
}
|
||||||
+822
-68
File diff suppressed because it is too large.
Load diff
@@ -5,7 +5,7 @@ import os from 'os'
|
|||||||
import { app } from 'electron'
|
import { app } from 'electron'
|
||||||
import { execFile } from 'child_process'
|
import { execFile } from 'child_process'
|
||||||
import { Worker } from 'worker_threads'
|
import { Worker } from 'worker_threads'
|
||||||
import ffmpegStaticPath from 'ffmpeg-static'
|
import { resolveBundledFfmpegPath } from './ffmpeg-path'
|
||||||
import type { ImageDecoderSource, ImageDecoderStatus } from '../shared/image-decryption'
|
import type { ImageDecoderSource, ImageDecoderStatus } from '../shared/image-decryption'
|
||||||
import { imageFileQuality, imageQualityRank } from '../shared/image-quality'
|
import { imageFileQuality, imageQualityRank } from '../shared/image-quality'
|
||||||
import { loadSettings } from './services/settings-store'
|
import { loadSettings } from './services/settings-store'
|
||||||
@@ -78,9 +78,7 @@ function getFfmpegCandidates(selectedPath = loadSettings().ffmpegPath): FfmpegCa
|
|||||||
const selected = String(selectedPath || '').trim()
|
const selected = String(selectedPath || '').trim()
|
||||||
const environment = String(process.env['FFMPEG_BIN'] || '').trim()
|
const environment = String(process.env['FFMPEG_BIN'] || '').trim()
|
||||||
const executable = process.platform === 'win32' ? 'ffmpeg.exe' : 'ffmpeg'
|
const executable = process.platform === 'win32' ? 'ffmpeg.exe' : 'ffmpeg'
|
||||||
const staticExecutable = String(ffmpegStaticPath || '')
|
const staticExecutable = resolveBundledFfmpegPath()
|
||||||
.replace('app.asar', 'app.asar.unpacked')
|
|
||||||
.trim()
|
|
||||||
const candidates: FfmpegCandidate[] = [
|
const candidates: FfmpegCandidate[] = [
|
||||||
...(selected ? [{ executable: selected, source: 'selected' as const }] : []),
|
...(selected ? [{ executable: selected, source: 'selected' as const }] : []),
|
||||||
...(environment ? [{ executable: environment, source: 'environment' as const }] : []),
|
...(environment ? [{ executable: environment, source: 'environment' as const }] : []),
|
||||||
|
|||||||
+887
-18
File diff suppressed because it is too large.
Load diff
@@ -7,6 +7,8 @@ import { isValidDatabaseKey } from './database-key-store'
|
|||||||
import crypto from 'crypto'
|
import crypto from 'crypto'
|
||||||
import { findResource, getResourceCandidates } from './resource-paths'
|
import { findResource, getResourceCandidates } from './resource-paths'
|
||||||
import { detectWechatVersion } from './services/connection-diagnostics'
|
import { detectWechatVersion } from './services/connection-diagnostics'
|
||||||
|
import { getMacArchSnapshot } from './macos-arch'
|
||||||
|
import { ARCH_MISMATCH_X64_ON_ARM_ERROR, shouldProbeIntelEnvironment } from '../shared/macos-arch'
|
||||||
|
|
||||||
const execFileAsync = promisify(execFile)
|
const execFileAsync = promisify(execFile)
|
||||||
|
|
||||||
@@ -239,6 +241,15 @@ export class KeyServiceMac {
|
|||||||
fridaAvailable: boolean
|
fridaAvailable: boolean
|
||||||
wechatAdhocSigned: boolean
|
wechatAdhocSigned: boolean
|
||||||
}> {
|
}> {
|
||||||
|
// 方法内部再守一道:调用方漏判时也不能起 x86 helper。
|
||||||
|
if (!shouldProbeIntelEnvironment(getMacArchSnapshot().macKeyFlow)) {
|
||||||
|
return {
|
||||||
|
sipDisabled: false,
|
||||||
|
pythonAvailable: false,
|
||||||
|
fridaAvailable: false,
|
||||||
|
wechatAdhocSigned: false
|
||||||
|
}
|
||||||
|
}
|
||||||
const payload = await this.runMacKeyTool(
|
const payload = await this.runMacKeyTool(
|
||||||
['status', '--runtime-dir', this.getMacKeyRuntimeDir()],
|
['status', '--runtime-dir', this.getMacKeyRuntimeDir()],
|
||||||
15_000
|
15_000
|
||||||
@@ -254,7 +265,15 @@ export class KeyServiceMac {
|
|||||||
async installIntelKeyRuntime(
|
async installIntelKeyRuntime(
|
||||||
onStatus?: (message: string) => void
|
onStatus?: (message: string) => void
|
||||||
): Promise<{ success: boolean; error?: string; code?: string }> {
|
): Promise<{ success: boolean; error?: string; code?: string }> {
|
||||||
if (process.platform !== 'darwin' || process.arch !== 'x64') {
|
const arch = getMacArchSnapshot()
|
||||||
|
if (arch.macKeyFlow === 'arch-mismatch') {
|
||||||
|
return {
|
||||||
|
success: false,
|
||||||
|
code: 'ARCH_MISMATCH_X64_ON_ARM',
|
||||||
|
error: ARCH_MISMATCH_X64_ON_ARM_ERROR
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (arch.macKeyFlow !== 'intel') {
|
||||||
return { success: false, code: 'UNSUPPORTED_PLATFORM', error: '仅 Intel Mac 需要安装此运行环境' }
|
return { success: false, code: 'UNSUPPORTED_PLATFORM', error: '仅 Intel Mac 需要安装此运行环境' }
|
||||||
}
|
}
|
||||||
onStatus?.('正在准备连接环境,请保持网络连接…')
|
onStatus?.('正在准备连接环境,请保持网络连接…')
|
||||||
@@ -354,12 +373,25 @@ export class KeyServiceMac {
|
|||||||
if (process.platform !== 'darwin') {
|
if (process.platform !== 'darwin') {
|
||||||
return { success: false, error: '自动获取密钥目前仅支持 macOS' }
|
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()) {
|
if (await this.isSipEnabled()) {
|
||||||
return { success: false, code: 'SIP_ENABLED', error: SIP_ENABLED_ERROR }
|
return { success: false, code: 'SIP_ENABLED', error: SIP_ENABLED_ERROR }
|
||||||
}
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
if (process.arch === 'x64') {
|
if (arch.macKeyFlow === 'intel') {
|
||||||
onStatus?.('Intel Mac 将通过 Frida 获取微信主密钥,请让微信停留在未登录界面')
|
onStatus?.('Intel Mac 将通过 Frida 获取微信主密钥,请让微信停留在未登录界面')
|
||||||
const result = await this.captureIntelDbKey(accountRoot, timeoutMs, onStatus)
|
const result = await this.captureIntelDbKey(accountRoot, timeoutMs, onStatus)
|
||||||
onStatus?.(result.success ? '密钥获取成功' : '密钥获取失败')
|
onStatus?.(result.success ? '密钥获取成功' : '密钥获取失败')
|
||||||
|
|||||||
@@ -689,7 +689,7 @@ export class KeyService {
|
|||||||
return {
|
return {
|
||||||
success: false,
|
success: false,
|
||||||
error:
|
error:
|
||||||
'微信可能已经启动并登录,请先在微信客户端保持未登录状态,具体点击上方“查看5分钟上手教程” ',
|
'微信可能没有在上一步点击微信登录,请先在微信客户端保持未登录状态,具体点击上方“查看5分钟上手教程” ',
|
||||||
logs
|
logs
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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
|
||||||
|
}
|
||||||
@@ -0,0 +1,90 @@
|
|||||||
|
import fs from 'node:fs'
|
||||||
|
import path from 'node:path'
|
||||||
|
import { app } from 'electron'
|
||||||
|
|
||||||
|
import { findResource } from './resource-paths'
|
||||||
|
|
||||||
|
export type NativeRuntimeProfile = 'public' | 'native'
|
||||||
|
|
||||||
|
const BUILD_MARKER = 'tracememo-build.json'
|
||||||
|
const RUNTIME_RELATIVE = 'runtime/darwin-arm64'
|
||||||
|
|
||||||
|
let cachedProfile: NativeRuntimeProfile | null = null
|
||||||
|
let cachedMarkerRead = false
|
||||||
|
|
||||||
|
function getNativeRuntimeProfile(): NativeRuntimeProfile {
|
||||||
|
const envProfile = !app.isPackaged ? process.env.TRACEMEMO_RUNTIME_PROFILE : undefined
|
||||||
|
if (envProfile === 'public' || envProfile === 'native') return envProfile
|
||||||
|
if (cachedMarkerRead && cachedProfile) return cachedProfile
|
||||||
|
cachedMarkerRead = true
|
||||||
|
const marker = findResource(BUILD_MARKER)
|
||||||
|
if (marker) {
|
||||||
|
try {
|
||||||
|
const parsed = JSON.parse(fs.readFileSync(marker, 'utf8')) as { profile?: unknown }
|
||||||
|
if (parsed.profile === 'public' || parsed.profile === 'native') {
|
||||||
|
cachedProfile = app.isPackaged ? parsed.profile : 'native'
|
||||||
|
return cachedProfile
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
// Packaged builds fail closed below when the marker cannot be read.
|
||||||
|
}
|
||||||
|
}
|
||||||
|
cachedProfile = app.isPackaged ? 'public' : 'native'
|
||||||
|
return cachedProfile
|
||||||
|
}
|
||||||
|
|
||||||
|
export function hasMacNativeBundle(): boolean {
|
||||||
|
return process.platform === 'darwin' && getNativeRuntimeProfile() === 'native'
|
||||||
|
}
|
||||||
|
|
||||||
|
export function isMacNativeRuntimeUnavailable(): boolean {
|
||||||
|
return process.platform === 'darwin' && !hasMacNativeBundle()
|
||||||
|
}
|
||||||
|
|
||||||
|
export function resolveWcdbLibrary(): string | null {
|
||||||
|
if (process.platform !== 'darwin') return null
|
||||||
|
const arch = process.arch === 'arm64' ? 'arm64' : 'x64'
|
||||||
|
return findResource(`wcdb/macos/${arch}/libwcdb_api.dylib`)
|
||||||
|
}
|
||||||
|
|
||||||
|
export function resolveWcdbDependency(): string | null {
|
||||||
|
const library = resolveWcdbLibrary()
|
||||||
|
if (!library) return null
|
||||||
|
const dependency = path.join(path.dirname(library), 'libWCDB.dylib')
|
||||||
|
return fs.existsSync(dependency) ? dependency : null
|
||||||
|
}
|
||||||
|
|
||||||
|
export function resolveWcdbConfigHelper(): string | null {
|
||||||
|
if (isMacNativeRuntimeUnavailable()) return null
|
||||||
|
const arch = process.arch === 'arm64' ? 'arm64' : 'x64'
|
||||||
|
return findResource(`wcdb/macos/${arch}/tm-wcdb-config-helper`)
|
||||||
|
}
|
||||||
|
|
||||||
|
export function resolveWechatRuntimeDirectory(): string | null {
|
||||||
|
if (!hasMacNativeBundle()) return null
|
||||||
|
const manifest =
|
||||||
|
findResource(`${RUNTIME_RELATIVE}/runtime-manifest.json`) ||
|
||||||
|
(!app.isPackaged ? findResource('runtime/darwin-arm64/runtime-manifest.json') : null)
|
||||||
|
return manifest ? path.dirname(manifest) : null
|
||||||
|
}
|
||||||
|
|
||||||
|
export function resolveWechatHost(): string | null {
|
||||||
|
const directory = resolveWechatRuntimeDirectory()
|
||||||
|
if (!directory) return null
|
||||||
|
const candidate = path.join(directory, 'tm-wechat-host')
|
||||||
|
return fs.existsSync(candidate) ? candidate : null
|
||||||
|
}
|
||||||
|
|
||||||
|
export function resolveWechatDylib(): string | null {
|
||||||
|
const directory = resolveWechatRuntimeDirectory()
|
||||||
|
if (!directory) return null
|
||||||
|
const candidate = path.join(directory, 'libtmwechat.dylib')
|
||||||
|
return fs.existsSync(candidate) ? candidate : null
|
||||||
|
}
|
||||||
|
|
||||||
|
export function resolveWechatRuntimeManifest(): string | null {
|
||||||
|
const directory = resolveWechatRuntimeDirectory()
|
||||||
|
if (!directory) return null
|
||||||
|
const candidate = path.join(directory, 'runtime-manifest.json')
|
||||||
|
return fs.existsSync(candidate) ? candidate : null
|
||||||
|
}
|
||||||
@@ -230,7 +230,12 @@ function builtInTemplate(template: ReportTemplateDefinition): InstalledReportTem
|
|||||||
}
|
}
|
||||||
|
|
||||||
export class ReportTemplateService {
|
export class ReportTemplateService {
|
||||||
private readonly directory = rootPath()
|
/* 延迟到首次真正用到时再取 app.getPath('userData')。
|
||||||
|
* 这个类在模块顶层被 new(见文件末尾),而 import 顺序一变,模块就可能
|
||||||
|
* 在 electron.app 可用之前被 require —— 那时 app 是 undefined,getPath 直接抛。 */
|
||||||
|
private get directory(): string {
|
||||||
|
return rootPath()
|
||||||
|
}
|
||||||
|
|
||||||
async list(): Promise<InstalledReportTemplate[]> {
|
async list(): Promise<InstalledReportTemplate[]> {
|
||||||
await fs.mkdir(path.join(this.directory, INSTALLED_DIR), { recursive: true })
|
await fs.mkdir(path.join(this.directory, INSTALLED_DIR), { recursive: true })
|
||||||
|
|||||||
@@ -7,6 +7,10 @@ function unique(values: string[]): string[] {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export function getResourceRoots(): string[] {
|
export function getResourceRoots(): string[] {
|
||||||
|
if (app.isPackaged && process.platform === 'darwin') {
|
||||||
|
const packagedResources = join(process.resourcesPath || '', 'resources')
|
||||||
|
return existsSync(packagedResources) ? [packagedResources] : []
|
||||||
|
}
|
||||||
const appPath = app.getAppPath()
|
const appPath = app.getAppPath()
|
||||||
const appPathDir = dirname(appPath)
|
const appPathDir = dirname(appPath)
|
||||||
const execDir = dirname(process.execPath)
|
const execDir = dirname(process.execPath)
|
||||||
|
|||||||
@@ -5,8 +5,13 @@ import { join } from 'path'
|
|||||||
export function isPackagedRuntime(): boolean {
|
export function isPackagedRuntime(): boolean {
|
||||||
if (app.isPackaged) return true
|
if (app.isPackaged) return true
|
||||||
|
|
||||||
|
// 非 Electron 进程(例如单元/集成测试)里 process.resourcesPath 不存在,
|
||||||
|
// 此时 join 会抛错。没有 resources 目录就必然不是打包运行时。
|
||||||
|
const resourcesPath = process.resourcesPath
|
||||||
|
if (!resourcesPath) return false
|
||||||
|
|
||||||
return (
|
return (
|
||||||
existsSync(join(process.resourcesPath, 'app.asar')) &&
|
existsSync(join(resourcesPath, 'app.asar')) &&
|
||||||
existsSync(join(process.resourcesPath, 'app-update.yml'))
|
existsSync(join(resourcesPath, 'app-update.yml'))
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
@@ -148,12 +148,48 @@ export function resolveInboundRoute(text: string): InboundRoute {
|
|||||||
/** 查询大脑不可用时的统一文案(不暴露 stack / provider raw response / 内部 id)。 */
|
/** 查询大脑不可用时的统一文案(不暴露 stack / provider raw response / 内部 id)。 */
|
||||||
export const QUERY_AGENT_UNAVAILABLE_TEXT = '当前 AI 查询服务暂时不可用,请稍后再试。'
|
export const QUERY_AGENT_UNAVAILABLE_TEXT = '当前 AI 查询服务暂时不可用,请稍后再试。'
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 桌面 UI 的 inline citation(`[E6]`)在微信里**没有落点** ——
|
||||||
|
* 点不开、也没有证据卡可以对照,留在正文里纯属噪音。下发前一律剥离。
|
||||||
|
*
|
||||||
|
* 只吃行内空格(`[ \t]`)而不是 `\s`:引用可能独占一行,用 `\s*` 会把上一行的换行
|
||||||
|
* 一起吞掉,把两行粘成一行。
|
||||||
|
*/
|
||||||
|
const INLINE_CITATION_PATTERN = /[ \t]*\[E\d+\]/g
|
||||||
|
|
||||||
|
function stripInlineCitations(text: string): string {
|
||||||
|
return text.replace(INLINE_CITATION_PATTERN, '').replace(/[ \t]+$/gm, '')
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 微信气泡的换行规则:**单个 `\n` 会被压成空格,只有空行(`\n\n`)才真的换行**。
|
||||||
|
*
|
||||||
|
* 所以列表项之间必须用**空行**分隔:单换行等于白发,多条 bullet 会被挤成一整段。
|
||||||
|
*
|
||||||
|
* 顺带把 Markdown 列表标记(`-` / `*` / `+`)统一成 `• `:下游
|
||||||
|
* `markdownToPlainText()` 虽然也做这一步,但它只保证 `• `、不保证前面有空行,
|
||||||
|
* 在这里先接住才能拿到正确行距。
|
||||||
|
*/
|
||||||
|
export function formatWechatReplyText(content: string): string {
|
||||||
|
return content
|
||||||
|
.replace(/\r\n?/g, '\n')
|
||||||
|
.replace(/^[ \t]*[-*+][ \t]+/gm, '• ')
|
||||||
|
.replace(/[ \t]*•[ \t]*/g, '\n\n• ')
|
||||||
|
.replace(/[ \t]+(?=\d+[.、][ \t])/g, '\n\n')
|
||||||
|
.replace(/\n{3,}/g, '\n\n')
|
||||||
|
.trim()
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 把 Query Agent 结果映射成**微信文字回复**。
|
* 把 Query Agent 结果映射成**微信文字回复**。
|
||||||
* 只输出用户可读文本;Tool trace / temporalBasis / Evidence / 诊断字段一律不下发。
|
* 只输出用户可读文本;Tool trace / temporalBasis / Evidence / 诊断字段一律不下发。
|
||||||
*/
|
*/
|
||||||
export function queryAgentReplyText(result: AskWechatQueryResult): string {
|
export function queryAgentReplyText(result: AskWechatQueryResult): string {
|
||||||
if (result.status === 'answered') return result.answer
|
if (result.status === 'answered') {
|
||||||
|
const text = stripInlineCitations(result.answer).trim()
|
||||||
|
// 极端情况(整段只有引用编号)宁可原样下发,也不能发一条空消息出去。
|
||||||
|
return text || result.answer.trim()
|
||||||
|
}
|
||||||
if (result.status === 'provider_unavailable' || result.status === 'error') return result.message
|
if (result.status === 'provider_unavailable' || result.status === 'error') return result.message
|
||||||
// Agent Hub 没有 Legacy runner,不会产生 legacy 结果;真出现时按服务不可用处理,不暴露内部结构。
|
// Agent Hub 没有 Legacy runner,不会产生 legacy 结果;真出现时按服务不可用处理,不暴露内部结构。
|
||||||
return QUERY_AGENT_UNAVAILABLE_TEXT
|
return QUERY_AGENT_UNAVAILABLE_TEXT
|
||||||
|
|||||||
@@ -17,6 +17,7 @@ import { QueryAgentService } from './query-agent-service'
|
|||||||
import { AskWechatService } from './ask-wechat-service'
|
import { AskWechatService } from './ask-wechat-service'
|
||||||
import {
|
import {
|
||||||
QUERY_AGENT_UNAVAILABLE_TEXT,
|
QUERY_AGENT_UNAVAILABLE_TEXT,
|
||||||
|
formatWechatReplyText,
|
||||||
queryAgentReplyText,
|
queryAgentReplyText,
|
||||||
resolveInboundRoute,
|
resolveInboundRoute,
|
||||||
type GroupMemberChatIntent,
|
type GroupMemberChatIntent,
|
||||||
@@ -700,7 +701,7 @@ export class AgentHubService {
|
|||||||
{ requestId: `agent-hub-${Date.now()}-${this.nextLogId}`, text },
|
{ requestId: `agent-hub-${Date.now()}-${this.nextLogId}`, text },
|
||||||
conversationKey
|
conversationKey
|
||||||
)
|
)
|
||||||
await this.sendToConversation(conversation, this.formatAIReply(queryAgentReplyText(result)))
|
await this.sendToConversation(conversation, formatWechatReplyText(queryAgentReplyText(result)))
|
||||||
this.addLog('agent-hub', 'info', `查询回答已发送(${result.status})`)
|
this.addLog('agent-hub', 'info', `查询回答已发送(${result.status})`)
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
this.addLog('agent-hub', 'error', `查询处理失败:${this.errorMessage(error)}`)
|
this.addLog('agent-hub', 'error', `查询处理失败:${this.errorMessage(error)}`)
|
||||||
@@ -834,7 +835,7 @@ export class AgentHubService {
|
|||||||
}
|
}
|
||||||
await this.sendToConversation(
|
await this.sendToConversation(
|
||||||
conversation,
|
conversation,
|
||||||
this.formatAIReply(
|
formatWechatReplyText(
|
||||||
`${displayName}在“${group.m_nsNickName}”的发言总结(共 ${messages.length} 条):\n\n${summary.data.trim().slice(0, 3500)}`
|
`${displayName}在“${group.m_nsNickName}”的发言总结(共 ${messages.length} 条):\n\n${summary.data.trim().slice(0, 3500)}`
|
||||||
)
|
)
|
||||||
)
|
)
|
||||||
@@ -850,15 +851,6 @@ export class AgentHubService {
|
|||||||
return `[${label}]`
|
return `[${label}]`
|
||||||
}
|
}
|
||||||
|
|
||||||
private formatAIReply(content: string): string {
|
|
||||||
return content
|
|
||||||
.replace(/\r\n?/g, '\n')
|
|
||||||
.replace(/[ \t]*•[ \t]*/g, '\n• ')
|
|
||||||
.replace(/[ \t]+(?=\d+[.、][ \t])/g, '\n')
|
|
||||||
.replace(/\n{3,}/g, '\n\n')
|
|
||||||
.trim()
|
|
||||||
}
|
|
||||||
|
|
||||||
private async generateAndSendReport(
|
private async generateAndSendReport(
|
||||||
conversation: AgentHubTarget,
|
conversation: AgentHubTarget,
|
||||||
intent: GroupReportIntent
|
intent: GroupReportIntent
|
||||||
|
|||||||
@@ -96,7 +96,15 @@ export class AIProviderRequestError extends Error {
|
|||||||
|
|
||||||
constructor(
|
constructor(
|
||||||
message: string,
|
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)
|
super(message)
|
||||||
this.name = 'AIProviderRequestError'
|
this.name = 'AIProviderRequestError'
|
||||||
@@ -358,7 +366,10 @@ export class AIProviderService {
|
|||||||
try {
|
try {
|
||||||
if (options?.apiKey) throw new Error('Tool Calling 不支持 legacy provider 配置')
|
if (options?.apiKey) throw new Error('Tool Calling 不支持 legacy provider 配置')
|
||||||
const resolved = this.resolveProvider(options)
|
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')
|
throw new Error('当前 Provider 协议暂不支持 Tool Calling POC')
|
||||||
}
|
}
|
||||||
const result = await requestOpenAICompatibleWithTools(
|
const result = await requestOpenAICompatibleWithTools(
|
||||||
@@ -377,7 +388,8 @@ export class AIProviderService {
|
|||||||
success: false,
|
success: false,
|
||||||
error: safeAIError(error),
|
error: safeAIError(error),
|
||||||
timedOut,
|
timedOut,
|
||||||
htmlInsteadOfJson: error instanceof AIProviderRequestError ? Boolean(error.htmlInsteadOfJson) : false,
|
htmlInsteadOfJson:
|
||||||
|
error instanceof AIProviderRequestError ? Boolean(error.htmlInsteadOfJson) : false,
|
||||||
...(error instanceof AIProviderRequestError
|
...(error instanceof AIProviderRequestError
|
||||||
? {
|
? {
|
||||||
...(error.status !== undefined ? { errorStatus: error.status } : {}),
|
...(error.status !== undefined ? { errorStatus: error.status } : {}),
|
||||||
@@ -638,7 +650,7 @@ function deepSeekProvider(baseUrl?: string, model?: string): AIProviderSummary {
|
|||||||
}
|
}
|
||||||
],
|
],
|
||||||
defaultModel: modelId,
|
defaultModel: modelId,
|
||||||
advanced: { timeoutMs: 120_000, temperature: 0.7, maxTokens: 4096, extraHeaders: {} },
|
advanced: { timeoutMs: 120_000, temperature: 0.7, maxTokens: 40960, extraHeaders: {} },
|
||||||
hasApiKey: false,
|
hasApiKey: false,
|
||||||
isDefault: true,
|
isDefault: true,
|
||||||
status: 'untested'
|
status: 'untested'
|
||||||
@@ -981,7 +993,12 @@ async function requestOpenAICompatibleWithTools(
|
|||||||
messages: Array<Record<string, unknown>>,
|
messages: Array<Record<string, unknown>>,
|
||||||
tools: AIChatToolDefinition[],
|
tools: AIChatToolDefinition[],
|
||||||
signal?: AbortSignal
|
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')
|
const endpoint = provider.baseUrl.endsWith('/chat/completions')
|
||||||
? provider.baseUrl
|
? provider.baseUrl
|
||||||
: `${provider.baseUrl.replace(/\/+$/, '')}/chat/completions`
|
: `${provider.baseUrl.replace(/\/+$/, '')}/chat/completions`
|
||||||
@@ -1013,7 +1030,8 @@ async function requestOpenAICompatibleWithTools(
|
|||||||
}
|
}
|
||||||
if (!response.ok) {
|
if (!response.ok) {
|
||||||
throw new AIProviderRequestError(
|
throw new AIProviderRequestError(
|
||||||
payload?.error?.message || (parseError ? safeAIError(parseError) : `AI 请求失败 (${response.status})`),
|
payload?.error?.message ||
|
||||||
|
(parseError ? safeAIError(parseError) : `AI 请求失败 (${response.status})`),
|
||||||
{
|
{
|
||||||
status: timing.status,
|
status: timing.status,
|
||||||
contentType: timing.contentType,
|
contentType: timing.contentType,
|
||||||
@@ -1034,7 +1052,13 @@ async function requestOpenAICompatibleWithTools(
|
|||||||
toolCalls: (message?.tool_calls || []).flatMap((call, index) => {
|
toolCalls: (message?.tool_calls || []).flatMap((call, index) => {
|
||||||
const name = call.function?.name
|
const name = call.function?.name
|
||||||
if (!name) return []
|
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),
|
usage: toOpenAIUsage(payload.usage),
|
||||||
elapsedMs: timing.elapsedMs
|
elapsedMs: timing.elapsedMs
|
||||||
|
|||||||
@@ -337,6 +337,19 @@ export class AutomationActionRunner {
|
|||||||
return { steps, status: 'failed', errorSummary: reportStep.error }
|
return { steps, status: 'failed', errorSummary: reportStep.error }
|
||||||
}
|
}
|
||||||
pngPath = result.pngPath
|
pngPath = result.pngPath
|
||||||
|
const persisted = await this.persistRunReport(input, result)
|
||||||
|
if (persisted.ok) {
|
||||||
|
// 发出去的图就是日报历史里的那一份(同一文件),避免「历史一张、发出去另一张」。
|
||||||
|
pngPath = persisted.pngPath || pngPath
|
||||||
|
} else {
|
||||||
|
/*
|
||||||
|
* 落库失败**不阻断发送**:日报确实生成了、图片已经在手上,把它扣下不发对用户没有任何好处。
|
||||||
|
* 但也**绝不假装没事** —— 失败会写进步骤细节,用户在执行详情里一眼能看见。
|
||||||
|
* 细节文案刻意不带原始错误串(fs 报错常含本地绝对路径),原始错误只进主进程日志。
|
||||||
|
*/
|
||||||
|
reportStep.detail = '日报已生成,但未写入日报历史。'
|
||||||
|
console.warn('[Automation] 日报历史写入失败:', persisted.error)
|
||||||
|
}
|
||||||
markSuccess(reportStep, this.now())
|
markSuccess(reportStep, this.now())
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -369,6 +382,61 @@ export class AutomationActionRunner {
|
|||||||
return { steps, status: 'success', pngPath }
|
return { steps, status: 'success', pngPath }
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 把「@我生成日报」产出的日报写进**日报历史**。
|
||||||
|
*
|
||||||
|
* 与定时日报共用同一个 `saveGeneratedReport`(同一条历史、同一个日报页),
|
||||||
|
* 唯一差别是 `source: 'automation'` —— 让用户能区分这条日报是谁触发的。
|
||||||
|
*
|
||||||
|
* 为什么必须在这里补:`run()` 只把 PNG 交给发送,图发出去之后**没有任何地方**
|
||||||
|
* 再碰这份日报。此前只有 `runScheduledReport` 落库,于是消息型规则产出的日报
|
||||||
|
* 在日报历史里**从来没存在过**(发出去的那张图成了孤儿)。
|
||||||
|
*
|
||||||
|
* 失败语义与 `runScheduledReport` **刻意不同**:那边发的是历史里的文件、落库是发送的前置,
|
||||||
|
* 所以落库失败即整次失败;这里图片已经在手上,落库失败只降级成一句提示,不阻断发送。
|
||||||
|
*/
|
||||||
|
private async persistRunReport(
|
||||||
|
input: AutomationRunInput,
|
||||||
|
generated: AgentGroupReportResult
|
||||||
|
): Promise<{ ok: boolean; error?: string; pngPath?: string }> {
|
||||||
|
try {
|
||||||
|
const reportContact = this.resolveReportContact(input.conversationId)
|
||||||
|
let contactAvatar = reportContact?.avatar
|
||||||
|
if (!contactAvatar && reportContact?.m_nsUsrName) {
|
||||||
|
try {
|
||||||
|
const avatars = await this.getContactAvatars([reportContact.m_nsUsrName])
|
||||||
|
contactAvatar = avatars[reportContact.m_nsUsrName]
|
||||||
|
} catch (error) {
|
||||||
|
console.warn('[Automation] 日报群头像补全失败:', error)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const saved = await this.saveGeneratedReport({
|
||||||
|
contactId: reportContact?.md5 || input.conversationId,
|
||||||
|
contactName:
|
||||||
|
generated.groupName || reportContact?.m_nsNickName || input.sourceDisplayName || '群聊',
|
||||||
|
contactAvatar,
|
||||||
|
source: 'automation',
|
||||||
|
dateRange: generated.reportMetadata?.dateRange || scheduledReportRangeLabel('today'),
|
||||||
|
reportDate: generated.reportMetadata?.reportDate,
|
||||||
|
messageCount: generated.messageCount ?? generated.reportMetadata?.messageCount ?? 0,
|
||||||
|
generatedAt: new Date(this.now()).toISOString(),
|
||||||
|
htmlPath: generated.htmlPath,
|
||||||
|
pngPath: generated.pngPath,
|
||||||
|
duration: generated.duration,
|
||||||
|
modelName: generated.modelName,
|
||||||
|
tokenUsage: generated.tokenUsage,
|
||||||
|
reportSnapshot: generated.reportSnapshot,
|
||||||
|
reportMetadata: generated.reportMetadata
|
||||||
|
})
|
||||||
|
if (!saved.success) {
|
||||||
|
return { ok: false, error: saved.error || '日报历史保存失败' }
|
||||||
|
}
|
||||||
|
return { ok: true, ...(saved.record?.pngPath ? { pngPath: saved.record.pngPath } : {}) }
|
||||||
|
} catch (error) {
|
||||||
|
return { ok: false, error: error instanceof Error ? error.message : String(error) }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 定时日报:把一次「到点触发 / 手动立即执行」跑成一次生成 + 一次发送。
|
* 定时日报:把一次「到点触发 / 手动立即执行」跑成一次生成 + 一次发送。
|
||||||
*
|
*
|
||||||
|
|||||||
@@ -50,6 +50,13 @@ const LEGACY_SCHEDULED_TASKS_FILE = 'tasks.json'
|
|||||||
const SCHEDULED_MIGRATION_BACKUP_FILE = 'scheduled-report-migration-backup.json'
|
const SCHEDULED_MIGRATION_BACKUP_FILE = 'scheduled-report-migration-backup.json'
|
||||||
const CURRENT_VERSION = 4
|
const CURRENT_VERSION = 4
|
||||||
|
|
||||||
|
export class AutomationRulePersistenceError extends Error {
|
||||||
|
constructor() {
|
||||||
|
super('自动化规则保存失败')
|
||||||
|
this.name = 'AutomationRulePersistenceError'
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
interface StoredRules {
|
interface StoredRules {
|
||||||
version: number
|
version: number
|
||||||
/** 内置「@我生成日报」是否已经播种过。**即使随后被删除也保持 true**。 */
|
/** 内置「@我生成日报」是否已经播种过。**即使随后被删除也保持 true**。 */
|
||||||
@@ -231,7 +238,8 @@ export class AutomationRuleStore {
|
|||||||
this.legacyConversationResolver = resolver
|
this.legacyConversationResolver = resolver
|
||||||
if (!this.loaded) return
|
if (!this.loaded) return
|
||||||
if (this.state.scheduledReportMigrated) return
|
if (this.state.scheduledReportMigrated) return
|
||||||
if (this.runScheduledReportMigration(this.state)) this.persist()
|
const next = structuredClone(this.state)
|
||||||
|
if (this.runScheduledReportMigration(next)) this.commitState(next)
|
||||||
}
|
}
|
||||||
|
|
||||||
/** 旧定时日报迁移是否仍在等待解析器(仅用于启动日志与测试断言)。 */
|
/** 旧定时日报迁移是否仍在等待解析器(仅用于启动日志与测试断言)。 */
|
||||||
@@ -274,8 +282,7 @@ export class AutomationRuleStore {
|
|||||||
createdAt: timestamp,
|
createdAt: timestamp,
|
||||||
updatedAt: timestamp
|
updatedAt: timestamp
|
||||||
}
|
}
|
||||||
this.state.rules = [...this.state.rules, rule]
|
this.commitRules([...this.state.rules, rule])
|
||||||
this.persist()
|
|
||||||
return structuredClone(rule)
|
return structuredClone(rule)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -316,8 +323,7 @@ export class AutomationRuleStore {
|
|||||||
} else {
|
} else {
|
||||||
delete rule.leaveNotification
|
delete rule.leaveNotification
|
||||||
}
|
}
|
||||||
this.state.rules = this.state.rules.map((item, at) => (at === index ? rule : item))
|
this.commitRules(this.state.rules.map((item, at) => (at === index ? rule : item)))
|
||||||
this.persist()
|
|
||||||
return structuredClone(rule)
|
return structuredClone(rule)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -346,8 +352,7 @@ export class AutomationRuleStore {
|
|||||||
createdAt: timestamp,
|
createdAt: timestamp,
|
||||||
updatedAt: timestamp
|
updatedAt: timestamp
|
||||||
}
|
}
|
||||||
this.state.rules = [...this.state.rules, rule]
|
this.commitRules([...this.state.rules, rule])
|
||||||
this.persist()
|
|
||||||
return structuredClone(rule)
|
return structuredClone(rule)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -355,9 +360,9 @@ export class AutomationRuleStore {
|
|||||||
this.ensureLoaded()
|
this.ensureLoaded()
|
||||||
const key = String(id || '').trim()
|
const key = String(id || '').trim()
|
||||||
const before = this.state.rules.length
|
const before = this.state.rules.length
|
||||||
this.state.rules = this.state.rules.filter((rule) => rule.id !== key)
|
const rules = this.state.rules.filter((rule) => rule.id !== key)
|
||||||
if (this.state.rules.length === before) return false
|
if (rules.length === before) return false
|
||||||
this.persist()
|
this.commitRules(rules)
|
||||||
return true
|
return true
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -394,8 +399,7 @@ export class AutomationRuleStore {
|
|||||||
},
|
},
|
||||||
updatedAt: this.now()
|
updatedAt: this.now()
|
||||||
}
|
}
|
||||||
this.state.rules = this.state.rules.map((item, at) => (at === index ? next : item))
|
this.commitRules(this.state.rules.map((item, at) => (at === index ? next : item)))
|
||||||
this.persist()
|
|
||||||
return structuredClone(next)
|
return structuredClone(next)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -428,7 +432,11 @@ export class AutomationRuleStore {
|
|||||||
this.runScheduledReportMigration(stored)
|
this.runScheduledReportMigration(stored)
|
||||||
stored.version = CURRENT_VERSION
|
stored.version = CURRENT_VERSION
|
||||||
this.state = stored
|
this.state = stored
|
||||||
this.persist()
|
try {
|
||||||
|
this.persist()
|
||||||
|
} catch {
|
||||||
|
// Keep the in-memory defaults available; later writes report persistence failures.
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/** 旧退群通知配置 → 内置退群通知规则。**只跑一次**,且先备份旧配置。 */
|
/** 旧退群通知配置 → 内置退群通知规则。**只跑一次**,且先备份旧配置。 */
|
||||||
@@ -641,6 +649,22 @@ export class AutomationRuleStore {
|
|||||||
console.warn(
|
console.warn(
|
||||||
`[Automation] 保存规则失败: ${error instanceof Error ? error.message : String(error)}`
|
`[Automation] 保存规则失败: ${error instanceof Error ? error.message : String(error)}`
|
||||||
)
|
)
|
||||||
|
throw new AutomationRulePersistenceError()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private commitRules(rules: AutomationRule[]): void {
|
||||||
|
this.commitState({ ...this.state, rules })
|
||||||
|
}
|
||||||
|
|
||||||
|
private commitState(next: StoredRules): void {
|
||||||
|
const previous = this.state
|
||||||
|
this.state = next
|
||||||
|
try {
|
||||||
|
this.persist()
|
||||||
|
} catch (error) {
|
||||||
|
this.state = previous
|
||||||
|
throw error
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -14,6 +14,8 @@ import {
|
|||||||
isWindowsVcRuntimeMissingError,
|
isWindowsVcRuntimeMissingError,
|
||||||
WINDOWS_VC_RUNTIME_ERROR_MESSAGE
|
WINDOWS_VC_RUNTIME_ERROR_MESSAGE
|
||||||
} from '../../shared/windows-runtime'
|
} from '../../shared/windows-runtime'
|
||||||
|
import { hasPermissionDeniedText, isPermissionDeniedError } from './path-access-probe'
|
||||||
|
import { getNativeErrorCode } from '../wcdb4-client'
|
||||||
import { mergeRecallArchiveMessages, recordRecallArchiveMessages } from './recall-archive-service'
|
import { mergeRecallArchiveMessages, recordRecallArchiveMessages } from './recall-archive-service'
|
||||||
import type { ExportImageQuality } from '../../shared/image-quality'
|
import type { ExportImageQuality } from '../../shared/image-quality'
|
||||||
import type { ImageMessageCountProbe } from '../../shared/image-text-index'
|
import type { ImageMessageCountProbe } from '../../shared/image-text-index'
|
||||||
@@ -1238,12 +1240,11 @@ export function testConnection(key: string, accountRoot?: string): DatabaseKeyVa
|
|||||||
messages: { available: true, count: messages.length }
|
messages: { available: true, count: messages.length }
|
||||||
}
|
}
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
const detail = error instanceof Error ? error.message : String(error)
|
const code = mapConnectionError(error)
|
||||||
const code = mapConnectionError(detail)
|
|
||||||
return {
|
return {
|
||||||
success: false,
|
success: false,
|
||||||
code,
|
code,
|
||||||
error: DATABASE_KEY_ERROR_MESSAGES[code]
|
error: databaseKeyErrorMessage(code)
|
||||||
}
|
}
|
||||||
} finally {
|
} finally {
|
||||||
try {
|
try {
|
||||||
@@ -1256,20 +1257,68 @@ export function testConnection(key: string, accountRoot?: string): DatabaseKeyVa
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const DATABASE_KEY_ERROR_MESSAGES: Record<DatabaseKeyValidationCode, string> = {
|
/**
|
||||||
|
* macOS 上的权限不足提示。
|
||||||
|
*
|
||||||
|
* 措辞刻意**不写成安装前置条件**:正常连接的用户什么都不该看到,
|
||||||
|
* 只有在真的读到 EPERM / EACCES 时才给出这一步。FDA 是故障恢复方案。
|
||||||
|
*/
|
||||||
|
const DATABASE_PERMISSION_HINT_DARWIN =
|
||||||
|
'TraceMemo 无法读取微信数据库。如果你使用 macOS 27 或更高版本,请在「系统设置 → 隐私与安全性 → 完全磁盘访问权限」中允许 TraceMemo,然后重新启动应用。'
|
||||||
|
|
||||||
|
/** 非 macOS 平台的权限不足提示:不给 macOS 专属指引。 */
|
||||||
|
const DATABASE_PERMISSION_HINT_GENERIC =
|
||||||
|
'TraceMemo 无法读取微信数据库,可能是当前用户对该目录没有读取权限。请检查目录权限后重试。'
|
||||||
|
|
||||||
|
export const DATABASE_KEY_ERROR_MESSAGES: Record<DatabaseKeyValidationCode, string> = {
|
||||||
INVALID_FORMAT: '密钥格式不正确',
|
INVALID_FORMAT: '密钥格式不正确',
|
||||||
DATABASE_OPEN_FAILED: '无法打开数据库',
|
DATABASE_OPEN_FAILED: '无法打开数据库',
|
||||||
ACCOUNT_MISMATCH: '密钥与当前账号不匹配',
|
ACCOUNT_MISMATCH: '密钥与当前账号不匹配',
|
||||||
ROOT_UNAVAILABLE: '当前数据库目录不可用',
|
ROOT_UNAVAILABLE: '当前数据库目录不可用',
|
||||||
DATABASE_FILE_MISSING: '数据库文件缺失',
|
DATABASE_FILE_MISSING: '数据库文件缺失',
|
||||||
|
DATABASE_PERMISSION_DENIED: DATABASE_PERMISSION_HINT_GENERIC,
|
||||||
VC_RUNTIME_MISSING: WINDOWS_VC_RUNTIME_ERROR_MESSAGE,
|
VC_RUNTIME_MISSING: WINDOWS_VC_RUNTIME_ERROR_MESSAGE,
|
||||||
UNKNOWN_VALIDATION_ERROR: '未知验证错误'
|
UNKNOWN_VALIDATION_ERROR: '未知验证错误'
|
||||||
}
|
}
|
||||||
|
|
||||||
function mapConnectionError(detail: string): DatabaseKeyValidationCode {
|
/**
|
||||||
|
* 取错误码对应的用户可见文案。
|
||||||
|
*
|
||||||
|
* 单独开一层是为了**按平台分叉**:`DATABASE_PERMISSION_DENIED` 这个码在两个平台都可能
|
||||||
|
* 出现,但只有 macOS 才该给出「完全磁盘访问权限」这条指引 —— 把它无条件塞给
|
||||||
|
* Windows 用户是无效指引。
|
||||||
|
*/
|
||||||
|
export function databaseKeyErrorMessage(
|
||||||
|
code: DatabaseKeyValidationCode,
|
||||||
|
platform: NodeJS.Platform = process.platform
|
||||||
|
): string {
|
||||||
|
if (code === 'DATABASE_PERMISSION_DENIED' && platform === 'darwin') {
|
||||||
|
return DATABASE_PERMISSION_HINT_DARWIN
|
||||||
|
}
|
||||||
|
return DATABASE_KEY_ERROR_MESSAGES[code]
|
||||||
|
}
|
||||||
|
|
||||||
|
// 顺序有约束:原生码先于文本匹配,权限先于文件缺失(existsSync 对 EPERM 返回 false)。
|
||||||
|
export function mapConnectionError(
|
||||||
|
error: unknown,
|
||||||
|
platform: NodeJS.Platform = process.platform
|
||||||
|
): DatabaseKeyValidationCode {
|
||||||
|
const detail = error instanceof Error ? error.message : String(error)
|
||||||
const normalized = detail.toLowerCase()
|
const normalized = detail.toLowerCase()
|
||||||
if (isWindowsVcRuntimeMissingError(detail, process.platform)) return 'VC_RUNTIME_MISSING'
|
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 (normalized.includes('-1005') || normalized.includes('不匹配')) return 'ACCOUNT_MISMATCH'
|
||||||
|
if (isPermissionDeniedError(error) || hasPermissionDeniedText(normalized)) {
|
||||||
|
return 'DATABASE_PERMISSION_DENIED'
|
||||||
|
}
|
||||||
if (normalized.includes('session.db') || normalized.includes('数据库文件')) {
|
if (normalized.includes('session.db') || normalized.includes('数据库文件')) {
|
||||||
return 'DATABASE_FILE_MISSING'
|
return 'DATABASE_FILE_MISSING'
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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()
|
||||||
|
}
|
||||||
@@ -101,6 +101,15 @@ class GroupExitMonitorService {
|
|||||||
private events: GroupExitMonitorEvent[] = []
|
private events: GroupExitMonitorEvent[] = []
|
||||||
private monitorSelectionConfigured = true
|
private monitorSelectionConfigured = true
|
||||||
private monitoredRoomIds = new Set<string>()
|
private monitoredRoomIds = new Set<string>()
|
||||||
|
/*
|
||||||
|
* 「微信内退群监控消息」的范围:**全部群聊**,与退群监控勾选的群无关。
|
||||||
|
*
|
||||||
|
* 勾选只决定「哪些群的退群走自动化通知」;内提示是面向全体的展示能力。
|
||||||
|
* 所以这里只持有开关状态 + 全部群 id(随群名刷新一起更新),
|
||||||
|
* 检测范围取两者的并集 —— 两个消费者都要拿到事件。
|
||||||
|
*/
|
||||||
|
private noticeEnabled = false
|
||||||
|
private allGroupRoomIds = new Set<string>()
|
||||||
private loaded = false
|
private loaded = false
|
||||||
private accountRoot = ''
|
private accountRoot = ''
|
||||||
private groupNamesByRoomId = new Map<string, string>()
|
private groupNamesByRoomId = new Map<string, string>()
|
||||||
@@ -131,6 +140,11 @@ class GroupExitMonitorService {
|
|||||||
/** 永久保留的事件总数(`events` 只是最新的一批)。 */
|
/** 永久保留的事件总数(`events` 只是最新的一批)。 */
|
||||||
totalEventCount: this.events.length,
|
totalEventCount: this.events.length,
|
||||||
enabled: this.enabled,
|
enabled: this.enabled,
|
||||||
|
/*
|
||||||
|
* 这里仍然按「用户勾选的那套监控」报状态,不掺内提示的范围:
|
||||||
|
* `running` 同时是本地 Agent API 的可用性判据,改语义会波及它。
|
||||||
|
* 注意:内提示开着时检测其实也在跑(见 detectionEnabled),只是不算「退群监控在跑」。
|
||||||
|
*/
|
||||||
running: this.enabled && this.active && chat.isReady(),
|
running: this.enabled && this.active && chat.isReady(),
|
||||||
nativeMonitorActive: this.nativeMonitorActive,
|
nativeMonitorActive: this.nativeMonitorActive,
|
||||||
monitoredGroupCount: this.snapshots.size,
|
monitoredGroupCount: this.snapshots.size,
|
||||||
@@ -168,7 +182,7 @@ class GroupExitMonitorService {
|
|||||||
this.active = true
|
this.active = true
|
||||||
this.nativeMonitorActive = nativeMonitorActive
|
this.nativeMonitorActive = nativeMonitorActive
|
||||||
this.checkQueued = false
|
this.checkQueued = false
|
||||||
if (!this.enabled) {
|
if (!this.detectionEnabled()) {
|
||||||
this.save()
|
this.save()
|
||||||
this.broadcast()
|
this.broadcast()
|
||||||
return
|
return
|
||||||
@@ -194,6 +208,77 @@ class GroupExitMonitorService {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 由主进程注入「微信内退群监控消息」开关状态。
|
||||||
|
*
|
||||||
|
* 注入的是**开关**而不是群列表:群列表由本服务在刷新群名时一并更新(同一份会话快照),
|
||||||
|
* 所以群变动后不会过期,上层也不必维护第二份群清单。
|
||||||
|
*/
|
||||||
|
setNoticeEnabled(enabled: boolean): void {
|
||||||
|
this.ensureLoaded()
|
||||||
|
const next = enabled === true
|
||||||
|
if (this.noticeEnabled === next) return
|
||||||
|
this.noticeEnabled = next
|
||||||
|
this.eventSequence += 1
|
||||||
|
this.scopeGeneration += 1
|
||||||
|
this.dropOutOfScopeSnapshots()
|
||||||
|
this.lastCheckedAt = undefined
|
||||||
|
this.groupNamesRefreshPending = true
|
||||||
|
this.broadcast()
|
||||||
|
if (!this.detectionEnabled() || !chat.isReady()) return
|
||||||
|
if (!this.active) void this.start(false)
|
||||||
|
else void this.check()
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 内提示开关是否打开。 */
|
||||||
|
isNoticeEnabled(): boolean {
|
||||||
|
return this.noticeEnabled
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 内提示覆盖的群聊数(开关卡片的范围说明用)。 */
|
||||||
|
getNoticeGroupCount(): number {
|
||||||
|
return this.allGroupRoomIds.size
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 该房间是否属于内提示范围(= 全部群聊)。 */
|
||||||
|
isNoticeRoom(roomId: string): boolean {
|
||||||
|
const normalized = String(roomId || '').trim()
|
||||||
|
return this.noticeEnabled && this.allGroupRoomIds.has(normalized)
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 该房间是否要走自动化通知:**退群监控开着** 且 该房间在勾选范围内。
|
||||||
|
*
|
||||||
|
* 保留 `enabled` 这个前提是有意的 —— 关掉退群监控就等于「这些群我不看了」,
|
||||||
|
* 自动化通知不该因为内提示开关开着而偷偷恢复。
|
||||||
|
*/
|
||||||
|
isMonitoredRoom(roomId: string): boolean {
|
||||||
|
return this.enabled && this.monitoredRoomIds.has(String(roomId || '').trim())
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 检测范围 = 勾选的群 ∪ 内提示覆盖的群。 */
|
||||||
|
private detectionRoomIds(): Set<string> {
|
||||||
|
const ids = new Set(this.monitoredRoomIds)
|
||||||
|
if (this.noticeEnabled) for (const roomId of this.allGroupRoomIds) ids.add(roomId)
|
||||||
|
return ids
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 是否要继续检测:任一消费者开着就要跑。 */
|
||||||
|
private detectionEnabled(): boolean {
|
||||||
|
return this.enabled || this.noticeEnabled
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 丢掉已不在检测范围内的快照(换号、改范围、切开关都会用到)。 */
|
||||||
|
private dropOutOfScopeSnapshots(): void {
|
||||||
|
const inScope = this.detectionRoomIds()
|
||||||
|
for (const roomId of this.snapshots.keys()) {
|
||||||
|
if (!inScope.has(roomId)) this.snapshots.delete(roomId)
|
||||||
|
}
|
||||||
|
for (const roomId of this.hydrationQueue) {
|
||||||
|
if (!inScope.has(roomId)) this.hydrationQueue.delete(roomId)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
stop(): void {
|
stop(): void {
|
||||||
this.active = false
|
this.active = false
|
||||||
this.nativeMonitorActive = false
|
this.nativeMonitorActive = false
|
||||||
@@ -208,7 +293,7 @@ class GroupExitMonitorService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
notifyDatabaseChanged(rawPayload: string): void {
|
notifyDatabaseChanged(rawPayload: string): void {
|
||||||
if (!this.enabled || !this.active || !isContactEvent(rawPayload)) return
|
if (!this.detectionEnabled() || !this.active || !isContactEvent(rawPayload)) return
|
||||||
try {
|
try {
|
||||||
chat.getChatDb()?.getWcdb4Client().invalidateGroupNicknameCache()
|
chat.getChatDb()?.getWcdb4Client().invalidateGroupNicknameCache()
|
||||||
} catch {
|
} catch {
|
||||||
@@ -224,7 +309,7 @@ class GroupExitMonitorService {
|
|||||||
|
|
||||||
async checkNow(): Promise<GroupExitMonitorState> {
|
async checkNow(): Promise<GroupExitMonitorState> {
|
||||||
this.ensureLoaded()
|
this.ensureLoaded()
|
||||||
if (!this.enabled) return this.getState()
|
if (!this.detectionEnabled()) return this.getState()
|
||||||
if (!this.active && chat.isReady()) await this.start(false)
|
if (!this.active && chat.isReady()) await this.start(false)
|
||||||
await this.check()
|
await this.check()
|
||||||
return this.getState()
|
return this.getState()
|
||||||
@@ -237,49 +322,66 @@ class GroupExitMonitorService {
|
|||||||
* 本服务不再持有任何通知配置。
|
* 本服务不再持有任何通知配置。
|
||||||
*/
|
*/
|
||||||
async setMonitoredRoomIds(roomIds: string[]): Promise<GroupExitMonitorState> {
|
async setMonitoredRoomIds(roomIds: string[]): Promise<GroupExitMonitorState> {
|
||||||
|
return this.configure({ monitoredRoomIds: roomIds })
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Atomically update the monitor scope and enabled state.
|
||||||
|
*
|
||||||
|
* Agent API PATCH validates the whole request before calling this method. Keeping the
|
||||||
|
* two mutations in one service operation also means persistence and the renderer broadcast
|
||||||
|
* observe one final configuration rather than an intermediate half-patched state.
|
||||||
|
*/
|
||||||
|
async configure(configuration: {
|
||||||
|
monitoredRoomIds?: string[]
|
||||||
|
enabled?: boolean
|
||||||
|
}): Promise<GroupExitMonitorState> {
|
||||||
this.ensureLoaded()
|
this.ensureLoaded()
|
||||||
this.eventSequence += 1
|
const hasScope = configuration.monitoredRoomIds !== undefined
|
||||||
this.scopeGeneration += 1
|
const hasEnabled = configuration.enabled !== undefined
|
||||||
this.monitorSelectionConfigured = true
|
if (!hasScope && !hasEnabled) return this.getState()
|
||||||
const nextMonitoredRoomIds = normalizeRoomIds(roomIds)
|
if (hasEnabled && !hasScope && this.enabled === configuration.enabled) return this.getState()
|
||||||
for (const roomId of this.snapshots.keys()) {
|
|
||||||
if (!nextMonitoredRoomIds.has(roomId)) this.snapshots.delete(roomId)
|
if (hasScope) {
|
||||||
|
this.eventSequence += 1
|
||||||
|
this.scopeGeneration += 1
|
||||||
|
this.monitorSelectionConfigured = true
|
||||||
|
this.monitoredRoomIds = normalizeRoomIds(configuration.monitoredRoomIds || [])
|
||||||
|
this.dropOutOfScopeSnapshots()
|
||||||
|
this.groupNamesRefreshPending = true
|
||||||
|
this.lastCheckedAt = undefined
|
||||||
}
|
}
|
||||||
for (const roomId of this.hydrationQueue) {
|
|
||||||
if (!nextMonitoredRoomIds.has(roomId)) this.hydrationQueue.delete(roomId)
|
if (hasEnabled && this.enabled !== configuration.enabled) {
|
||||||
|
this.enabled = configuration.enabled === true
|
||||||
|
this.eventSequence += 1
|
||||||
|
this.scopeGeneration += 1
|
||||||
|
this.checkQueued = false
|
||||||
|
this.hydrationQueue.clear()
|
||||||
|
if (this.changeTimer) clearTimeout(this.changeTimer)
|
||||||
|
this.changeTimer = null
|
||||||
|
|
||||||
|
if (this.enabled) {
|
||||||
|
// 用户主动暂停期间的成员变化不补报;重新开启后从当前状态建立新基线。
|
||||||
|
this.snapshots.clear()
|
||||||
|
this.lastCheckedAt = undefined
|
||||||
|
this.groupNamesRefreshPending = true
|
||||||
|
}
|
||||||
}
|
}
|
||||||
this.monitoredRoomIds = nextMonitoredRoomIds
|
|
||||||
this.groupNamesRefreshPending = true
|
|
||||||
this.lastCheckedAt = undefined
|
|
||||||
this.save()
|
this.save()
|
||||||
this.broadcast()
|
this.broadcast()
|
||||||
// 建立基线放到后台,保存配置可以立即返回。
|
// 仅修改范围时保持原有的后台基线行为;涉及 enabled 的 PATCH 等待一次检查,
|
||||||
if (this.enabled && this.active) void this.check()
|
// 让调用方拿到的是最终运行状态。
|
||||||
|
if (this.enabled && this.active && chat.isReady()) {
|
||||||
|
if (hasEnabled) await this.check()
|
||||||
|
else void this.check()
|
||||||
|
}
|
||||||
return this.getState()
|
return this.getState()
|
||||||
}
|
}
|
||||||
|
|
||||||
async setEnabled(enabled: boolean): Promise<GroupExitMonitorState> {
|
async setEnabled(enabled: boolean): Promise<GroupExitMonitorState> {
|
||||||
this.ensureLoaded()
|
return this.configure({ enabled })
|
||||||
if (this.enabled === enabled) return this.getState()
|
|
||||||
|
|
||||||
this.enabled = enabled
|
|
||||||
this.eventSequence += 1
|
|
||||||
this.scopeGeneration += 1
|
|
||||||
this.checkQueued = false
|
|
||||||
this.hydrationQueue.clear()
|
|
||||||
if (this.changeTimer) clearTimeout(this.changeTimer)
|
|
||||||
this.changeTimer = null
|
|
||||||
|
|
||||||
if (enabled) {
|
|
||||||
// 用户主动暂停期间的成员变化不补报;重新开启后从当前状态建立新基线。
|
|
||||||
this.snapshots.clear()
|
|
||||||
this.lastCheckedAt = undefined
|
|
||||||
this.groupNamesRefreshPending = true
|
|
||||||
}
|
|
||||||
this.save()
|
|
||||||
this.broadcast()
|
|
||||||
if (enabled && this.active && chat.isReady()) await this.check()
|
|
||||||
return this.getState()
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -371,7 +473,12 @@ class GroupExitMonitorService {
|
|||||||
const result = await this.readMemberships()
|
const result = await this.readMemberships()
|
||||||
const membershipCostMs = Date.now() - startedAt
|
const membershipCostMs = Date.now() - startedAt
|
||||||
let changedGroups = 0
|
let changedGroups = 0
|
||||||
if (result.groups && this.enabled && this.active && scopeGeneration === this.scopeGeneration) {
|
if (
|
||||||
|
result.groups &&
|
||||||
|
this.detectionEnabled() &&
|
||||||
|
this.active &&
|
||||||
|
scopeGeneration === this.scopeGeneration
|
||||||
|
) {
|
||||||
changedGroups = await this.applyCurrentMemberships(result.groups, scopeGeneration)
|
changedGroups = await this.applyCurrentMemberships(result.groups, scopeGeneration)
|
||||||
}
|
}
|
||||||
console.log(
|
console.log(
|
||||||
@@ -383,7 +490,7 @@ class GroupExitMonitorService {
|
|||||||
private async readMemberships(): Promise<MembershipReadResult> {
|
private async readMemberships(): Promise<MembershipReadResult> {
|
||||||
await this.refreshGroupNamesIfNeeded()
|
await this.refreshGroupNamesIfNeeded()
|
||||||
const database = chat.getChatDb()
|
const database = chat.getChatDb()
|
||||||
const roomIds = Array.from(this.monitoredRoomIds)
|
const roomIds = Array.from(this.detectionRoomIds())
|
||||||
const batchAvailable = chat.isGroupMemberIdsBatchAvailable()
|
const batchAvailable = chat.isGroupMemberIdsBatchAvailable()
|
||||||
const mode: MembershipMode = batchAvailable ? 'batch' : 'legacy'
|
const mode: MembershipMode = batchAvailable ? 'batch' : 'legacy'
|
||||||
if (!database) return { mode, groupCount: roomIds.length, groups: null }
|
if (!database) return { mode, groupCount: roomIds.length, groups: null }
|
||||||
@@ -513,7 +620,7 @@ class GroupExitMonitorService {
|
|||||||
}
|
}
|
||||||
this.hydrationQueue.delete(roomId)
|
this.hydrationQueue.delete(roomId)
|
||||||
const baseline = this.snapshots.get(roomId)
|
const baseline = this.snapshots.get(roomId)
|
||||||
if (!baseline || !this.monitoredRoomIds.has(roomId)) {
|
if (!baseline || !this.detectionRoomIds().has(roomId)) {
|
||||||
this.startNextSnapshotHydration()
|
this.startNextSnapshotHydration()
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
@@ -587,6 +694,9 @@ class GroupExitMonitorService {
|
|||||||
const resolved = normalizeKnownGroupName(roomId, name)
|
const resolved = normalizeKnownGroupName(roomId, name)
|
||||||
if (resolved) this.groupNamesByRoomId.set(roomId, resolved)
|
if (resolved) this.groupNamesByRoomId.set(roomId, resolved)
|
||||||
}
|
}
|
||||||
|
/* 内提示覆盖的「全部群聊」与群名同源、同频刷新(都是会话表里的群聊),
|
||||||
|
* 这样群变动后自然跟上,上层不需要再维护第二份群清单。 */
|
||||||
|
this.allGroupRoomIds = new Set(Object.keys(names || {}))
|
||||||
} catch {
|
} catch {
|
||||||
// Session 群名是展示信息;读取失败时继续使用快照中的已知群名。
|
// Session 群名是展示信息;读取失败时继续使用快照中的已知群名。
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,967 @@
|
|||||||
|
import {
|
||||||
|
BUILTIN_DAILY_REPORT_RULE_ID,
|
||||||
|
BUILTIN_LEAVE_NOTIFICATION_RULE_ID,
|
||||||
|
calculateNextRunAt,
|
||||||
|
type AutomationExecution,
|
||||||
|
type AutomationRule,
|
||||||
|
type AutomationRuleDraft,
|
||||||
|
type AutomationRuleType
|
||||||
|
} from '../../shared/automation'
|
||||||
|
import { resolveContact } from './contact-resolution-service'
|
||||||
|
import { validateAutomationDraftShape } from '../../shared/agent-api/automation-validation'
|
||||||
|
import type {
|
||||||
|
AgentAutomationExecution,
|
||||||
|
AgentAutomationValidationIssue,
|
||||||
|
AgentAutomationValidationResult,
|
||||||
|
ApplicationCapabilities
|
||||||
|
} from '../../shared/agent-api/contracts'
|
||||||
|
import type {
|
||||||
|
AgentGroupExitMonitorEvent,
|
||||||
|
AgentGroupExitMonitorState
|
||||||
|
} from '../../shared/agent-api/group-exit-monitor'
|
||||||
|
import type { AgentGroupMemberStats } from '../../shared/agent-api/group-stats'
|
||||||
|
import type { GroupExitMonitorEvent } from '../../shared/group-exit-monitor'
|
||||||
|
import type { GroupMemberStatsQuery, GroupMemberStatsResult } from '../../shared/group-stats'
|
||||||
|
import type { Contact } from '../../shared/types'
|
||||||
|
import type { PersonalWechatSendCapability } from '../../shared/personal-wechat'
|
||||||
|
import type { AutomationExecutionLogService } from './automation-execution-log-service'
|
||||||
|
import type { AutomationRuleStore } from './automation-rule-store'
|
||||||
|
|
||||||
|
type AutomationRuleStoreApi = Pick<
|
||||||
|
AutomationRuleStore,
|
||||||
|
'listRules' | 'getRule' | 'createRule' | 'updateRule' | 'deleteRule' | 'setRuleEnabled'
|
||||||
|
>
|
||||||
|
type AutomationExecutionLogApi = Pick<AutomationExecutionLogService, 'list'>
|
||||||
|
type RuleScope = 'any' | 'person' | 'group'
|
||||||
|
|
||||||
|
type GroupExitMonitorStateSource = {
|
||||||
|
enabled: boolean
|
||||||
|
running: boolean
|
||||||
|
monitoredRoomIds?: string[]
|
||||||
|
nativeMonitorActive?: boolean
|
||||||
|
monitoredGroupCount?: number
|
||||||
|
monitorSelectionConfigured?: boolean
|
||||||
|
lastCheckedAt?: number
|
||||||
|
lastReadAt?: number
|
||||||
|
unreadCount?: number
|
||||||
|
totalEventCount?: number
|
||||||
|
events?: GroupExitMonitorEvent[]
|
||||||
|
}
|
||||||
|
|
||||||
|
type GroupExitMonitorConfiguration = {
|
||||||
|
enabled?: boolean
|
||||||
|
monitoredRoomIds?: string[]
|
||||||
|
}
|
||||||
|
|
||||||
|
type GroupExitMonitorEventQuery = {
|
||||||
|
roomId?: string
|
||||||
|
sinceMs?: number
|
||||||
|
untilMs?: number
|
||||||
|
limit?: number
|
||||||
|
}
|
||||||
|
|
||||||
|
export class LocalAgentApiError extends Error {
|
||||||
|
constructor(
|
||||||
|
readonly status: number,
|
||||||
|
readonly code: string,
|
||||||
|
message: string,
|
||||||
|
readonly details?: unknown
|
||||||
|
) {
|
||||||
|
super(message)
|
||||||
|
this.name = 'LocalAgentApiError'
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface LocalAgentApiDependencies {
|
||||||
|
automationRuleStore: AutomationRuleStoreApi
|
||||||
|
automationExecutionLogService: AutomationExecutionLogApi
|
||||||
|
listContacts: () => Promise<Contact[]>
|
||||||
|
isDatabaseReady: () => boolean
|
||||||
|
getVersion: () => string
|
||||||
|
getPersonalWechatCapability: () => Promise<PersonalWechatSendCapability>
|
||||||
|
getAgentHubStatus: () => { connector: string }
|
||||||
|
getGroupExitMonitorState: () => GroupExitMonitorStateSource
|
||||||
|
/** Preferred atomic monitor configuration operation. */
|
||||||
|
configureGroupExitMonitor?: (
|
||||||
|
configuration: GroupExitMonitorConfiguration
|
||||||
|
) => Promise<GroupExitMonitorStateSource> | GroupExitMonitorStateSource
|
||||||
|
setGroupExitMonitorRoomIds?: (roomIds: string[]) => Promise<GroupExitMonitorStateSource>
|
||||||
|
setGroupExitMonitorEnabled?: (enabled: boolean) => Promise<GroupExitMonitorStateSource>
|
||||||
|
listGroupExitMonitorEvents?: (query: GroupExitMonitorEventQuery) => GroupExitMonitorEvent[]
|
||||||
|
getGroupMemberStats?: (query: GroupMemberStatsQuery) => Promise<GroupMemberStatsResult>
|
||||||
|
}
|
||||||
|
|
||||||
|
const RULE_TYPES: AutomationRuleType[] = ['daily_report', 'scheduled_report', 'leave_notification']
|
||||||
|
const EXECUTION_STATUSES: AutomationExecution['status'][] = ['running', 'success', 'failed']
|
||||||
|
const UPDATE_FIELDS = new Set([
|
||||||
|
'name',
|
||||||
|
'trigger',
|
||||||
|
'scope',
|
||||||
|
'conditions',
|
||||||
|
'actions',
|
||||||
|
'cooldownSeconds',
|
||||||
|
'replyDelaySeconds',
|
||||||
|
'leaveNotification',
|
||||||
|
'scheduledReport'
|
||||||
|
])
|
||||||
|
|
||||||
|
function record(value: unknown): Record<string, unknown> | undefined {
|
||||||
|
return value !== null && typeof value === 'object' && !Array.isArray(value)
|
||||||
|
? (value as Record<string, unknown>)
|
||||||
|
: undefined
|
||||||
|
}
|
||||||
|
|
||||||
|
function toDraft(rule: AutomationRule): AutomationRuleDraft {
|
||||||
|
return {
|
||||||
|
name: rule.name,
|
||||||
|
enabled: false,
|
||||||
|
ruleType: rule.ruleType,
|
||||||
|
trigger: rule.trigger,
|
||||||
|
scope: rule.scope,
|
||||||
|
conditions: structuredClone(rule.conditions),
|
||||||
|
actions: structuredClone(rule.actions),
|
||||||
|
cooldownSeconds: rule.cooldownSeconds,
|
||||||
|
replyDelaySeconds: rule.replyDelaySeconds,
|
||||||
|
...(rule.leaveNotification
|
||||||
|
? { leaveNotification: structuredClone(rule.leaveNotification) }
|
||||||
|
: {}),
|
||||||
|
...(rule.scheduledReport ? { scheduledReport: structuredClone(rule.scheduledReport) } : {})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function deepMergeDraft(
|
||||||
|
current: AutomationRuleDraft,
|
||||||
|
patch: Record<string, unknown>
|
||||||
|
): Record<string, unknown> {
|
||||||
|
const next: Record<string, unknown> = { ...current, ...patch, enabled: false }
|
||||||
|
if (patch.conditions !== undefined) {
|
||||||
|
next.conditions = { ...current.conditions, ...record(patch.conditions) }
|
||||||
|
}
|
||||||
|
if (patch.leaveNotification !== undefined && current.leaveNotification) {
|
||||||
|
const leavePatch = record(patch.leaveNotification) || {}
|
||||||
|
next.leaveNotification = {
|
||||||
|
...current.leaveNotification,
|
||||||
|
...leavePatch,
|
||||||
|
...(leavePatch.target !== undefined ? { target: leavePatch.target } : {})
|
||||||
|
}
|
||||||
|
if (record(leavePatch.target)?.type !== undefined) {
|
||||||
|
delete (next.leaveNotification as Record<string, unknown>).targetNeedsReview
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (patch.scheduledReport !== undefined && current.scheduledReport) {
|
||||||
|
const schedulePatch = record(patch.scheduledReport) || {}
|
||||||
|
const currentConfig = current.scheduledReport
|
||||||
|
next.scheduledReport = {
|
||||||
|
...currentConfig,
|
||||||
|
...schedulePatch,
|
||||||
|
schedule: { ...currentConfig.schedule, ...record(schedulePatch.schedule) },
|
||||||
|
report: { ...currentConfig.report, ...record(schedulePatch.report) },
|
||||||
|
...(schedulePatch.target !== undefined ? { target: schedulePatch.target } : {})
|
||||||
|
}
|
||||||
|
if (record(schedulePatch.target)?.type !== undefined) {
|
||||||
|
delete (next.scheduledReport as Record<string, unknown>).targetNeedsReview
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return next
|
||||||
|
}
|
||||||
|
|
||||||
|
function stableId(contact: Contact): string {
|
||||||
|
return contact.type === 'user' ? contact.wxid || contact.m_nsUsrName : contact.m_nsUsrName
|
||||||
|
}
|
||||||
|
|
||||||
|
function toIsoTimestamp(value: number | undefined): string | null {
|
||||||
|
if (!Number.isFinite(value) || Number(value) <= 0) return null
|
||||||
|
const date = new Date(Number(value))
|
||||||
|
return Number.isNaN(date.getTime()) ? null : date.toISOString()
|
||||||
|
}
|
||||||
|
|
||||||
|
export class LocalAgentApiService {
|
||||||
|
private readonly deps: LocalAgentApiDependencies
|
||||||
|
|
||||||
|
constructor(dependencies: LocalAgentApiDependencies) {
|
||||||
|
this.deps = dependencies
|
||||||
|
}
|
||||||
|
|
||||||
|
async getCapabilities(): Promise<ApplicationCapabilities> {
|
||||||
|
const databaseReady = this.deps.isDatabaseReady()
|
||||||
|
const hub = this.deps.getAgentHubStatus()
|
||||||
|
const monitor = this.deps.getGroupExitMonitorState()
|
||||||
|
let personal: Pick<
|
||||||
|
PersonalWechatSendCapability,
|
||||||
|
'supported' | 'ready' | 'status' | 'capabilities'
|
||||||
|
>
|
||||||
|
try {
|
||||||
|
personal = await this.deps.getPersonalWechatCapability()
|
||||||
|
} catch {
|
||||||
|
personal = {
|
||||||
|
supported: true,
|
||||||
|
ready: false,
|
||||||
|
status: 'error',
|
||||||
|
capabilities: { text: false, image: false, voice: false }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
version: this.deps.getVersion(),
|
||||||
|
apiVersion: 'v1',
|
||||||
|
database: { ready: databaseReady },
|
||||||
|
query: {
|
||||||
|
supported: true,
|
||||||
|
available: databaseReady,
|
||||||
|
...(!databaseReady ? { reason: 'database_not_ready' } : {})
|
||||||
|
},
|
||||||
|
automations: {
|
||||||
|
supported: true,
|
||||||
|
available: true,
|
||||||
|
ruleTypes: [...RULE_TYPES],
|
||||||
|
operations: [
|
||||||
|
'list',
|
||||||
|
'get',
|
||||||
|
'create',
|
||||||
|
'update',
|
||||||
|
'validate',
|
||||||
|
'enable',
|
||||||
|
'disable',
|
||||||
|
'delete',
|
||||||
|
'executions'
|
||||||
|
]
|
||||||
|
},
|
||||||
|
groupExitMonitor: {
|
||||||
|
supported: true,
|
||||||
|
available: databaseReady && monitor.running,
|
||||||
|
operations: [
|
||||||
|
'read_state',
|
||||||
|
'configure_scope',
|
||||||
|
'enable',
|
||||||
|
'disable',
|
||||||
|
'list_events'
|
||||||
|
],
|
||||||
|
...(!databaseReady
|
||||||
|
? { reason: 'database_not_ready' }
|
||||||
|
: !monitor.enabled
|
||||||
|
? { reason: 'disabled' }
|
||||||
|
: !monitor.running
|
||||||
|
? { reason: 'not_running' }
|
||||||
|
: {})
|
||||||
|
},
|
||||||
|
groupStats: {
|
||||||
|
supported: true,
|
||||||
|
available: databaseReady,
|
||||||
|
operations: ['member_stats'],
|
||||||
|
...(!databaseReady ? { reason: 'database_not_ready' } : {})
|
||||||
|
},
|
||||||
|
wechat: {
|
||||||
|
personal: {
|
||||||
|
supported: personal.supported,
|
||||||
|
available: personal.ready,
|
||||||
|
status: personal.status,
|
||||||
|
content: { ...personal.capabilities },
|
||||||
|
...(!personal.ready ? { reason: personal.status } : {})
|
||||||
|
},
|
||||||
|
ilink: {
|
||||||
|
supported: true,
|
||||||
|
available: hub.connector === 'online',
|
||||||
|
status: hub.connector,
|
||||||
|
...(hub.connector !== 'online' ? { reason: 'connector_not_online' } : {})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
getGroupExitMonitorState(): AgentGroupExitMonitorState {
|
||||||
|
const state = this.deps.getGroupExitMonitorState()
|
||||||
|
return {
|
||||||
|
enabled: state.enabled === true,
|
||||||
|
running: state.running === true,
|
||||||
|
nativeMonitorActive: state.nativeMonitorActive === true,
|
||||||
|
monitoredConversationIds: [...(state.monitoredRoomIds || [])],
|
||||||
|
monitoredGroupCount: Number.isFinite(state.monitoredGroupCount)
|
||||||
|
? Number(state.monitoredGroupCount)
|
||||||
|
: state.monitoredRoomIds?.length || 0,
|
||||||
|
monitorSelectionConfigured: state.monitorSelectionConfigured !== false,
|
||||||
|
lastCheckedAt: toIsoTimestamp(state.lastCheckedAt),
|
||||||
|
lastReadAt: toIsoTimestamp(state.lastReadAt),
|
||||||
|
eventCount: Number.isFinite(state.totalEventCount)
|
||||||
|
? Number(state.totalEventCount)
|
||||||
|
: state.events?.length || 0,
|
||||||
|
unreadCount: Number.isFinite(state.unreadCount) ? Number(state.unreadCount) : 0
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async updateGroupExitMonitor(input: unknown): Promise<AgentGroupExitMonitorState> {
|
||||||
|
const patch = record(input)
|
||||||
|
if (!patch) {
|
||||||
|
throw new LocalAgentApiError(400, 'INVALID_ARGUMENT', '请求体必须是 JSON 对象')
|
||||||
|
}
|
||||||
|
const keys = Object.keys(patch)
|
||||||
|
const allowed = new Set(['enabled', 'monitoredConversationIds'])
|
||||||
|
const unknown = keys.find((key) => !allowed.has(key))
|
||||||
|
if (unknown) {
|
||||||
|
throw new LocalAgentApiError(400, 'INVALID_ARGUMENT', `不支持字段:${unknown}`)
|
||||||
|
}
|
||||||
|
if (keys.length === 0) {
|
||||||
|
throw new LocalAgentApiError(400, 'INVALID_ARGUMENT', '至少提供 enabled 或 monitoredConversationIds')
|
||||||
|
}
|
||||||
|
|
||||||
|
const enabled = patch.enabled
|
||||||
|
if (enabled !== undefined && typeof enabled !== 'boolean') {
|
||||||
|
throw new LocalAgentApiError(400, 'INVALID_ARGUMENT', 'enabled 必须是布尔值')
|
||||||
|
}
|
||||||
|
|
||||||
|
let monitoredRoomIds: string[] | undefined
|
||||||
|
if (patch.monitoredConversationIds !== undefined) {
|
||||||
|
if (!Array.isArray(patch.monitoredConversationIds)) {
|
||||||
|
throw new LocalAgentApiError(400, 'INVALID_ARGUMENT', 'monitoredConversationIds 必须是数组')
|
||||||
|
}
|
||||||
|
monitoredRoomIds = []
|
||||||
|
const seen = new Set<string>()
|
||||||
|
for (const value of patch.monitoredConversationIds) {
|
||||||
|
if (typeof value !== 'string' || !value.trim()) {
|
||||||
|
throw new LocalAgentApiError(400, 'INVALID_ARGUMENT', '监控群 ID 不能为空')
|
||||||
|
}
|
||||||
|
const roomId = value.trim()
|
||||||
|
if (seen.has(roomId)) {
|
||||||
|
throw new LocalAgentApiError(400, 'INVALID_ARGUMENT', `监控群 ID 重复:${roomId}`)
|
||||||
|
}
|
||||||
|
if (!roomId.endsWith('@chatroom') || roomId.includes('/') || roomId.includes('\\')) {
|
||||||
|
throw new LocalAgentApiError(400, 'INVALID_ARGUMENT', `无效的群会话 ID:${roomId}`)
|
||||||
|
}
|
||||||
|
seen.add(roomId)
|
||||||
|
monitoredRoomIds.push(roomId)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!this.deps.isDatabaseReady()) {
|
||||||
|
throw new LocalAgentApiError(409, 'DATABASE_NOT_READY', '数据库未就绪,无法修改退群监控配置')
|
||||||
|
}
|
||||||
|
if (monitoredRoomIds !== undefined) {
|
||||||
|
const contacts = await this.deps.listContacts()
|
||||||
|
const groups = new Set(
|
||||||
|
contacts
|
||||||
|
.filter((contact) => contact.type === 'group')
|
||||||
|
.map((contact) => contact.m_nsUsrName)
|
||||||
|
)
|
||||||
|
const missing = monitoredRoomIds.find((roomId) => !groups.has(roomId))
|
||||||
|
if (missing) {
|
||||||
|
throw new LocalAgentApiError(
|
||||||
|
422,
|
||||||
|
'VALIDATION_FAILED',
|
||||||
|
`监控群不存在或不是群联系人:${missing}`,
|
||||||
|
[{ path: 'monitoredConversationIds', code: 'group_not_found', message: missing }]
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const configuration: GroupExitMonitorConfiguration = {
|
||||||
|
...(enabled !== undefined ? { enabled } : {}),
|
||||||
|
...(monitoredRoomIds !== undefined ? { monitoredRoomIds } : {})
|
||||||
|
}
|
||||||
|
let nextState: GroupExitMonitorStateSource | undefined
|
||||||
|
if (this.deps.configureGroupExitMonitor) {
|
||||||
|
nextState = await this.deps.configureGroupExitMonitor(configuration)
|
||||||
|
} else {
|
||||||
|
// Test adapters and older embedders may only expose the two primitive operations.
|
||||||
|
// All validation is complete before this fallback starts mutating state.
|
||||||
|
const previous = this.deps.getGroupExitMonitorState()
|
||||||
|
try {
|
||||||
|
if (monitoredRoomIds !== undefined) {
|
||||||
|
if (!this.deps.setGroupExitMonitorRoomIds) {
|
||||||
|
throw new LocalAgentApiError(503, 'CAPABILITY_UNAVAILABLE', '退群监控配置能力尚未就绪')
|
||||||
|
}
|
||||||
|
nextState = await this.deps.setGroupExitMonitorRoomIds(monitoredRoomIds)
|
||||||
|
}
|
||||||
|
if (enabled !== undefined) {
|
||||||
|
if (!this.deps.setGroupExitMonitorEnabled) {
|
||||||
|
throw new LocalAgentApiError(503, 'CAPABILITY_UNAVAILABLE', '退群监控配置能力尚未就绪')
|
||||||
|
}
|
||||||
|
nextState = await this.deps.setGroupExitMonitorEnabled(enabled)
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
// Best-effort rollback for legacy adapters. Production uses the atomic operation above.
|
||||||
|
try {
|
||||||
|
if (monitoredRoomIds !== undefined && this.deps.setGroupExitMonitorRoomIds) {
|
||||||
|
await this.deps.setGroupExitMonitorRoomIds(previous.monitoredRoomIds || [])
|
||||||
|
}
|
||||||
|
if (enabled !== undefined && this.deps.setGroupExitMonitorEnabled) {
|
||||||
|
await this.deps.setGroupExitMonitorEnabled(previous.enabled)
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
// Preserve the original error; an adapter that cannot roll back is non-atomic by definition.
|
||||||
|
}
|
||||||
|
throw error
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return this.toGroupExitMonitorState(nextState || this.deps.getGroupExitMonitorState())
|
||||||
|
}
|
||||||
|
|
||||||
|
listGroupExitMonitorEvents(query: URLSearchParams): {
|
||||||
|
count: number
|
||||||
|
events: AgentGroupExitMonitorEvent[]
|
||||||
|
} {
|
||||||
|
if (!this.deps.listGroupExitMonitorEvents) {
|
||||||
|
throw new LocalAgentApiError(503, 'CAPABILITY_UNAVAILABLE', '退群事件查询能力尚未就绪')
|
||||||
|
}
|
||||||
|
const rawConversationId = query.get('conversationId')
|
||||||
|
let roomId: string | undefined
|
||||||
|
if (rawConversationId !== null) {
|
||||||
|
roomId = rawConversationId.trim()
|
||||||
|
if (!roomId || !roomId.endsWith('@chatroom') || roomId.includes('/') || roomId.includes('\\')) {
|
||||||
|
throw new LocalAgentApiError(400, 'INVALID_ARGUMENT', 'conversationId 必须是有效的群会话 ID')
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const since = this.parseDateFilter(query.get('since'), 'since')
|
||||||
|
const until = this.parseDateFilter(query.get('until'), 'until')
|
||||||
|
if (since !== undefined && until !== undefined && since > until) {
|
||||||
|
throw new LocalAgentApiError(400, 'INVALID_ARGUMENT', 'since 不能晚于 until')
|
||||||
|
}
|
||||||
|
const rawLimit = query.get('limit')
|
||||||
|
const limit = rawLimit === null ? 50 : Number(rawLimit)
|
||||||
|
if (!Number.isInteger(limit) || limit < 1 || limit > 200) {
|
||||||
|
throw new LocalAgentApiError(400, 'INVALID_ARGUMENT', 'limit 必须是 1 到 200 之间的整数')
|
||||||
|
}
|
||||||
|
const events = this.deps
|
||||||
|
.listGroupExitMonitorEvents({ roomId, sinceMs: since, untilMs: until, limit })
|
||||||
|
.slice()
|
||||||
|
.sort((left, right) => left.detectedAt - right.detectedAt)
|
||||||
|
.map((event) => this.toAgentGroupExitEvent(event))
|
||||||
|
return { count: events.length, events }
|
||||||
|
}
|
||||||
|
|
||||||
|
async getGroupMemberStats(
|
||||||
|
conversationId: string,
|
||||||
|
query: URLSearchParams
|
||||||
|
): Promise<AgentGroupMemberStats> {
|
||||||
|
if (!this.deps.isDatabaseReady()) {
|
||||||
|
throw new LocalAgentApiError(409, 'DATABASE_NOT_READY', '数据库未就绪,无法查询群员统计')
|
||||||
|
}
|
||||||
|
const normalizedConversationId = conversationId.trim()
|
||||||
|
if (!normalizedConversationId || normalizedConversationId.includes('/') || normalizedConversationId.includes('\\')) {
|
||||||
|
throw new LocalAgentApiError(400, 'INVALID_ARGUMENT', 'conversationId 格式无效')
|
||||||
|
}
|
||||||
|
const start = this.parseDateFilter(query.get('start'), 'start')
|
||||||
|
const end = this.parseDateFilter(query.get('end'), 'end')
|
||||||
|
if (start === undefined || end === undefined) {
|
||||||
|
throw new LocalAgentApiError(400, 'INVALID_ARGUMENT', 'start 和 end 必须同时提供')
|
||||||
|
}
|
||||||
|
if (start > end) {
|
||||||
|
throw new LocalAgentApiError(400, 'INVALID_ARGUMENT', 'start 不能晚于 end')
|
||||||
|
}
|
||||||
|
|
||||||
|
const contacts = await this.deps.listContacts()
|
||||||
|
const matches = contacts.filter((contact) => contact.m_nsUsrName === normalizedConversationId)
|
||||||
|
if (matches.length === 0) {
|
||||||
|
throw new LocalAgentApiError(404, 'NOT_FOUND', '未找到指定会话')
|
||||||
|
}
|
||||||
|
if (matches.length > 1) {
|
||||||
|
throw new LocalAgentApiError(409, 'AMBIGUOUS_CONTACT', 'conversationId 匹配到多个会话')
|
||||||
|
}
|
||||||
|
const contact = matches[0]
|
||||||
|
if (contact.type !== 'group') {
|
||||||
|
throw new LocalAgentApiError(422, 'NOT_GROUP_CONVERSATION', 'conversationId 不是群会话')
|
||||||
|
}
|
||||||
|
if (!contact.m_nsUsrName.endsWith('@chatroom')) {
|
||||||
|
throw new LocalAgentApiError(422, 'NOT_GROUP_CONVERSATION', 'conversationId 不是有效的群会话 ID')
|
||||||
|
}
|
||||||
|
if (!this.deps.getGroupMemberStats) {
|
||||||
|
throw new LocalAgentApiError(503, 'CAPABILITY_UNAVAILABLE', '群员统计能力尚未就绪')
|
||||||
|
}
|
||||||
|
|
||||||
|
const result = await this.deps.getGroupMemberStats({
|
||||||
|
userMd5: contact.md5,
|
||||||
|
startTime: start,
|
||||||
|
endTime: end
|
||||||
|
})
|
||||||
|
return this.toAgentGroupMemberStats(contact, result)
|
||||||
|
}
|
||||||
|
|
||||||
|
async listAutomations(filter: {
|
||||||
|
type?: string | null
|
||||||
|
enabled?: string | null
|
||||||
|
}): Promise<unknown[]> {
|
||||||
|
if (filter.type && !RULE_TYPES.includes(filter.type as AutomationRuleType)) {
|
||||||
|
throw new LocalAgentApiError(400, 'INVALID_ARGUMENT', 'type 不受支持')
|
||||||
|
}
|
||||||
|
let enabled: boolean | undefined
|
||||||
|
if (filter.enabled !== undefined && filter.enabled !== null) {
|
||||||
|
if (filter.enabled !== 'true' && filter.enabled !== 'false') {
|
||||||
|
throw new LocalAgentApiError(400, 'INVALID_ARGUMENT', 'enabled 必须是 true 或 false')
|
||||||
|
}
|
||||||
|
enabled = filter.enabled === 'true'
|
||||||
|
}
|
||||||
|
const rules = this.deps.automationRuleStore
|
||||||
|
.listRules()
|
||||||
|
.filter(
|
||||||
|
(rule) =>
|
||||||
|
(!filter.type || rule.ruleType === filter.type) &&
|
||||||
|
(enabled === undefined || rule.enabled === enabled)
|
||||||
|
)
|
||||||
|
return this.toApiRules(rules)
|
||||||
|
}
|
||||||
|
|
||||||
|
async getAutomation(id: string): Promise<unknown> {
|
||||||
|
const rule = this.deps.automationRuleStore.getRule(id)
|
||||||
|
if (!rule) throw new LocalAgentApiError(404, 'NOT_FOUND', '未找到自动化规则')
|
||||||
|
return (await this.toApiRules([rule]))[0]
|
||||||
|
}
|
||||||
|
|
||||||
|
async validateAutomation(input: unknown): Promise<AgentAutomationValidationResult> {
|
||||||
|
const structural = validateAutomationDraftShape(input)
|
||||||
|
if (!structural.valid || !structural.normalized) {
|
||||||
|
return { valid: false, issues: structural.issues }
|
||||||
|
}
|
||||||
|
|
||||||
|
const issues = [...structural.issues]
|
||||||
|
const draft = structuredClone(structural.normalized)
|
||||||
|
const references = await this.resolveDraftReferences(draft, issues)
|
||||||
|
if (issues.length) return { valid: false, issues }
|
||||||
|
|
||||||
|
const config = draft.scheduledReport
|
||||||
|
const nextRunAt = config ? calculateNextRunAt(config.schedule.time) : null
|
||||||
|
const effects = this.describeEffects(draft)
|
||||||
|
return {
|
||||||
|
valid: true,
|
||||||
|
issues: [],
|
||||||
|
normalized: draft,
|
||||||
|
effects,
|
||||||
|
nextRunAt,
|
||||||
|
capabilities: {
|
||||||
|
databaseReady: this.deps.isDatabaseReady(),
|
||||||
|
referencedConversationsResolved: references
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async createAutomation(input: unknown): Promise<unknown> {
|
||||||
|
const raw = record(input)
|
||||||
|
if (raw?.ruleType === 'leave_notification') {
|
||||||
|
throw new LocalAgentApiError(409, 'SINGLETON_RULE', '退群通知是系统单例规则,请修改现有规则')
|
||||||
|
}
|
||||||
|
const validation = await this.validateAutomation(input)
|
||||||
|
if (!validation.valid || !validation.normalized) {
|
||||||
|
throw new LocalAgentApiError(
|
||||||
|
422,
|
||||||
|
'VALIDATION_FAILED',
|
||||||
|
'自动化规则校验失败',
|
||||||
|
validation.issues
|
||||||
|
)
|
||||||
|
}
|
||||||
|
const contacts = await this.deps.listContacts()
|
||||||
|
const storedDraft = this.toStoreDraft(validation.normalized as AutomationRuleDraft, contacts)
|
||||||
|
storedDraft.enabled = false
|
||||||
|
const created = this.deps.automationRuleStore.createRule(storedDraft)
|
||||||
|
return (await this.toApiRules([created]))[0]
|
||||||
|
}
|
||||||
|
|
||||||
|
async updateAutomation(id: string, patchInput: unknown): Promise<unknown> {
|
||||||
|
const current = this.deps.automationRuleStore.getRule(id)
|
||||||
|
if (!current) throw new LocalAgentApiError(404, 'NOT_FOUND', '未找到自动化规则')
|
||||||
|
const patch = record(patchInput)
|
||||||
|
if (!patch) throw new LocalAgentApiError(400, 'INVALID_ARGUMENT', '请求体必须是 JSON 对象')
|
||||||
|
for (const key of Object.keys(patch)) {
|
||||||
|
if (key === 'ruleType') {
|
||||||
|
throw new LocalAgentApiError(400, 'RULE_TYPE_IMMUTABLE', 'ruleType 不可修改')
|
||||||
|
}
|
||||||
|
if (key === 'id' || key === 'createdAt' || key === 'updatedAt') {
|
||||||
|
throw new LocalAgentApiError(400, 'IMMUTABLE_FIELD', `${key} 不允许由客户端修改`)
|
||||||
|
}
|
||||||
|
if (key === 'enabled') {
|
||||||
|
throw new LocalAgentApiError(400, 'USE_ENABLE_OPERATION', '请使用 enable 或 disable 操作')
|
||||||
|
}
|
||||||
|
if (!UPDATE_FIELDS.has(key)) {
|
||||||
|
throw new LocalAgentApiError(400, 'INVALID_ARGUMENT', `不支持字段:${key}`)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for (const configKey of ['leaveNotification', 'scheduledReport']) {
|
||||||
|
if (Object.hasOwn(record(patch[configKey]) || {}, 'targetNeedsReview')) {
|
||||||
|
throw new LocalAgentApiError(
|
||||||
|
400,
|
||||||
|
'IMMUTABLE_FIELD',
|
||||||
|
`${configKey}.targetNeedsReview 只能通过更新 target 清除`
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const apiCurrent = (await this.toApiRules([current]))[0] as AutomationRule & {
|
||||||
|
requiresReview?: boolean
|
||||||
|
}
|
||||||
|
const candidate = deepMergeDraft(toDraft(apiCurrent), patch)
|
||||||
|
const validation = await this.validateAutomation(candidate)
|
||||||
|
if (!validation.valid || !validation.normalized) {
|
||||||
|
throw new LocalAgentApiError(
|
||||||
|
422,
|
||||||
|
'VALIDATION_FAILED',
|
||||||
|
'自动化规则校验失败',
|
||||||
|
validation.issues
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
const contacts = await this.deps.listContacts()
|
||||||
|
const storedDraft = this.toStoreDraft(validation.normalized as AutomationRuleDraft, contacts)
|
||||||
|
storedDraft.enabled = current.enabled
|
||||||
|
const updated = this.deps.automationRuleStore.updateRule(id, storedDraft)
|
||||||
|
if (!updated) throw new LocalAgentApiError(404, 'NOT_FOUND', '未找到自动化规则')
|
||||||
|
return (await this.toApiRules([updated]))[0]
|
||||||
|
}
|
||||||
|
|
||||||
|
async setAutomationEnabled(id: string, enabled: boolean): Promise<unknown> {
|
||||||
|
const current = this.deps.automationRuleStore.getRule(id)
|
||||||
|
if (!current) throw new LocalAgentApiError(404, 'NOT_FOUND', '未找到自动化规则')
|
||||||
|
if (enabled) {
|
||||||
|
if (!this.deps.isDatabaseReady()) {
|
||||||
|
throw new LocalAgentApiError(409, 'VALIDATION_FAILED', '数据库未就绪,无法启用自动化规则', [
|
||||||
|
{ path: 'database', code: 'database_not_ready', message: 'TraceMemo 数据库未初始化' }
|
||||||
|
])
|
||||||
|
}
|
||||||
|
const apiCurrent = (await this.toApiRules([current]))[0] as AutomationRule
|
||||||
|
const draft = toDraft(apiCurrent)
|
||||||
|
const validation = await this.validateAutomation(draft)
|
||||||
|
if (!validation.valid) {
|
||||||
|
throw new LocalAgentApiError(
|
||||||
|
409,
|
||||||
|
'VALIDATION_FAILED',
|
||||||
|
'自动化规则校验失败,未启用',
|
||||||
|
validation.issues
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const updated = this.deps.automationRuleStore.setRuleEnabled(id, enabled)
|
||||||
|
if (!updated) throw new LocalAgentApiError(404, 'NOT_FOUND', '未找到自动化规则')
|
||||||
|
return (await this.toApiRules([updated]))[0]
|
||||||
|
}
|
||||||
|
|
||||||
|
async deleteAutomation(id: string): Promise<{ deletedId: string }> {
|
||||||
|
if (id === BUILTIN_DAILY_REPORT_RULE_ID || id === BUILTIN_LEAVE_NOTIFICATION_RULE_ID) {
|
||||||
|
throw new LocalAgentApiError(409, 'PROTECTED_RULE', '系统内置自动化规则不能删除')
|
||||||
|
}
|
||||||
|
const rule = this.deps.automationRuleStore.getRule(id)
|
||||||
|
if (!rule) throw new LocalAgentApiError(404, 'NOT_FOUND', '未找到自动化规则')
|
||||||
|
if (rule.ruleType === 'leave_notification') {
|
||||||
|
throw new LocalAgentApiError(409, 'PROTECTED_RULE', '退群通知是系统单例规则,不能删除')
|
||||||
|
}
|
||||||
|
const deleted = this.deps.automationRuleStore.deleteRule(id)
|
||||||
|
if (!deleted) throw new LocalAgentApiError(404, 'NOT_FOUND', '未找到自动化规则')
|
||||||
|
return { deletedId: id }
|
||||||
|
}
|
||||||
|
|
||||||
|
listExecutions(query: URLSearchParams): {
|
||||||
|
count: number
|
||||||
|
executions: AgentAutomationExecution[]
|
||||||
|
} {
|
||||||
|
const ruleId = query.get('ruleId') || undefined
|
||||||
|
const status = query.get('status') || undefined
|
||||||
|
if (status && !EXECUTION_STATUSES.includes(status as AutomationExecution['status'])) {
|
||||||
|
throw new LocalAgentApiError(400, 'INVALID_ARGUMENT', 'status 不受支持')
|
||||||
|
}
|
||||||
|
const since = this.parseDateFilter(query.get('since'), 'since')
|
||||||
|
const until = this.parseDateFilter(query.get('until'), 'until')
|
||||||
|
if (since !== undefined && until !== undefined && since > until) {
|
||||||
|
throw new LocalAgentApiError(400, 'INVALID_ARGUMENT', 'since 不能晚于 until')
|
||||||
|
}
|
||||||
|
const rawLimit = query.get('limit')
|
||||||
|
const limit = rawLimit === null ? 50 : Number(rawLimit)
|
||||||
|
if (!Number.isInteger(limit) || limit < 1 || limit > 200) {
|
||||||
|
throw new LocalAgentApiError(400, 'INVALID_ARGUMENT', 'limit 必须是 1 到 200 之间的整数')
|
||||||
|
}
|
||||||
|
const rulesById = new Map(
|
||||||
|
this.deps.automationRuleStore.listRules().map((rule) => [rule.id, rule])
|
||||||
|
)
|
||||||
|
const executions = this.deps.automationExecutionLogService
|
||||||
|
.list({ limit: 200 })
|
||||||
|
.filter((item) => !ruleId || item.ruleId === ruleId)
|
||||||
|
.filter((item) => !status || item.status === status)
|
||||||
|
.filter((item) => since === undefined || item.triggerTime >= since)
|
||||||
|
.filter((item) => until === undefined || item.triggerTime <= until)
|
||||||
|
.slice(0, limit)
|
||||||
|
.map((item) => this.toApiExecution(item, rulesById.get(item.ruleId)?.ruleType))
|
||||||
|
return { count: executions.length, executions }
|
||||||
|
}
|
||||||
|
|
||||||
|
private toGroupExitMonitorState(state: GroupExitMonitorStateSource): AgentGroupExitMonitorState {
|
||||||
|
const eventCount = Number.isFinite(state.totalEventCount)
|
||||||
|
? Number(state.totalEventCount)
|
||||||
|
: state.events?.length || 0
|
||||||
|
return {
|
||||||
|
enabled: state.enabled === true,
|
||||||
|
running: state.running === true,
|
||||||
|
nativeMonitorActive: state.nativeMonitorActive === true,
|
||||||
|
monitoredConversationIds: [...(state.monitoredRoomIds || [])],
|
||||||
|
monitoredGroupCount: Number.isFinite(state.monitoredGroupCount)
|
||||||
|
? Number(state.monitoredGroupCount)
|
||||||
|
: state.monitoredRoomIds?.length || 0,
|
||||||
|
monitorSelectionConfigured: state.monitorSelectionConfigured !== false,
|
||||||
|
lastCheckedAt: toIsoTimestamp(state.lastCheckedAt),
|
||||||
|
lastReadAt: toIsoTimestamp(state.lastReadAt),
|
||||||
|
eventCount,
|
||||||
|
unreadCount: Number.isFinite(state.unreadCount) ? Number(state.unreadCount) : 0
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private toAgentGroupExitEvent(event: GroupExitMonitorEvent): AgentGroupExitMonitorEvent {
|
||||||
|
return {
|
||||||
|
eventId: event.id,
|
||||||
|
conversationId: event.roomId,
|
||||||
|
groupName: event.groupName,
|
||||||
|
memberId: event.memberWxid,
|
||||||
|
memberName: event.memberName,
|
||||||
|
wechatName: event.wechatName || '',
|
||||||
|
groupRemark: event.groupRemark || '',
|
||||||
|
contactRemark: event.contactRemark || '',
|
||||||
|
previousCount: event.previousCount,
|
||||||
|
currentCount: event.currentCount,
|
||||||
|
delta: event.delta,
|
||||||
|
message: event.message,
|
||||||
|
detectedAt: new Date(event.detectedAt).toISOString()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private toAgentGroupMemberStats(contact: Contact, result: GroupMemberStatsResult): AgentGroupMemberStats {
|
||||||
|
const conversationName =
|
||||||
|
contact.m_nsNickName || contact.remark || contact.wechatNickname || contact.m_nsUsrName
|
||||||
|
return {
|
||||||
|
conversation: { id: contact.m_nsUsrName, name: conversationName },
|
||||||
|
conversationId: contact.m_nsUsrName,
|
||||||
|
range: {
|
||||||
|
start: new Date(result.startTime).toISOString(),
|
||||||
|
end: new Date(result.endTime).toISOString()
|
||||||
|
},
|
||||||
|
memberCount: result.memberCount,
|
||||||
|
activeMemberCount: result.activeMemberCount,
|
||||||
|
silentMemberCount: result.silentMemberCount,
|
||||||
|
activeMembers: result.activeMembers.map((member) => ({
|
||||||
|
memberId: member.senderId,
|
||||||
|
displayName: member.displayName,
|
||||||
|
groupNickname: member.groupNickname,
|
||||||
|
messageCount: member.messageCount,
|
||||||
|
lastMessageAt: toIsoTimestamp(member.lastMessageTime)
|
||||||
|
})),
|
||||||
|
silentMembers: result.silentMembers.map((member) => ({
|
||||||
|
memberId: member.senderId,
|
||||||
|
displayName: member.displayName,
|
||||||
|
groupNickname: member.groupNickname
|
||||||
|
})),
|
||||||
|
freshness: result.freshness,
|
||||||
|
complete: result.complete,
|
||||||
|
limitations: [...result.limitations],
|
||||||
|
unattributedMessages: result.unattributedMessages,
|
||||||
|
excludedSystemMessages: result.excludedSystemMessages,
|
||||||
|
firstMessageAt:
|
||||||
|
toIsoTimestamp(result.firstMessageTime ?? undefined)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private parseDateFilter(value: string | null, name: string): number | undefined {
|
||||||
|
if (value === null) return undefined
|
||||||
|
if (!/T.*(?:Z|[+-]\d{2}:\d{2})$/.test(value)) {
|
||||||
|
throw new LocalAgentApiError(400, 'INVALID_ARGUMENT', `${name} 必须是带时区的 ISO-8601 时间`)
|
||||||
|
}
|
||||||
|
const timestamp = Date.parse(value)
|
||||||
|
if (!Number.isFinite(timestamp)) {
|
||||||
|
throw new LocalAgentApiError(400, 'INVALID_ARGUMENT', `${name} 不是有效时间`)
|
||||||
|
}
|
||||||
|
return timestamp
|
||||||
|
}
|
||||||
|
|
||||||
|
private toApiExecution(
|
||||||
|
execution: AutomationExecution,
|
||||||
|
ruleType?: AutomationRuleType
|
||||||
|
): AgentAutomationExecution {
|
||||||
|
return {
|
||||||
|
executionId: execution.executionId,
|
||||||
|
ruleId: execution.ruleId,
|
||||||
|
ruleName: execution.ruleName,
|
||||||
|
...(ruleType ? { ruleType } : {}),
|
||||||
|
...(execution.trigger ? { trigger: execution.trigger } : {}),
|
||||||
|
status: execution.status,
|
||||||
|
triggerTime: execution.triggerTime,
|
||||||
|
durationMs: execution.durationMs,
|
||||||
|
sourceDisplayName: execution.sourceDisplayName,
|
||||||
|
startedAt: new Date(execution.triggerTime).toISOString(),
|
||||||
|
finishedAt:
|
||||||
|
execution.status === 'running'
|
||||||
|
? null
|
||||||
|
: new Date(execution.triggerTime + execution.durationMs).toISOString(),
|
||||||
|
...(execution.errorSummary ? { error: execution.errorSummary } : {})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private async resolveDraftReferences(
|
||||||
|
draft: AutomationRuleDraft,
|
||||||
|
issues: AgentAutomationValidationIssue[]
|
||||||
|
): Promise<boolean> {
|
||||||
|
const needsContacts =
|
||||||
|
(draft.ruleType === 'daily_report' && draft.conditions.conversationIds.length > 0) ||
|
||||||
|
draft.ruleType === 'scheduled_report' ||
|
||||||
|
(draft.ruleType === 'leave_notification' &&
|
||||||
|
(draft.leaveNotification?.target.type === 'contact' ||
|
||||||
|
(draft.leaveNotification?.notifyRoomIds.length ?? 0) > 0))
|
||||||
|
if (!needsContacts) return true
|
||||||
|
if (!this.deps.isDatabaseReady()) {
|
||||||
|
issues.push({
|
||||||
|
path: 'database',
|
||||||
|
code: 'database_not_ready',
|
||||||
|
message: 'TraceMemo 数据库未初始化,无法解析联系人或群聊 ID'
|
||||||
|
})
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
const contacts = await this.deps.listContacts()
|
||||||
|
let resolved = true
|
||||||
|
const resolve = (query: string, scope: RuleScope, path: string): Contact | undefined => {
|
||||||
|
const direct = contacts.filter((contact) => {
|
||||||
|
const identifiers = [
|
||||||
|
contact.md5,
|
||||||
|
contact.m_nsUsrName,
|
||||||
|
contact.wxid,
|
||||||
|
contact.wechatId,
|
||||||
|
contact.alias
|
||||||
|
]
|
||||||
|
return identifiers.some(
|
||||||
|
(identifier) => identifier?.toLocaleLowerCase() === query.toLocaleLowerCase()
|
||||||
|
)
|
||||||
|
})
|
||||||
|
const scopedDirect = direct.filter(
|
||||||
|
(contact) =>
|
||||||
|
scope === 'any' ||
|
||||||
|
(scope === 'person' ? contact.type === 'user' : contact.type === 'group')
|
||||||
|
)
|
||||||
|
if (scopedDirect.length === 1) return scopedDirect[0]
|
||||||
|
|
||||||
|
const result = resolveContact(query, contacts, scope)
|
||||||
|
if (result.matched && result.conversationId) {
|
||||||
|
return contacts.find((contact) => contact.md5 === result.conversationId)
|
||||||
|
}
|
||||||
|
resolved = false
|
||||||
|
issues.push({
|
||||||
|
path,
|
||||||
|
code: result.ambiguous ? 'ambiguous_contact' : 'contact_not_found',
|
||||||
|
message: result.ambiguous
|
||||||
|
? '标识匹配到多个联系人,请使用稳定 ID'
|
||||||
|
: '无法解析到现有联系人或群聊',
|
||||||
|
...(result.ambiguous
|
||||||
|
? {
|
||||||
|
details: {
|
||||||
|
candidates: result.candidates.map((candidate) => {
|
||||||
|
const contact = contacts.find((item) => item.md5 === candidate.conversationId)
|
||||||
|
return contact
|
||||||
|
? { id: stableId(contact), name: candidate.displayName }
|
||||||
|
: { id: candidate.conversationId, name: candidate.displayName }
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
: {})
|
||||||
|
})
|
||||||
|
return undefined
|
||||||
|
}
|
||||||
|
|
||||||
|
if (draft.ruleType === 'daily_report') {
|
||||||
|
const scope: RuleScope =
|
||||||
|
draft.scope === 'group' ? 'group' : draft.scope === 'direct' ? 'person' : 'any'
|
||||||
|
const ids: string[] = []
|
||||||
|
for (const [index, query] of draft.conditions.conversationIds.entries()) {
|
||||||
|
const contact = resolve(query, scope, `conditions.conversationIds[${index}]`)
|
||||||
|
if (contact) ids.push(stableId(contact))
|
||||||
|
}
|
||||||
|
draft.conditions.conversationIds = ids
|
||||||
|
}
|
||||||
|
|
||||||
|
if (draft.ruleType === 'scheduled_report' && draft.scheduledReport) {
|
||||||
|
const source = resolve(
|
||||||
|
draft.scheduledReport.report.sourceConversationId,
|
||||||
|
'group',
|
||||||
|
'scheduledReport.report.sourceConversationId'
|
||||||
|
)
|
||||||
|
if (source) draft.scheduledReport.report.sourceConversationId = source.m_nsUsrName
|
||||||
|
if (draft.scheduledReport.target.type === 'contact') {
|
||||||
|
const target = resolve(
|
||||||
|
draft.scheduledReport.target.contactId || '',
|
||||||
|
'person',
|
||||||
|
'scheduledReport.target.contactId'
|
||||||
|
)
|
||||||
|
if (target) draft.scheduledReport.target.contactId = stableId(target)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (draft.ruleType === 'leave_notification' && draft.leaveNotification) {
|
||||||
|
if (draft.leaveNotification.target.type === 'contact') {
|
||||||
|
const target = resolve(
|
||||||
|
draft.leaveNotification.target.contactId || '',
|
||||||
|
'person',
|
||||||
|
'leaveNotification.target.contactId'
|
||||||
|
)
|
||||||
|
if (target) draft.leaveNotification.target.contactId = stableId(target)
|
||||||
|
}
|
||||||
|
const ids: string[] = []
|
||||||
|
for (const [index, query] of draft.leaveNotification.notifyRoomIds.entries()) {
|
||||||
|
const group = resolve(query, 'group', `leaveNotification.notifyRoomIds[${index}]`)
|
||||||
|
if (group) ids.push(group.m_nsUsrName)
|
||||||
|
}
|
||||||
|
draft.leaveNotification.notifyRoomIds = ids
|
||||||
|
}
|
||||||
|
return resolved
|
||||||
|
}
|
||||||
|
|
||||||
|
private toStoreDraft(draft: AutomationRuleDraft, contacts: Contact[]): AutomationRuleDraft {
|
||||||
|
const stored = structuredClone(draft)
|
||||||
|
if (stored.ruleType === 'daily_report') {
|
||||||
|
stored.conditions.conversationIds = stored.conditions.conversationIds.map(
|
||||||
|
(id) => contacts.find((contact) => stableId(contact) === id)?.md5 || id
|
||||||
|
)
|
||||||
|
}
|
||||||
|
return stored
|
||||||
|
}
|
||||||
|
|
||||||
|
private async toApiRules(rules: AutomationRule[]): Promise<unknown[]> {
|
||||||
|
const contacts = await this.deps.listContacts().catch(() => [])
|
||||||
|
return rules.map((rule) => {
|
||||||
|
const copy = structuredClone(rule) as AutomationRule & { requiresReview?: boolean }
|
||||||
|
if (copy.ruleType === 'daily_report') {
|
||||||
|
copy.conditions.conversationIds = copy.conditions.conversationIds.map((id) =>
|
||||||
|
contacts.find((contact) => contact.md5 === id)
|
||||||
|
? stableId(contacts.find((contact) => contact.md5 === id)!)
|
||||||
|
: id
|
||||||
|
)
|
||||||
|
}
|
||||||
|
if (copy.ruleType === 'scheduled_report' && copy.scheduledReport) {
|
||||||
|
copy.requiresReview = copy.scheduledReport.targetNeedsReview === true
|
||||||
|
delete copy.scheduledReport.legacyTarget
|
||||||
|
delete copy.scheduledReport.legacySourceGroup
|
||||||
|
delete copy.scheduledReport.lastRunAt
|
||||||
|
delete copy.scheduledReport.lastScheduledSlot
|
||||||
|
}
|
||||||
|
if (copy.ruleType === 'leave_notification' && copy.leaveNotification) {
|
||||||
|
copy.requiresReview = copy.leaveNotification.targetNeedsReview === true
|
||||||
|
}
|
||||||
|
return copy
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
private describeEffects(draft: AutomationRuleDraft): Record<string, unknown> {
|
||||||
|
if (draft.ruleType === 'scheduled_report' && draft.scheduledReport) {
|
||||||
|
const config = draft.scheduledReport
|
||||||
|
return {
|
||||||
|
generatesReport: true,
|
||||||
|
sendsWechatMessage: true,
|
||||||
|
sourceConversationId: config.report.sourceConversationId,
|
||||||
|
target: config.target
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (draft.ruleType === 'leave_notification' && draft.leaveNotification) {
|
||||||
|
return {
|
||||||
|
sendsWechatMessage: true,
|
||||||
|
monitorScope: 'configured_in_group_exit_monitor',
|
||||||
|
notificationScope: draft.leaveNotification.notifyScope,
|
||||||
|
notificationRoomIds:
|
||||||
|
draft.leaveNotification.notifyScope === 'selected'
|
||||||
|
? draft.leaveNotification.notifyRoomIds
|
||||||
|
: undefined,
|
||||||
|
target: draft.leaveNotification.target
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
actions: draft.actions.filter((action) => action.enabled).map((action) => action.type),
|
||||||
|
sendsWechatMessage: draft.actions.some(
|
||||||
|
(action) => action.enabled && action.type === 'sendReportImage'
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -46,6 +46,21 @@ function parseBody(bodyText: string, contentType?: string): { json?: unknown; bo
|
|||||||
return { bodyText }
|
return { bodyText }
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function materializeEndpointPath(pathname: string, query: Record<string, string>): string {
|
||||||
|
return pathname.replace('{conversationId}', encodeURIComponent(query.conversationId || ''))
|
||||||
|
}
|
||||||
|
|
||||||
|
function appendQueryParameters(
|
||||||
|
url: URL,
|
||||||
|
endpointPath: string,
|
||||||
|
entries: Array<[string, string]>
|
||||||
|
): void {
|
||||||
|
for (const [key, value] of entries) {
|
||||||
|
if (endpointPath.includes(`{${key}}`)) continue
|
||||||
|
if (value.trim()) url.searchParams.set(key, value.trim())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
export function buildLocalApiCurlCommand(payload: unknown): {
|
export function buildLocalApiCurlCommand(payload: unknown): {
|
||||||
success: boolean
|
success: boolean
|
||||||
command?: string
|
command?: string
|
||||||
@@ -71,18 +86,17 @@ export function buildLocalApiCurlCommand(payload: unknown): {
|
|||||||
const service = apiServer.getState()
|
const service = apiServer.getState()
|
||||||
const targetHost = requestHost(service.host)
|
const targetHost = requestHost(service.host)
|
||||||
const hostPart = targetHost.includes(':') ? `[${targetHost}]` : targetHost
|
const hostPart = targetHost.includes(':') ? `[${targetHost}]` : targetHost
|
||||||
const url = new URL(endpoint.path, `http://${hostPart}:${service.port}`)
|
const endpointPath = materializeEndpointPath(endpoint.path, query as Record<string, string>)
|
||||||
entries.forEach(([key, value]) => {
|
const url = new URL(endpointPath, `http://${hostPart}:${service.port}`)
|
||||||
if (value.trim()) url.searchParams.set(key, value.trim())
|
appendQueryParameters(url, endpoint.path, entries)
|
||||||
})
|
|
||||||
const token = endpointId === 'health' ? null : apiTokenStore.getTokenForAuthentication()
|
const token = endpointId === 'health' ? null : apiTokenStore.getTokenForAuthentication()
|
||||||
if (endpointId !== 'health' && !token) {
|
if (endpointId !== 'health' && !token) {
|
||||||
return { success: false, error: 'API Token 安全存储不可用,请在 API Center 检查 Token 状态' }
|
return { success: false, error: 'API Token 安全存储不可用,请在 API Center 检查 Token 状态' }
|
||||||
}
|
}
|
||||||
const authHeader = token ? ` -H 'Authorization: Bearer ${token}'` : ''
|
const authHeader = token ? ` -H 'Authorization: Bearer ${token}'` : ''
|
||||||
const command =
|
const command =
|
||||||
endpoint.method === 'POST'
|
endpoint.method === 'POST' || endpoint.method === 'PATCH'
|
||||||
? `curl -X POST '${url.toString()}'${authHeader} -H 'Content-Type: application/json' -d '${body.replaceAll("'", "\\'")}'`
|
? `curl -X ${endpoint.method} '${url.toString()}'${authHeader} -H 'Content-Type: application/json' -d '${body.replaceAll("'", "\\'")}'`
|
||||||
: `curl '${url.toString()}'${authHeader}`
|
: `curl '${url.toString()}'${authHeader}`
|
||||||
return { success: true, command }
|
return { success: true, command }
|
||||||
}
|
}
|
||||||
@@ -110,10 +124,9 @@ export async function testLocalApiRequest(payload: unknown): Promise<LocalApiTes
|
|||||||
const targetHost = requestHost(service.host)
|
const targetHost = requestHost(service.host)
|
||||||
const targetPort = service.port
|
const targetPort = service.port
|
||||||
const hostPart = targetHost.includes(':') ? `[${targetHost}]` : targetHost
|
const hostPart = targetHost.includes(':') ? `[${targetHost}]` : targetHost
|
||||||
const url = new URL(endpoint.path, `http://${hostPart}:${targetPort}`)
|
const endpointPath = materializeEndpointPath(endpoint.path, query as Record<string, string>)
|
||||||
entries.forEach(([key, value]) => {
|
const url = new URL(endpointPath, `http://${hostPart}:${targetPort}`)
|
||||||
if (value.trim()) url.searchParams.set(key, value.trim())
|
appendQueryParameters(url, endpoint.path, entries)
|
||||||
})
|
|
||||||
|
|
||||||
if (!service.running) {
|
if (!service.running) {
|
||||||
return {
|
return {
|
||||||
@@ -150,7 +163,9 @@ export async function testLocalApiRequest(payload: unknown): Promise<LocalApiTes
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
const headers: Record<string, string> = {}
|
const headers: Record<string, string> = {}
|
||||||
if (endpoint.method === 'POST') headers['Content-Type'] = 'application/json'
|
if (endpoint.method === 'POST' || endpoint.method === 'PATCH') {
|
||||||
|
headers['Content-Type'] = 'application/json'
|
||||||
|
}
|
||||||
if (token) headers.Authorization = `Bearer ${token}`
|
if (token) headers.Authorization = `Bearer ${token}`
|
||||||
const request = http.request(
|
const request = http.request(
|
||||||
url,
|
url,
|
||||||
@@ -208,7 +223,7 @@ export async function testLocalApiRequest(payload: unknown): Promise<LocalApiTes
|
|||||||
error: error.message
|
error: error.message
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
if (endpoint.method === 'POST') request.write(body)
|
if (endpoint.method === 'POST' || endpoint.method === 'PATCH') request.write(body)
|
||||||
request.end()
|
request.end()
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
@@ -19,15 +19,27 @@ import type {
|
|||||||
QueryMessagesRequest,
|
QueryMessagesRequest,
|
||||||
SearchMessagesRequest,
|
SearchMessagesRequest,
|
||||||
MessageContextRequest,
|
MessageContextRequest,
|
||||||
ConversationOverviewRequest
|
ConversationOverviewRequest,
|
||||||
|
VoiceTranscribeItem,
|
||||||
|
VoiceTranscribeRequest,
|
||||||
|
VoiceTranscribeResponse
|
||||||
} from '../../shared/local-query-api'
|
} from '../../shared/local-query-api'
|
||||||
// messageRef 编解码是 main 与 renderer 共用的契约,只定义一次(`src/shared/local-query-api.ts`):
|
// messageRef 编解码是 main 与 renderer 共用的契约,只定义一次(`src/shared/local-query-api.ts`):
|
||||||
// 两侧各写一份 base64url 实现会悄悄漂移,那会让「跳转到原聊天」偶发失效。
|
// 两侧各写一份 base64url 实现会悄悄漂移,那会让「跳转到原聊天」偶发失效。
|
||||||
import {
|
import {
|
||||||
encodeMessageRef as toRef,
|
encodeMessageRef as toRef,
|
||||||
decodeMessageRef as fromRef,
|
decodeMessageRef as fromRef,
|
||||||
normalizeMessageIdentity
|
normalizeMessageIdentity,
|
||||||
|
VOICE_TRANSCRIBE_DEFAULT_WAIT_MS,
|
||||||
|
VOICE_TRANSCRIBE_MAX_REFS,
|
||||||
|
VOICE_TRANSCRIBE_MAX_WAIT_MS
|
||||||
} from '../../shared/local-query-api'
|
} from '../../shared/local-query-api'
|
||||||
|
import type { VoiceMessageReference, VoiceTranscriptSnapshot } from '../../shared/voice-recognition'
|
||||||
|
import { voiceMessageReferenceOf } from '../voice-pipeline/voice-message-identity'
|
||||||
|
import type {
|
||||||
|
VoiceTranscriptionGateway,
|
||||||
|
VoiceTranscriptionOutcome
|
||||||
|
} from '../voice-pipeline/voice-transcription-gateway'
|
||||||
import {
|
import {
|
||||||
IMAGE_TEXT_BACKFILL_TIER_LABEL,
|
IMAGE_TEXT_BACKFILL_TIER_LABEL,
|
||||||
describeImageTextCoverage,
|
describeImageTextCoverage,
|
||||||
@@ -52,8 +64,11 @@ const kinds: QueryMessageType[] = ['text', 'image', 'voice', 'video', 'file', 'l
|
|||||||
*
|
*
|
||||||
* 一次完整 pass 的耗时以分钟计,远超任何交互预算。所以这个预算只用来兜住「已经很接近追平」
|
* 一次完整 pass 的耗时以分钟计,远超任何交互预算。所以这个预算只用来兜住「已经很接近追平」
|
||||||
* 的情况:追不上就按当前覆盖如实回答并让后台继续追,而不是把查询卡在索引上。
|
* 的情况:追不上就按当前覆盖如实回答并让后台继续追,而不是把查询卡在索引上。
|
||||||
|
*
|
||||||
|
* 2 秒连"索引已经快跑完"都等不到,就会出现**索引正在追、查询却拿旧覆盖下结论**的矛盾表现。
|
||||||
|
* 15 秒仍远小于一次完整 pass,不会把查询卡住,但足以覆盖"追平在即"的绝大多数情况。
|
||||||
*/
|
*/
|
||||||
const QUERY_FRESHNESS_WAIT_BUDGET_MS = 2000
|
const QUERY_FRESHNESS_WAIT_BUDGET_MS = 15000
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 两次由查询触发的追赶之间的最小间隔,避免每个 Query 都重跑一遍索引。
|
* 两次由查询触发的追赶之间的最小间隔,避免每个 Query 都重跑一遍索引。
|
||||||
@@ -108,17 +123,26 @@ function formatLocalMinute(ms: number): string {
|
|||||||
function buildIndexCoverage(
|
function buildIndexCoverage(
|
||||||
indexLatestAt: number | null,
|
indexLatestAt: number | null,
|
||||||
sourceLatestAt: number | null,
|
sourceLatestAt: number | null,
|
||||||
covered: boolean
|
covered: boolean,
|
||||||
|
directReadApplied = false
|
||||||
): QueryIndexCoverage | undefined {
|
): QueryIndexCoverage | undefined {
|
||||||
if (indexLatestAt === null) return undefined
|
if (indexLatestAt === null) return undefined
|
||||||
const indexLabel = formatLocalMinute(indexLatestAt)
|
const indexLabel = formatLocalMinute(indexLatestAt)
|
||||||
return {
|
return {
|
||||||
|
// 注意:直读补齐**不**把 covered 改成 true。
|
||||||
|
//
|
||||||
|
// 直读只扫了 `indexLatestAt` 之后那一段(权威源、全量),更早的部分仍然依赖索引;
|
||||||
|
// 而 `indexLatestAt` 是**全局**水位,不代表"这个会话在更早区间被索引得多完整"。
|
||||||
|
// 所以这里保持诚实:覆盖结论不变,只在 summary 里说明"这之后已用直读补齐"。
|
||||||
|
// 一旦把 covered 改成 true,prompt 就会允许模型在 0 结果时下"没有",那是错误的否定。
|
||||||
covered,
|
covered,
|
||||||
indexLatestAtLabel: indexLabel,
|
indexLatestAtLabel: indexLabel,
|
||||||
...(sourceLatestAt !== null ? { sourceLatestAtLabel: formatLocalMinute(sourceLatestAt) } : {}),
|
...(sourceLatestAt !== null ? { sourceLatestAtLabel: formatLocalMinute(sourceLatestAt) } : {}),
|
||||||
summary: covered
|
summary: directReadApplied
|
||||||
? `可搜索索引已覆盖所问的时间范围(索引最新到 ${indexLabel})。`
|
? `关键词索引只更新到 ${indexLabel};这之后的聊天已改用直读原始记录补齐,本会话该区间的结果来自直读。`
|
||||||
: `可搜索索引只更新到 ${indexLabel},这之后的聊天还没进索引,这段时间是否聊过暂时无法确认。`
|
: covered
|
||||||
|
? `可搜索索引已覆盖所问的时间范围(索引最新到 ${indexLabel})。`
|
||||||
|
: `可搜索索引只更新到 ${indexLabel},这之后的聊天还没进索引,这段时间是否聊过暂时无法确认。`
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -223,7 +247,8 @@ function toQueryMessage(
|
|||||||
conversationId: string,
|
conversationId: string,
|
||||||
message: FormattedMessage,
|
message: FormattedMessage,
|
||||||
target: FormattedContact,
|
target: FormattedContact,
|
||||||
imageOcr?: { state: string; text: string }
|
imageOcr?: { state: string; text: string },
|
||||||
|
voice?: VoiceTranscriptSnapshot
|
||||||
): QueryMessage {
|
): QueryMessage {
|
||||||
const kind = kindOf(message)
|
const kind = kindOf(message)
|
||||||
const content = message.contentData
|
const content = message.contentData
|
||||||
@@ -247,7 +272,12 @@ function toQueryMessage(
|
|||||||
: derived.state === 'empty'
|
: derived.state === 'empty'
|
||||||
? 'empty'
|
? 'empty'
|
||||||
: 'not_indexed'
|
: 'not_indexed'
|
||||||
return { messageRef: toRef(conversationId, message.id), timestamp: (message.createTime || 0) * 1000, datetime: message.datetime, sender: message.isSender ? '我' : (message.name || target.m_nsNickName), direction: message.isSender ? 'to_target' : 'from_target', messageType: kind, sourceKind: kind, ...(attachment ? { attachment } : {}), ...(text ? { text } : {}), ...(ocrText ? { imageOcrText: ocrText, derivedSource: 'image_ocr' as const } : {}), ...(kind === 'image' ? { imageTextState } : {}) }
|
// 语音转写与图片 OCR 同为派生文本:走独立字段,不改写 `text`(语音正文是 `[语音消息]`)。
|
||||||
|
const voiceText = kind === 'voice' && voice?.state === 'transcribed' ? voice.transcript?.trim() || '' : ''
|
||||||
|
const voiceFields = kind === 'voice' && voice
|
||||||
|
? { voiceTranscriptState: voice.state, ...(voiceText ? { voiceTranscript: voiceText, derivedSource: 'voice_transcript' as const } : {}) }
|
||||||
|
: {}
|
||||||
|
return { messageRef: toRef(conversationId, message.id), timestamp: (message.createTime || 0) * 1000, datetime: message.datetime, sender: message.isSender ? '我' : (message.name || target.m_nsNickName), direction: message.isSender ? 'to_target' : 'from_target', messageType: kind, sourceKind: kind, ...(attachment ? { attachment } : {}), ...(text ? { text } : {}), ...(ocrText ? { imageOcrText: ocrText, derivedSource: 'image_ocr' as const } : {}), ...(kind === 'image' ? { imageTextState } : {}), ...voiceFields }
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -299,6 +329,45 @@ function outsideScopeError(scope: ResolvedCorpusScope, actual: string): { status
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
type VoiceTranscriptionPort = Pick<VoiceTranscriptionGateway, 'snapshot' | 'transcribe' | 'modelReady' | 'inFlightCount'>
|
||||||
|
|
||||||
|
const VOICE_MODEL_NOT_READY_HINT =
|
||||||
|
'本机还没有可用的离线语音识别模型。请让用户在 TraceMemo 设置里下载语音识别模型后再试;在此之前不要重试。'
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 语音转写条目的原因码 → 给调用方(通常是 AI)的下一步建议。
|
||||||
|
* 关键是把"还没转完 / 转不了 / 不该转"三类分开,避免模型把它们说成"语音里没内容"。
|
||||||
|
*/
|
||||||
|
const VOICE_ITEM_HINTS: Record<string, string> = {
|
||||||
|
invalid_message_ref: 'messageRef 无法解析。请原样使用 query/messages、query/message-context 或 chatlog 返回的 messageRef,不要自行构造。',
|
||||||
|
message_not_found: '找不到这条消息(可能已切换账号或消息已不存在)。请重新读取消息,用新的 messageRef 调用。',
|
||||||
|
not_voice_message: '这不是语音消息,不需要转写。只对 messageType=voice(chatlog 中 type=语音)的消息调用。',
|
||||||
|
still_processing: '已在本机后台排队转写。稍后用同样的 messageRef 再调用一次即可取回结果,不会重复排队;在此之前不能认定这条语音没有内容。',
|
||||||
|
previously_failed: '这条语音之前识别失败,默认不会自动重跑。除非用户明确要求,不要反复重试;确需重试时传 force=true。',
|
||||||
|
recognition_timeout: '本机识别超时。可以稍后传 force=true 重试一次;仍失败就如实告诉用户这条语音无法转写。',
|
||||||
|
recognition_failed: '本机识别失败(音频可能损坏、过短或没有人声)。不要立即重复调用,如实告诉用户这条语音无法转写即可。',
|
||||||
|
voice_model_not_ready: VOICE_MODEL_NOT_READY_HINT,
|
||||||
|
not_connected: 'TraceMemo 当前没有连接微信数据库。请让用户在 TraceMemo 中重新连接后再试。',
|
||||||
|
cancelled: '识别被取消(可能切换了账号或移除了模型)。确认环境正常后可再调用一次。'
|
||||||
|
}
|
||||||
|
|
||||||
|
function voiceFailureCode(outcome: Extract<VoiceTranscriptionOutcome, { state: 'failed' }>): string {
|
||||||
|
if (outcome.code === 'PREVIOUSLY_FAILED') return 'previously_failed'
|
||||||
|
if (outcome.code === 'TIMEOUT') return 'recognition_timeout'
|
||||||
|
if (outcome.code === 'MODEL_NOT_READY') return 'voice_model_not_ready'
|
||||||
|
if (outcome.code === 'NOT_CONNECTED') return 'not_connected'
|
||||||
|
if (outcome.code === 'CANCELLED') return 'cancelled'
|
||||||
|
return 'recognition_failed'
|
||||||
|
}
|
||||||
|
|
||||||
|
function voiceItemProblem(messageRef: string, state: 'pending' | 'failed', code: string, error?: string): VoiceTranscribeItem {
|
||||||
|
return { messageRef, state, code, ...(error ? { error } : {}), hint: VOICE_ITEM_HINTS[code] }
|
||||||
|
}
|
||||||
|
|
||||||
|
function invalidVoiceTranscribeArguments(field: string, constraint: string, hint: string): VoiceTranscribeResponse & Record<string, unknown> {
|
||||||
|
return { status: 'invalid_tool_arguments', field, constraint, hint }
|
||||||
|
}
|
||||||
|
|
||||||
export class LocalQueryApiService {
|
export class LocalQueryApiService {
|
||||||
/**
|
/**
|
||||||
* 图片文字索引覆盖度提供者(同步、只读)。
|
* 图片文字索引覆盖度提供者(同步、只读)。
|
||||||
@@ -343,8 +412,24 @@ export class LocalQueryApiService {
|
|||||||
): void {
|
): void {
|
||||||
this.imageOcrEntry = provider
|
this.imageOcrEntry = provider
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 语音转写入口。读消息时只读它的缓存快照(不触发识别);
|
||||||
|
* 只有 `transcribeVoice` 会真正排队识别。
|
||||||
|
*/
|
||||||
|
private voiceTranscription: VoiceTranscriptionPort | undefined
|
||||||
|
|
||||||
|
setVoiceTranscriptionGateway(gateway: VoiceTranscriptionPort | undefined): void {
|
||||||
|
this.voiceTranscription = gateway
|
||||||
|
}
|
||||||
|
|
||||||
|
private voiceSnapshot(message: FormattedMessage): VoiceTranscriptSnapshot | undefined {
|
||||||
|
const reference = voiceMessageReferenceOf(message)
|
||||||
|
return reference ? this.voiceTranscription?.snapshot(reference) : undefined
|
||||||
|
}
|
||||||
|
|
||||||
capabilities(): QueryCapabilitiesResponse {
|
capabilities(): QueryCapabilitiesResponse {
|
||||||
return { version: 1, tools: { query_messages: { operation: '读取指定联系人的确定性消息', directions: ['any', 'from_target', 'to_target'], messageTypes: kinds, timeRanges: ['all', 'today', 'yesterday', 'this_week', 'last_7_days', 'this_month', 'previous_month', 'this_year', 'previous_year', 'absolute'], limitMax: LIMIT_MAX }, search_messages: { operation: '受限 Knowledge 关键词检索', timeRanges: ['all', 'today', 'yesterday', 'this_week', 'last_7_days', 'this_month', 'previous_month', 'this_year', 'previous_year', 'absolute'], limitMax: LIMIT_MAX }, message_context: { operation: '读取消息前后文', timeRanges: ['all'], limitMax: CONTEXT_MAX }, conversation_overview: { operation: '按会话时间片提取概览证据', timeRanges: ['all', 'today', 'yesterday', 'this_week', 'last_7_days', 'this_month', 'previous_month', 'this_year', 'previous_year', 'absolute'], limitMax: LIMIT_MAX } } }
|
return { version: 1, tools: { query_messages: { operation: '读取指定联系人的确定性消息', directions: ['any', 'from_target', 'to_target'], messageTypes: kinds, timeRanges: ['all', 'today', 'yesterday', 'this_week', 'last_7_days', 'this_month', 'previous_month', 'this_year', 'previous_year', 'absolute'], limitMax: LIMIT_MAX }, search_messages: { operation: '受限 Knowledge 关键词检索', timeRanges: ['all', 'today', 'yesterday', 'this_week', 'last_7_days', 'this_month', 'previous_month', 'this_year', 'previous_year', 'absolute'], limitMax: LIMIT_MAX }, message_context: { operation: '读取消息前后文', timeRanges: ['all'], limitMax: CONTEXT_MAX }, conversation_overview: { operation: '按会话时间片提取概览证据', timeRanges: ['all', 'today', 'yesterday', 'this_week', 'last_7_days', 'this_month', 'previous_month', 'this_year', 'previous_year', 'absolute'], limitMax: LIMIT_MAX }, voice_transcribe: { operation: '把指定语音消息转成文字(本机离线识别,结果缓存)', timeRanges: [], limitMax: VOICE_TRANSCRIBE_MAX_REFS } } }
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -416,7 +501,7 @@ export class LocalQueryApiService {
|
|||||||
kindOf(message) === 'image'
|
kindOf(message) === 'image'
|
||||||
? this.imageOcrEntry?.(contact.md5, sourceMessageId(message))
|
? this.imageOcrEntry?.(contact.md5, sourceMessageId(message))
|
||||||
: undefined
|
: undefined
|
||||||
return toQueryMessage(contact.md5, message, contact, ocr)
|
return toQueryMessage(contact.md5, message, contact, ocr, this.voiceSnapshot(message))
|
||||||
})
|
})
|
||||||
const imageOcrCoverage = buildImageOcrCoverage(this.imageTextCoverage())
|
const imageOcrCoverage = buildImageOcrCoverage(this.imageTextCoverage())
|
||||||
return { status: 'completed' as const, target: contactView(contact), query: { direction, messageTypes: request.messageTypes || [], order: request.order || 'asc', limit: Math.min(LIMIT_MAX, Math.max(1, request.limit || 20)), excludeSystem: request.excludeSystem !== false, resolvedTimeRange: range }, coverage: { state: 'complete' as const }, returnedCount: filtered.length, messages, scope: corpus.scope, ...(imageOcrCoverage ? { imageOcrCoverage } : {}) }
|
return { status: 'completed' as const, target: contactView(contact), query: { direction, messageTypes: request.messageTypes || [], order: request.order || 'asc', limit: Math.min(LIMIT_MAX, Math.max(1, request.limit || 20)), excludeSystem: request.excludeSystem !== false, resolvedTimeRange: range }, coverage: { state: 'complete' as const }, returnedCount: filtered.length, messages, scope: corpus.scope, ...(imageOcrCoverage ? { imageOcrCoverage } : {}) }
|
||||||
@@ -471,6 +556,7 @@ export class LocalQueryApiService {
|
|||||||
let found: Awaited<ReturnType<LocalQueryApiService['probe']>>
|
let found: Awaited<ReturnType<LocalQueryApiService['probe']>>
|
||||||
let freshness: { resynced: boolean; catchUp: 'none' | 'reused' | 'skipped' | 'completed' | 'pending' }
|
let freshness: { resynced: boolean; catchUp: 'none' | 'reused' | 'skipped' | 'completed' | 'pending' }
|
||||||
let freshnessMs = 0
|
let freshnessMs = 0
|
||||||
|
let directFallback: { evidence: Map<string, QueryEvidenceItem>; scanned: number } | undefined
|
||||||
try {
|
try {
|
||||||
found = await this.probe(probes, conversationIds, range, limit, contactByMd5, retrievalSessionId)
|
found = await this.probe(probes, conversationIds, range, limit, contactByMd5, retrievalSessionId)
|
||||||
probeMs.push(...found.probeMs)
|
probeMs.push(...found.probeMs)
|
||||||
@@ -489,13 +575,38 @@ export class LocalQueryApiService {
|
|||||||
enrichmentMs += reProbe.enrichmentMs
|
enrichmentMs += reProbe.enrichmentMs
|
||||||
found = reProbe
|
found = reProbe
|
||||||
}
|
}
|
||||||
|
// 直读兜底必须在这个 `beginInteractiveQuery` 窗口内跑。
|
||||||
|
//
|
||||||
|
// 这个窗口的作用就是让后台索引让路;一旦 `endInteractiveQuery()` 放开,
|
||||||
|
// 正在追赶的索引会立刻进来抢 WCDB,把直读拖成几十秒。
|
||||||
|
const soleId = conversationIds && conversationIds.length === 1 ? conversationIds[0] : undefined
|
||||||
|
const soleContact = soleId ? contactByMd5.get(soleId) : undefined
|
||||||
|
if (!indexCovers(found.indexLatestAt, requestedEnd, found.sourceLatestAt) && soleContact) {
|
||||||
|
// 索引不可信、而范围又恰好是一个会话 → 用 WCDB 直读把索引落后的那一段补上。
|
||||||
|
// 微信机器人问"某个群最近聊了 X"时,这正是"索引没追完就拿不到东西"的解药。
|
||||||
|
directFallback = await this.directReadKeywordFallback({
|
||||||
|
conversationId: soleContact.md5,
|
||||||
|
contact: soleContact,
|
||||||
|
probes,
|
||||||
|
fromMs: found.indexLatestAt,
|
||||||
|
range,
|
||||||
|
limit
|
||||||
|
})
|
||||||
|
}
|
||||||
} finally {
|
} finally {
|
||||||
this.knowledge.endInteractiveQuery()
|
this.knowledge.endInteractiveQuery()
|
||||||
}
|
}
|
||||||
const requestedEnd = rangeEndMs(range, this.nowProvider().getTime())
|
const requestedEnd = rangeEndMs(range, this.nowProvider().getTime())
|
||||||
|
|
||||||
const covered = indexCovers(found.indexLatestAt, requestedEnd, found.sourceLatestAt)
|
const covered = indexCovers(found.indexLatestAt, requestedEnd, found.sourceLatestAt)
|
||||||
const indexCoverage = buildIndexCoverage(found.indexLatestAt, found.sourceLatestAt, covered)
|
const evidence = new Map(found.evidence)
|
||||||
|
if (directFallback) for (const [key, item] of directFallback.evidence) evidence.set(key, item)
|
||||||
|
const indexCoverage = buildIndexCoverage(
|
||||||
|
found.indexLatestAt,
|
||||||
|
found.sourceLatestAt,
|
||||||
|
covered,
|
||||||
|
directFallback !== undefined
|
||||||
|
)
|
||||||
// 图片文字索引是**独立覆盖维度**:文字索引再完整也不代表图片里的文字搜得到。
|
// 图片文字索引是**独立覆盖维度**:文字索引再完整也不代表图片里的文字搜得到。
|
||||||
const imageOcrCoverage = buildImageOcrCoverage(this.imageTextCoverage())
|
const imageOcrCoverage = buildImageOcrCoverage(this.imageTextCoverage())
|
||||||
const timings: QuerySearchTimings = {
|
const timings: QuerySearchTimings = {
|
||||||
@@ -513,8 +624,8 @@ export class LocalQueryApiService {
|
|||||||
resolvedTimeRange: range,
|
resolvedTimeRange: range,
|
||||||
coverage: { state: this.searchCoverage(found, requestedEnd) },
|
coverage: { state: this.searchCoverage(found, requestedEnd) },
|
||||||
probeCount: probes.length,
|
probeCount: probes.length,
|
||||||
evidenceCount: found.evidence.size,
|
evidenceCount: evidence.size,
|
||||||
evidence: Array.from(found.evidence.values()).slice(0, limit),
|
evidence: Array.from(evidence.values()).slice(0, limit),
|
||||||
scope: corpus.scope,
|
scope: corpus.scope,
|
||||||
indexLatestAt: found.indexLatestAt,
|
indexLatestAt: found.indexLatestAt,
|
||||||
sourceLatestAt: found.sourceLatestAt,
|
sourceLatestAt: found.sourceLatestAt,
|
||||||
@@ -525,6 +636,80 @@ export class LocalQueryApiService {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 索引不可信时的**直读兜底** —— 只在"范围恰好是一个会话"时启用。
|
||||||
|
*
|
||||||
|
* `search_messages` 是四个 Query Tool 里唯一依赖派生索引的:索引在追赶期间它给不出新消息,
|
||||||
|
* 而 WCDB 才是权威源、永远最新。跨会话直读不可行(要遍历上千个会话,实测大会话全量读一次
|
||||||
|
* 15s 以上),但**单个会话**成本可控 —— 所以只在这一种形状下降级,其余情况仍如实标 partial。
|
||||||
|
*
|
||||||
|
* 只扫索引**没覆盖**的那一段(`fromMs` 之后):已经进索引的部分仍以索引结果为准,不重复劳动。
|
||||||
|
* 匹配口径与索引保持一致:正文 + 语音转写 + 图片 OCR 派生文本。
|
||||||
|
*/
|
||||||
|
private async directReadKeywordFallback(input: {
|
||||||
|
conversationId: string
|
||||||
|
contact: FormattedContact
|
||||||
|
probes: string[]
|
||||||
|
/** 索引水位(epoch **毫秒**);null 表示索引还没建立过,那就从头扫。 */
|
||||||
|
fromMs: number | null
|
||||||
|
range: ResolvedTimeRange
|
||||||
|
limit: number
|
||||||
|
}): Promise<{ evidence: Map<string, QueryEvidenceItem>; scanned: number }> {
|
||||||
|
// freshness 是**毫秒**口径,而 WCDB 读消息的时间窗是**秒**口径。
|
||||||
|
// 显式换算,不让两种单位在同一个表达式里静默错位(这个坑历史上踩过)。
|
||||||
|
const coveredSeconds = input.fromMs === null ? undefined : Math.floor(input.fromMs / 1000)
|
||||||
|
const startTime =
|
||||||
|
coveredSeconds === undefined
|
||||||
|
? input.range.startTime
|
||||||
|
: input.range.startTime === undefined
|
||||||
|
? coveredSeconds
|
||||||
|
: Math.max(input.range.startTime, coveredSeconds)
|
||||||
|
|
||||||
|
const raw = await listMessagesAsync(input.conversationId, startTime, input.range.endTime)
|
||||||
|
const needles = input.probes
|
||||||
|
.map((value) => value.trim().toLowerCase())
|
||||||
|
.filter(Boolean)
|
||||||
|
const evidence = new Map<string, QueryEvidenceItem>()
|
||||||
|
for (const message of raw) {
|
||||||
|
if (evidence.size >= input.limit) break
|
||||||
|
const kind = kindOf(message)
|
||||||
|
const ocr =
|
||||||
|
kind === 'image' ? this.imageOcrEntry?.(input.conversationId, sourceMessageId(message)) : undefined
|
||||||
|
const haystack = [
|
||||||
|
message.content,
|
||||||
|
message.voiceTranscript,
|
||||||
|
ocr && ocr.state === 'indexed' ? ocr.text : ''
|
||||||
|
]
|
||||||
|
.filter(Boolean)
|
||||||
|
.join('\n')
|
||||||
|
.toLowerCase()
|
||||||
|
if (!haystack || !needles.some((needle) => haystack.includes(needle))) continue
|
||||||
|
const item = toQueryMessage(
|
||||||
|
input.conversationId,
|
||||||
|
message,
|
||||||
|
input.contact,
|
||||||
|
ocr,
|
||||||
|
this.voiceSnapshot(message)
|
||||||
|
)
|
||||||
|
// key 必须与索引路径一致(`会话:归一化消息 id`):两条路径可能命中同一条消息,
|
||||||
|
// 合并时要能去重。`message.id` 可能带 `local:` 装饰,所以走归一化。
|
||||||
|
const normalizedId = normalizeMessageIdentity(input.conversationId, message.id)?.messageId
|
||||||
|
if (!normalizedId) continue
|
||||||
|
evidence.set(`${input.conversationId}:${normalizedId}`, {
|
||||||
|
messageRef: item.messageRef,
|
||||||
|
timestamp: item.timestamp,
|
||||||
|
sender: item.sender,
|
||||||
|
sourceKind: item.sourceKind,
|
||||||
|
text: toEvidenceDisplayText(item.text ?? ''),
|
||||||
|
...(item.derivedSource ? { derivedSource: item.derivedSource } : {}),
|
||||||
|
...(item.imageOcrText ? { imageOcrText: item.imageOcrText } : {}),
|
||||||
|
conversationName: contactView(input.contact).displayName,
|
||||||
|
conversationType: input.contact.type
|
||||||
|
})
|
||||||
|
}
|
||||||
|
return { evidence, scanned: raw.length }
|
||||||
|
}
|
||||||
|
|
||||||
/** 逐 probe 检索并合并去重;同时记录派生索引的覆盖口径与真实耗时分解。 */
|
/** 逐 probe 检索并合并去重;同时记录派生索引的覆盖口径与真实耗时分解。 */
|
||||||
private async probe(
|
private async probe(
|
||||||
probes: string[],
|
probes: string[],
|
||||||
@@ -648,12 +833,19 @@ export class LocalQueryApiService {
|
|||||||
if (lag <= worthThreshold) return { resynced: false, catchUp: 'skipped' }
|
if (lag <= worthThreshold) return { resynced: false, catchUp: 'skipped' }
|
||||||
|
|
||||||
const request = this.knowledge.requestCatchUp(QUERY_CATCH_UP_MIN_INTERVAL_MS)
|
const request = this.knowledge.requestCatchUp(QUERY_CATCH_UP_MIN_INTERVAL_MS)
|
||||||
if (!request.triggered) {
|
// 只有在"刚刚触发过、节流窗口内"时才不等 —— 那种情况再等也没意义。
|
||||||
// 已经在跑 → 复用;刚触发过 → 节流。两种都不阻塞本次查询,后台继续追。
|
if (!request.triggered && !request.inProgress) {
|
||||||
return { resynced: false, catchUp: request.inProgress ? 'reused' : 'skipped' }
|
return { resynced: false, catchUp: 'skipped' }
|
||||||
}
|
}
|
||||||
|
// 本次触发、以及**正在跑(复用)**两种都要等。
|
||||||
|
//
|
||||||
|
// 复用场景若直接返回旧快照,就会出现**索引明明在追、查询却拿旧覆盖下结论**的表现。
|
||||||
|
// 等待后统一 `resynced: true`:即使没等到追平,索引也可能前进了一段,值得按新覆盖重查一次。
|
||||||
const completed = await this.knowledge.waitForIndexingComplete(QUERY_FRESHNESS_WAIT_BUDGET_MS)
|
const completed = await this.knowledge.waitForIndexingComplete(QUERY_FRESHNESS_WAIT_BUDGET_MS)
|
||||||
return { resynced: true, catchUp: completed ? 'completed' : 'pending' }
|
return {
|
||||||
|
resynced: true,
|
||||||
|
catchUp: completed ? 'completed' : request.triggered ? 'pending' : 'reused'
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -685,9 +877,92 @@ export class LocalQueryApiService {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
const before = Math.min(CONTEXT_MAX, Math.max(0, request.before ?? 10)); const after = Math.min(CONTEXT_MAX, Math.max(0, request.after ?? 10)); const messages = await listMessagesAsync(ref.conversationId); const index = messages.findIndex((message) => normalizeMessageIdentity(ref.conversationId, message.id)?.messageId === ref.messageId); if (index < 0) return { status: 'contact_not_found' as const }
|
const before = Math.min(CONTEXT_MAX, Math.max(0, request.before ?? 10)); const after = Math.min(CONTEXT_MAX, Math.max(0, request.after ?? 10)); const messages = await listMessagesAsync(ref.conversationId); const index = messages.findIndex((message) => normalizeMessageIdentity(ref.conversationId, message.id)?.messageId === ref.messageId); if (index < 0) return { status: 'contact_not_found' as const }
|
||||||
const contact = (await listContactsAsync()).find((item) => item.md5 === ref.conversationId); if (!contact) return { status: 'contact_not_found' as const }; const map = (message: FormattedMessage) => toQueryMessage(ref.conversationId, message, contact)
|
const contact = (await listContactsAsync()).find((item) => item.md5 === ref.conversationId); if (!contact) return { status: 'contact_not_found' as const }; const map = (message: FormattedMessage) => toQueryMessage(ref.conversationId, message, contact, undefined, this.voiceSnapshot(message))
|
||||||
return { status: 'completed' as const, anchor: map(messages[index]), before: messages.slice(Math.max(0, index - before), index).map(map), after: messages.slice(index + 1, index + 1 + after).map(map) }
|
return { status: 'completed' as const, anchor: map(messages[index]), before: messages.slice(Math.max(0, index - before), index).map(map), after: messages.slice(index + 1, index + 1 + after).map(map) }
|
||||||
}
|
}
|
||||||
|
/**
|
||||||
|
* 把指定语音消息转成文字。
|
||||||
|
*
|
||||||
|
* 这是 Query API 里**唯一会触发计算**的操作:识别在本机离线进行、结果写入语音缓存,
|
||||||
|
* 之后 query/messages 等读路径就能直接读到。并发、去重与排队上限见 VoiceTranscriptionGateway。
|
||||||
|
*/
|
||||||
|
async transcribeVoice(request: VoiceTranscribeRequest): Promise<VoiceTranscribeResponse> {
|
||||||
|
const refs = request?.messageRefs
|
||||||
|
if (!Array.isArray(refs) || refs.length === 0 || refs.some((ref) => typeof ref !== 'string' || !ref)) {
|
||||||
|
return invalidVoiceTranscribeArguments('messageRefs', 'non_empty_string_array', 'messageRefs 必须是非空字符串数组,元素取自 query/messages 或 chatlog 返回的语音消息 messageRef。')
|
||||||
|
}
|
||||||
|
if (refs.length > VOICE_TRANSCRIBE_MAX_REFS) {
|
||||||
|
return invalidVoiceTranscribeArguments('messageRefs', `max_items_${VOICE_TRANSCRIBE_MAX_REFS}`, `一次最多转写 ${VOICE_TRANSCRIBE_MAX_REFS} 条语音,请分批调用。`)
|
||||||
|
}
|
||||||
|
if (request.force !== undefined && typeof request.force !== 'boolean') {
|
||||||
|
return invalidVoiceTranscribeArguments('force', 'boolean', 'force 只能是 true 或 false。')
|
||||||
|
}
|
||||||
|
const waitMs = request.waitMs ?? VOICE_TRANSCRIBE_DEFAULT_WAIT_MS
|
||||||
|
if (typeof waitMs !== 'number' || !Number.isFinite(waitMs) || waitMs < 0 || waitMs > VOICE_TRANSCRIBE_MAX_WAIT_MS) {
|
||||||
|
return invalidVoiceTranscribeArguments('waitMs', `0_to_${VOICE_TRANSCRIBE_MAX_WAIT_MS}`, `waitMs 必须是 0 到 ${VOICE_TRANSCRIBE_MAX_WAIT_MS} 之间的毫秒数;0 表示只排队、不等待。`)
|
||||||
|
}
|
||||||
|
const gateway = this.voiceTranscription
|
||||||
|
if (!gateway) return { status: 'voice_transcription_unavailable', hint: '当前 TraceMemo 没有启用语音转写服务,无法转写语音。' }
|
||||||
|
if (!isReady()) return { status: 'knowledge_unavailable', hint: VOICE_ITEM_HINTS.not_connected }
|
||||||
|
if (!(await gateway.modelReady())) return { status: 'voice_model_not_ready', hint: VOICE_MODEL_NOT_READY_HINT }
|
||||||
|
|
||||||
|
const uniqueRefs = Array.from(new Set(refs))
|
||||||
|
const problems = new Map<string, VoiceTranscribeItem>()
|
||||||
|
const references = new Map<string, VoiceMessageReference>()
|
||||||
|
const refsByConversation = new Map<string, Array<{ messageRef: string; messageId: string }>>()
|
||||||
|
for (const messageRef of uniqueRefs) {
|
||||||
|
const identity = fromRef(messageRef)
|
||||||
|
if (!identity) {
|
||||||
|
problems.set(messageRef, voiceItemProblem(messageRef, 'failed', 'invalid_message_ref'))
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
const group = refsByConversation.get(identity.conversationId) || []
|
||||||
|
group.push({ messageRef, messageId: identity.messageId })
|
||||||
|
refsByConversation.set(identity.conversationId, group)
|
||||||
|
}
|
||||||
|
// 同一会话只读一次源消息;与 message-context 同样按会话读取后匹配消息身份。
|
||||||
|
for (const [conversationId, wanted] of refsByConversation) {
|
||||||
|
const messages = await listMessagesAsync(conversationId)
|
||||||
|
const byId = new Map(messages.map((message) => [normalizeMessageIdentity(conversationId, message.id)?.messageId, message]))
|
||||||
|
for (const { messageRef, messageId } of wanted) {
|
||||||
|
const message = byId.get(messageId)
|
||||||
|
const reference = message ? voiceMessageReferenceOf(message) : undefined
|
||||||
|
if (reference) references.set(messageRef, reference)
|
||||||
|
else problems.set(messageRef, voiceItemProblem(messageRef, 'failed', message ? 'not_voice_message' : 'message_not_found'))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const pendingRefs = Array.from(references.keys())
|
||||||
|
const outcomes = pendingRefs.length
|
||||||
|
? await gateway.transcribe(pendingRefs.map((ref) => references.get(ref)!), { force: request.force, waitMs })
|
||||||
|
: []
|
||||||
|
if (!outcomes) {
|
||||||
|
// 粗估:按每条语音约 1 秒的本机识别耗时。
|
||||||
|
const retryAfterSeconds = Math.max(5, gateway.inFlightCount)
|
||||||
|
return { status: 'busy', retryAfterSeconds, hint: `本机语音转写队列已满。请等待约 ${retryAfterSeconds} 秒后用同样的参数重试,或减少本次的 messageRefs 数量。` }
|
||||||
|
}
|
||||||
|
const resolved = new Map<string, VoiceTranscribeItem>()
|
||||||
|
pendingRefs.forEach((messageRef, index) => {
|
||||||
|
const outcome = outcomes[index]
|
||||||
|
if (outcome.state === 'transcribed') {
|
||||||
|
resolved.set(messageRef, { messageRef, state: 'transcribed', transcript: outcome.transcript, cached: outcome.cached, ...(outcome.durationMs !== undefined ? { durationMs: outcome.durationMs } : {}) })
|
||||||
|
} else if (outcome.state === 'pending') {
|
||||||
|
resolved.set(messageRef, voiceItemProblem(messageRef, 'pending', 'still_processing'))
|
||||||
|
} else {
|
||||||
|
resolved.set(messageRef, voiceItemProblem(messageRef, 'failed', voiceFailureCode(outcome), outcome.error))
|
||||||
|
}
|
||||||
|
})
|
||||||
|
const items = uniqueRefs.map((ref) => resolved.get(ref) || problems.get(ref)!)
|
||||||
|
const summary = { transcribed: 0, pending: 0, failed: 0 }
|
||||||
|
for (const item of items) summary[item.state] += 1
|
||||||
|
return {
|
||||||
|
status: 'completed',
|
||||||
|
items,
|
||||||
|
summary,
|
||||||
|
...(summary.pending ? { hint: VOICE_ITEM_HINTS.still_processing } : {})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 会话概览。
|
* 会话概览。
|
||||||
*
|
*
|
||||||
|
|||||||
@@ -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
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,20 +1,30 @@
|
|||||||
import { spawn, type ChildProcess } from 'child_process'
|
import { spawn, type ChildProcess } from 'child_process'
|
||||||
import { chmodSync, existsSync } from 'fs'
|
import { chmodSync, existsSync } from 'fs'
|
||||||
import { get } from 'http'
|
import { get, request as httpRequest } from 'http'
|
||||||
import { join } from 'path'
|
import { join } from 'path'
|
||||||
|
|
||||||
import { app } from 'electron'
|
import { app } from 'electron'
|
||||||
|
|
||||||
import { appLogger } from '../app-logger'
|
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 {
|
import type {
|
||||||
MacWechatBindResult,
|
MacWechatBindResult,
|
||||||
MacWechatBindingStatus,
|
MacWechatBindingStatus,
|
||||||
MacWechatRuntimeManifest,
|
MacWechatRuntimeManifest,
|
||||||
MacWechatRuntimeLifecycle,
|
MacWechatRuntimeLifecycle,
|
||||||
MacWechatRuntimeSnapshot
|
MacWechatRuntimeSnapshot,
|
||||||
|
MacWechatSendRuntimeAvailabilityResult
|
||||||
} from '../../shared/personal-wechat-mac-runtime'
|
} from '../../shared/personal-wechat-mac-runtime'
|
||||||
import type { PersonalWechatSenderStatus } from '../../shared/personal-wechat'
|
import type { PersonalWechatSenderStatus } from '../../shared/personal-wechat'
|
||||||
|
import { hasValidWechatLicense } from '../../shared/personal-wechat-mac-send-action'
|
||||||
import {
|
import {
|
||||||
bindingMatchesRuntimeManifest,
|
bindingMatchesRuntimeManifest,
|
||||||
readMacWechatRuntimeManifest
|
readMacWechatRuntimeManifest
|
||||||
@@ -38,11 +48,18 @@ import {
|
|||||||
* auto-binding, that path dead-ends in a 20s attach timeout every time.
|
* 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 HOST = '127.0.0.1'
|
||||||
const START_TIMEOUT_MS = 15_000
|
const START_TIMEOUT_MS = 15_000
|
||||||
const REQUEST_TIMEOUT_MS = 30_000
|
const REQUEST_TIMEOUT_MS = 30_000
|
||||||
const CRASH_RESTART_DELAY_MS = 1_500
|
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 {
|
interface MacWechatSenderStatusInput {
|
||||||
snapshot: MacWechatRuntimeSnapshot
|
snapshot: MacWechatRuntimeSnapshot
|
||||||
@@ -66,6 +83,16 @@ export function deriveMacWechatSenderStatus({
|
|||||||
}: MacWechatSenderStatusInput): PersonalWechatSenderStatus {
|
}: MacWechatSenderStatusInput): PersonalWechatSenderStatus {
|
||||||
const identityMatches = binding !== null && bindingMatchesRuntimeManifest(binding, manifest)
|
const identityMatches = binding !== null && bindingMatchesRuntimeManifest(binding, manifest)
|
||||||
const stale = binding?.bindingState === 'stale'
|
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 state: PersonalWechatSenderStatus['state'] = 'stopped'
|
||||||
let message = '正在初始化微信发送能力'
|
let message = '正在初始化微信发送能力'
|
||||||
@@ -78,12 +105,17 @@ export function deriveMacWechatSenderStatus({
|
|||||||
} else if (binding && !binding.wechatRunning) {
|
} else if (binding && !binding.wechatRunning) {
|
||||||
state = 'wechat_not_running'
|
state = 'wechat_not_running'
|
||||||
message = '微信未运行'
|
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'
|
state = 'online'
|
||||||
message = '个人微信已准备好发送日报'
|
message = '个人微信已准备好发送日报'
|
||||||
} else if (binding?.bindingState === 'bound' || binding?.bindingState === 'binding') {
|
} else if (binding?.bindingState === 'bound' || binding?.bindingState === 'binding') {
|
||||||
state = 'hook_not_ready'
|
state = 'hook_not_ready'
|
||||||
message = '已绑定,等待捕获微信发送上下文'
|
message = nativeMechanism ? '已绑定,等待原生发送 hook 就绪' : '已绑定,等待捕获微信发送上下文'
|
||||||
} else if (stale) {
|
} else if (stale) {
|
||||||
state = 'stopped'
|
state = 'stopped'
|
||||||
message = '检测到微信已重启,请重新绑定'
|
message = '检测到微信已重启,请重新绑定'
|
||||||
@@ -96,13 +128,17 @@ export function deriveMacWechatSenderStatus({
|
|||||||
}
|
}
|
||||||
|
|
||||||
const runtimeCapabilities = new Set(manifest.capabilities)
|
const runtimeCapabilities = new Set(manifest.capabilities)
|
||||||
const bindingReady = identityMatches && state === 'online' && binding?.sendContextReady === true
|
const supportsCapability = (name: 'text' | 'image' | 'voice'): boolean => {
|
||||||
const canSendText =
|
if (manifest.capabilitiesByVersion) return versionCapabilities?.[name] === 'verified'
|
||||||
bindingReady && runtimeCapabilities.has('text') && binding?.canSendText === true
|
return runtimeCapabilities.has(name)
|
||||||
const canSendImage =
|
}
|
||||||
bindingReady && runtimeCapabilities.has('image') && binding?.canSendImage === true
|
const bindingReady =
|
||||||
const canSendVoice =
|
identityMatches &&
|
||||||
bindingReady && runtimeCapabilities.has('voice') && binding?.canSendVoice === true
|
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 sessionAttached = identityMatches && (binding?.sessionAttached ?? false)
|
||||||
const scriptLoaded = identityMatches && (binding?.scriptLoaded ?? 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 {
|
class MacWechatRuntimeManager {
|
||||||
private child: ChildProcess | null = null
|
private child: ChildProcess | null = null
|
||||||
private lifecycle: MacWechatRuntimeLifecycle = 'stopped'
|
private lifecycle: MacWechatRuntimeLifecycle = 'stopped'
|
||||||
@@ -147,6 +202,7 @@ class MacWechatRuntimeManager {
|
|||||||
private manifest: MacWechatRuntimeManifest | null = null
|
private manifest: MacWechatRuntimeManifest | null = null
|
||||||
private lastError: string | null = null
|
private lastError: string | null = null
|
||||||
private restartTimer: NodeJS.Timeout | null = null
|
private restartTimer: NodeJS.Timeout | null = null
|
||||||
|
private manuallyStopped = false
|
||||||
|
|
||||||
getPort(): number {
|
getPort(): number {
|
||||||
return PORT
|
return PORT
|
||||||
@@ -158,43 +214,94 @@ class MacWechatRuntimeManager {
|
|||||||
wechatRestartRequired: this.wechatRestartRequired,
|
wechatRestartRequired: this.wechatRestartRequired,
|
||||||
endpoint: `http://${HOST}:${PORT}`,
|
endpoint: `http://${HOST}:${PORT}`,
|
||||||
port: PORT,
|
port: PORT,
|
||||||
runtimeDir: this.resolveRuntimeDir(),
|
runtimeDir: this.resolveRuntimeDir() ?? undefined,
|
||||||
manifest: this.manifest ?? undefined,
|
|
||||||
error: this.lastError ?? undefined,
|
error: this.lastError ?? undefined,
|
||||||
binding: this.lastBinding ?? undefined
|
binding: this.lastBinding ?? undefined
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private resolveRuntimeDir(): string {
|
prepareForResidualCleanup(): void {
|
||||||
const base = isPackagedRuntime() ? process.resourcesPath : app.getAppPath()
|
if (this.restartTimer) {
|
||||||
return join(base, 'resources', 'runtime', 'darwin-arm64')
|
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 {
|
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. */
|
/** Runtime binaries present and executable? Cheap check for the settings UI. */
|
||||||
isRuntimePresent(): boolean {
|
isRuntimePresent(): boolean {
|
||||||
|
if (isMacNativeRuntimeUnavailable()) return false
|
||||||
try {
|
try {
|
||||||
this.manifest = readMacWechatRuntimeManifest(this.resolveRuntimeDir())
|
const runtimeDir = this.resolveRuntimeDir()
|
||||||
|
if (!runtimeDir) return false
|
||||||
|
this.manifest = readMacWechatRuntimeManifest(runtimeDir)
|
||||||
return true
|
return true
|
||||||
} catch {
|
} catch {
|
||||||
return false
|
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
|
* 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
|
* comes up WITHOUT touching WeChat (lazy init inside the host), so "runtime
|
||||||
* online" and "WeChat bound" stay two independent states.
|
* 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') {
|
if (this.lifecycle === 'starting') {
|
||||||
return this.getSnapshot()
|
return this.getSnapshot()
|
||||||
}
|
}
|
||||||
|
|
||||||
const runtimeDir = this.resolveRuntimeDir()
|
const runtimeDir = this.resolveRuntimeDir()
|
||||||
|
if (!runtimeDir) {
|
||||||
|
this.lifecycle = 'stopped'
|
||||||
|
this.lastError = '暂无发送能力'
|
||||||
|
return this.getSnapshot()
|
||||||
|
}
|
||||||
try {
|
try {
|
||||||
this.manifest = readMacWechatRuntimeManifest(runtimeDir)
|
this.manifest = readMacWechatRuntimeManifest(runtimeDir)
|
||||||
appLogger.write({
|
appLogger.write({
|
||||||
@@ -385,11 +492,28 @@ class MacWechatRuntimeManager {
|
|||||||
private request(
|
private request(
|
||||||
method: string,
|
method: string,
|
||||||
path: string,
|
path: string,
|
||||||
timeoutMs = REQUEST_TIMEOUT_MS
|
timeoutMs = REQUEST_TIMEOUT_MS,
|
||||||
|
body?: string
|
||||||
): Promise<{ status: number | null; body: string }> {
|
): Promise<{ status: number | null; body: string }> {
|
||||||
return new Promise((resolve) => {
|
return new Promise((resolve) => {
|
||||||
const request = get(
|
const payload = body !== undefined ? Buffer.from(body, 'utf8') : undefined
|
||||||
{ host: HOST, port: PORT, path, method, timeout: timeoutMs },
|
// 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) => {
|
(response) => {
|
||||||
let body = ''
|
let body = ''
|
||||||
response.on('data', (chunk) => {
|
response.on('data', (chunk) => {
|
||||||
@@ -400,14 +524,15 @@ class MacWechatRuntimeManager {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
)
|
)
|
||||||
request.on('timeout', () => {
|
req.on('timeout', () => {
|
||||||
request.destroy()
|
req.destroy()
|
||||||
resolve({ status: null, body: '' })
|
resolve({ status: null, body: '' })
|
||||||
})
|
})
|
||||||
request.on('error', () => {
|
req.on('error', () => {
|
||||||
resolve({ status: null, body: '' })
|
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')
|
const { status, body } = await this.request('GET', '/bindingStatus')
|
||||||
if (status !== 200) return null
|
if (status !== 200) return null
|
||||||
try {
|
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
|
* 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
|
* stale-rebind path the host worker waits up to 45s for the old session
|
||||||
@@ -485,6 +614,109 @@ class MacWechatRuntimeManager {
|
|||||||
return this.lastBinding
|
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
|
* Build the legacy PersonalWechatSenderStatus contract from the live mac
|
||||||
* runtime state. Lives here (not in the capability service) so BOTH the
|
* runtime state. Lives here (not in the capability service) so BOTH the
|
||||||
@@ -492,6 +724,32 @@ class MacWechatRuntimeManager {
|
|||||||
* circular import.
|
* circular import.
|
||||||
*/
|
*/
|
||||||
async buildSenderStatus(): Promise<PersonalWechatSenderStatus> {
|
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.
|
* 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.
|
* 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.
|
* 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)
|
await this.ensureStarted().catch(() => undefined)
|
||||||
}
|
}
|
||||||
/* Self-heal the status card too: if WeChat was restarted, drop the stale
|
/* Self-heal the status card too: if WeChat was restarted, drop the stale
|
||||||
* restartRequired before it is read into the UI as an error. */
|
* restartRequired before it is read into the UI as an error. */
|
||||||
try {
|
try {
|
||||||
this.manifest = readMacWechatRuntimeManifest(this.resolveRuntimeDir())
|
const runtimeDir = this.resolveRuntimeDir()
|
||||||
|
if (!runtimeDir) throw new Error('runtime missing')
|
||||||
|
this.manifest = readMacWechatRuntimeManifest(runtimeDir)
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
const detail = error instanceof Error ? error.message : String(error)
|
const detail = error instanceof Error ? error.message : String(error)
|
||||||
appLogger.write({
|
appLogger.write({
|
||||||
@@ -580,8 +840,20 @@ class MacWechatRuntimeManager {
|
|||||||
* live WeChat pid again returns attached=false and never double-attaches.
|
* live WeChat pid again returns attached=false and never double-attaches.
|
||||||
*/
|
*/
|
||||||
async bind(): Promise<MacWechatBindResult> {
|
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') {
|
if (this.lifecycle !== 'online') {
|
||||||
const snapshot = await this.ensureStarted()
|
const snapshot = await this.ensureStarted({ allowManualRestart: true })
|
||||||
if (snapshot.lifecycle !== 'online') {
|
if (snapshot.lifecycle !== 'online') {
|
||||||
return {
|
return {
|
||||||
ok: false,
|
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')
|
const { status, body } = await this.request('POST', '/bindWeChat')
|
||||||
await this.refreshBinding().catch(() => null)
|
await this.refreshBinding().catch(() => null)
|
||||||
|
|
||||||
@@ -644,7 +938,7 @@ class MacWechatRuntimeManager {
|
|||||||
async reload(): Promise<MacWechatRuntimeSnapshot> {
|
async reload(): Promise<MacWechatRuntimeSnapshot> {
|
||||||
await this.shutdown().catch(() => undefined)
|
await this.shutdown().catch(() => undefined)
|
||||||
await new Promise((resolve) => setTimeout(resolve, 2_000))
|
await new Promise((resolve) => setTimeout(resolve, 2_000))
|
||||||
return this.ensureStarted()
|
return this.ensureStarted({ allowManualRestart: true })
|
||||||
}
|
}
|
||||||
|
|
||||||
private isProcessAlive(pid: number): boolean {
|
private isProcessAlive(pid: number): boolean {
|
||||||
@@ -662,6 +956,7 @@ class MacWechatRuntimeManager {
|
|||||||
* leave its injected agent inside WeChat and make the next attach hang.
|
* leave its injected agent inside WeChat and make the next attach hang.
|
||||||
*/
|
*/
|
||||||
async shutdown(): Promise<void> {
|
async shutdown(): Promise<void> {
|
||||||
|
if (isMacNativeRuntimeUnavailable()) return
|
||||||
if (this.restartTimer) {
|
if (this.restartTimer) {
|
||||||
clearTimeout(this.restartTimer)
|
clearTimeout(this.restartTimer)
|
||||||
this.restartTimer = null
|
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
|
||||||
|
})
|
||||||
@@ -0,0 +1,777 @@
|
|||||||
|
/**
|
||||||
|
* 微信消息插入开关 —— 主进程侧封装。
|
||||||
|
*
|
||||||
|
* 为什么写操作不能在本进程做
|
||||||
|
* --------------------------
|
||||||
|
* WCDB 的 CommonCore 按**路径**池化底层库对象(CoreBridge.cpp:
|
||||||
|
* `getOrCreateDatabase` + 只在 readOnly 时 `setReadOnly()`),而只读标志一旦
|
||||||
|
* 设上去就没有逆操作。TraceMemo 启动后会用只读方式打开 message 分片,于是同一
|
||||||
|
* 进程里任何「可写打开」拿到的都是那个只读对象 —— 写入必然得到
|
||||||
|
* `-3004 attempt to write a readonly database`。
|
||||||
|
*
|
||||||
|
* 所以:
|
||||||
|
* **读** → 本进程只读路径(分片目录 + 开关值),零写权限
|
||||||
|
* **写** → spawn 一次性子进程 `tm-wcdb-config-helper`,池随进程销毁
|
||||||
|
*
|
||||||
|
* 子进程的密钥只从 stdin 进,绝不进 argv / env(否则会出现在 `ps` 与进程环境里)。
|
||||||
|
*
|
||||||
|
* 状态语义(不要退回「开关值写成功 = 功能已生效」)
|
||||||
|
* ------------------------------------------------
|
||||||
|
* 真正干活的是挂在 `Msg_<md5(roomId)>` 表上的规则。一个分片完全可能
|
||||||
|
* 「有 _tm_config 却没规则」,此时开关写成 1 也毫无效果。而且一个会话可能同时
|
||||||
|
* 存在于 2~4 个分片,必须**所有命中分片都 ready** 才算这个会话 ready。
|
||||||
|
*
|
||||||
|
* 判断「是否生效」始终按目标会话算,不按分片算。
|
||||||
|
*/
|
||||||
|
|
||||||
|
import { spawn } from 'node:child_process'
|
||||||
|
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,
|
||||||
|
type MsgInsertApplyResult,
|
||||||
|
type MsgInsertErrorCode,
|
||||||
|
type MsgInsertScope,
|
||||||
|
type MsgInsertSwitchName,
|
||||||
|
type MsgInsertSwitchStatus,
|
||||||
|
type MsgInsertSwitchesSnapshot
|
||||||
|
} from '../../shared/msg-insert-switch'
|
||||||
|
|
||||||
|
export {
|
||||||
|
MSG_INSERT_SWITCHES,
|
||||||
|
type MsgInsertSwitchName,
|
||||||
|
type MsgInsertSwitchStatus,
|
||||||
|
type MsgInsertSwitchesSnapshot
|
||||||
|
}
|
||||||
|
|
||||||
|
/* --------------------------------------------------------------- 常量 */
|
||||||
|
|
||||||
|
const HELPER_NAME = 'tm-wcdb-config-helper'
|
||||||
|
const HELPER_TIMEOUT_MS = 60_000
|
||||||
|
/** 分片里规则的名字(与 native 侧一致) */
|
||||||
|
const RULE_CAPTURE = '_tm_msg_insert_capture'
|
||||||
|
/* notice 规则只装在 winner 分片、且不参与就绪判据,读路径不需要它的名字。
|
||||||
|
* 退群已改事件驱动,不再有 queue 规则(常量已退役)。 */
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 规则名在 native 侧按会话加了后缀。
|
||||||
|
*
|
||||||
|
* SQLite 的 trigger 名是**库级唯一**的:如果所有会话都用固定名字,给第二个会话装规则
|
||||||
|
* 会直接覆盖第一个。所以真实名字形如 `_tm_msg_insert_capture_<md5(roomId)>`。
|
||||||
|
*
|
||||||
|
* ⚠️ 读路径必须用带后缀的名字去查目录,否则会得出「库里明明有规则、界面却显示 0」这种
|
||||||
|
* 自相矛盾的结论。
|
||||||
|
*/
|
||||||
|
function ruleName(base: string, roomId: string): string {
|
||||||
|
return `${base}_${md5Hex(roomId)}`
|
||||||
|
}
|
||||||
|
|
||||||
|
const SWITCH_SCOPE: Record<MsgInsertSwitchName, MsgInsertScope> = {
|
||||||
|
// 防撤回:群聊和私聊都要覆盖,所以目标是「全部可定位会话」
|
||||||
|
recall_notice: 'all_sessions',
|
||||||
|
// 退群提示:任意群有人退出都要提示,所以目标是「全部群聊」(与退群监控的勾选无关)
|
||||||
|
group_exit_notice: 'all_group_chats'
|
||||||
|
}
|
||||||
|
|
||||||
|
interface HelperRunResult {
|
||||||
|
ok: boolean
|
||||||
|
exitCode: number | null
|
||||||
|
json?: Record<string, unknown>
|
||||||
|
errorCode?: MsgInsertErrorCode
|
||||||
|
message?: string
|
||||||
|
detail?: string
|
||||||
|
}
|
||||||
|
|
||||||
|
function md5Hex(value: string): string {
|
||||||
|
return createHash('md5').update(value).digest('hex')
|
||||||
|
}
|
||||||
|
|
||||||
|
function messageTableFor(roomId: string): string {
|
||||||
|
return `Msg_${md5Hex(roomId)}`
|
||||||
|
}
|
||||||
|
|
||||||
|
export const SWITCH_MODE: Record<MsgInsertSwitchName, 'rules' | 'event'> = {
|
||||||
|
// 防撤回靠装规则
|
||||||
|
recall_notice: 'rules',
|
||||||
|
// 退群提示靠事件驱动的一次性插入,不装规则
|
||||||
|
group_exit_notice: 'event'
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 事件驱动型开关的状态。
|
||||||
|
*
|
||||||
|
* 它没有 room / shard 维度(不装规则),所以 room 计数一律为 0 —— UI 据此不显示
|
||||||
|
* 「N / M 已启用」。desired 与 effective 同值:这条路径没有「值写了对但规则没装」
|
||||||
|
* 的中间态,插入失败会记在 service 的 recent 里,不影响开关本身。
|
||||||
|
*/
|
||||||
|
export function eventModeStatus(
|
||||||
|
name: MsgInsertSwitchName,
|
||||||
|
enabled: boolean,
|
||||||
|
monitoredRoomCount = 0
|
||||||
|
): MsgInsertSwitchStatus {
|
||||||
|
const status = emptyMsgInsertStatus(name)
|
||||||
|
status.mode = 'event'
|
||||||
|
status.desiredEnabled = enabled
|
||||||
|
status.effectiveEnabled = enabled
|
||||||
|
status.operationOk = true
|
||||||
|
/* 事件驱动型没有「预装规则覆盖率」。这里给的只是**监控范围**,
|
||||||
|
* 用来告诉用户「开了之后哪些群的退群会被插提示」,不是覆盖率。 */
|
||||||
|
status.monitoredRoomCount = monitoredRoomCount
|
||||||
|
return status
|
||||||
|
}
|
||||||
|
|
||||||
|
export function emptyMsgInsertStatus(
|
||||||
|
name: MsgInsertSwitchName,
|
||||||
|
errorCode?: MsgInsertErrorCode,
|
||||||
|
message?: string
|
||||||
|
): MsgInsertSwitchStatus {
|
||||||
|
return {
|
||||||
|
switch: name,
|
||||||
|
scope: SWITCH_SCOPE[name],
|
||||||
|
mode: SWITCH_MODE[name],
|
||||||
|
desiredEnabled: false,
|
||||||
|
effectiveEnabled: false,
|
||||||
|
operationOk: false,
|
||||||
|
totalInstallableRooms: 0,
|
||||||
|
readyInstallableRooms: 0,
|
||||||
|
roomsWithoutTable: 0,
|
||||||
|
totalShards: 0,
|
||||||
|
targetShards: 0,
|
||||||
|
configuredShards: 0,
|
||||||
|
readyShards: 0,
|
||||||
|
notReadyShards: 0,
|
||||||
|
failedShards: 0,
|
||||||
|
errorCode,
|
||||||
|
message
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ------------------------------------------------------- helper 定位与调用 */
|
||||||
|
|
||||||
|
/**
|
||||||
|
* helper 与 libwcdb_api.dylib 同目录部署(依赖 @loader_path 解析 dylib)。
|
||||||
|
* 开发态与打包态都靠 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 能直接加载。
|
||||||
|
*/
|
||||||
|
const archDir = process.arch === 'x64' ? 'x64' : 'arm64'
|
||||||
|
const otherArchDir = archDir === 'arm64' ? 'x64' : 'arm64'
|
||||||
|
const platformDir = process.platform === 'win32' ? 'win32' : 'macos'
|
||||||
|
const suffix = process.platform === 'win32' ? '.exe' : ''
|
||||||
|
const candidates = [
|
||||||
|
`wcdb/${platformDir}/${archDir}/${HELPER_NAME}${suffix}`,
|
||||||
|
`wcdb/${platformDir}/${otherArchDir}/${HELPER_NAME}${suffix}`,
|
||||||
|
`wcdb/${platformDir}/${HELPER_NAME}${suffix}`
|
||||||
|
]
|
||||||
|
for (const candidate of candidates) {
|
||||||
|
const resolved = findResource(candidate)
|
||||||
|
if (resolved) return resolved
|
||||||
|
}
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 从分片路径反推账号根目录(helper 需要它来枚举分片) */
|
||||||
|
function accountRootFromShard(shardPath: string): string {
|
||||||
|
// <root>/db_storage/message/message_N.db
|
||||||
|
return path.dirname(path.dirname(path.dirname(shardPath)))
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 跑一次 helper。**密钥只走 stdin**。
|
||||||
|
*
|
||||||
|
* 请求体是一行 JSON:{"key":"<hex>","rooms":[...],"myWxid":"..."}
|
||||||
|
* 用 JSON 而不是 argv,是因为目标会话可能有上千个,argv 会被撑爆;
|
||||||
|
* 顺带保证密钥永远不进进程参数表。
|
||||||
|
*/
|
||||||
|
function runHelper(
|
||||||
|
helperPath: string,
|
||||||
|
args: string[],
|
||||||
|
request: { key: string; rooms: string[]; myWxid: string },
|
||||||
|
timeoutMs = HELPER_TIMEOUT_MS
|
||||||
|
): Promise<HelperRunResult> {
|
||||||
|
return new Promise((resolve) => {
|
||||||
|
let child: ReturnType<typeof spawn>
|
||||||
|
try {
|
||||||
|
child = spawn(helperPath, args, { stdio: ['pipe', 'pipe', 'pipe'] })
|
||||||
|
} catch (error) {
|
||||||
|
resolve({
|
||||||
|
ok: false,
|
||||||
|
exitCode: null,
|
||||||
|
errorCode: 'HELPER_START_FAILED',
|
||||||
|
message: 'helper 启动失败',
|
||||||
|
detail: error instanceof Error ? error.message : String(error)
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
let stdout = ''
|
||||||
|
let stderr = ''
|
||||||
|
let settled = false
|
||||||
|
const finish = (result: HelperRunResult): void => {
|
||||||
|
if (settled) return
|
||||||
|
settled = true
|
||||||
|
clearTimeout(timer)
|
||||||
|
resolve(result)
|
||||||
|
}
|
||||||
|
|
||||||
|
const timer = setTimeout(() => {
|
||||||
|
try {
|
||||||
|
child.kill('SIGKILL')
|
||||||
|
} catch {
|
||||||
|
/* 已经退出了 */
|
||||||
|
}
|
||||||
|
finish({
|
||||||
|
ok: false,
|
||||||
|
exitCode: null,
|
||||||
|
errorCode: 'HELPER_TIMEOUT',
|
||||||
|
message: '写入超时,已中止',
|
||||||
|
detail: `timeout=${timeoutMs}ms stderr=${stderr.slice(-400)}`
|
||||||
|
})
|
||||||
|
}, timeoutMs)
|
||||||
|
|
||||||
|
child.stdout?.on('data', (chunk: Buffer) => {
|
||||||
|
stdout += chunk.toString()
|
||||||
|
})
|
||||||
|
child.stderr?.on('data', (chunk: Buffer) => {
|
||||||
|
stderr = `${stderr}${chunk.toString()}`.slice(-4000)
|
||||||
|
})
|
||||||
|
child.on('error', (error) => {
|
||||||
|
finish({
|
||||||
|
ok: false,
|
||||||
|
exitCode: null,
|
||||||
|
errorCode: 'HELPER_START_FAILED',
|
||||||
|
message: 'helper 启动失败',
|
||||||
|
detail: error.message
|
||||||
|
})
|
||||||
|
})
|
||||||
|
child.on('close', (code) => {
|
||||||
|
const lines = stdout.trim().split('\n').filter(Boolean)
|
||||||
|
let json: Record<string, unknown> | undefined
|
||||||
|
try {
|
||||||
|
json = JSON.parse(lines[lines.length - 1] || '') as Record<string, unknown>
|
||||||
|
} catch {
|
||||||
|
finish({
|
||||||
|
ok: false,
|
||||||
|
exitCode: code,
|
||||||
|
errorCode: 'HELPER_BAD_OUTPUT',
|
||||||
|
message: 'helper 返回了无法解析的结果',
|
||||||
|
detail: `exit=${code} stdout=${stdout.slice(-400)} stderr=${stderr.slice(-400)}`
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
const success = json.success === true
|
||||||
|
finish({
|
||||||
|
ok: code === 0 || (code === 1 && json.success === false),
|
||||||
|
exitCode: code,
|
||||||
|
json,
|
||||||
|
errorCode: success ? undefined : inferErrorCode(json),
|
||||||
|
message: success ? undefined : describeFailure(json),
|
||||||
|
detail: `exit=${code} ${stderr.slice(-400)}`.trim()
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
/* 密钥与请求一起写进 stdin,然后立刻关闭 —— 不进 argv、不进 env、不落盘。 */
|
||||||
|
try {
|
||||||
|
child.stdin?.write(`${JSON.stringify(request)}\n`)
|
||||||
|
child.stdin?.end()
|
||||||
|
} catch (error) {
|
||||||
|
finish({
|
||||||
|
ok: false,
|
||||||
|
exitCode: null,
|
||||||
|
errorCode: 'HELPER_START_FAILED',
|
||||||
|
message: '无法把密钥交给 helper',
|
||||||
|
detail: error instanceof Error ? error.message : String(error)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
function inferErrorCode(json: Record<string, unknown>): MsgInsertErrorCode {
|
||||||
|
const code = String(json.code || '')
|
||||||
|
if (code === 'HELPER_BAD_ARGS') return 'HELPER_BAD_OUTPUT'
|
||||||
|
if (code === 'UNSUPPORTED_SWITCH') return 'UNSUPPORTED_SWITCH'
|
||||||
|
if (code === 'HELPER_NO_SHARDS') return 'DATABASE_UNAVAILABLE'
|
||||||
|
if (code === 'RULE_MISSING') return 'RULE_MISSING'
|
||||||
|
const failed = Number(json.failedShards || 0)
|
||||||
|
if (failed > 0) return 'SHARD_WRITE_FAILED'
|
||||||
|
/* roomsWithoutTable 是中性 pending,不是失败 —— 只有当**一个可安装会话都没有**
|
||||||
|
* 的时候才算没有目标。 */
|
||||||
|
if (
|
||||||
|
Number(json.totalTargetRooms || 0) > 0 &&
|
||||||
|
Number(json.totalTargetRooms || 0) === Number(json.roomsWithoutTable || 0)
|
||||||
|
) {
|
||||||
|
return 'NO_TARGET_ROOMS'
|
||||||
|
}
|
||||||
|
return 'UNKNOWN'
|
||||||
|
}
|
||||||
|
|
||||||
|
function describeFailure(json: Record<string, unknown>): string {
|
||||||
|
const failed = Number(json.failedShards || 0)
|
||||||
|
if (failed > 0) return `${failed} 个消息库写入失败`
|
||||||
|
const without = Number(json.roomsWithoutTable || 0)
|
||||||
|
if (Number(json.totalTargetRooms || 0) > 0 && Number(json.totalTargetRooms) === without) {
|
||||||
|
return `${without} 个目标会话在微信库里都还没有消息表`
|
||||||
|
}
|
||||||
|
const code = String(json.code || '')
|
||||||
|
const detail = String(json.error || '')
|
||||||
|
return code ? `${code}${detail ? `:${detail}` : ''}` : '操作未完成'
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ----------------------------------------------------------- 目标会话解析 */
|
||||||
|
|
||||||
|
export interface MsgInsertScopeInput {
|
||||||
|
client: Wcdb4Client
|
||||||
|
/** 退群监控当前选中的群(来自 group-exit-monitor 服务,不在这里另维护一份) */
|
||||||
|
monitoredRoomIds: string[]
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 解析某个开关的目标会话集合。
|
||||||
|
*
|
||||||
|
* - group_exit_notice → 全部群聊(事件驱动:真实范围由 GroupExitMonitorService 持有,
|
||||||
|
* 退群监控勾选的群只决定「哪些群的退群走自动化通知」)
|
||||||
|
* - recall_notice → 全部可定位会话(群聊 + 私聊)
|
||||||
|
*/
|
||||||
|
export function resolveTargetRooms(
|
||||||
|
input: MsgInsertScopeInput,
|
||||||
|
name: MsgInsertSwitchName
|
||||||
|
): { scope: MsgInsertScope; rooms: string[]; error?: string } {
|
||||||
|
const scope = SWITCH_SCOPE[name]
|
||||||
|
if (scope === 'monitored_rooms') {
|
||||||
|
const rooms = Array.from(new Set(input.monitoredRoomIds.filter(Boolean)))
|
||||||
|
return { scope, rooms }
|
||||||
|
}
|
||||||
|
if (scope === 'all_group_chats') {
|
||||||
|
/* 事件驱动型:不装规则,真实范围由 GroupExitMonitorService 持有。
|
||||||
|
* 这里回一份群聊清单只为状态展示口径一致(调用方不拿它装规则)。 */
|
||||||
|
try {
|
||||||
|
const rooms = Array.from(
|
||||||
|
new Set(
|
||||||
|
input.client
|
||||||
|
.getSessions()
|
||||||
|
.map((session) => String(session.username || '').trim())
|
||||||
|
.filter((username) => username.endsWith('@chatroom'))
|
||||||
|
)
|
||||||
|
)
|
||||||
|
return { scope, rooms }
|
||||||
|
} catch (error) {
|
||||||
|
return {
|
||||||
|
scope,
|
||||||
|
rooms: [],
|
||||||
|
error: error instanceof Error ? error.message : String(error)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
const rooms = Array.from(
|
||||||
|
new Set(
|
||||||
|
input.client
|
||||||
|
.getSessions()
|
||||||
|
.map((session) => String(session.username || '').trim())
|
||||||
|
.filter(Boolean)
|
||||||
|
)
|
||||||
|
)
|
||||||
|
return { scope, rooms }
|
||||||
|
} catch (error) {
|
||||||
|
return {
|
||||||
|
scope,
|
||||||
|
rooms: [],
|
||||||
|
error: error instanceof Error ? error.message : String(error)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/* --------------------------------------------------------------- 只读状态 */
|
||||||
|
|
||||||
|
interface CatalogShard {
|
||||||
|
shard: string
|
||||||
|
dbPath: string
|
||||||
|
configTable: boolean
|
||||||
|
tables: Set<string>
|
||||||
|
ruleTables: Map<string, string>
|
||||||
|
}
|
||||||
|
|
||||||
|
function readCatalog(client: Wcdb4Client): {
|
||||||
|
shards: CatalogShard[]
|
||||||
|
rawCount: number
|
||||||
|
error?: string
|
||||||
|
} {
|
||||||
|
const result = client.listMsgInsertShardCatalog()
|
||||||
|
if (!result.success || !result.catalog) {
|
||||||
|
return { shards: [], rawCount: 0, error: result.error || '分片目录读取失败' }
|
||||||
|
}
|
||||||
|
const shards = result.catalog.shards.map<CatalogShard>((entry) => ({
|
||||||
|
shard: entry.shard,
|
||||||
|
dbPath: entry.dbPath,
|
||||||
|
configTable: entry.configTable,
|
||||||
|
tables: new Set(entry.tables || []),
|
||||||
|
ruleTables: new Map((entry.rules || []).map((rule) => [rule.name, rule.table]))
|
||||||
|
}))
|
||||||
|
return { shards, rawCount: shards.length }
|
||||||
|
}
|
||||||
|
|
||||||
|
function roomReadiness(
|
||||||
|
shards: CatalogShard[],
|
||||||
|
roomId: string,
|
||||||
|
name: MsgInsertSwitchName
|
||||||
|
): { matched: string[]; ready: boolean; notReady: string[] } {
|
||||||
|
const table = messageTableFor(roomId)
|
||||||
|
const matched: string[] = []
|
||||||
|
const notReady: string[] = []
|
||||||
|
const captureName = ruleName(RULE_CAPTURE, roomId)
|
||||||
|
/* notice 规则只装在 winner 分片,就绪判据不看它(见下),所以这里不需要它的名字。 */
|
||||||
|
for (const shard of shards) {
|
||||||
|
if (!shard.tables.has(table)) continue
|
||||||
|
matched.push(shard.shard)
|
||||||
|
/* 同时接受历史遗留的无后缀规则(只要它挂在同一张表上)—— 与 native 侧判据一致,
|
||||||
|
* 否则用旧脚本装过的那一个会话会被误判成未就绪。 */
|
||||||
|
const attachedTo = (...names: string[]): boolean =>
|
||||||
|
names.some((candidate) => shard.ruleTables.get(candidate) === table)
|
||||||
|
const capture = attachedTo(captureName, RULE_CAPTURE)
|
||||||
|
/*
|
||||||
|
* ⚠️ 只要求 capture。
|
||||||
|
*
|
||||||
|
* notice 规则**只装在 winner 分片**上(分片之间是独立数据库文件、没有共享状态,
|
||||||
|
* 每个分片各生成一条会重复插提示)。所以这里不能再要求每个分片都有 notice ——
|
||||||
|
* 否则所有跨分片会话都会显示成「未就绪」。
|
||||||
|
* 这条必须与 native 侧 `msgInsertEvaluateRoomShard` 的 `recallReady = capture` 一致。
|
||||||
|
*/
|
||||||
|
const ready = name === 'recall_notice' ? capture : true
|
||||||
|
if (!ready) notReady.push(shard.shard)
|
||||||
|
}
|
||||||
|
return { matched, ready: matched.length > 0 && notReady.length === 0, notReady }
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 本进程只读地聚合两个开关的状态。
|
||||||
|
*
|
||||||
|
* 只用「分片目录 + 开关值」:目录一次拿全,之后在本地用 md5(roomId) 匹配,
|
||||||
|
* 所以哪怕目标会话很多也不会有额外的查库开销。
|
||||||
|
*/
|
||||||
|
export function readMsgInsertSwitches(input: MsgInsertScopeInput): MsgInsertSwitchesSnapshot {
|
||||||
|
const catalog = readCatalog(input.client)
|
||||||
|
const shardCount = catalog.rawCount
|
||||||
|
const switches = {} as Record<MsgInsertSwitchName, MsgInsertSwitchStatus>
|
||||||
|
|
||||||
|
if (catalog.error || shardCount === 0) {
|
||||||
|
for (const name of MSG_INSERT_SWITCHES) {
|
||||||
|
switches[name] = emptyMsgInsertStatus(
|
||||||
|
name,
|
||||||
|
'DATABASE_UNAVAILABLE',
|
||||||
|
catalog.error || '找不到消息分片(数据库可能尚未连接)'
|
||||||
|
)
|
||||||
|
}
|
||||||
|
return { success: false, switches, helperAvailable: resolveHelperPath() !== null }
|
||||||
|
}
|
||||||
|
|
||||||
|
/* 每个分片读一次开关值,后面既用来算 desired,也用来算分片级 ready */
|
||||||
|
const valuesByShard = new Map<string, Record<string, boolean>>()
|
||||||
|
for (const shard of catalog.shards) {
|
||||||
|
const read = input.client.getMsgInsertSwitches(shard.dbPath)
|
||||||
|
valuesByShard.set(
|
||||||
|
shard.shard,
|
||||||
|
read.success && read.switches
|
||||||
|
? read.switches
|
||||||
|
: { recall_notice: false, group_exit_notice: false }
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
for (const name of MSG_INSERT_SWITCHES) {
|
||||||
|
const resolved = resolveTargetRooms(input, name)
|
||||||
|
const status = emptyMsgInsertStatus(
|
||||||
|
name,
|
||||||
|
resolved.error ? 'DATABASE_UNAVAILABLE' : undefined,
|
||||||
|
resolved.error
|
||||||
|
)
|
||||||
|
status.scope = resolved.scope
|
||||||
|
status.totalShards = shardCount
|
||||||
|
|
||||||
|
const targetShardNames = new Set<string>()
|
||||||
|
const notReadyRooms: MsgInsertSwitchStatus['notReadyRooms'] = []
|
||||||
|
let readyRooms = 0
|
||||||
|
let roomsWithoutTable = 0
|
||||||
|
|
||||||
|
for (const room of resolved.rooms) {
|
||||||
|
const readiness = roomReadiness(catalog.shards, room, name)
|
||||||
|
if (readiness.matched.length === 0) {
|
||||||
|
/* 公众号 / 服务号 / 系统会话没有 Msg_ 表,装不了规则 —— **中性 pending**,
|
||||||
|
* 既不算失败,也不进 notReadyRooms,更不能拖累 effectiveEnabled。 */
|
||||||
|
roomsWithoutTable += 1
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
for (const shard of readiness.matched) targetShardNames.add(shard)
|
||||||
|
if (readiness.ready) {
|
||||||
|
readyRooms += 1
|
||||||
|
} else {
|
||||||
|
notReadyRooms.push({
|
||||||
|
roomId: room,
|
||||||
|
reason: 'rules-missing',
|
||||||
|
matchedShards: readiness.matched,
|
||||||
|
notReadyShards: readiness.notReady
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
status.targetShards = targetShardNames.size
|
||||||
|
/* 分母是「有消息表、可安装」的会话数,不是全部会话数。
|
||||||
|
* 否则总会有一部分会话装不了规则,界面会一直显示「部分成功」。 */
|
||||||
|
status.totalInstallableRooms = readyRooms + notReadyRooms.length
|
||||||
|
status.readyInstallableRooms = readyRooms
|
||||||
|
status.roomsWithoutTable = roomsWithoutTable
|
||||||
|
|
||||||
|
let configured = 0
|
||||||
|
let readyShards = 0
|
||||||
|
let notReadyShards = 0
|
||||||
|
for (const shard of catalog.shards) {
|
||||||
|
const values = valuesByShard.get(shard.shard)
|
||||||
|
const on = Boolean(values?.[name])
|
||||||
|
if (on) configured += 1
|
||||||
|
if (!targetShardNames.has(shard.shard)) continue
|
||||||
|
const recallOk = roomShardsReady(catalog.shards, shard.shard, resolved.rooms, name)
|
||||||
|
if (on && recallOk) readyShards += 1
|
||||||
|
else if (on) notReadyShards += 1
|
||||||
|
}
|
||||||
|
status.configuredShards = configured
|
||||||
|
status.readyShards = readyShards
|
||||||
|
status.notReadyShards = notReadyShards
|
||||||
|
status.failedShards = 0
|
||||||
|
status.desiredEnabled = configured > 0
|
||||||
|
status.operationOk = true
|
||||||
|
/* 生效判定只看可安装会话:roomsWithoutTable 不能阻止 effectiveEnabled。 */
|
||||||
|
status.effectiveEnabled =
|
||||||
|
status.desiredEnabled &&
|
||||||
|
status.totalInstallableRooms > 0 &&
|
||||||
|
readyRooms === status.totalInstallableRooms
|
||||||
|
status.notReadyRooms = notReadyRooms.slice(0, 20)
|
||||||
|
|
||||||
|
if (resolved.rooms.length === 0) {
|
||||||
|
status.message = '没有可作用的目标会话'
|
||||||
|
}
|
||||||
|
switches[name] = status
|
||||||
|
}
|
||||||
|
|
||||||
|
return { success: true, switches, helperAvailable: resolveHelperPath() !== null }
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 某分片上「所有目标会话」的规则是否都齐 */
|
||||||
|
function roomShardsReady(
|
||||||
|
shards: CatalogShard[],
|
||||||
|
shardName: string,
|
||||||
|
rooms: string[],
|
||||||
|
name: MsgInsertSwitchName
|
||||||
|
): boolean {
|
||||||
|
const shard = shards.find((entry) => entry.shard === shardName)
|
||||||
|
if (!shard) return false
|
||||||
|
let any = false
|
||||||
|
for (const room of rooms) {
|
||||||
|
const table = messageTableFor(room)
|
||||||
|
if (!shard.tables.has(table)) continue
|
||||||
|
any = true
|
||||||
|
const attachedTo = (...names: string[]): boolean =>
|
||||||
|
names.some((candidate) => shard.ruleTables.get(candidate) === table)
|
||||||
|
const capture = attachedTo(ruleName(RULE_CAPTURE, room), RULE_CAPTURE)
|
||||||
|
/* 与 roomReadiness、以及 native 侧 `msgInsertEvaluateRoomShard` 用同一判据:
|
||||||
|
* notice 只装在 winner 分片,就绪只看 capture。 */
|
||||||
|
const ready = name === 'recall_notice' ? capture : true
|
||||||
|
if (!ready) return false
|
||||||
|
}
|
||||||
|
return any
|
||||||
|
}
|
||||||
|
|
||||||
|
/* --------------------------------------------------------------- 写入动作 */
|
||||||
|
|
||||||
|
export interface MsgInsertApplyInput extends MsgInsertScopeInput {
|
||||||
|
name: MsgInsertSwitchName
|
||||||
|
enabled: boolean
|
||||||
|
myWxid: string
|
||||||
|
databaseKey: string
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 打开 / 关闭一个开关。
|
||||||
|
*
|
||||||
|
* 顺序是**先规则、后开关**:开的时候必须先把目标会话的规则补齐并确认 ready,
|
||||||
|
* 才写开关值;关的时候只写值(规则体自己读 _tm_config,值为 0 时一行都不执行,
|
||||||
|
* 所以关闭不需要昂贵 DDL,下次打开直接恢复)。
|
||||||
|
*/
|
||||||
|
export async function applyMsgInsertSwitch(
|
||||||
|
input: MsgInsertApplyInput
|
||||||
|
): Promise<MsgInsertApplyResult> {
|
||||||
|
/*
|
||||||
|
* 防御:事件驱动型开关(退群提示)**不允许**走规则路径。
|
||||||
|
*
|
||||||
|
* 它没有 per-room 规则,走 apply 只会把 `_tm_config.group_exit_notice` 写成 1 ——
|
||||||
|
* 一个写了也没人读的脏值,界面还会显示成关闭。
|
||||||
|
*/
|
||||||
|
if (SWITCH_MODE[input.name] !== 'rules') {
|
||||||
|
return {
|
||||||
|
success: false,
|
||||||
|
status: eventModeStatus(input.name, false),
|
||||||
|
errorCode: 'UNSUPPORTED_SWITCH',
|
||||||
|
message: '这个开关不走规则路径'
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const resolved = resolveTargetRooms(input, input.name)
|
||||||
|
if (resolved.rooms.length === 0) {
|
||||||
|
return {
|
||||||
|
success: false,
|
||||||
|
status: emptyMsgInsertStatus(input.name, 'NO_TARGET_ROOMS', '没有可作用的目标会话'),
|
||||||
|
errorCode: 'NO_TARGET_ROOMS',
|
||||||
|
message: '没有可作用的目标会话'
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (!input.databaseKey) {
|
||||||
|
return {
|
||||||
|
success: false,
|
||||||
|
status: emptyMsgInsertStatus(input.name, 'DATABASE_UNAVAILABLE', '数据库密钥不可用'),
|
||||||
|
errorCode: 'DATABASE_UNAVAILABLE',
|
||||||
|
message: '数据库密钥不可用,请先连接微信数据库'
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
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 {
|
||||||
|
success: false,
|
||||||
|
status: emptyMsgInsertStatus(input.name, 'HELPER_NOT_FOUND', '暂无法使用'),
|
||||||
|
errorCode: 'HELPER_NOT_FOUND',
|
||||||
|
/* 面向用户是能力语义;errorCode 仍是 HELPER_NOT_FOUND,门禁/授权层照旧能判。 */
|
||||||
|
message: '暂无法使用:当前安装不包含发送能力组件'
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const shards = input.client.listMessageShardPaths()
|
||||||
|
const accountRoot = shards.length > 0 ? accountRootFromShard(shards[0]) : ''
|
||||||
|
if (!accountRoot) {
|
||||||
|
return {
|
||||||
|
success: false,
|
||||||
|
status: emptyMsgInsertStatus(input.name, 'DATABASE_UNAVAILABLE', '找不到账号目录'),
|
||||||
|
errorCode: 'DATABASE_UNAVAILABLE',
|
||||||
|
message: '找不到微信账号目录'
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const run = await runHelper(
|
||||||
|
helperPath,
|
||||||
|
[
|
||||||
|
'--account-root',
|
||||||
|
accountRoot,
|
||||||
|
'--action',
|
||||||
|
'apply',
|
||||||
|
'--switch',
|
||||||
|
input.name === 'recall_notice' ? 'recall' : 'group_exit',
|
||||||
|
'--value',
|
||||||
|
input.enabled ? '1' : '0'
|
||||||
|
],
|
||||||
|
{ key: input.databaseKey, rooms: resolved.rooms, myWxid: input.myWxid }
|
||||||
|
)
|
||||||
|
|
||||||
|
/* 无论 helper 成功与否,都用本进程只读路径复核一遍,不拿 helper 的自述当结论 */
|
||||||
|
const snapshot = readMsgInsertSwitches(input)
|
||||||
|
const status = snapshot.switches[input.name]
|
||||||
|
|
||||||
|
if (!run.json) {
|
||||||
|
return {
|
||||||
|
success: false,
|
||||||
|
status,
|
||||||
|
errorCode: run.errorCode || 'UNKNOWN',
|
||||||
|
message: run.message || '操作失败',
|
||||||
|
detail: run.detail
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const success = run.json.success === true
|
||||||
|
/* 用 helper 的权威计数覆盖本地只读快照里的 room 分母,避免两边口径漂移。 */
|
||||||
|
status.totalInstallableRooms = Number(
|
||||||
|
run.json.installableTargetRooms ?? status.totalInstallableRooms
|
||||||
|
)
|
||||||
|
status.readyInstallableRooms = Number(run.json.readyTargetRooms ?? status.readyInstallableRooms)
|
||||||
|
status.roomsWithoutTable = Number(run.json.roomsWithoutTable ?? status.roomsWithoutTable)
|
||||||
|
return {
|
||||||
|
success,
|
||||||
|
status,
|
||||||
|
errorCode: success ? undefined : run.errorCode || 'PARTIAL_SUCCESS',
|
||||||
|
message: success ? undefined : run.message,
|
||||||
|
detail: run.detail
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 轻量 reconciliation:把目标会话缺失的规则补齐,**不动开关值**。
|
||||||
|
*
|
||||||
|
* 触发时机:启动连库后 / 退群监控群列表变化后 / 用户打开开关时。
|
||||||
|
* 微信新建 message_4.db 并把某个目标群的新表放进去时,下一次触发就会自动补上。
|
||||||
|
*/
|
||||||
|
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 {
|
||||||
|
done: false,
|
||||||
|
rooms: 0,
|
||||||
|
written: 0,
|
||||||
|
errorCode: helperPath ? 'DATABASE_UNAVAILABLE' : 'HELPER_NOT_FOUND'
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const shards = input.client.listMessageShardPaths()
|
||||||
|
if (shards.length === 0) {
|
||||||
|
return { done: false, rooms: 0, written: 0, errorCode: 'DATABASE_UNAVAILABLE' }
|
||||||
|
}
|
||||||
|
/*
|
||||||
|
* 目标会话 = 退群监控选中的群 ∪ 调用方额外指定的会话。
|
||||||
|
* 清残留与规则定义自愈都复用这条链路,只是换会话集合。
|
||||||
|
*/
|
||||||
|
const rooms = Array.from(
|
||||||
|
new Set([
|
||||||
|
...input.monitoredRoomIds.filter(Boolean),
|
||||||
|
...(input.extraRooms || []).filter(Boolean)
|
||||||
|
])
|
||||||
|
)
|
||||||
|
if (rooms.length === 0) return { done: true, rooms: 0, written: 0 }
|
||||||
|
|
||||||
|
const run = await runHelper(
|
||||||
|
helperPath,
|
||||||
|
['--account-root', accountRootFromShard(shards[0]), '--action', 'ensure-rules'],
|
||||||
|
{ key: input.databaseKey, rooms, myWxid: input.myWxid },
|
||||||
|
/* 目标会话可能是「全部可定位会话」(几百个),比默认 60s 给宽一点。 */
|
||||||
|
180_000
|
||||||
|
)
|
||||||
|
if (!run.json) {
|
||||||
|
return { done: false, rooms: rooms.length, written: 0, errorCode: run.errorCode || 'UNKNOWN' }
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
done: run.json.success === true,
|
||||||
|
rooms: rooms.length,
|
||||||
|
written: Number(run.json.rulesWritten || 0),
|
||||||
|
errorCode: run.json.success === true ? undefined : 'RULE_MISSING'
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,100 @@
|
|||||||
|
import fs from 'fs'
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 区分「路径不存在」与「路径存在、但当前进程读不了」。
|
||||||
|
*
|
||||||
|
* 为什么需要它:`fs.existsSync()` 对**任何**错误都返回 `false` —— 包括 `EPERM`
|
||||||
|
* 与 `EACCES`。于是"权限被拒绝"会被静默降级成"文件不存在",调用方再据此报出
|
||||||
|
* 「文件缺失」,把用户指向路径排查和重装。
|
||||||
|
*
|
||||||
|
* macOS 上最容易踩到的是**完全磁盘访问权限**未授予:微信数据在另一个 App 的容器里,
|
||||||
|
* TCC 会以 `EPERM`(而不是 ENOENT)拒绝访问。此时数据目录其实是完整的。
|
||||||
|
*
|
||||||
|
* 只用 `statSync` 探**一次**,因为只有它会把 errno 如实抛出来。三种结果:
|
||||||
|
* - 能 stat → `ok`
|
||||||
|
* - ENOENT / ENOTDIR → `missing`
|
||||||
|
* - EPERM / EACCES → `denied`
|
||||||
|
*
|
||||||
|
* 不做递归遍历、不做缓存:调用点通常已经失败在即,这里不再额外制造 IO。
|
||||||
|
*/
|
||||||
|
export type PathAccess = 'ok' | 'missing' | 'denied'
|
||||||
|
|
||||||
|
/** 权限类 errno。TCC 拒绝一般给 `EPERM`;传统文件权限位不足给 `EACCES`。 */
|
||||||
|
const PERMISSION_ERRNOS = new Set(['EPERM', 'EACCES'])
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 「路径拿不到,原因是没有权限」——带 `code` 的显式错误类型。
|
||||||
|
*
|
||||||
|
* 存在的意义是**不要靠 message 文本传递原因**:上层据此调用 `isPermissionDeniedError()`
|
||||||
|
* 就能判定,不需要去匹配「无权读取」这类措辞(措辞会随文案调整而漂移)。
|
||||||
|
*/
|
||||||
|
export class PathAccessDeniedError extends Error {
|
||||||
|
/** 与 Node 的 fs errno 对齐,让通用的 errno 判定路径直接适用。 */
|
||||||
|
readonly code = 'EPERM'
|
||||||
|
readonly target: string
|
||||||
|
|
||||||
|
constructor(target: string) {
|
||||||
|
super(`无权读取微信数据目录: ${target}`)
|
||||||
|
this.name = 'PathAccessDeniedError'
|
||||||
|
this.target = target
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function probePathAccess(target: string): PathAccess {
|
||||||
|
try {
|
||||||
|
fs.statSync(target)
|
||||||
|
return 'ok'
|
||||||
|
} catch (error) {
|
||||||
|
const code = (error as NodeJS.ErrnoException | null)?.code
|
||||||
|
if (typeof code === 'string' && PERMISSION_ERRNOS.has(code)) return 'denied'
|
||||||
|
return 'missing'
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 从任意抛出物里取 errno —— 有些包装层只保留 `code`,有些只保留 message。
|
||||||
|
*
|
||||||
|
* 返回 null 表示拿不到 errno(调用方应退回文本匹配,而不是直接当成"不存在")。
|
||||||
|
*/
|
||||||
|
export function readErrnoCode(error: unknown): string | null {
|
||||||
|
const code = (error as NodeJS.ErrnoException | null)?.code
|
||||||
|
return typeof code === 'string' && code ? code : null
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 该抛出物是否是权限类错误(按 errno 判断,不做文本猜测)。 */
|
||||||
|
export function isPermissionDeniedError(error: unknown): boolean {
|
||||||
|
const code = readErrnoCode(error)
|
||||||
|
return code !== null && PERMISSION_ERRNOS.has(code)
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 目标路径**自身**读不了时,是否属于"权限不足"。
|
||||||
|
*
|
||||||
|
* 与 `probePathAccess` 的区别:这个只在调用方**已经**判定"拿不到"之后追问原因,
|
||||||
|
* 用于把「文件缺失」纠正成「权限不足」。返回 `false` 表示要么能读、要么是真的不存在
|
||||||
|
* —— 两种情况都不该被改判。
|
||||||
|
*/
|
||||||
|
export function looksLikePermissionDenied(target: string): boolean {
|
||||||
|
return probePathAccess(target) === 'denied'
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 错误文本里的权限特征(小写匹配)。
|
||||||
|
*
|
||||||
|
* 只在拿不到 errno 时兜底 —— 底层把错误包成字符串(例如 native / helper 的 stderr)
|
||||||
|
* 时这是唯一的线索。刻意逐个列举显式模式,不用 `includes('permission')`
|
||||||
|
* 这类过宽判断:那会把 "permission config not found" 之类误判成权限问题。
|
||||||
|
*/
|
||||||
|
export const PERMISSION_DENIED_TEXT_PATTERNS: readonly RegExp[] = [
|
||||||
|
/\beperm\b/,
|
||||||
|
/\beacces\b/,
|
||||||
|
/operation not permitted/,
|
||||||
|
/permission denied/,
|
||||||
|
/access denied/,
|
||||||
|
/权限不足/
|
||||||
|
]
|
||||||
|
|
||||||
|
/** 文本里是否出现权限特征(调用方应确保传入的是已小写的字符串)。 */
|
||||||
|
export function hasPermissionDeniedText(lowercasedDetail: string): boolean {
|
||||||
|
return PERMISSION_DENIED_TEXT_PATTERNS.some((pattern) => pattern.test(lowercasedDetail))
|
||||||
|
}
|
||||||
@@ -12,7 +12,7 @@ import {
|
|||||||
} from 'fs'
|
} from 'fs'
|
||||||
import { homedir, tmpdir } from 'os'
|
import { homedir, tmpdir } from 'os'
|
||||||
import { delimiter, dirname, extname, join, sep } from 'path'
|
import { delimiter, dirname, extname, join, sep } from 'path'
|
||||||
import ffmpegStaticPath from 'ffmpeg-static'
|
import { resolveBundledFfmpegPath } from '../ffmpeg-path'
|
||||||
import { promisify } from 'util'
|
import { promisify } from 'util'
|
||||||
import type {
|
import type {
|
||||||
PersonalWechatSendRequest,
|
PersonalWechatSendRequest,
|
||||||
@@ -64,9 +64,7 @@ function windowsHookHost(port?: unknown): string | null {
|
|||||||
|
|
||||||
export function buildPersonalWechatRuntimePath(): string {
|
export function buildPersonalWechatRuntimePath(): string {
|
||||||
const existing = String(process.env['PATH'] || '')
|
const existing = String(process.env['PATH'] || '')
|
||||||
const bundledFfmpeg = String(ffmpegStaticPath || '')
|
const bundledFfmpeg = resolveBundledFfmpegPath()
|
||||||
.replace('app.asar', 'app.asar.unpacked')
|
|
||||||
.trim()
|
|
||||||
if (!bundledFfmpeg || !existsSync(bundledFfmpeg)) return existing
|
if (!bundledFfmpeg || !existsSync(bundledFfmpeg)) return existing
|
||||||
return [dirname(bundledFfmpeg), existing].filter(Boolean).join(delimiter)
|
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
|
if (!ffmpegPath || !existsSync(ffmpegPath)) return undefined
|
||||||
let output = ''
|
let output = ''
|
||||||
try {
|
try {
|
||||||
@@ -203,7 +201,7 @@ async function prepareWindowsVoiceFile(filePath: string): Promise<{
|
|||||||
return { filePath, durationMs: await detectVoiceDurationMs(filePath), temporary: false }
|
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)) {
|
if (!ffmpegPath || !existsSync(ffmpegPath)) {
|
||||||
throw new Error('Windows 语音发送需要可用的 FFmpeg 才能转换为 SILK')
|
throw new Error('Windows 语音发送需要可用的 FFmpeg 才能转换为 SILK')
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -299,6 +299,8 @@ const SYSTEM_PROMPT = `你是 TraceMemo 的本地聊天查询助手,只能使
|
|||||||
- indexCoverage.covered 为 false 时,说明这段时间还没进索引:此时即使结果为 0 也只能说"索引尚未覆盖这段时间,暂时无法确认",**绝不能**说成"没有"。必须如实引用结论里的索引更新时间。
|
- indexCoverage.covered 为 false 时,说明这段时间还没进索引:此时即使结果为 0 也只能说"索引尚未覆盖这段时间,暂时无法确认",**绝不能**说成"没有"。必须如实引用结论里的索引更新时间。
|
||||||
- 已经检索到 Evidence 时,只有当这个覆盖边界真的会影响结论时才补一句说明,不要机械附加警告。
|
- 已经检索到 Evidence 时,只有当这个覆盖边界真的会影响结论时才补一句说明,不要机械附加警告。
|
||||||
- 只有 coverage.state 为 complete(indexCoverage.covered 为 true)且结果为 0,才可以下"没有找到"的结论。不要自己把 partial 说成 complete。
|
- 只有 coverage.state 为 complete(indexCoverage.covered 为 true)且结果为 0,才可以下"没有找到"的结论。不要自己把 partial 说成 complete。
|
||||||
|
- 结论句说"暂时无法确认"时**不能只停在那里**:必须同时给出可执行的下一步 —— 明确告诉用户「指定某个群或联系人、再加上时间再问一次」,这类精确查询读的是原始聊天记录,**不受索引进度影响**。索引在后台追赶可以如实说明,但那是背景,不是结论的终点。
|
||||||
|
- 结论句若说"已改用直读原始记录补齐",表示这段**已经查过原始记录了**:直接按检索结果回答即可,**不要**再让用户换问法,也不要再说"暂时无法确认"。
|
||||||
图片文字索引:search_messages 的 imageOcrCoverage 是**独立于文字索引**的覆盖维度,只针对“图片里的文字”(截图、报价图、公告截图、海报)。规则:
|
图片文字索引:search_messages 的 imageOcrCoverage 是**独立于文字索引**的覆盖维度,只针对“图片里的文字”(截图、报价图、公告截图、海报)。规则:
|
||||||
- 文字消息索引完整**不代表**图片里的文字搜得到。不要把这两个维度混着说。
|
- 文字消息索引完整**不代表**图片里的文字搜得到。不要把这两个维度混着说。
|
||||||
- 问题涉及图片里的文字、而 imageOcrCoverage.state 不是 complete 时:即使图片证据为 0,也**绝不能**回答“没有”或“没找到”。必须如实引用 imageOcrCoverage.summary,说明图片文字索引尚未完成、当前无法确认全部历史图片。
|
- 问题涉及图片里的文字、而 imageOcrCoverage.state 不是 complete 时:即使图片证据为 0,也**绝不能**回答“没有”或“没找到”。必须如实引用 imageOcrCoverage.summary,说明图片文字索引尚未完成、当前无法确认全部历史图片。
|
||||||
|
|||||||
@@ -613,7 +613,10 @@ export class ScheduledReportService {
|
|||||||
payload?.severity || notification.severity,
|
payload?.severity || notification.severity,
|
||||||
payload?.title || notification.title,
|
payload?.title || notification.title,
|
||||||
payload?.message || notification.message,
|
payload?.message || notification.message,
|
||||||
payload?.suggestedAction
|
payload?.suggestedAction,
|
||||||
|
// 用**失败发生时刻**而不是发送时刻:pending 通知会跨天补发,
|
||||||
|
// 同一批里几条文案完全相同的失败,只有这个时间能区分开。
|
||||||
|
notification.createdAt
|
||||||
)
|
)
|
||||||
})
|
})
|
||||||
if (result.success) {
|
if (result.success) {
|
||||||
@@ -679,17 +682,20 @@ export class ScheduledReportService {
|
|||||||
severity: ScheduledReportNotificationSeverity,
|
severity: ScheduledReportNotificationSeverity,
|
||||||
title: string,
|
title: string,
|
||||||
message: string,
|
message: string,
|
||||||
suggestedAction?: string
|
suggestedAction?: string,
|
||||||
|
occurredAt?: string
|
||||||
): string {
|
): string {
|
||||||
const icon = severity === 'error' ? '❌' : severity === 'warning' ? '⚠️' : '✅'
|
const icon = severity === 'error' ? '❌' : severity === 'warning' ? '⚠️' : '✅'
|
||||||
|
const stamp = formatNotificationTimestamp(occurredAt)
|
||||||
return [
|
return [
|
||||||
`${icon} ${ruleName}`,
|
`${icon} ${ruleName}${stamp ? ` · ${stamp}` : ''}`,
|
||||||
title,
|
title,
|
||||||
message,
|
message,
|
||||||
suggestedAction ? `建议:${suggestedAction}` : ''
|
suggestedAction ? `建议:${suggestedAction}` : ''
|
||||||
]
|
]
|
||||||
.filter(Boolean)
|
.filter(Boolean)
|
||||||
.join('\n')
|
// 必须用**空行**分隔:微信会把单个换行压成空格,否则整条通知会连成一行长句。
|
||||||
|
.join('\n\n')
|
||||||
}
|
}
|
||||||
|
|
||||||
// ---------------------------------------------------------------------------
|
// ---------------------------------------------------------------------------
|
||||||
@@ -996,6 +1002,21 @@ export class ScheduledReportService {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 微信通知里的时间戳(「10月13日 16:28」)。
|
||||||
|
*
|
||||||
|
* 必须精确到分钟而不是只到「几月几日」:pending 通知会跨天补发,同一批里
|
||||||
|
* 几条文案完全相同的失败(同规则、同原因),只到日仍然分不清谁是谁。
|
||||||
|
* 时间非法时返回空串,调用方据此去掉整段前缀。
|
||||||
|
*/
|
||||||
|
const formatNotificationTimestamp = (iso?: string): string => {
|
||||||
|
if (!iso) return ''
|
||||||
|
const date = new Date(iso)
|
||||||
|
if (Number.isNaN(date.getTime())) return ''
|
||||||
|
const pad = (value: number): string => String(value).padStart(2, '0')
|
||||||
|
return `${date.getMonth() + 1}月${date.getDate()}日 ${pad(date.getHours())}:${pad(date.getMinutes())}`
|
||||||
|
}
|
||||||
|
|
||||||
const asArray = <T>(value: unknown): T[] => (Array.isArray(value) ? (value as T[]) : [])
|
const asArray = <T>(value: unknown): T[] => (Array.isArray(value) ? (value as T[]) : [])
|
||||||
|
|
||||||
const executionStatuses = new Set<ScheduledReportExecution['status']>([
|
const executionStatuses = new Set<ScheduledReportExecution['status']>([
|
||||||
|
|||||||
@@ -20,6 +20,8 @@ function redirectLegacyWeChatFilesToXwechat(candidate: string): string {
|
|||||||
return candidate
|
return candidate
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export type CloseAction = 'ask' | 'tray' | 'quit'
|
||||||
|
|
||||||
export interface AppSettings {
|
export interface AppSettings {
|
||||||
dbRoot: string
|
dbRoot: string
|
||||||
apiEnabled: boolean
|
apiEnabled: boolean
|
||||||
@@ -47,6 +49,32 @@ export interface AppSettings {
|
|||||||
* 不在用户界面暴露实验性名称)。
|
* 不在用户界面暴露实验性名称)。
|
||||||
*/
|
*/
|
||||||
queryAgentEnabled: boolean
|
queryAgentEnabled: boolean
|
||||||
|
/**
|
||||||
|
* 关闭主窗口时的行为。
|
||||||
|
*
|
||||||
|
* - `ask`:每次弹窗询问(默认,保持既有行为)
|
||||||
|
* - `tray`:直接最小化到系统托盘,应用继续在后台跑
|
||||||
|
* - `quit`:直接退出整个进程
|
||||||
|
*
|
||||||
|
* 只有用户在关闭弹窗里勾了"记住我的选择"才会离开 `ask`;
|
||||||
|
* 设置页随时可以改回来。
|
||||||
|
*/
|
||||||
|
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 {
|
function getDefaultDbRoot(): string {
|
||||||
@@ -131,7 +159,9 @@ const DEFAULT_SETTINGS: AppSettings = {
|
|||||||
ttsModel: 's2.1-pro-free',
|
ttsModel: 's2.1-pro-free',
|
||||||
windowsWechatPort: '',
|
windowsWechatPort: '',
|
||||||
reportImagePostfixText: '今日日报',
|
reportImagePostfixText: '今日日报',
|
||||||
queryAgentEnabled: true
|
queryAgentEnabled: true,
|
||||||
|
closeAction: 'ask',
|
||||||
|
skippedUpdateVersion: ''
|
||||||
}
|
}
|
||||||
|
|
||||||
const SETTINGS_FILE = path.join(
|
const SETTINGS_FILE = path.join(
|
||||||
@@ -176,6 +206,17 @@ export function loadSettings(): AppSettings {
|
|||||||
if (cache.dbRoot) {
|
if (cache.dbRoot) {
|
||||||
cache.dbRoot = redirectLegacyWeChatFilesToXwechat(cache.dbRoot)
|
cache.dbRoot = redirectLegacyWeChatFilesToXwechat(cache.dbRoot)
|
||||||
}
|
}
|
||||||
|
// 关闭行为可能来自旧版本或手改过的 settings.json —— 非法值一律收敛回 `ask`。
|
||||||
|
// 放任非法值会造成最难排查的一种表现:点关闭窗口什么也不发生。
|
||||||
|
if (
|
||||||
|
cache.closeAction !== 'ask' &&
|
||||||
|
cache.closeAction !== 'tray' &&
|
||||||
|
cache.closeAction !== 'quit'
|
||||||
|
) {
|
||||||
|
cache.closeAction = 'ask'
|
||||||
|
}
|
||||||
|
// 版本号是拿来逐字比对的:脏值会让「忽略」永远命中不了同一条记录。
|
||||||
|
cache.skippedUpdateVersion = normalizeSkippedUpdateVersion(cache.skippedUpdateVersion)
|
||||||
// 防撤回已下线(设置入口已隐藏):历史版本可能把它持久化为 true。
|
// 防撤回已下线(设置入口已隐藏):历史版本可能把它持久化为 true。
|
||||||
// 这里强制收敛为 false 并回写磁盘,确保旧的撤回监听与撤回日志不会继续运行。
|
// 这里强制收敛为 false 并回写磁盘,确保旧的撤回监听与撤回日志不会继续运行。
|
||||||
if (cache.recallProtectionEnabled || retiredKeepProcess !== undefined) {
|
if (cache.recallProtectionEnabled || retiredKeepProcess !== undefined) {
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
|
import { createHash } from 'crypto'
|
||||||
import { app, shell } from 'electron'
|
import { app, shell } from 'electron'
|
||||||
import { existsSync, promises as fs } from 'fs'
|
import { existsSync, readFileSync, promises as fs, statSync } from 'fs'
|
||||||
import { dirname, join } from 'path'
|
import { dirname, join } from 'path'
|
||||||
import { isPackagedRuntime } from '../runtime-mode'
|
import { isPackagedRuntime } from '../runtime-mode'
|
||||||
|
|
||||||
@@ -8,7 +9,8 @@ const SKILL_RELATIVE_PATHS = [
|
|||||||
join('skill', 'wechatexplorer-reader', 'SKILL.md')
|
join('skill', 'wechatexplorer-reader', 'SKILL.md')
|
||||||
]
|
]
|
||||||
const GITHUB_URL = 'https://github.com/Wxw-Gu/TraceMemo/tree/main/docs/skill/tracememo-reader'
|
const GITHUB_URL = 'https://github.com/Wxw-Gu/TraceMemo/tree/main/docs/skill/tracememo-reader'
|
||||||
const SKILL_VERSION = 'v1.2'
|
|
||||||
|
export const READER_SKILL_NAME = 'tracememo-reader'
|
||||||
|
|
||||||
type SkillResourceSource = 'development' | 'bundled'
|
type SkillResourceSource = 'development' | 'bundled'
|
||||||
|
|
||||||
@@ -27,7 +29,9 @@ interface SkillCandidate {
|
|||||||
|
|
||||||
export interface SkillResourceStatus {
|
export interface SkillResourceStatus {
|
||||||
available: boolean
|
available: boolean
|
||||||
|
name?: string
|
||||||
version?: string
|
version?: string
|
||||||
|
contentHash?: string
|
||||||
filePath?: string
|
filePath?: string
|
||||||
directoryPath?: string
|
directoryPath?: string
|
||||||
source: SkillResourceSource
|
source: SkillResourceSource
|
||||||
@@ -35,6 +39,27 @@ export interface SkillResourceStatus {
|
|||||||
error?: string
|
error?: string
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export interface SkillDocument {
|
||||||
|
name: string
|
||||||
|
version?: string
|
||||||
|
contentHash: string
|
||||||
|
modifiedAt: string
|
||||||
|
markdown: string
|
||||||
|
filePath: string
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface SkillFrontmatter {
|
||||||
|
name?: string
|
||||||
|
version?: string
|
||||||
|
}
|
||||||
|
|
||||||
|
interface SkillDocumentCacheEntry {
|
||||||
|
filePath: string
|
||||||
|
mtimeMs: number
|
||||||
|
size: number
|
||||||
|
document: SkillDocument
|
||||||
|
}
|
||||||
|
|
||||||
function currentEnvironment(): SkillPathEnvironment {
|
function currentEnvironment(): SkillPathEnvironment {
|
||||||
return {
|
return {
|
||||||
appPath: app.getAppPath(),
|
appPath: app.getAppPath(),
|
||||||
@@ -54,6 +79,81 @@ function uniqueCandidates(candidates: SkillCandidate[]): SkillCandidate[] {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 版本号只认 SKILL.md frontmatter 的 `version`,不再维护源码常量:
|
||||||
|
* 常量与文档分离必然漂移,曾经出现过文档改了两轮而版本号纹丝不动的情况。
|
||||||
|
*/
|
||||||
|
export function parseSkillFrontmatter(content: string): SkillFrontmatter {
|
||||||
|
const match = /^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/.exec(content)
|
||||||
|
if (!match) return {}
|
||||||
|
const block = match[1]
|
||||||
|
if (!block) return {}
|
||||||
|
|
||||||
|
const frontmatter: SkillFrontmatter = {}
|
||||||
|
for (const rawLine of block.split(/\r?\n/)) {
|
||||||
|
const line = rawLine.trim()
|
||||||
|
if (!line || line.startsWith('#')) continue
|
||||||
|
const separator = line.indexOf(':')
|
||||||
|
if (separator <= 0) continue
|
||||||
|
const key = line.slice(0, separator).trim().toLowerCase()
|
||||||
|
const value = line
|
||||||
|
.slice(separator + 1)
|
||||||
|
.trim()
|
||||||
|
.replace(/^["']/, '')
|
||||||
|
.replace(/["']$/, '')
|
||||||
|
if (!value) continue
|
||||||
|
if (key === 'name') frontmatter.name = value
|
||||||
|
else if (key === 'version') frontmatter.version = value
|
||||||
|
}
|
||||||
|
return frontmatter
|
||||||
|
}
|
||||||
|
|
||||||
|
function hashSkillContent(content: string): string {
|
||||||
|
return createHash('sha256').update(content, 'utf8').digest('hex')
|
||||||
|
}
|
||||||
|
|
||||||
|
let cachedDocument: SkillDocumentCacheEntry | null = null
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 同步读取 Skill 文档。`/health` 属于高频接口,因此按 mtime + size 缓存,
|
||||||
|
* 文件被替换(版本升级)后缓存自动失效。
|
||||||
|
*/
|
||||||
|
export function readSkillDocument(filePath: string): SkillDocument | null {
|
||||||
|
try {
|
||||||
|
const stats = statSync(filePath)
|
||||||
|
if (
|
||||||
|
cachedDocument &&
|
||||||
|
cachedDocument.filePath === filePath &&
|
||||||
|
cachedDocument.mtimeMs === stats.mtimeMs &&
|
||||||
|
cachedDocument.size === stats.size
|
||||||
|
) {
|
||||||
|
return cachedDocument.document
|
||||||
|
}
|
||||||
|
|
||||||
|
const markdown = readFileSync(filePath, 'utf-8')
|
||||||
|
const frontmatter = parseSkillFrontmatter(markdown)
|
||||||
|
const document: SkillDocument = {
|
||||||
|
name: frontmatter.name || READER_SKILL_NAME,
|
||||||
|
contentHash: hashSkillContent(markdown),
|
||||||
|
modifiedAt: stats.mtime.toISOString(),
|
||||||
|
markdown,
|
||||||
|
filePath
|
||||||
|
}
|
||||||
|
if (frontmatter.version) document.version = frontmatter.version
|
||||||
|
|
||||||
|
cachedDocument = {
|
||||||
|
filePath,
|
||||||
|
mtimeMs: stats.mtimeMs,
|
||||||
|
size: stats.size,
|
||||||
|
document
|
||||||
|
}
|
||||||
|
return document
|
||||||
|
} catch {
|
||||||
|
cachedDocument = null
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
export function getSkillCandidates(environment?: SkillPathEnvironment): SkillCandidate[] {
|
export function getSkillCandidates(environment?: SkillPathEnvironment): SkillCandidate[] {
|
||||||
const runtime = environment || currentEnvironment()
|
const runtime = environment || currentEnvironment()
|
||||||
const developmentPaths = SKILL_RELATIVE_PATHS.flatMap((relativePath) => [
|
const developmentPaths = SKILL_RELATIVE_PATHS.flatMap((relativePath) => [
|
||||||
@@ -82,26 +182,40 @@ export function getSkillCandidates(environment?: SkillPathEnvironment): SkillCan
|
|||||||
export function resolveSkillResourceStatus(
|
export function resolveSkillResourceStatus(
|
||||||
environment?: SkillPathEnvironment
|
environment?: SkillPathEnvironment
|
||||||
): SkillResourceStatus {
|
): SkillResourceStatus {
|
||||||
const candidates = getSkillCandidates(environment)
|
let candidates: SkillCandidate[] = []
|
||||||
const resolved = candidates.find((candidate) => existsSync(candidate.path))
|
let source: SkillResourceSource = environment?.packaged ? 'bundled' : 'development'
|
||||||
const filePath = resolved?.path || candidates[0].path
|
try {
|
||||||
const source = resolved?.source || candidates[0].source
|
candidates = getSkillCandidates(environment)
|
||||||
const directoryPath = dirname(filePath)
|
const resolved = candidates.find((candidate) => existsSync(candidate.path))
|
||||||
if (!resolved) {
|
if (resolved) {
|
||||||
return {
|
const filePath = resolved.path
|
||||||
available: false,
|
const status: SkillResourceStatus = {
|
||||||
source,
|
available: true,
|
||||||
githubUrl: GITHUB_URL,
|
filePath,
|
||||||
error: `未找到 TraceMemo Reader Skill 文件(已检查:${candidates.map((item) => item.path).join(';')})`
|
directoryPath: dirname(filePath),
|
||||||
|
source: resolved.source,
|
||||||
|
githubUrl: GITHUB_URL
|
||||||
|
}
|
||||||
|
const document = readSkillDocument(filePath)
|
||||||
|
if (document) {
|
||||||
|
status.name = document.name
|
||||||
|
status.contentHash = document.contentHash
|
||||||
|
if (document.version) status.version = document.version
|
||||||
|
}
|
||||||
|
return status
|
||||||
}
|
}
|
||||||
|
const fallback = candidates[0]
|
||||||
|
if (fallback) source = fallback.source
|
||||||
|
} catch {
|
||||||
|
// 环境探测失败(例如非 Electron 进程)时退化成“不可用”:
|
||||||
|
// /health 是外部 Agent 的自检入口,不能因为 Skill 读不到就整条挂掉。
|
||||||
}
|
}
|
||||||
|
|
||||||
return {
|
return {
|
||||||
available: true,
|
available: false,
|
||||||
version: SKILL_VERSION,
|
|
||||||
filePath,
|
|
||||||
directoryPath,
|
|
||||||
source,
|
source,
|
||||||
githubUrl: GITHUB_URL
|
githubUrl: GITHUB_URL,
|
||||||
|
error: `未找到 TraceMemo Reader Skill 文件(已检查:${candidates.map((item) => item.path).join(';')})`
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -112,6 +226,12 @@ function getStatus(): SkillResourceStatus {
|
|||||||
export const skillResourceService = {
|
export const skillResourceService = {
|
||||||
getStatus,
|
getStatus,
|
||||||
|
|
||||||
|
getDocument(): SkillDocument | null {
|
||||||
|
const status = this.getStatus()
|
||||||
|
if (!status.available || !status.filePath) return null
|
||||||
|
return readSkillDocument(status.filePath)
|
||||||
|
},
|
||||||
|
|
||||||
async read(): Promise<{ success: boolean; content?: string; error?: string }> {
|
async read(): Promise<{ success: boolean; content?: string; error?: string }> {
|
||||||
const status = this.getStatus()
|
const status = this.getStatus()
|
||||||
if (!status.available || !status.filePath) return { success: false, error: status.error }
|
if (!status.available || !status.filePath) return { success: false, error: status.error }
|
||||||
|
|||||||
@@ -36,6 +36,7 @@
|
|||||||
// - macOS 没有"语言包缺失"这一失败模式。
|
// - macOS 没有"语言包缺失"这一失败模式。
|
||||||
|
|
||||||
import crypto from 'node:crypto'
|
import crypto from 'node:crypto'
|
||||||
|
import { resolveBundledFfmpegPath } from '../ffmpeg-path'
|
||||||
import { spawn } from 'node:child_process'
|
import { spawn } from 'node:child_process'
|
||||||
import {
|
import {
|
||||||
SYSTEM_OCR_CACHE_TTL_MS,
|
SYSTEM_OCR_CACHE_TTL_MS,
|
||||||
@@ -125,7 +126,7 @@ const defaultResolveFfmpegExecutable = (): string => {
|
|||||||
const fromEnvironment = String(process.env['FFMPEG_BIN'] || '').trim()
|
const fromEnvironment = String(process.env['FFMPEG_BIN'] || '').trim()
|
||||||
if (fromEnvironment) return fromEnvironment
|
if (fromEnvironment) return fromEnvironment
|
||||||
try {
|
try {
|
||||||
const bundled = require('ffmpeg-static') as string | null
|
const bundled = resolveBundledFfmpegPath()
|
||||||
if (bundled) return bundled
|
if (bundled) return bundled
|
||||||
} catch {
|
} catch {
|
||||||
// 忽略:退回到 PATH 上的 ffmpeg
|
// 忽略:退回到 PATH 上的 ffmpeg
|
||||||
|
|||||||
@@ -0,0 +1,322 @@
|
|||||||
|
/**
|
||||||
|
* 微信内退群监控消息 —— 事件驱动的一次性插入。
|
||||||
|
*
|
||||||
|
* 为什么不再用 persistent trigger
|
||||||
|
* ------------------------------
|
||||||
|
* 退群提示以前是给每个监控群装一条 `_tm_msg_insert_queue` 规则,靠微信自己插消息时
|
||||||
|
* 触发。问题:粒度是「群 × 分片」,监控群一多就要铺成百上千条规则;而退群这个事实
|
||||||
|
* TraceMemo 本来就已经知道了(GroupExitMonitorService 是**唯一**退群事实源)。
|
||||||
|
* 让数据库再算一遍,等于维护两套退群判断,迟早不一致。
|
||||||
|
*
|
||||||
|
* 现在改成:
|
||||||
|
* GroupExitMonitorService → GroupMemberExitedEvent → 本服务 → one-shot helper 插一条
|
||||||
|
*
|
||||||
|
* 三条硬约束(都不能违反)
|
||||||
|
* ------------------------
|
||||||
|
* 1. **不产生第二套退群事实**:本服务只消费事件、只插消息,从不自己判断谁退群。
|
||||||
|
* 2. **失败不回滚、不阻塞**:插入失败绝不能让退群事件回滚、不能影响监控循环、
|
||||||
|
* 不能影响自动化通知。所以 handleExitEvent **永不抛异常**,调用方也不必 await。
|
||||||
|
* 3. **幂等**:以 eventId 为幂等键,同一事件最多插一次。幂等日志写在微信库里
|
||||||
|
* (不是内存),所以跨进程、跨重启都有效。
|
||||||
|
*
|
||||||
|
* 只插一个目标消息存储:写入分片由 native 侧按 MAX(sort_seq) 选出,不在历史分片
|
||||||
|
* 重复插入。没有可插入的消息表时返回 NO_MESSAGE_STORE,TraceMemo 内部的退群记录
|
||||||
|
* 照常保留。
|
||||||
|
*/
|
||||||
|
|
||||||
|
import { spawn } from 'node:child_process'
|
||||||
|
import fs from 'node:fs'
|
||||||
|
import path from 'node:path'
|
||||||
|
|
||||||
|
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 { resolveWcdbConfigHelper } from '../native-runtime-paths'
|
||||||
|
import { msgInsertCapabilityService } from './msg-insert-capability-service'
|
||||||
|
import { resolveHelperPath } from './msg-insert-switch-service'
|
||||||
|
|
||||||
|
export type LocalExitNoticeOutcome =
|
||||||
|
| 'inserted'
|
||||||
|
| 'duplicate'
|
||||||
|
| 'disabled'
|
||||||
|
| 'no_message_store'
|
||||||
|
| 'failed'
|
||||||
|
| 'helper_unavailable'
|
||||||
|
|
||||||
|
export interface LocalExitNoticeResult {
|
||||||
|
outcome: LocalExitNoticeOutcome
|
||||||
|
eventId: string
|
||||||
|
conversationId: string
|
||||||
|
shard?: string
|
||||||
|
localId?: number
|
||||||
|
/** 机器可读的原因,只进日志 */
|
||||||
|
code?: string
|
||||||
|
}
|
||||||
|
|
||||||
|
interface StoredState {
|
||||||
|
enabled?: boolean
|
||||||
|
}
|
||||||
|
|
||||||
|
const HELPER_TIMEOUT_MS = 20_000
|
||||||
|
/** 最近若干次插入结果,只用于诊断展示,不参与判定 */
|
||||||
|
const RECENT_LIMIT = 50
|
||||||
|
|
||||||
|
function helperPath(): string | null {
|
||||||
|
if (process.platform === 'darwin') return resolveWcdbConfigHelper()
|
||||||
|
/*
|
||||||
|
* 不在这里重复一份 resources 搜索逻辑。
|
||||||
|
* Windows 上 helper 可能被部署到外置目录,
|
||||||
|
* 只有一处解析入口,两条链路才不会各解析各的。
|
||||||
|
*/
|
||||||
|
return resolveHelperPath()
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 退群本地提示服务。
|
||||||
|
*
|
||||||
|
* 与 GroupExitMonitorService 是**消费**关系:它发事件,这里负责往微信里插一条。
|
||||||
|
* 这里不持有任何群列表,也不判断退群 —— 避免第二套事实源。
|
||||||
|
*/
|
||||||
|
export class WechatLocalExitNoticeService {
|
||||||
|
private enabled = false
|
||||||
|
private loaded = false
|
||||||
|
private recent: LocalExitNoticeResult[] = []
|
||||||
|
|
||||||
|
private statePath(): string {
|
||||||
|
return path.join(app.getPath('userData'), 'wechat-local-exit-notice.json')
|
||||||
|
}
|
||||||
|
|
||||||
|
private ensureLoaded(): void {
|
||||||
|
if (this.loaded) return
|
||||||
|
this.loaded = true
|
||||||
|
try {
|
||||||
|
const raw = fs.readFileSync(this.statePath(), 'utf8')
|
||||||
|
const stored = JSON.parse(raw) as StoredState
|
||||||
|
this.enabled = stored.enabled === true
|
||||||
|
} catch {
|
||||||
|
this.enabled = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
isEnabled(): boolean {
|
||||||
|
this.ensureLoaded()
|
||||||
|
return this.enabled
|
||||||
|
}
|
||||||
|
|
||||||
|
setEnabled(enabled: boolean): { enabled: boolean; error?: string } {
|
||||||
|
this.ensureLoaded()
|
||||||
|
this.enabled = enabled === true
|
||||||
|
try {
|
||||||
|
fs.mkdirSync(path.dirname(this.statePath()), { recursive: true })
|
||||||
|
fs.writeFileSync(this.statePath(), JSON.stringify({ enabled: this.enabled }, null, 2), 'utf8')
|
||||||
|
return { enabled: this.enabled }
|
||||||
|
} catch (error) {
|
||||||
|
return {
|
||||||
|
enabled: this.enabled,
|
||||||
|
error: error instanceof Error ? error.message : String(error)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
getRecent(): LocalExitNoticeResult[] {
|
||||||
|
return [...this.recent]
|
||||||
|
}
|
||||||
|
|
||||||
|
private remember(result: LocalExitNoticeResult): void {
|
||||||
|
this.recent = [result, ...this.recent].slice(0, RECENT_LIMIT)
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 处理一次退群事件。
|
||||||
|
*
|
||||||
|
* ⚠️ 本方法**永不抛异常**:它挂在退群监控的事件回调上,抛出去会污染监控循环。
|
||||||
|
* 返回值只用于日志与诊断,调用方不需要(也不应该)等它。
|
||||||
|
*/
|
||||||
|
async handleExitEvent(event: GroupMemberExitedEvent): Promise<LocalExitNoticeResult> {
|
||||||
|
const base: LocalExitNoticeResult = {
|
||||||
|
outcome: 'failed',
|
||||||
|
eventId: event.eventId,
|
||||||
|
conversationId: event.conversationId
|
||||||
|
}
|
||||||
|
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' })
|
||||||
|
}
|
||||||
|
|
||||||
|
const resolved = helperPath()
|
||||||
|
if (!resolved) {
|
||||||
|
return this.finish({ ...base, outcome: 'helper_unavailable', code: 'HELPER_NOT_FOUND' })
|
||||||
|
}
|
||||||
|
|
||||||
|
const key = resolveDatabaseKey()
|
||||||
|
const myWxid = resolveMyWxid()
|
||||||
|
if (!key || !myWxid) {
|
||||||
|
return this.finish({ ...base, outcome: 'failed', code: 'DATABASE_UNAVAILABLE' })
|
||||||
|
}
|
||||||
|
|
||||||
|
const accountRoot = resolveAccountRoot()
|
||||||
|
if (!accountRoot) {
|
||||||
|
return this.finish({ ...base, outcome: 'failed', code: 'ACCOUNT_ROOT_UNRESOLVED' })
|
||||||
|
}
|
||||||
|
|
||||||
|
const text = renderLeaveNotificationText(event, GROUP_EXIT_NOTIFICATION_TEMPLATE)
|
||||||
|
const payload = JSON.stringify({
|
||||||
|
key,
|
||||||
|
myWxid,
|
||||||
|
roomId: event.conversationId,
|
||||||
|
text,
|
||||||
|
dedupeKey: event.eventId
|
||||||
|
})
|
||||||
|
|
||||||
|
const parsed = await runInsertHelper(resolved, accountRoot, payload)
|
||||||
|
if (!parsed) {
|
||||||
|
return this.finish({ ...base, outcome: 'failed', code: 'HELPER_BAD_OUTPUT' })
|
||||||
|
}
|
||||||
|
|
||||||
|
const code = String(parsed.code || '')
|
||||||
|
const shard = typeof parsed.shard === 'string' && parsed.shard ? parsed.shard : undefined
|
||||||
|
const localId = Number(parsed.localId) || undefined
|
||||||
|
if (parsed.ok === true) {
|
||||||
|
return this.finish({
|
||||||
|
...base,
|
||||||
|
outcome: code === 'ALREADY_INSERTED' ? 'duplicate' : 'inserted',
|
||||||
|
shard,
|
||||||
|
localId,
|
||||||
|
code
|
||||||
|
})
|
||||||
|
}
|
||||||
|
if (code === 'NO_MESSAGE_STORE') {
|
||||||
|
return this.finish({ ...base, outcome: 'no_message_store', code })
|
||||||
|
}
|
||||||
|
return this.finish({ ...base, outcome: 'failed', shard, localId, code })
|
||||||
|
} catch (error) {
|
||||||
|
/* 兜底:任何意外都不许冒到监控循环里去。 */
|
||||||
|
return this.finish({
|
||||||
|
...base,
|
||||||
|
outcome: 'failed',
|
||||||
|
code: error instanceof Error ? error.message : String(error)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private finish(result: LocalExitNoticeResult): LocalExitNoticeResult {
|
||||||
|
this.remember(result)
|
||||||
|
if (result.outcome === 'failed' || result.outcome === 'helper_unavailable') {
|
||||||
|
console.warn(
|
||||||
|
`[LocalExitNotice] 插入未成功 outcome=${result.outcome} code=${result.code || 'UNKNOWN'}`
|
||||||
|
)
|
||||||
|
}
|
||||||
|
return result
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export const wechatLocalExitNoticeService = new WechatLocalExitNoticeService()
|
||||||
|
|
||||||
|
/* --------------------------------------------------------------- 依赖注入 */
|
||||||
|
|
||||||
|
interface LocalExitRuntime {
|
||||||
|
resolveDatabaseKey: () => string
|
||||||
|
resolveMyWxid: () => string
|
||||||
|
resolveAccountRoot: () => string
|
||||||
|
}
|
||||||
|
|
||||||
|
let runtime: LocalExitRuntime | null = null
|
||||||
|
|
||||||
|
/** 由主进程在启动时注入;这样服务本身不依赖 chat-service 的具体形态。 */
|
||||||
|
export function configureWechatLocalExitNotice(next: LocalExitRuntime): void {
|
||||||
|
runtime = next
|
||||||
|
}
|
||||||
|
|
||||||
|
function resolveDatabaseKey(): string {
|
||||||
|
try {
|
||||||
|
return runtime?.resolveDatabaseKey() || ''
|
||||||
|
} catch {
|
||||||
|
return ''
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function resolveMyWxid(): string {
|
||||||
|
try {
|
||||||
|
return runtime?.resolveMyWxid() || ''
|
||||||
|
} catch {
|
||||||
|
return ''
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function resolveAccountRoot(): string {
|
||||||
|
try {
|
||||||
|
return runtime?.resolveAccountRoot() || ''
|
||||||
|
} catch {
|
||||||
|
return ''
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ------------------------------------------------------------------ 执行 */
|
||||||
|
|
||||||
|
function runInsertHelper(
|
||||||
|
executable: string,
|
||||||
|
accountRoot: string,
|
||||||
|
payload: string
|
||||||
|
): Promise<Record<string, unknown> | null> {
|
||||||
|
return new Promise((resolve) => {
|
||||||
|
let child: ReturnType<typeof spawn>
|
||||||
|
try {
|
||||||
|
child = spawn(executable, ['--account-root', accountRoot, '--action', 'insert-notice'], {
|
||||||
|
stdio: ['pipe', 'pipe', 'pipe']
|
||||||
|
})
|
||||||
|
} catch {
|
||||||
|
resolve(null)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
let stdout = ''
|
||||||
|
let settled = false
|
||||||
|
const finish = (value: Record<string, unknown> | null): void => {
|
||||||
|
if (settled) return
|
||||||
|
settled = true
|
||||||
|
clearTimeout(timer)
|
||||||
|
resolve(value)
|
||||||
|
}
|
||||||
|
const timer = setTimeout(() => {
|
||||||
|
try {
|
||||||
|
child.kill('SIGKILL')
|
||||||
|
} catch {
|
||||||
|
/* 已退出 */
|
||||||
|
}
|
||||||
|
finish(null)
|
||||||
|
}, HELPER_TIMEOUT_MS)
|
||||||
|
|
||||||
|
child.stdout?.on('data', (chunk: Buffer) => {
|
||||||
|
stdout += chunk.toString()
|
||||||
|
})
|
||||||
|
child.stderr?.on('data', () => {
|
||||||
|
/* 人类日志直接丢弃:里面不该有密钥,也没必要留 */
|
||||||
|
})
|
||||||
|
child.on('error', () => finish(null))
|
||||||
|
child.on('close', () => {
|
||||||
|
try {
|
||||||
|
const lines = stdout.trim().split('\n').filter(Boolean)
|
||||||
|
finish(JSON.parse(lines[lines.length - 1] || '') as Record<string, unknown>)
|
||||||
|
} catch {
|
||||||
|
finish(null)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
try {
|
||||||
|
child.stdin?.write(`${payload}\n`)
|
||||||
|
child.stdin?.end()
|
||||||
|
} catch {
|
||||||
|
finish(null)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
@@ -0,0 +1,51 @@
|
|||||||
|
import { readFileSync } from 'fs'
|
||||||
|
|
||||||
|
export interface TrayNativeImage {
|
||||||
|
addRepresentation(options: { scaleFactor: number; dataURL: string }): void
|
||||||
|
isEmpty(): boolean
|
||||||
|
resize(options: { width: number; height: number; quality: 'best' }): TrayNativeImage
|
||||||
|
setTemplateImage(option: boolean): void
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface TrayNativeImageFactory<T extends TrayNativeImage = TrayNativeImage> {
|
||||||
|
createEmpty(): T
|
||||||
|
createFromPath(path: string): T
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface TrayTemplateIconPaths {
|
||||||
|
oneX: string
|
||||||
|
twoX: string
|
||||||
|
}
|
||||||
|
|
||||||
|
type ReadImageFile = (path: string) => Buffer
|
||||||
|
|
||||||
|
function toPngDataUrl(buffer: Buffer): string {
|
||||||
|
return `data:image/png;base64,${buffer.toString('base64')}`
|
||||||
|
}
|
||||||
|
|
||||||
|
export function createTrayImage<T extends TrayNativeImage>(
|
||||||
|
platform: NodeJS.Platform,
|
||||||
|
appIconPath: string,
|
||||||
|
templateIconPaths: TrayTemplateIconPaths,
|
||||||
|
nativeImage: TrayNativeImageFactory<T>,
|
||||||
|
readImageFile: ReadImageFile = readFileSync
|
||||||
|
): T {
|
||||||
|
if (platform === 'darwin') {
|
||||||
|
const image = nativeImage.createEmpty()
|
||||||
|
image.addRepresentation({
|
||||||
|
scaleFactor: 1,
|
||||||
|
dataURL: toPngDataUrl(readImageFile(templateIconPaths.oneX))
|
||||||
|
})
|
||||||
|
image.addRepresentation({
|
||||||
|
scaleFactor: 2,
|
||||||
|
dataURL: toPngDataUrl(readImageFile(templateIconPaths.twoX))
|
||||||
|
})
|
||||||
|
image.setTemplateImage(true)
|
||||||
|
return image
|
||||||
|
}
|
||||||
|
|
||||||
|
const image = nativeImage.createFromPath(appIconPath)
|
||||||
|
return image.isEmpty()
|
||||||
|
? nativeImage.createEmpty()
|
||||||
|
: (image.resize({ width: 24, height: 24, quality: 'best' }) as T)
|
||||||
|
}
|
||||||
@@ -23,3 +23,30 @@ export function voiceAccountIdentity(accountRoot: string): string {
|
|||||||
)
|
)
|
||||||
.digest('hex')
|
.digest('hex')
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 从一条已格式化的消息里取出语音定位信息;不是语音或标识不完整时返回 undefined。
|
||||||
|
* 本地 API 用它判断"这条消息能否转写",与批量转写的口径一致。
|
||||||
|
*/
|
||||||
|
export function voiceMessageReferenceOf(message: {
|
||||||
|
type?: string
|
||||||
|
sessionId?: string
|
||||||
|
localId?: number
|
||||||
|
createTime?: number
|
||||||
|
serverId?: string
|
||||||
|
}): VoiceMessageReference | undefined {
|
||||||
|
if (
|
||||||
|
message.type !== '语音' ||
|
||||||
|
!message.sessionId ||
|
||||||
|
message.localId === undefined ||
|
||||||
|
!message.createTime
|
||||||
|
) {
|
||||||
|
return undefined
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
sessionId: message.sessionId,
|
||||||
|
localId: message.localId,
|
||||||
|
createTime: message.createTime,
|
||||||
|
svrId: message.serverId
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,154 @@
|
|||||||
|
import type {
|
||||||
|
VoiceMessageReference,
|
||||||
|
VoiceRecognitionErrorCode,
|
||||||
|
VoiceRecognitionResult,
|
||||||
|
VoiceTranscriptSnapshot
|
||||||
|
} from '../../shared/voice-recognition'
|
||||||
|
import { voiceMessageIdentity } from './voice-message-identity'
|
||||||
|
import type { VoiceRecognitionUseCase } from './voice-recognition-use-case'
|
||||||
|
|
||||||
|
/** API 发起、尚未完成的转写任务上限(跨请求共享)。 */
|
||||||
|
export const VOICE_TRANSCRIBE_MAX_IN_FLIGHT = 100
|
||||||
|
/** 被界面上的交互请求抢占后,最多重新排队几次。 */
|
||||||
|
const MAX_PREEMPTION_RETRIES = 5
|
||||||
|
|
||||||
|
type Recognition = Pick<
|
||||||
|
VoiceRecognitionUseCase,
|
||||||
|
'recognize' | 'getTranscriptSnapshot' | 'getModelStatus' | 'accountIdentity'
|
||||||
|
>
|
||||||
|
|
||||||
|
export type VoiceTranscriptionOutcome =
|
||||||
|
| { state: 'transcribed'; transcript: string; cached: boolean; durationMs?: number }
|
||||||
|
| { state: 'pending' }
|
||||||
|
| { state: 'failed'; code: VoiceRecognitionErrorCode | 'PREVIOUSLY_FAILED'; error: string }
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 本地 API 触发语音转写的入口。
|
||||||
|
*
|
||||||
|
* 识别本身(缓存、单 worker 串行调度、失败记录、Knowledge 增量)仍完全由
|
||||||
|
* VoiceRecognitionUseCase 负责;这里只补 API 调用方需要的三件事:
|
||||||
|
* - 同一条语音被反复轮询时复用同一个进行中的任务,不重复排队;
|
||||||
|
* - 限制 API 积压的任务总量,避免一次塞入上千条把界面上的识别饿死;
|
||||||
|
* - 调用方只等待有限时间,没做完的继续在后台跑,结果进缓存供下次读取。
|
||||||
|
*/
|
||||||
|
export class VoiceTranscriptionGateway {
|
||||||
|
private readonly inFlight = new Map<string, Promise<VoiceRecognitionResult>>()
|
||||||
|
|
||||||
|
constructor(
|
||||||
|
private readonly recognition: Recognition,
|
||||||
|
private readonly maxInFlight = VOICE_TRANSCRIBE_MAX_IN_FLIGHT
|
||||||
|
) {}
|
||||||
|
|
||||||
|
/** 只读缓存,不触发识别。 */
|
||||||
|
snapshot(reference: VoiceMessageReference): VoiceTranscriptSnapshot {
|
||||||
|
return this.recognition.getTranscriptSnapshot(reference)
|
||||||
|
}
|
||||||
|
|
||||||
|
async modelReady(): Promise<boolean> {
|
||||||
|
return (await this.recognition.getModelStatus()).state === 'ready'
|
||||||
|
}
|
||||||
|
|
||||||
|
get inFlightCount(): number {
|
||||||
|
return this.inFlight.size
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 返回与 references 一一对应的结果;剩余容量装不下本次新增任务时返回 null,
|
||||||
|
* 且不排入任何任务(整批拒绝,调用方稍后原样重试即可)。
|
||||||
|
*/
|
||||||
|
async transcribe(
|
||||||
|
references: VoiceMessageReference[],
|
||||||
|
options: { force?: boolean; waitMs: number }
|
||||||
|
): Promise<VoiceTranscriptionOutcome[] | null> {
|
||||||
|
const accountIdentity = this.recognition.accountIdentity
|
||||||
|
const keyOf = (reference: VoiceMessageReference): string =>
|
||||||
|
`${accountIdentity}:${voiceMessageIdentity(reference)}`
|
||||||
|
|
||||||
|
const immediate = references.map((reference): VoiceTranscriptionOutcome | undefined => {
|
||||||
|
if (options.force || this.inFlight.has(keyOf(reference))) return undefined
|
||||||
|
const snapshot = this.recognition.getTranscriptSnapshot(reference)
|
||||||
|
if (snapshot.state === 'transcribed' && snapshot.transcript?.trim()) {
|
||||||
|
return { state: 'transcribed', transcript: snapshot.transcript.trim(), cached: true }
|
||||||
|
}
|
||||||
|
// 失败过的语音不自动重跑:调用方轮询时会反复命中同一条坏音频。
|
||||||
|
if (snapshot.state === 'failed') {
|
||||||
|
return {
|
||||||
|
state: 'failed',
|
||||||
|
code: 'PREVIOUSLY_FAILED',
|
||||||
|
error: snapshot.error || '语音识别失败'
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return undefined
|
||||||
|
})
|
||||||
|
|
||||||
|
const newKeys = new Set<string>()
|
||||||
|
references.forEach((reference, index) => {
|
||||||
|
const key = keyOf(reference)
|
||||||
|
if (!immediate[index] && !this.inFlight.has(key)) newKeys.add(key)
|
||||||
|
})
|
||||||
|
if (this.inFlight.size + newKeys.size > this.maxInFlight) return null
|
||||||
|
|
||||||
|
const tasks = references.map((reference, index) => {
|
||||||
|
if (immediate[index]) return undefined
|
||||||
|
const key = keyOf(reference)
|
||||||
|
let task = this.inFlight.get(key)
|
||||||
|
if (!task) {
|
||||||
|
task = this.run(reference, options.force, accountIdentity).finally(() => {
|
||||||
|
this.inFlight.delete(key)
|
||||||
|
})
|
||||||
|
this.inFlight.set(key, task)
|
||||||
|
}
|
||||||
|
return task
|
||||||
|
})
|
||||||
|
|
||||||
|
let timer: NodeJS.Timeout | undefined
|
||||||
|
const deadline = new Promise<'pending'>((resolve) => {
|
||||||
|
timer = setTimeout(() => resolve('pending'), Math.max(0, options.waitMs))
|
||||||
|
})
|
||||||
|
try {
|
||||||
|
return await Promise.all(
|
||||||
|
references.map(async (_reference, index): Promise<VoiceTranscriptionOutcome> => {
|
||||||
|
const done = immediate[index]
|
||||||
|
if (done) return done
|
||||||
|
const result = await Promise.race([tasks[index]!, deadline])
|
||||||
|
if (result === 'pending') return { state: 'pending' }
|
||||||
|
if (result.success) {
|
||||||
|
return {
|
||||||
|
state: 'transcribed',
|
||||||
|
transcript: result.transcript?.trim() || '',
|
||||||
|
cached: Boolean(result.cached),
|
||||||
|
...(result.durationMs !== undefined ? { durationMs: result.durationMs } : {})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
state: 'failed',
|
||||||
|
code: result.code || 'RECOGNITION_FAILED',
|
||||||
|
error: result.error || '语音识别失败'
|
||||||
|
}
|
||||||
|
})
|
||||||
|
)
|
||||||
|
} finally {
|
||||||
|
clearTimeout(timer)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private async run(
|
||||||
|
reference: VoiceMessageReference,
|
||||||
|
force: boolean | undefined,
|
||||||
|
accountIdentity: string
|
||||||
|
): Promise<VoiceRecognitionResult> {
|
||||||
|
for (let attempt = 0; ; attempt += 1) {
|
||||||
|
// 用后台优先级:用户在界面上点开语音时可以立即抢占,不必排在 API 积压之后。
|
||||||
|
const result = await this.recognition.recognize(reference, { priority: 'background', force })
|
||||||
|
if (
|
||||||
|
result.success ||
|
||||||
|
result.code !== 'CANCELLED' ||
|
||||||
|
attempt >= MAX_PREEMPTION_RETRIES ||
|
||||||
|
this.recognition.accountIdentity !== accountIdentity
|
||||||
|
) {
|
||||||
|
return result
|
||||||
|
}
|
||||||
|
// 被交互请求抢占:账号没变就重新排队,与批量转写的处理一致。
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
+565
-49
@@ -5,7 +5,9 @@ import crypto from 'crypto'
|
|||||||
import { createRequire } from 'module'
|
import { createRequire } from 'module'
|
||||||
import { createConnection, Socket } from 'net'
|
import { createConnection, Socket } from 'net'
|
||||||
import { getResourceRoots } from './resource-paths'
|
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 type { ImageMessageCountProbe } from '../shared/image-text-index'
|
||||||
import { imageTextWindowToSeconds } from '../shared/image-text-index'
|
import { imageTextWindowToSeconds } from '../shared/image-text-index'
|
||||||
|
|
||||||
@@ -54,6 +56,7 @@ export interface WindowsNativePathBridgeOptions {
|
|||||||
type Wcdb4MessageStore = {
|
type Wcdb4MessageStore = {
|
||||||
tableName: string
|
tableName: string
|
||||||
dbPath: string
|
dbPath: string
|
||||||
|
senderTableName?: string
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface Wcdb4GroupMember {
|
export interface Wcdb4GroupMember {
|
||||||
@@ -145,6 +148,71 @@ type KoffiModule = {
|
|||||||
// library reference for every Wcdb4Client instance.
|
// library reference for every Wcdb4Client instance.
|
||||||
let wcdbBootstrapLib: KoffiLibrary | null = null
|
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
|
let wcdbBootstrapAsyncPromise: Promise<KoffiLibrary> | null = null
|
||||||
|
|
||||||
export function bootstrapWcdbNative(libPath?: string, libDirOverride?: string): KoffiLibrary {
|
export function bootstrapWcdbNative(libPath?: string, libDirOverride?: string): KoffiLibrary {
|
||||||
@@ -203,16 +271,28 @@ export function bootstrapWcdbNative(libPath?: string, libDirOverride?: string):
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (!initOk) {
|
if (!initOk) {
|
||||||
console.warn(
|
if (lastCode === -2003) {
|
||||||
`[WCDB4] bootstrap InitProtection 返回 ${lastCode},继续尝试 wcdb_init/open; tried=${resourceRoots.join(' | ')}`
|
// -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 {
|
} else {
|
||||||
const wcdbInit = lib.func('int32 wcdb_init()') as () => number
|
const wcdbInit = lib.func('int32 wcdb_init()') as () => number
|
||||||
console.log('[WCDB4] bootstrap wcdb_init begin')
|
console.log('[WCDB4] bootstrap wcdb_init begin')
|
||||||
const initRc = Number(wcdbInit())
|
const initRc = Number(wcdbInit())
|
||||||
console.log(`[WCDB4] bootstrap wcdb_init rc=${initRc}`)
|
console.log(`[WCDB4] bootstrap wcdb_init rc=${initRc}`)
|
||||||
if (initRc !== 0) {
|
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 未成功,继续尝试打开数据库'
|
||||||
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -259,9 +339,11 @@ export function bootstrapWcdbNativeAsync(
|
|||||||
)
|
)
|
||||||
)
|
)
|
||||||
let initOk = false
|
let initOk = false
|
||||||
|
let lastInitCode = -1
|
||||||
for (const resourceRoot of resourceRoots) {
|
for (const resourceRoot of resourceRoots) {
|
||||||
try {
|
try {
|
||||||
if (Number(initProtection(resourceRoot)) === 0) {
|
lastInitCode = Number(initProtection(resourceRoot))
|
||||||
|
if (lastInitCode === 0) {
|
||||||
initOk = true
|
initOk = true
|
||||||
break
|
break
|
||||||
}
|
}
|
||||||
@@ -269,6 +351,9 @@ export function bootstrapWcdbNativeAsync(
|
|||||||
// Try the next resource root.
|
// Try the next resource root.
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
if (!initOk && lastInitCode === -2003) {
|
||||||
|
throw new NativeDbInitError(DB_COMPONENT_UNAVAILABLE_MESSAGE, lastInitCode, 'InitProtection')
|
||||||
|
}
|
||||||
if (initOk) {
|
if (initOk) {
|
||||||
const wcdbInit = lib.func('int32 wcdb_init()') as KoffiAsyncFunction
|
const wcdbInit = lib.func('int32 wcdb_init()') as KoffiAsyncFunction
|
||||||
await new Promise<void>((resolve, reject) => {
|
await new Promise<void>((resolve, reject) => {
|
||||||
@@ -457,6 +542,41 @@ export function parseMonitorEvent(rawPayload: string): Wcdb4MonitorEvent {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** 老版「防撤回保护」在某个消息分片上留下的残留。 */
|
||||||
|
export interface LegacyRecallResidueShard {
|
||||||
|
/** 分片文件名,如 `message_0.db`(不含会话信息,可以进日志)。 */
|
||||||
|
shard: string
|
||||||
|
dbPath: string
|
||||||
|
/** 本应用自己装的抓取触发器:`_wxe_capture_<sha1(表名)[0:16]>` */
|
||||||
|
triggers: string[]
|
||||||
|
/** 老日志表:`_wxe_recall_journal_<sha1(表名)[0:16]>` */
|
||||||
|
journals: string[]
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface LegacyRecallResidueReport {
|
||||||
|
found: boolean
|
||||||
|
shards: LegacyRecallResidueShard[]
|
||||||
|
triggerCount: number
|
||||||
|
journalCount: number
|
||||||
|
/**
|
||||||
|
* 行为分类:`blocking*` 带 `RAISE(IGNORE)`、会吃掉微信写库动作;
|
||||||
|
* `passive` 只复制行,不改变微信行为。
|
||||||
|
*/
|
||||||
|
blockingDeleteCount: number
|
||||||
|
blockingInsertCount: number
|
||||||
|
passiveCount: number
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 老版防撤回保护(recall journal)的命名规则,安装侧与扫描侧共用。
|
||||||
|
*/
|
||||||
|
const LEGACY_RECALL_TRIGGER_PREFIX = '_wxe_capture_'
|
||||||
|
const LEGACY_RECALL_JOURNAL_PREFIX = '_wxe_recall_journal_'
|
||||||
|
/**
|
||||||
|
* 触发器体里必须同时出现这两个列名才算「本应用装的」(安装时写入的私有标记)。
|
||||||
|
*/
|
||||||
|
const LEGACY_RECALL_TRIGGER_MARKERS = ['_wxe_source_table', '_wxe_captured_at'] as const
|
||||||
|
|
||||||
export class Wcdb4Client {
|
export class Wcdb4Client {
|
||||||
static readonly defaultRoot = Wcdb4Client.findExistingDefaultRoot()
|
static readonly defaultRoot = Wcdb4Client.findExistingDefaultRoot()
|
||||||
|
|
||||||
@@ -525,6 +645,13 @@ export class Wcdb4Client {
|
|||||||
private wcdbGetGroupMembersBatch:
|
private wcdbGetGroupMembersBatch:
|
||||||
| ((handle: number, chatroomIdsJson: string, outJson: WcdbVoidOut) => number)
|
| ((handle: number, chatroomIdsJson: string, outJson: WcdbVoidOut) => number)
|
||||||
| null = null
|
| null = null
|
||||||
|
// 微信消息插入开关(native extension,不属于最初 27 个绑定)
|
||||||
|
private wcdbMsgInsertSetSwitch:
|
||||||
|
| ((handle: number, dbPath: string, name: string, enabled: number) => number)
|
||||||
|
| null = null
|
||||||
|
private wcdbMsgInsertGetSwitches:
|
||||||
|
| ((handle: number, dbPath: string, outJson: WcdbVoidOut) => number)
|
||||||
|
| null = null
|
||||||
private wcdbGetGroupNicknames:
|
private wcdbGetGroupNicknames:
|
||||||
| ((handle: number, chatroomId: string, outJson: WcdbVoidOut) => number)
|
| ((handle: number, chatroomId: string, outJson: WcdbVoidOut) => number)
|
||||||
| null = null
|
| null = null
|
||||||
@@ -585,6 +712,18 @@ export class Wcdb4Client {
|
|||||||
this.sessionDbPath = this.findSessionDb()
|
this.sessionDbPath = this.findSessionDb()
|
||||||
|
|
||||||
if (!this.sessionDbPath) {
|
if (!this.sessionDbPath) {
|
||||||
|
/*
|
||||||
|
* 先追问一次「到底是文件缺失,还是读不了」。
|
||||||
|
*
|
||||||
|
* `findSessionDb()` 依赖 `fs.existsSync()`,而它对 EPERM / EACCES 同样返回
|
||||||
|
* `false` —— 权限被拒会被静默降级成"文件不存在"。macOS 上未授予完全磁盘访问
|
||||||
|
* 权限时走的正是这条路径:数据目录其实是完整的。此时若照旧抛「未找到」,
|
||||||
|
* 用户会去查路径和重装,而真正该做的是去系统设置授权。
|
||||||
|
*/
|
||||||
|
const expected = path.join(this.dbStoragePath, 'session', 'session.db')
|
||||||
|
if (looksLikePermissionDenied(expected) || looksLikePermissionDenied(this.dbStoragePath)) {
|
||||||
|
throw new PathAccessDeniedError(this.dbStoragePath)
|
||||||
|
}
|
||||||
throw new Error(`未找到微信 4.0 session.db: ${this.dbStoragePath}`)
|
throw new Error(`未找到微信 4.0 session.db: ${this.dbStoragePath}`)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -598,6 +737,8 @@ export class Wcdb4Client {
|
|||||||
return target
|
return target
|
||||||
}
|
}
|
||||||
if (!fs.existsSync(target)) {
|
if (!fs.existsSync(target)) {
|
||||||
|
// 同 session.db:existsSync 分不出"不存在"与"读不了",追问一次再下结论。
|
||||||
|
if (looksLikePermissionDenied(target)) throw new PathAccessDeniedError(target)
|
||||||
throw new Error(`未找到微信 4.0 数据目录: ${target}`)
|
throw new Error(`未找到微信 4.0 数据目录: ${target}`)
|
||||||
}
|
}
|
||||||
const candidates = fs
|
const candidates = fs
|
||||||
@@ -614,6 +755,8 @@ export class Wcdb4Client {
|
|||||||
static findLatestAccountRoot(): string {
|
static findLatestAccountRoot(): string {
|
||||||
const root = Wcdb4Client.defaultRoot
|
const root = Wcdb4Client.defaultRoot
|
||||||
if (!fs.existsSync(root)) {
|
if (!fs.existsSync(root)) {
|
||||||
|
// 默认根目录读不了同样要区分:macOS 上这就是"没授权"的表现,不是"没装微信"。
|
||||||
|
if (looksLikePermissionDenied(root)) throw new PathAccessDeniedError(root)
|
||||||
throw new Error(`未找到微信 4.0 数据目录: ${root}`)
|
throw new Error(`未找到微信 4.0 数据目录: ${root}`)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -719,12 +862,16 @@ export class Wcdb4Client {
|
|||||||
openResult = this.wcdbOpenAccount(this.sessionDbPath, this.key, handleOut)
|
openResult = this.wcdbOpenAccount(this.sessionDbPath, this.key, handleOut)
|
||||||
|
|
||||||
if (openResult !== 0 || handleOut[0] <= 0) {
|
if (openResult !== 0 || handleOut[0] <= 0) {
|
||||||
const hint =
|
// message 只放分类文案;路径与 wxid 不进 message,原生码在 nativeCode 字段上。
|
||||||
openResult === -1005
|
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 Error(
|
)
|
||||||
`wcdb_open_account 失败,错误码: ${openResult}${hint}; sessionDb=${this.sessionDbPath}; accountRoot=${this.accountRoot}; wxid=${this.wxid}; keyLength=${this.key.length}`
|
}
|
||||||
|
throw new NativeDbInitError(
|
||||||
|
describeDbOpenFailure(openResult, this.sessionDbPath),
|
||||||
|
openResult,
|
||||||
|
'wcdb_open_account'
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -752,8 +899,15 @@ export class Wcdb4Client {
|
|||||||
handleOut
|
handleOut
|
||||||
)
|
)
|
||||||
if (openResult !== 0 || handleOut[0] <= 0) {
|
if (openResult !== 0 || handleOut[0] <= 0) {
|
||||||
throw new Error(
|
if (isWcdbDebugEnabled()) {
|
||||||
`wcdb_open_account failed, code=${openResult}; sessionDb=${this.sessionDbPath}; accountRoot=${this.accountRoot}; wxid=${this.wxid}; keyLength=${this.key.length}`
|
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]
|
this.handle = handleOut[0]
|
||||||
@@ -860,7 +1014,11 @@ export class Wcdb4Client {
|
|||||||
)
|
)
|
||||||
if (startResult !== 0) {
|
if (startResult !== 0) {
|
||||||
this.monitorCallback = null
|
this.monitorCallback = null
|
||||||
console.warn(`[WCDB4] wcdb_start_monitor_pipe 失败,错误码: ${startResult}`)
|
console.warn(
|
||||||
|
isWcdbDebugEnabled()
|
||||||
|
? `[WCDB4] wcdb_start_monitor_pipe rc=${startResult}`
|
||||||
|
: '[WCDB4] 消息监听启动失败,将退回轮询'
|
||||||
|
)
|
||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
this.monitorStarted = true
|
this.monitorStarted = true
|
||||||
@@ -875,7 +1033,11 @@ export class Wcdb4Client {
|
|||||||
outName
|
outName
|
||||||
)
|
)
|
||||||
if (nameResult !== 0 || !outName[0]) {
|
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()
|
this.stopMonitor()
|
||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
@@ -1180,7 +1342,12 @@ export class Wcdb4Client {
|
|||||||
try {
|
try {
|
||||||
const cursorMessages = this.getMessagesByCursor(username, startTime, endTime, maxRows)
|
const cursorMessages = this.getMessagesByCursor(username, startTime, endTime, maxRows)
|
||||||
if (cursorMessages && cursorMessages.length > 0) {
|
if (cursorMessages && cursorMessages.length > 0) {
|
||||||
const recoveredMessages = this.readRecallJournal(username, startTime, endTime)
|
/*
|
||||||
|
* 老 recall journal 的合并必须跟开关联动:无条件合并会让「关掉防撤回」失效。
|
||||||
|
*/
|
||||||
|
const recoveredMessages = this.recallJournalEnabled
|
||||||
|
? this.readRecallJournal(username, startTime, endTime)
|
||||||
|
: []
|
||||||
const mergedMessages = this.mergeMessageRows(cursorMessages, recoveredMessages, maxRows)
|
const mergedMessages = this.mergeMessageRows(cursorMessages, recoveredMessages, maxRows)
|
||||||
console.log(
|
console.log(
|
||||||
`[WCDB4] getMessages cursor ok username=${username} rows=${mergedMessages.length} recovered=${recoveredMessages.length} cost=${Date.now() - startedAt}ms`
|
`[WCDB4] getMessages cursor ok username=${username} rows=${mergedMessages.length} recovered=${recoveredMessages.length} cost=${Date.now() - startedAt}ms`
|
||||||
@@ -1623,7 +1790,7 @@ export class Wcdb4Client {
|
|||||||
try {
|
try {
|
||||||
const order = limit ? 'DESC' : 'ASC'
|
const order = limit ? 'DESC' : 'ASC'
|
||||||
const rowLimit = limit || 5000
|
const rowLimit = limit || 5000
|
||||||
const sql = `SELECT * FROM ${this.quoteSqlIdentifier(table.tableName)}${whereSql} ORDER BY "create_time" ${order} LIMIT ${rowLimit}`
|
const sql = `${this.messageTableSelect(table)}${whereSql} ORDER BY "create_time" ${order} LIMIT ${rowLimit}`
|
||||||
const rows = this.callJson<Record<string, unknown>[]>((handle, outJson) =>
|
const rows = this.callJson<Record<string, unknown>[]>((handle, outJson) =>
|
||||||
this.wcdbExecQuery!(handle, 'message', table.dbPath, sql, outJson)
|
this.wcdbExecQuery!(handle, 'message', table.dbPath, sql, outJson)
|
||||||
)
|
)
|
||||||
@@ -1699,7 +1866,7 @@ export class Wcdb4Client {
|
|||||||
// `local_id` 参与排序:`create_time` 同秒的消息需要一个稳定次序,
|
// `local_id` 参与排序:`create_time` 同秒的消息需要一个稳定次序,
|
||||||
// 否则多次读取的行序可能不同,调用方无法做稳定游标。
|
// 否则多次读取的行序可能不同,调用方无法做稳定游标。
|
||||||
const direction = options.order === 'desc' ? 'DESC' : 'ASC'
|
const direction = options.order === 'desc' ? 'DESC' : 'ASC'
|
||||||
const sql = `SELECT * FROM ${this.quoteSqlIdentifier(table.tableName)} WHERE ${where} ORDER BY "create_time" ${direction}, "local_id" ${direction} LIMIT ${limit}`
|
const sql = `${this.messageTableSelect(table)} WHERE ${where} ORDER BY "create_time" ${direction}, "local_id" ${direction} LIMIT ${limit}`
|
||||||
const queryStartedAt = Date.now()
|
const queryStartedAt = Date.now()
|
||||||
const rows = await this.callJsonAsync<Record<string, unknown>[]>(
|
const rows = await this.callJsonAsync<Record<string, unknown>[]>(
|
||||||
this.wcdbExecQuery as unknown as KoffiAsyncFunction,
|
this.wcdbExecQuery as unknown as KoffiAsyncFunction,
|
||||||
@@ -1771,7 +1938,7 @@ export class Wcdb4Client {
|
|||||||
let successfulTables = 0
|
let successfulTables = 0
|
||||||
for (const table of tables) {
|
for (const table of tables) {
|
||||||
try {
|
try {
|
||||||
const sql = `SELECT * FROM ${this.quoteSqlIdentifier(table.tableName)}${whereSql} ORDER BY "create_time" ${order} LIMIT ${rowLimit}`
|
const sql = `${this.messageTableSelect(table)}${whereSql} ORDER BY "create_time" ${order} LIMIT ${rowLimit}`
|
||||||
const queryStartedAt = Date.now()
|
const queryStartedAt = Date.now()
|
||||||
const rows = await this.callJsonAsync<Record<string, unknown>[]>(
|
const rows = await this.callJsonAsync<Record<string, unknown>[]>(
|
||||||
this.wcdbExecQuery as unknown as KoffiAsyncFunction,
|
this.wcdbExecQuery as unknown as KoffiAsyncFunction,
|
||||||
@@ -1803,6 +1970,133 @@ export class Wcdb4Client {
|
|||||||
return result
|
return result
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 列出账号目录下所有消息分片路径(message_<n>.db)。
|
||||||
|
*
|
||||||
|
* 供「微信消息插入开关」这类**按分片存放**的状态遍历使用。
|
||||||
|
* 只认 message_<数字>.db,不包含 biz_message_* / media_*。
|
||||||
|
*/
|
||||||
|
listMessageShardPaths(): string[] {
|
||||||
|
const messageRoot = path.join(this.dbStoragePath, 'message')
|
||||||
|
if (!fs.existsSync(messageRoot)) return []
|
||||||
|
return fs
|
||||||
|
.readdirSync(messageRoot)
|
||||||
|
.filter((name) => /^message_\d+\.db$/.test(name))
|
||||||
|
.sort()
|
||||||
|
.map((name) => path.join(messageRoot, name))
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 读取某个消息分片上的「微信消息插入开关」。
|
||||||
|
*
|
||||||
|
* 开关按消息分片存放(native 侧的 _tm_config 表),所以调用方要先把分片路径定下来。
|
||||||
|
* 返回形如 { recall_notice: boolean, group_exit_notice: boolean }。
|
||||||
|
*/
|
||||||
|
getMsgInsertSwitches(dbPath: string): {
|
||||||
|
success: boolean
|
||||||
|
switches?: Record<string, boolean>
|
||||||
|
error?: string
|
||||||
|
} {
|
||||||
|
if (!this.wcdbMsgInsertGetSwitches) {
|
||||||
|
return { success: false, error: '当前 WCDB 服务不支持微信消息插入开关' }
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
const switches = this.callJson<Record<string, boolean>>((handle, outJson) =>
|
||||||
|
this.wcdbMsgInsertGetSwitches!(handle, dbPath, outJson)
|
||||||
|
)
|
||||||
|
return { success: true, switches }
|
||||||
|
} catch (error) {
|
||||||
|
return { success: false, error: error instanceof Error ? error.message : String(error) }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 设置某个消息分片上的「微信消息插入开关」。
|
||||||
|
*
|
||||||
|
* name 只接受 recall_notice / group_exit_notice(native 侧白名单)。
|
||||||
|
* 写入走 native 单独维护的可写连接,只读查询链路不受影响。
|
||||||
|
*/
|
||||||
|
setMsgInsertSwitch(
|
||||||
|
dbPath: string,
|
||||||
|
name: string,
|
||||||
|
enabled: boolean
|
||||||
|
): { success: boolean; error?: string } {
|
||||||
|
if (!this.wcdbMsgInsertSetSwitch) {
|
||||||
|
return { success: false, error: '当前 WCDB 服务不支持微信消息插入开关' }
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
const handle = this.ensureHandle()
|
||||||
|
const rc = this.wcdbMsgInsertSetSwitch(handle, dbPath, name, enabled ? 1 : 0)
|
||||||
|
if (rc !== 0) return { success: false, error: `返回码 ${rc}` }
|
||||||
|
return { success: true }
|
||||||
|
} catch (error) {
|
||||||
|
return { success: false, error: error instanceof Error ? error.message : String(error) }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 读取「微信消息插入规则」的分片目录(只读)。
|
||||||
|
*
|
||||||
|
* 每个分片只跑一条 sqlite_master 查询,拿回来之后调用方可以在本地用
|
||||||
|
* md5(roomId) 匹配出「每个会话落在哪些分片、规则齐不齐」。这样即使会话很多,
|
||||||
|
* 判断全部会话的状态也只是一次目录读取,不需要按会话逐个查库。
|
||||||
|
*/
|
||||||
|
listMsgInsertShardCatalog(): {
|
||||||
|
success: boolean
|
||||||
|
catalog?: {
|
||||||
|
shardCount: number
|
||||||
|
shards: Array<{
|
||||||
|
shard: string
|
||||||
|
dbPath: string
|
||||||
|
configTable: boolean
|
||||||
|
tables: string[]
|
||||||
|
rules: Array<{ name: string; table: string }>
|
||||||
|
}>
|
||||||
|
}
|
||||||
|
error?: string
|
||||||
|
} {
|
||||||
|
if (!this.wcdbExecQuery) {
|
||||||
|
return { success: false, error: '当前 WCDB 服务不支持消息插入规则目录' }
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
// 专用 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) }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 老「防撤回保护」(recall journal)是否活动。只影响读取路径,默认 false。
|
||||||
|
*/
|
||||||
|
private recallJournalEnabled = false
|
||||||
|
|
||||||
|
setRecallJournalEnabled(enabled: boolean): void {
|
||||||
|
this.recallJournalEnabled = enabled
|
||||||
|
}
|
||||||
|
|
||||||
installRecallJournal(usernames: string[]): { installed: number; failed: number } {
|
installRecallJournal(usernames: string[]): { installed: number; failed: number } {
|
||||||
const stores = new Map<string, Wcdb4MessageStore>()
|
const stores = new Map<string, Wcdb4MessageStore>()
|
||||||
for (const username of this.uniq(usernames)) {
|
for (const username of this.uniq(usernames)) {
|
||||||
@@ -1847,7 +2141,7 @@ export class Wcdb4Client {
|
|||||||
if (!username.startsWith('gh_')) throw error
|
if (!username.startsWith('gh_')) throw error
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return stores.length > 0 ? stores : this.listBizMessageStores(username)
|
return stores.length > 0 ? stores : this.listFallbackMessageStores(username)
|
||||||
}
|
}
|
||||||
|
|
||||||
private async listMessageStoresAsync(username: string): Promise<Wcdb4MessageStore[]> {
|
private async listMessageStoresAsync(username: string): Promise<Wcdb4MessageStore[]> {
|
||||||
@@ -1863,7 +2157,7 @@ export class Wcdb4Client {
|
|||||||
if (!username.startsWith('gh_')) throw error
|
if (!username.startsWith('gh_')) throw error
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return stores.length > 0 ? stores : this.listBizMessageStoresAsync(username)
|
return stores.length > 0 ? stores : this.listFallbackMessageStoresAsync(username)
|
||||||
}
|
}
|
||||||
|
|
||||||
private parseMessageStores(rows: Record<string, unknown>[]): Wcdb4MessageStore[] {
|
private parseMessageStores(rows: Record<string, unknown>[]): Wcdb4MessageStore[] {
|
||||||
@@ -1875,12 +2169,17 @@ export class Wcdb4Client {
|
|||||||
.filter((row) => row.tableName && row.dbPath)
|
.filter((row) => row.tableName && row.dbPath)
|
||||||
}
|
}
|
||||||
|
|
||||||
private getBizMessageDatabasePaths(): string[] {
|
private getMessageDatabasePaths(username: string): string[] {
|
||||||
|
// Native shard discovery can return no stores on Windows even when SQL reads work.
|
||||||
|
// Enumerate only canonical databases; sync-conflict copies are not message shards.
|
||||||
const messageRoot = path.join(this.dbStoragePath, 'message')
|
const messageRoot = path.join(this.dbStoragePath, 'message')
|
||||||
|
const pattern = username.startsWith('gh_')
|
||||||
|
? /^biz_message(?:_\d+)?\.db$/i
|
||||||
|
: /^message(?:_\d+)?\.db$/i
|
||||||
try {
|
try {
|
||||||
return fs
|
return fs
|
||||||
.readdirSync(messageRoot)
|
.readdirSync(messageRoot)
|
||||||
.filter((name) => /^biz_message(?:_\d+)?\.db$/i.test(name))
|
.filter((name) => pattern.test(name))
|
||||||
.sort()
|
.sort()
|
||||||
.map((name) => path.join(messageRoot, name))
|
.map((name) => path.join(messageRoot, name))
|
||||||
} catch {
|
} catch {
|
||||||
@@ -1888,51 +2187,71 @@ export class Wcdb4Client {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private listBizMessageStores(username: string): Wcdb4MessageStore[] {
|
private listFallbackMessageStores(username: string): Wcdb4MessageStore[] {
|
||||||
if (!this.wcdbExecQuery || !username.startsWith('gh_')) return []
|
if (!this.wcdbExecQuery) return []
|
||||||
const tableName = `Msg_${this.md5(username)}`
|
const tableName = `Msg_${this.md5(username)}`
|
||||||
const escapedTableName = tableName.replace(/'/g, "''")
|
const escapedTableName = tableName.replace(/'/g, "''")
|
||||||
const stores: Wcdb4MessageStore[] = []
|
const stores: Wcdb4MessageStore[] = []
|
||||||
for (const dbPath of this.getBizMessageDatabasePaths()) {
|
for (const dbPath of this.getMessageDatabasePaths(username)) {
|
||||||
try {
|
try {
|
||||||
const rows = this.callJson<Record<string, unknown>[]>((handle, outJson) =>
|
const rows = this.callJson<Record<string, unknown>[]>((handle, outJson) =>
|
||||||
this.wcdbExecQuery!(
|
this.wcdbExecQuery!(
|
||||||
handle,
|
handle,
|
||||||
'message',
|
'message',
|
||||||
dbPath,
|
dbPath,
|
||||||
`SELECT name FROM sqlite_master WHERE type='table' AND name='${escapedTableName}'`,
|
`SELECT name FROM sqlite_master WHERE type='table' AND (name='${escapedTableName}' OR name LIKE 'Name2Id%') ORDER BY name DESC`,
|
||||||
outJson
|
outJson
|
||||||
)
|
)
|
||||||
)
|
)
|
||||||
if (Array.isArray(rows) && rows.length > 0) stores.push({ tableName, dbPath })
|
if (Array.isArray(rows) && rows.some((row) => row.name === tableName)) {
|
||||||
|
const senderTableName = rows.find((row) => /^Name2Id/i.test(String(row.name)))?.name
|
||||||
|
stores.push({
|
||||||
|
tableName,
|
||||||
|
dbPath,
|
||||||
|
...(senderTableName ? { senderTableName: String(senderTableName) } : {})
|
||||||
|
})
|
||||||
|
}
|
||||||
} catch {
|
} catch {
|
||||||
// Older biz shards may be absent or use a different key; continue scanning.
|
// A shard may use a different key; continue checking the other databases.
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return stores
|
return stores
|
||||||
}
|
}
|
||||||
|
|
||||||
private async listBizMessageStoresAsync(username: string): Promise<Wcdb4MessageStore[]> {
|
private async listFallbackMessageStoresAsync(username: string): Promise<Wcdb4MessageStore[]> {
|
||||||
if (!this.wcdbExecQuery || !username.startsWith('gh_')) return []
|
if (!this.wcdbExecQuery) return []
|
||||||
const tableName = `Msg_${this.md5(username)}`
|
const tableName = `Msg_${this.md5(username)}`
|
||||||
const escapedTableName = tableName.replace(/'/g, "''")
|
const escapedTableName = tableName.replace(/'/g, "''")
|
||||||
const stores: Wcdb4MessageStore[] = []
|
const stores: Wcdb4MessageStore[] = []
|
||||||
for (const dbPath of this.getBizMessageDatabasePaths()) {
|
for (const dbPath of this.getMessageDatabasePaths(username)) {
|
||||||
try {
|
try {
|
||||||
const rows = await this.callJsonAsync<Record<string, unknown>[]>(
|
const rows = await this.callJsonAsync<Record<string, unknown>[]>(
|
||||||
this.wcdbExecQuery as unknown as KoffiAsyncFunction,
|
this.wcdbExecQuery as unknown as KoffiAsyncFunction,
|
||||||
'message',
|
'message',
|
||||||
dbPath,
|
dbPath,
|
||||||
`SELECT name FROM sqlite_master WHERE type='table' AND name='${escapedTableName}'`
|
`SELECT name FROM sqlite_master WHERE type='table' AND (name='${escapedTableName}' OR name LIKE 'Name2Id%') ORDER BY name DESC`
|
||||||
)
|
)
|
||||||
if (Array.isArray(rows) && rows.length > 0) stores.push({ tableName, dbPath })
|
if (Array.isArray(rows) && rows.some((row) => row.name === tableName)) {
|
||||||
|
const senderTableName = rows.find((row) => /^Name2Id/i.test(String(row.name)))?.name
|
||||||
|
stores.push({
|
||||||
|
tableName,
|
||||||
|
dbPath,
|
||||||
|
...(senderTableName ? { senderTableName: String(senderTableName) } : {})
|
||||||
|
})
|
||||||
|
}
|
||||||
} catch {
|
} catch {
|
||||||
// Older biz shards may be absent or use a different key; continue scanning.
|
// A shard may use a different key; continue checking the other databases.
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return stores
|
return stores
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private messageTableSelect(store: Wcdb4MessageStore): string {
|
||||||
|
const table = this.quoteSqlIdentifier(store.tableName)
|
||||||
|
if (!store.senderTableName) return `SELECT * FROM ${table}`
|
||||||
|
return `SELECT m.*, n.user_name AS sender_username FROM ${table} AS m LEFT JOIN ${this.quoteSqlIdentifier(store.senderTableName)} AS n ON n.rowid = m.real_sender_id`
|
||||||
|
}
|
||||||
|
|
||||||
private executeMessageSql(store: Wcdb4MessageStore, sql: string): Record<string, unknown>[] {
|
private executeMessageSql(store: Wcdb4MessageStore, sql: string): Record<string, unknown>[] {
|
||||||
if (!this.wcdbExecQuery) throw new Error('当前 WCDB 数据服务不支持 SQL 通道')
|
if (!this.wcdbExecQuery) throw new Error('当前 WCDB 数据服务不支持 SQL 通道')
|
||||||
const rows = this.callJson<Record<string, unknown>[]>((handle, outJson) =>
|
const rows = this.callJson<Record<string, unknown>[]>((handle, outJson) =>
|
||||||
@@ -2056,6 +2375,92 @@ export class Wcdb4Client {
|
|||||||
.slice(0, 16)}`
|
.slice(0, 16)}`
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 只读扫描:老版防撤回保护在微信库里留下的 `_wxe_capture_*` 触发器与老日志表。
|
||||||
|
*
|
||||||
|
* 认领规则(保守:只认本应用装的):触发器名以 `_wxe_capture_` 开头、挂在 `Msg_*`
|
||||||
|
* 上、且触发器体里同时出现 `_wxe_source_table` / `_wxe_captured_at` 私有列名;
|
||||||
|
* 表则要求名字以 `_wxe_recall_journal_` 开头。WeFlow 的 `anti_revoke_*`、新机制的
|
||||||
|
* `_tm_msg_insert_*`、微信自己的触发器都不在结果里。
|
||||||
|
*
|
||||||
|
* 顺带按触发器体判行为(blocking* / passive,见返回值)。纯只读;没有残留时不写库。
|
||||||
|
*/
|
||||||
|
scanLegacyRecallResidue(): LegacyRecallResidueReport {
|
||||||
|
const shards: LegacyRecallResidueShard[] = []
|
||||||
|
let triggerCount = 0
|
||||||
|
let journalCount = 0
|
||||||
|
let blockingDeleteCount = 0
|
||||||
|
let blockingInsertCount = 0
|
||||||
|
let passiveCount = 0
|
||||||
|
for (const dbPath of this.listMessageShardPaths()) {
|
||||||
|
const triggers: string[] = []
|
||||||
|
const journals: string[] = []
|
||||||
|
for (const row of this.queryShardSqliteMaster(dbPath)) {
|
||||||
|
const name = String(row.name || '')
|
||||||
|
const type = String(row.type || '')
|
||||||
|
const tblName = String(row.tbl_name || '')
|
||||||
|
const sql = String(row.sql || '')
|
||||||
|
if (
|
||||||
|
type === 'trigger' &&
|
||||||
|
name.startsWith(LEGACY_RECALL_TRIGGER_PREFIX) &&
|
||||||
|
/^Msg_/i.test(tblName) &&
|
||||||
|
LEGACY_RECALL_TRIGGER_MARKERS.every((marker) => sql.includes(marker))
|
||||||
|
) {
|
||||||
|
triggers.push(name)
|
||||||
|
/* 分类只看定义文本,不执行任何语句。合并空白便于匹配多行写法。 */
|
||||||
|
const normalized = sql.replace(/\s+/g, ' ').toUpperCase()
|
||||||
|
const blocks = normalized.includes('RAISE(IGNORE)')
|
||||||
|
if (normalized.includes('BEFORE DELETE')) {
|
||||||
|
if (blocks) blockingDeleteCount += 1
|
||||||
|
else passiveCount += 1
|
||||||
|
} else if (normalized.includes('BEFORE INSERT') && blocks) {
|
||||||
|
blockingInsertCount += 1
|
||||||
|
} else {
|
||||||
|
passiveCount += 1
|
||||||
|
}
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if (type === 'table' && name.startsWith(LEGACY_RECALL_JOURNAL_PREFIX)) {
|
||||||
|
journals.push(name)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (triggers.length === 0 && journals.length === 0) continue
|
||||||
|
triggerCount += triggers.length
|
||||||
|
journalCount += journals.length
|
||||||
|
shards.push({ shard: path.basename(dbPath), dbPath, triggers, journals })
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
found: triggerCount > 0 || journalCount > 0,
|
||||||
|
shards,
|
||||||
|
triggerCount,
|
||||||
|
journalCount,
|
||||||
|
blockingDeleteCount,
|
||||||
|
blockingInsertCount,
|
||||||
|
passiveCount
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/*
|
||||||
|
* DROP 不在本进程做:对分片只有只读连接,发 DDL 必然失败。删除由 native 在其可写
|
||||||
|
* 连接里顺手完成(见 dll 侧 `_wxe_capture_*` 清理段);调用方只做扫描与复核。
|
||||||
|
*/
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 读分片 sqlite_master 里可能属于老防撤回的对象。用 GLOB 而非 LIKE:
|
||||||
|
* `_` 在 LIKE 里是单字符通配,会误伤相似名字。
|
||||||
|
*/
|
||||||
|
private queryShardSqliteMaster(dbPath: string): Record<string, unknown>[] {
|
||||||
|
if (!this.wcdbExecQuery) throw new Error('当前 WCDB 数据服务不支持 SQL 通道')
|
||||||
|
const sql =
|
||||||
|
"SELECT name, type, tbl_name, COALESCE(sql, '') AS sql FROM sqlite_master" +
|
||||||
|
` WHERE (type = 'trigger' AND name GLOB '${LEGACY_RECALL_TRIGGER_PREFIX}*')` +
|
||||||
|
` OR (type = 'table' AND name GLOB '${LEGACY_RECALL_JOURNAL_PREFIX}*')`
|
||||||
|
const rows = this.callJson<Record<string, unknown>[]>((handle, outJson) =>
|
||||||
|
this.wcdbExecQuery!(handle, 'message', dbPath, sql, outJson)
|
||||||
|
)
|
||||||
|
return Array.isArray(rows) ? rows : []
|
||||||
|
}
|
||||||
|
|
||||||
getMyAvatarUrl(): string | undefined {
|
getMyAvatarUrl(): string | undefined {
|
||||||
const candidates = this.getMyUsernameCandidates()
|
const candidates = this.getMyUsernameCandidates()
|
||||||
this.hydrateAvatarUrls(candidates)
|
this.hydrateAvatarUrls(candidates)
|
||||||
@@ -2628,7 +3033,7 @@ export class Wcdb4Client {
|
|||||||
|
|
||||||
const handle = this.ensureHandle()
|
const handle = this.ensureHandle()
|
||||||
const fn = this.wcdbGetVoiceData as unknown as KoffiAsyncFunction
|
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]
|
const outHex: WcdbVoidOut = [null]
|
||||||
fn.async(
|
fn.async(
|
||||||
handle,
|
handle,
|
||||||
@@ -2653,7 +3058,9 @@ export class Wcdb4Client {
|
|||||||
resolve(
|
resolve(
|
||||||
hex === null
|
hex === null
|
||||||
? { success: false, error: '解析语音数据失败' }
|
? { success: false, error: '解析语音数据失败' }
|
||||||
: { success: true, hex, error: '' }
|
: hex
|
||||||
|
? { success: true, hex, error: '' }
|
||||||
|
: { success: false, error: '语音数据为空' }
|
||||||
)
|
)
|
||||||
} finally {
|
} finally {
|
||||||
this.wcdbFreeString?.(outHex[0])
|
this.wcdbFreeString?.(outHex[0])
|
||||||
@@ -2661,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[]> {
|
async getVoiceDataBatch(requests: Wcdb4VoiceDataRequest[]): Promise<Wcdb4VoiceDataResult[]> {
|
||||||
@@ -2749,6 +3201,50 @@ export class Wcdb4Client {
|
|||||||
return this.key
|
return this.key
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** 按 (localId, createTime) 取回一条消息的原始 content。 */
|
||||||
|
getRawMessageContent(username: string, localId: number, createTime?: number): string | null {
|
||||||
|
if (!this.wcdbExecQuery) return null
|
||||||
|
const targetId = Math.trunc(Number(localId) || 0)
|
||||||
|
if (!username || targetId <= 0) return null
|
||||||
|
const anchorTime = Math.trunc(Number(createTime) || 0)
|
||||||
|
|
||||||
|
let stores: Wcdb4MessageStore[] = []
|
||||||
|
try {
|
||||||
|
stores = this.listMessageStores(username)
|
||||||
|
} catch {
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
|
||||||
|
const candidates: string[] = []
|
||||||
|
for (const store of stores) {
|
||||||
|
const conditions = [`"local_id" = ${targetId}`]
|
||||||
|
if (anchorTime > 0) {
|
||||||
|
conditions.push(`"create_time" = ${anchorTime}`)
|
||||||
|
}
|
||||||
|
const sql = `${this.messageTableSelect(store)} WHERE ${conditions.join(' AND ')} LIMIT 5`
|
||||||
|
let rows: Record<string, unknown>[] = []
|
||||||
|
try {
|
||||||
|
rows = this.executeMessageSql(store, sql)
|
||||||
|
} catch {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
for (const row of rows) {
|
||||||
|
try {
|
||||||
|
const message = this.normalizeMessage(row)
|
||||||
|
if (typeof message.msgContent === 'string' && message.msgContent.trim()) {
|
||||||
|
candidates.push(message.msgContent)
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
// 单行解析失败不影响其它分片;定位信息不全时这里本来就可能拿不到。
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (candidates.length === 0) return null
|
||||||
|
candidates.sort((left, right) => right.length - left.length)
|
||||||
|
return candidates[0]
|
||||||
|
}
|
||||||
|
|
||||||
resolveImageHardlink(md5: string): Wcdb4ImageHardlink | null {
|
resolveImageHardlink(md5: string): Wcdb4ImageHardlink | null {
|
||||||
if (!this.wcdbResolveImageHardlink) return null
|
if (!this.wcdbResolveImageHardlink) return null
|
||||||
const normalizedMd5 = String(md5 || '')
|
const normalizedMd5 = String(md5 || '')
|
||||||
@@ -2985,6 +3481,22 @@ export class Wcdb4Client {
|
|||||||
this.wcdbGetGroupMembersBatch = null
|
this.wcdbGetGroupMembersBatch = null
|
||||||
}
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
this.wcdbMsgInsertSetSwitch = lib.func(
|
||||||
|
'int32 wcdb_msg_insert_set_switch(int64 handle, const char* dbPath, const char* name, int32 enabled)'
|
||||||
|
) as (handle: number, dbPath: string, name: string, enabled: number) => number
|
||||||
|
} catch {
|
||||||
|
this.wcdbMsgInsertSetSwitch = null
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
this.wcdbMsgInsertGetSwitches = lib.func(
|
||||||
|
'int32 wcdb_msg_insert_get_switches(int64 handle, const char* dbPath, _Out_ void** outJson)'
|
||||||
|
) as (handle: number, dbPath: string, outJson: WcdbVoidOut) => number
|
||||||
|
} catch {
|
||||||
|
this.wcdbMsgInsertGetSwitches = null
|
||||||
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
this.wcdbGetGroupNicknames = lib.func(
|
this.wcdbGetGroupNicknames = lib.func(
|
||||||
'int32 wcdb_get_group_nicknames(int64 handle, const char* chatroomId, _Out_ void** outJson)'
|
'int32 wcdb_get_group_nicknames(int64 handle, const char* chatroomId, _Out_ void** outJson)'
|
||||||
@@ -3122,16 +3634,14 @@ export class Wcdb4Client {
|
|||||||
}
|
}
|
||||||
|
|
||||||
static resolveNativeLibrary(): string {
|
static resolveNativeLibrary(): string {
|
||||||
const libName =
|
if (process.platform === 'darwin') {
|
||||||
process.platform === 'darwin'
|
const library = resolveWcdbLibrary()
|
||||||
? 'libwcdb_api.dylib'
|
if (library) return library
|
||||||
: process.platform === 'linux'
|
throw new Error('找不到当前发行版对应的 WCDB native 库')
|
||||||
? 'libwcdb_api.so'
|
}
|
||||||
: 'wcdb_api.dll'
|
const libName = process.platform === 'linux' ? 'libwcdb_api.so' : 'wcdb_api.dll'
|
||||||
const platformDir =
|
const platformDir =
|
||||||
process.platform === 'darwin'
|
process.platform === 'win32'
|
||||||
? 'macos'
|
|
||||||
: process.platform === 'win32'
|
|
||||||
? 'win32'
|
? 'win32'
|
||||||
: process.platform
|
: process.platform
|
||||||
const archDir = process.arch === 'arm64' ? 'arm64' : 'x64'
|
const archDir = process.arch === 'arm64' ? 'arm64' : 'x64'
|
||||||
@@ -3208,7 +3718,10 @@ export class Wcdb4Client {
|
|||||||
const outJson: WcdbVoidOut = [null]
|
const outJson: WcdbVoidOut = [null]
|
||||||
const result = call(handle, outJson)
|
const result = call(handle, outJson)
|
||||||
if (result !== 0 || !outJson[0]) {
|
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 {
|
try {
|
||||||
@@ -3230,7 +3743,10 @@ export class Wcdb4Client {
|
|||||||
}
|
}
|
||||||
const code = Number(result)
|
const code = Number(result)
|
||||||
if (code !== 0 || !outJson[0]) {
|
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
|
return
|
||||||
}
|
}
|
||||||
try {
|
try {
|
||||||
|
|||||||
Vendored
+49
-3
@@ -39,6 +39,8 @@ import type {
|
|||||||
SaveImageKeyRequest,
|
SaveImageKeyRequest,
|
||||||
TestImageDecryptionRequest
|
TestImageDecryptionRequest
|
||||||
} from '../shared/image-decryption'
|
} from '../shared/image-decryption'
|
||||||
|
import type { ImageDebugInfoRequest, ImageDebugInfoResult } from '../shared/image-debug-info'
|
||||||
|
import type { ImageMessageXmlRequest, ImageMessageXmlResult } from '../shared/image-message-xml'
|
||||||
import type {
|
import type {
|
||||||
AIChatRequestOptions,
|
AIChatRequestOptions,
|
||||||
AiSearchExternalAuthorizationRequest,
|
AiSearchExternalAuthorizationRequest,
|
||||||
@@ -82,6 +84,13 @@ import type {
|
|||||||
PersonalWechatVoiceDiagnostic
|
PersonalWechatVoiceDiagnostic
|
||||||
} from '../shared/personal-wechat'
|
} from '../shared/personal-wechat'
|
||||||
import type { PersonalWechatSendCapability } 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 { GroupMemberStatsQuery, GroupMemberStatsResult } from '../shared/group-stats'
|
||||||
import type {
|
import type {
|
||||||
ScheduledReportExecution,
|
ScheduledReportExecution,
|
||||||
@@ -105,6 +114,11 @@ import type {
|
|||||||
ScheduledRuleRunOutcome
|
ScheduledRuleRunOutcome
|
||||||
} from '../shared/automation'
|
} from '../shared/automation'
|
||||||
import type { ActionLogEntry } from '../shared/action-log'
|
import type { ActionLogEntry } from '../shared/action-log'
|
||||||
|
import type {
|
||||||
|
MsgInsertApplyResult,
|
||||||
|
MsgInsertSwitchName,
|
||||||
|
MsgInsertSwitchesSnapshot
|
||||||
|
} from '../shared/msg-insert-switch'
|
||||||
import type {
|
import type {
|
||||||
AppUpdateCheckResult,
|
AppUpdateCheckResult,
|
||||||
AppUpdateInstallResult,
|
AppUpdateInstallResult,
|
||||||
@@ -225,6 +239,8 @@ declare global {
|
|||||||
downloadAppUpdate: () => Promise<AppUpdateCheckResult>
|
downloadAppUpdate: () => Promise<AppUpdateCheckResult>
|
||||||
installAppUpdate: () => Promise<AppUpdateInstallResult>
|
installAppUpdate: () => Promise<AppUpdateInstallResult>
|
||||||
openAppUpdateDownloadPage: () => Promise<AppUpdateOpenDownloadPageResult>
|
openAppUpdateDownloadPage: () => Promise<AppUpdateOpenDownloadPageResult>
|
||||||
|
getIgnoredUpdateVersion: () => Promise<string>
|
||||||
|
setIgnoredUpdateVersion: (version: string | null) => Promise<string>
|
||||||
onAppUpdateState: (callback: (state: AppUpdateState) => void) => () => void
|
onAppUpdateState: (callback: (state: AppUpdateState) => void) => () => void
|
||||||
getCacheSummary: () => Promise<CacheSummary>
|
getCacheSummary: () => Promise<CacheSummary>
|
||||||
clearCache: (scope: CacheClearScope) => Promise<CacheSummary>
|
clearCache: (scope: CacheClearScope) => Promise<CacheSummary>
|
||||||
@@ -326,6 +342,24 @@ declare global {
|
|||||||
saveLeaveNotificationRule: (draft: AutomationRuleDraft) => Promise<AutomationRule>
|
saveLeaveNotificationRule: (draft: AutomationRuleDraft) => Promise<AutomationRule>
|
||||||
/** 「指定好友」的可选项;已在 main 侧过滤掉群聊 / 公众号 / 文件传输助手 / 自己。 */
|
/** 「指定好友」的可选项;已在 main 侧过滤掉群聊 / 公众号 / 文件传输助手 / 自己。 */
|
||||||
listSendableContacts: () => Promise<Array<{ id: string; name: string }>>
|
listSendableContacts: () => Promise<Array<{ id: string; name: string }>>
|
||||||
|
/**
|
||||||
|
* 微信消息插入开关:读取当前状态。
|
||||||
|
*
|
||||||
|
* 逐目标会话返回 desiredEnabled / effectiveEnabled —— 开关值写成功不等于
|
||||||
|
* 功能真的生效(规则可能没装齐),界面不能只看前者。
|
||||||
|
*/
|
||||||
|
getMsgInsertSwitches: () => Promise<MsgInsertSwitchesSnapshot>
|
||||||
|
refreshMsgInsertSwitches: () => Promise<MsgInsertSwitchesSnapshot>
|
||||||
|
/**
|
||||||
|
* 微信消息插入开关:打开 / 关闭。
|
||||||
|
*
|
||||||
|
* 开的时候先补规则再写值;写入由一次性 helper 子进程完成,
|
||||||
|
* 失败会带 failedShards / notReadyRooms 回来,不伪装成功。
|
||||||
|
*/
|
||||||
|
setMsgInsertSwitch: (
|
||||||
|
name: MsgInsertSwitchName,
|
||||||
|
enabled: boolean
|
||||||
|
) => Promise<MsgInsertApplyResult>
|
||||||
onGroupExitMonitorState: (callback: (state: GroupExitMonitorState) => void) => () => void
|
onGroupExitMonitorState: (callback: (state: GroupExitMonitorState) => void) => () => void
|
||||||
search: (keyword: string) => Promise<string | null>
|
search: (keyword: string) => Promise<string | null>
|
||||||
searchKnowledge: (request: KnowledgeSearchIpcRequest) => Promise<KnowledgeSearchIpcResult>
|
searchKnowledge: (request: KnowledgeSearchIpcRequest) => Promise<KnowledgeSearchIpcResult>
|
||||||
@@ -435,6 +469,8 @@ declare global {
|
|||||||
isThumb?: boolean
|
isThumb?: boolean
|
||||||
filePath?: string
|
filePath?: string
|
||||||
}>
|
}>
|
||||||
|
getImageDebugInfo: (request: ImageDebugInfoRequest) => Promise<ImageDebugInfoResult>
|
||||||
|
getImageMessageXml: (request: ImageMessageXmlRequest) => Promise<ImageMessageXmlResult>
|
||||||
getVideo: (
|
getVideo: (
|
||||||
hashes: string[],
|
hashes: string[],
|
||||||
options?: {
|
options?: {
|
||||||
@@ -539,6 +575,7 @@ declare global {
|
|||||||
appearanceTheme: 'system' | 'light' | 'dark'
|
appearanceTheme: 'system' | 'light' | 'dark'
|
||||||
compactMode: boolean
|
compactMode: boolean
|
||||||
showStartupProgress: boolean
|
showStartupProgress: boolean
|
||||||
|
closeAction: 'ask' | 'tray' | 'quit'
|
||||||
ttsSelectedVoiceId: string
|
ttsSelectedVoiceId: string
|
||||||
ttsModel: import('../shared/text-to-speech').TextToSpeechModel
|
ttsModel: import('../shared/text-to-speech').TextToSpeechModel
|
||||||
windowsWechatPort: string
|
windowsWechatPort: string
|
||||||
@@ -580,6 +617,7 @@ declare global {
|
|||||||
appearanceTheme: 'system' | 'light' | 'dark'
|
appearanceTheme: 'system' | 'light' | 'dark'
|
||||||
compactMode: boolean
|
compactMode: boolean
|
||||||
showStartupProgress: boolean
|
showStartupProgress: boolean
|
||||||
|
closeAction: 'ask' | 'tray' | 'quit'
|
||||||
ttsSelectedVoiceId: string
|
ttsSelectedVoiceId: string
|
||||||
ttsModel: import('../shared/text-to-speech').TextToSpeechModel
|
ttsModel: import('../shared/text-to-speech').TextToSpeechModel
|
||||||
windowsWechatPort: string
|
windowsWechatPort: string
|
||||||
@@ -604,6 +642,7 @@ declare global {
|
|||||||
appearanceTheme: 'system' | 'light' | 'dark'
|
appearanceTheme: 'system' | 'light' | 'dark'
|
||||||
compactMode: boolean
|
compactMode: boolean
|
||||||
showStartupProgress: boolean
|
showStartupProgress: boolean
|
||||||
|
closeAction: 'ask' | 'tray' | 'quit'
|
||||||
ttsSelectedVoiceId: string
|
ttsSelectedVoiceId: string
|
||||||
ttsModel: import('../shared/text-to-speech').TextToSpeechModel
|
ttsModel: import('../shared/text-to-speech').TextToSpeechModel
|
||||||
windowsWechatPort: string
|
windowsWechatPort: string
|
||||||
@@ -626,6 +665,7 @@ declare global {
|
|||||||
appearanceTheme: 'system' | 'light' | 'dark'
|
appearanceTheme: 'system' | 'light' | 'dark'
|
||||||
compactMode: boolean
|
compactMode: boolean
|
||||||
showStartupProgress: boolean
|
showStartupProgress: boolean
|
||||||
|
closeAction: 'ask' | 'tray' | 'quit'
|
||||||
windowsWechatPort: string
|
windowsWechatPort: string
|
||||||
imageXorKey: string
|
imageXorKey: string
|
||||||
imageAesKey: string
|
imageAesKey: string
|
||||||
@@ -720,6 +760,14 @@ declare global {
|
|||||||
repairImageTextIndex: () => Promise<ImageTextIndexRepairResult>
|
repairImageTextIndex: () => Promise<ImageTextIndexRepairResult>
|
||||||
onImageTextIndexStatus: (callback: (status: ImageTextIndexStatus) => void) => () => void
|
onImageTextIndexStatus: (callback: (status: ImageTextIndexStatus) => void) => () => void
|
||||||
getPersonalWechatSenderStatus: () => Promise<PersonalWechatSenderStatus>
|
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>
|
getPersonalWechatSendCapability: () => Promise<PersonalWechatSendCapability>
|
||||||
checkPersonalWechatSenderStatus: (port?: string) => Promise<PersonalWechatSenderStatus>
|
checkPersonalWechatSenderStatus: (port?: string) => Promise<PersonalWechatSenderStatus>
|
||||||
checkPersonalWechatVoiceEncodingEnvironment: () => Promise<PersonalWechatVoiceEncodingEnvironment>
|
checkPersonalWechatVoiceEncodingEnvironment: () => Promise<PersonalWechatVoiceEncodingEnvironment>
|
||||||
@@ -738,9 +786,7 @@ declare global {
|
|||||||
ruleId: string
|
ruleId: string
|
||||||
) => Promise<{ success: boolean; error?: string; data?: ScheduledRuleRunOutcome }>
|
) => Promise<{ success: boolean; error?: string; data?: ScheduledRuleRunOutcome }>
|
||||||
/** 定时日报:旧执行记录**只读存档**(旧记录无法无损转换,原样展示)。 */
|
/** 定时日报:旧执行记录**只读存档**(旧记录无法无损转换,原样展示)。 */
|
||||||
listScheduledReportLegacyExecutions: (
|
listScheduledReportLegacyExecutions: (ruleId?: string) => Promise<ScheduledReportExecution[]>
|
||||||
ruleId?: string
|
|
||||||
) => Promise<ScheduledReportExecution[]>
|
|
||||||
/** 定时日报:微信异常通知开关与能力检测。 */
|
/** 定时日报:微信异常通知开关与能力检测。 */
|
||||||
getScheduledReportNotificationSettings: () => Promise<ScheduledReportNotificationSettings>
|
getScheduledReportNotificationSettings: () => Promise<ScheduledReportNotificationSettings>
|
||||||
getScheduledReportNotificationCapability: () => Promise<ScheduledReportNotificationCapability>
|
getScheduledReportNotificationCapability: () => Promise<ScheduledReportNotificationCapability>
|
||||||
|
|||||||
@@ -14,6 +14,13 @@ import type {
|
|||||||
SaveGeneratedReportRequest,
|
SaveGeneratedReportRequest,
|
||||||
UpdateGeneratedReportTemplateRequest
|
UpdateGeneratedReportTemplateRequest
|
||||||
} from '../shared/report-history'
|
} 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 {
|
import type {
|
||||||
AIChatRequestOptions,
|
AIChatRequestOptions,
|
||||||
AiSearchExternalAuthorizationRequest,
|
AiSearchExternalAuthorizationRequest,
|
||||||
@@ -75,9 +82,16 @@ import type {
|
|||||||
} from '../shared/automation'
|
} from '../shared/automation'
|
||||||
import type { GroupMemberStatsQuery, GroupMemberStatsResult } from '../shared/group-stats'
|
import type { GroupMemberStatsQuery, GroupMemberStatsResult } from '../shared/group-stats'
|
||||||
import type { ActionLogEntry } from '../shared/action-log'
|
import type { ActionLogEntry } from '../shared/action-log'
|
||||||
|
import type {
|
||||||
|
MsgInsertApplyResult,
|
||||||
|
MsgInsertSwitchName,
|
||||||
|
MsgInsertSwitchesSnapshot
|
||||||
|
} from '../shared/msg-insert-switch'
|
||||||
import type { CacheClearScope, CacheSummary } from '../shared/cache'
|
import type { CacheClearScope, CacheSummary } from '../shared/cache'
|
||||||
import type { ExportRequest, ExportJobProgress } from '../shared/export'
|
import type { ExportRequest, ExportJobProgress } from '../shared/export'
|
||||||
import type { ImageDecoderSelectionResult, ImageDecoderStatus } from '../shared/image-decryption'
|
import type { ImageDecoderSelectionResult, ImageDecoderStatus } from '../shared/image-decryption'
|
||||||
|
import type { ImageDebugInfoRequest, ImageDebugInfoResult } from '../shared/image-debug-info'
|
||||||
|
import type { ImageMessageXmlRequest, ImageMessageXmlResult } from '../shared/image-message-xml'
|
||||||
import type { AccountDiscoveryResult } from '../shared/database-key'
|
import type { AccountDiscoveryResult } from '../shared/database-key'
|
||||||
import type {
|
import type {
|
||||||
VoiceBatchConversationSummary,
|
VoiceBatchConversationSummary,
|
||||||
@@ -128,6 +142,11 @@ const api = {
|
|||||||
downloadAppUpdate: () => ipcRenderer.invoke('app-update:download'),
|
downloadAppUpdate: () => ipcRenderer.invoke('app-update:download'),
|
||||||
installAppUpdate: () => ipcRenderer.invoke('app-update:install'),
|
installAppUpdate: () => ipcRenderer.invoke('app-update:install'),
|
||||||
openAppUpdateDownloadPage: () => ipcRenderer.invoke('app-update:openDownloadPage'),
|
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) => {
|
onAppUpdateState: (callback: (state: AppUpdateState) => void) => {
|
||||||
const listener = (_event: Electron.IpcRendererEvent, state: AppUpdateState): void =>
|
const listener = (_event: Electron.IpcRendererEvent, state: AppUpdateState): void =>
|
||||||
callback(state)
|
callback(state)
|
||||||
@@ -222,6 +241,30 @@ const api = {
|
|||||||
*/
|
*/
|
||||||
listSendableContacts: (): Promise<Array<{ id: string; name: string }>> =>
|
listSendableContacts: (): Promise<Array<{ id: string; name: string }>> =>
|
||||||
ipcRenderer.invoke('automation:listSendableContacts'),
|
ipcRenderer.invoke('automation:listSendableContacts'),
|
||||||
|
/**
|
||||||
|
* 微信消息插入开关 —— 读取当前状态。
|
||||||
|
*
|
||||||
|
* 返回的是**逐目标会话**的状态:desiredEnabled(开关值)与 effectiveEnabled
|
||||||
|
* (真的会生效)是两个概念,界面不能只看前者。数据库未连接时 `success=false`。
|
||||||
|
*/
|
||||||
|
getMsgInsertSwitches: (): Promise<MsgInsertSwitchesSnapshot> =>
|
||||||
|
ipcRenderer.invoke('automation:getMsgInsertSwitches'),
|
||||||
|
/** 运行期刷新:允许在消息分片集合变化时补一次规则,再返回最新状态。 */
|
||||||
|
refreshMsgInsertSwitches: (): Promise<MsgInsertSwitchesSnapshot> =>
|
||||||
|
ipcRenderer.invoke('automation:refreshMsgInsertSwitches'),
|
||||||
|
/**
|
||||||
|
* 微信消息插入开关 —— 打开 / 关闭。
|
||||||
|
*
|
||||||
|
* 开的时候会先把目标会话的规则补齐、确认 ready 才写开关值;写不进本进程,
|
||||||
|
* 由一次性 helper 子进程完成。失败不伪装成功:`status.failedShards > 0`
|
||||||
|
* 表示真的有分片写失败,`status.readyTargetRooms < status.totalTargetRooms`
|
||||||
|
* 表示只是规则没装齐。
|
||||||
|
*/
|
||||||
|
setMsgInsertSwitch: (
|
||||||
|
name: MsgInsertSwitchName,
|
||||||
|
enabled: boolean
|
||||||
|
): Promise<MsgInsertApplyResult> =>
|
||||||
|
ipcRenderer.invoke('automation:setMsgInsertSwitch', { name, enabled }),
|
||||||
onGroupExitMonitorState: (callback: (state: GroupExitMonitorState) => void) => {
|
onGroupExitMonitorState: (callback: (state: GroupExitMonitorState) => void) => {
|
||||||
const listener = (_event: Electron.IpcRendererEvent, state: GroupExitMonitorState): void =>
|
const listener = (_event: Electron.IpcRendererEvent, state: GroupExitMonitorState): void =>
|
||||||
callback(state)
|
callback(state)
|
||||||
@@ -365,6 +408,11 @@ const api = {
|
|||||||
includeData?: boolean
|
includeData?: boolean
|
||||||
}
|
}
|
||||||
) => ipcRenderer.invoke('db:getImage', imageMd5, imageDatNameOrThumb, sessionId, options),
|
) => ipcRenderer.invoke('db:getImage', imageMd5, imageDatNameOrThumb, sessionId, options),
|
||||||
|
getImageDebugInfo: (request: ImageDebugInfoRequest): Promise<ImageDebugInfoResult> =>
|
||||||
|
ipcRenderer.invoke('image:getDebugInfo', request),
|
||||||
|
/** 图片消息原始 XML。 */
|
||||||
|
getImageMessageXml: (request: ImageMessageXmlRequest): Promise<ImageMessageXmlResult> =>
|
||||||
|
ipcRenderer.invoke('image:getMessageXml', request),
|
||||||
getVideo: (
|
getVideo: (
|
||||||
hashes: string[],
|
hashes: string[],
|
||||||
options?: {
|
options?: {
|
||||||
@@ -549,6 +597,20 @@ const api = {
|
|||||||
},
|
},
|
||||||
getPersonalWechatSenderStatus: (): Promise<PersonalWechatSenderStatus> =>
|
getPersonalWechatSenderStatus: (): Promise<PersonalWechatSenderStatus> =>
|
||||||
ipcRenderer.invoke('wechat-personal:getStatus'),
|
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> =>
|
getPersonalWechatSendCapability: (): Promise<PersonalWechatSendCapability> =>
|
||||||
ipcRenderer.invoke('wechat-personal:getSendCapability'),
|
ipcRenderer.invoke('wechat-personal:getSendCapability'),
|
||||||
checkPersonalWechatSenderStatus: (port?: string): Promise<PersonalWechatSenderStatus> =>
|
checkPersonalWechatSenderStatus: (port?: string): Promise<PersonalWechatSenderStatus> =>
|
||||||
|
|||||||
@@ -136,8 +136,11 @@ export function DatabaseConnectionPage({
|
|||||||
onClearKey
|
onClearKey
|
||||||
}: DatabaseConnectionPageProps): React.ReactElement {
|
}: DatabaseConnectionPageProps): React.ReactElement {
|
||||||
const isMac = platform === 'darwin'
|
const isMac = platform === 'darwin'
|
||||||
const isIntelMac = isMac && environment?.architecture === 'x64'
|
// 流程由主进程的 macKeyFlow 决定;只有旧版主进程不回传该字段时才回落到运行架构。
|
||||||
const isAppleSiliconMac = isMac && !isIntelMac
|
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
|
const defaultPath = isMac
|
||||||
? '~/Library/Containers/com.tencent.xinWeChat/Data/Library/Application Support/com.tencent.xinWeChat/'
|
? '~/Library/Containers/com.tencent.xinWeChat/Data/Library/Application Support/com.tencent.xinWeChat/'
|
||||||
: 'C:\\Users\\...\\WeChat Files\\Msg'
|
: 'C:\\Users\\...\\WeChat Files\\Msg'
|
||||||
@@ -282,6 +285,21 @@ export function DatabaseConnectionPage({
|
|||||||
</div>
|
</div>
|
||||||
{guideStep === 1 && (
|
{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">
|
<dl className="database-login-diagnostics">
|
||||||
<div>
|
<div>
|
||||||
<dt>操作系统</dt>
|
<dt>操作系统</dt>
|
||||||
@@ -420,7 +438,7 @@ export function DatabaseConnectionPage({
|
|||||||
<Button
|
<Button
|
||||||
className="database-login-primary"
|
className="database-login-primary"
|
||||||
onClick={onGuideNext}
|
onClick={onGuideNext}
|
||||||
disabled={!selectedAccountId}
|
disabled={!selectedAccountId || isArchMismatch}
|
||||||
>
|
>
|
||||||
检查完成,继续
|
检查完成,继续
|
||||||
</Button>
|
</Button>
|
||||||
@@ -446,7 +464,11 @@ export function DatabaseConnectionPage({
|
|||||||
</Button>
|
</Button>
|
||||||
)}
|
)}
|
||||||
{guideStep === 3 && (
|
{guideStep === 3 && (
|
||||||
<Button className="database-login-primary" onClick={onAutoGetKey}>
|
<Button
|
||||||
|
className="database-login-primary"
|
||||||
|
onClick={onAutoGetKey}
|
||||||
|
disabled={isArchMismatch}
|
||||||
|
>
|
||||||
{isMac ? '开始获取密钥' : '开始准备连接组件'}
|
{isMac ? '开始获取密钥' : '开始准备连接组件'}
|
||||||
</Button>
|
</Button>
|
||||||
)}
|
)}
|
||||||
|
|||||||
@@ -6,6 +6,9 @@ interface ImageBubbleProps {
|
|||||||
imageMd5?: string
|
imageMd5?: string
|
||||||
imageDatName?: string
|
imageDatName?: string
|
||||||
sessionId?: string
|
sessionId?: string
|
||||||
|
localId?: number
|
||||||
|
serverId?: string
|
||||||
|
createTime?: number
|
||||||
isThumb?: boolean
|
isThumb?: boolean
|
||||||
fallbackUrl?: string
|
fallbackUrl?: string
|
||||||
onImageClick?: (imageUrl: string) => void
|
onImageClick?: (imageUrl: string) => void
|
||||||
@@ -15,6 +18,9 @@ export function ImageBubble({
|
|||||||
imageMd5,
|
imageMd5,
|
||||||
imageDatName,
|
imageDatName,
|
||||||
sessionId,
|
sessionId,
|
||||||
|
localId,
|
||||||
|
serverId,
|
||||||
|
createTime,
|
||||||
fallbackUrl,
|
fallbackUrl,
|
||||||
onImageClick
|
onImageClick
|
||||||
}: ImageBubbleProps): JSX.Element {
|
}: ImageBubbleProps): JSX.Element {
|
||||||
@@ -125,6 +131,28 @@ export function ImageBubble({
|
|||||||
alert('图片已复制')
|
alert('图片已复制')
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** 右键复制消息原始 XML。 */
|
||||||
|
const handleCopyMessageXml = async (event: MouseEvent): Promise<void> => {
|
||||||
|
event.preventDefault()
|
||||||
|
event.stopPropagation()
|
||||||
|
try {
|
||||||
|
const result = await window.api.getImageMessageXml({
|
||||||
|
sessionId,
|
||||||
|
localId,
|
||||||
|
serverId,
|
||||||
|
createTime
|
||||||
|
})
|
||||||
|
if (!result.success || !result.xml) {
|
||||||
|
alert(result.error ? `XML 获取失败:${result.error}` : 'XML 获取失败')
|
||||||
|
return
|
||||||
|
}
|
||||||
|
await navigator.clipboard.writeText(result.xml)
|
||||||
|
alert('图片消息 XML 已复制')
|
||||||
|
} catch (error) {
|
||||||
|
alert(error instanceof Error ? `XML 复制失败:${error.message}` : 'XML 复制失败')
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
const handleClick = async (): Promise<void> => {
|
const handleClick = async (): Promise<void> => {
|
||||||
if (!imageUrl && !error) return
|
if (!imageUrl && !error) return
|
||||||
if (!imageMd5 && !imageDatName) {
|
if (!imageMd5 && !imageDatName) {
|
||||||
@@ -196,6 +224,7 @@ export function ImageBubble({
|
|||||||
tabIndex={0}
|
tabIndex={0}
|
||||||
aria-label="查看图片"
|
aria-label="查看图片"
|
||||||
onClick={handleClick}
|
onClick={handleClick}
|
||||||
|
onContextMenu={handleCopyMessageXml}
|
||||||
onKeyDown={handlePreviewKeyDown}
|
onKeyDown={handlePreviewKeyDown}
|
||||||
>
|
>
|
||||||
<img
|
<img
|
||||||
|
|||||||
@@ -382,12 +382,18 @@ function QuoteBubble({
|
|||||||
}): JSX.Element {
|
}): JSX.Element {
|
||||||
const quotedText = data.quotedContent || data.content || '[引用消息]'
|
const quotedText = data.quotedContent || data.content || '[引用消息]'
|
||||||
const replyText = data.content || data.title || ''
|
const replyText = data.content || data.title || ''
|
||||||
const quotedSender = data.quotedSender || data.sender || ''
|
// 空白 sender 不渲染:否则只剩下 `.quoted-sender::after` 的冒号,看着像乱码。
|
||||||
|
const quotedSender = String(data.quotedSender || data.sender || '').trim()
|
||||||
const hasQuotedImage = Boolean(data.quotedImageMd5 || data.quotedImageDatName)
|
const hasQuotedImage = Boolean(data.quotedImageMd5 || data.quotedImageDatName)
|
||||||
|
// 引用框里只放一行(超出用省略号),全文交给 hover 的 title 兜底。
|
||||||
|
const quotedTitle = quotedSender ? `${quotedSender}: ${quotedText}` : quotedText
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="quote-message">
|
<div className="quote-message">
|
||||||
<div className={`quoted-message${hasQuotedImage ? ' quoted-message-image' : ''}`}>
|
<div
|
||||||
|
className={`quoted-message${hasQuotedImage ? ' quoted-message-image' : ''}`}
|
||||||
|
title={quotedTitle}
|
||||||
|
>
|
||||||
{quotedSender && <span className="quoted-sender">{quotedSender}</span>}
|
{quotedSender && <span className="quoted-sender">{quotedSender}</span>}
|
||||||
{hasQuotedImage ? (
|
{hasQuotedImage ? (
|
||||||
<ImageBubble
|
<ImageBubble
|
||||||
|
|||||||
@@ -26,11 +26,7 @@ export function AccountSummary({
|
|||||||
const displayName =
|
const displayName =
|
||||||
showAccount && selfInfo ? selfInfo.nickname || selfInfo.wxid || '当前账号' : '未连接'
|
showAccount && selfInfo ? selfInfo.nickname || selfInfo.wxid || '当前账号' : '未连接'
|
||||||
const subtitle = showAccount && selfInfo ? selfInfo.wxid : '打开设置'
|
const subtitle = showAccount && selfInfo ? selfInfo.wxid : '打开设置'
|
||||||
const statusText = dbReady
|
const statusText = dbReady ? '数据库已连接' : dbConnecting ? '正在连接数据库' : '数据库未连接'
|
||||||
? '数据库已连接'
|
|
||||||
: dbConnecting
|
|
||||||
? '正在连接数据库'
|
|
||||||
: '数据库未连接'
|
|
||||||
const statusClass = dbReady ? 'ready' : dbConnecting ? 'connecting' : ''
|
const statusClass = dbReady ? 'ready' : dbConnecting ? 'connecting' : ''
|
||||||
const initial = (displayName || '?').charAt(0)
|
const initial = (displayName || '?').charAt(0)
|
||||||
const title = `${displayName}\n${subtitle}`
|
const title = `${displayName}\n${subtitle}`
|
||||||
@@ -66,8 +62,8 @@ export function AccountSummary({
|
|||||||
</span>
|
</span>
|
||||||
<button type="button" className="account-summary-settings" onClick={onClick} title="设置">
|
<button type="button" className="account-summary-settings" onClick={onClick} title="设置">
|
||||||
<svg viewBox="0 0 24 24" aria-hidden="true" focusable="false">
|
<svg viewBox="0 0 24 24" aria-hidden="true" focusable="false">
|
||||||
<path d="M12 8.5a3.5 3.5 0 1 0 0 7 3.5 3.5 0 0 0 0-7Z" />
|
<path d="M12.22 2h-.44a2 2 0 0 0-2 1.72l-.15 1.58a8 8 0 0 0-1.77 1.03l-1.48-.6a2 2 0 0 0-2.5.88l-.22.39a2 2 0 0 0 .51 2.68l1.25.98a8 8 0 0 0 0 2.08l-1.25.98a2 2 0 0 0-.51 2.68l.22.39a2 2 0 0 0 2.5.88l1.48-.6c.54.43 1.14.78 1.77 1.03l.15 1.58a2 2 0 0 0 2 1.72h.44a2 2 0 0 0 2-1.72l.15-1.58c.63-.25 1.23-.6 1.77-1.03l1.48.6a2 2 0 0 0 2.5-.88l.22-.39a2 2 0 0 0-.51-2.68l-1.25-.98a8 8 0 0 0 0-2.08l1.25-.98a2 2 0 0 0 .51-2.68l-.22-.39a2 2 0 0 0-2.5-.88l-1.48.6a8 8 0 0 0-1.77-1.03l-.15-1.58a2 2 0 0 0-2-1.72Z" />
|
||||||
<path d="M19.4 15a8.2 8.2 0 0 0 .1-1l2-1.5-2-3.5-2.4 1a7.5 7.5 0 0 0-1.7-1l-.3-2.5h-4l-.4 2.5a7.5 7.5 0 0 0-1.7 1l-2.3-1-2 3.5 2 1.5a8.2 8.2 0 0 0 0 2l-2 1.5 2 3.5 2.3-1a7.5 7.5 0 0 0 1.7 1l.4 2.5h4l.3-2.5a7.5 7.5 0 0 0 1.7-1l2.4 1 2-3.5-2.1-1.5Z" />
|
<circle cx="12" cy="12" r="3" />
|
||||||
</svg>
|
</svg>
|
||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -74,6 +74,9 @@ export function MessageBubble({
|
|||||||
imageMd5={message.contentData.md5}
|
imageMd5={message.contentData.md5}
|
||||||
imageDatName={message.contentData.datName}
|
imageDatName={message.contentData.datName}
|
||||||
sessionId={message.sessionId}
|
sessionId={message.sessionId}
|
||||||
|
localId={message.localId}
|
||||||
|
serverId={message.serverId}
|
||||||
|
createTime={message.createTime}
|
||||||
onImageClick={onImageClick}
|
onImageClick={onImageClick}
|
||||||
/>
|
/>
|
||||||
) : isVideo && message.contentData && message.contentData.type === 'video' ? (
|
) : isVideo && message.contentData && message.contentData.type === 'video' ? (
|
||||||
|
|||||||
@@ -8,19 +8,20 @@ interface PersonalWechatSetupGuideProps {
|
|||||||
binding: boolean
|
binding: boolean
|
||||||
detecting: boolean
|
detecting: boolean
|
||||||
sessionBound: boolean
|
sessionBound: boolean
|
||||||
onBind: () => void
|
onBind?: () => void
|
||||||
onStartSending: () => void
|
onStartSending?: () => void
|
||||||
onOpenTextToSpeechSettings?: () => void
|
onOpenTextToSpeechSettings?: () => void
|
||||||
}
|
showBindAction?: boolean
|
||||||
|
showStartSendingAction?: boolean
|
||||||
function capabilityLabel(ready: boolean, initializing: boolean): string {
|
showCapabilityStatus?: boolean
|
||||||
if (ready) return '已就绪'
|
showBindingInstructionsInInitialization?: boolean
|
||||||
return initializing ? '初始化中' : '未就绪'
|
showAuthorizationWarning?: boolean
|
||||||
|
canBind?: boolean
|
||||||
}
|
}
|
||||||
|
|
||||||
function bindingHint(status: PersonalWechatSenderStatus): string {
|
function bindingHint(status: PersonalWechatSenderStatus): string {
|
||||||
if (status.state === 'wechat_not_running') {
|
if (status.state === 'wechat_not_running') {
|
||||||
return '请保持微信未登录窗口状态,点击“绑定微信”后,再点击微信窗口登录。'
|
return '4.1.13以下请保持微信未登录窗口状态,点击“绑定微信”后,再点击微信窗口登录。4.1.13以上登录状态微信直接点击“绑定微信”'
|
||||||
}
|
}
|
||||||
if (status.state === 'unsupported_platform') return '当前系统暂不支持个人微信发送。'
|
if (status.state === 'unsupported_platform') return '当前系统暂不支持个人微信发送。'
|
||||||
if (status.state === 'unsupported_version')
|
if (status.state === 'unsupported_version')
|
||||||
@@ -29,7 +30,7 @@ function bindingHint(status: PersonalWechatSenderStatus): string {
|
|||||||
return '请先完成发送运行时准备。'
|
return '请先完成发送运行时准备。'
|
||||||
}
|
}
|
||||||
if (status.state === 'error') return '连接微信时遇到问题,请稍后重试。'
|
if (status.state === 'error') return '连接微信时遇到问题,请稍后重试。'
|
||||||
return '请保持微信未登录窗口状态,点击“绑定微信”后,再点击微信窗口登录。'
|
return '4.1.13以下请保持微信未登录窗口状态,点击“绑定微信”后,再点击微信窗口登录。4.1.13以上登录状态微信直接点击“绑定微信”'
|
||||||
}
|
}
|
||||||
|
|
||||||
function isWechatBound(status: PersonalWechatSenderStatus): boolean {
|
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({
|
export function PersonalWechatSetupGuide({
|
||||||
senderStatus,
|
senderStatus,
|
||||||
binding,
|
binding,
|
||||||
@@ -48,7 +54,13 @@ export function PersonalWechatSetupGuide({
|
|||||||
sessionBound,
|
sessionBound,
|
||||||
onBind,
|
onBind,
|
||||||
onStartSending,
|
onStartSending,
|
||||||
onOpenTextToSpeechSettings
|
onOpenTextToSpeechSettings,
|
||||||
|
showBindAction = true,
|
||||||
|
showStartSendingAction = true,
|
||||||
|
showCapabilityStatus = true,
|
||||||
|
showBindingInstructionsInInitialization = false,
|
||||||
|
showAuthorizationWarning = true,
|
||||||
|
canBind = true
|
||||||
}: PersonalWechatSetupGuideProps): React.ReactElement {
|
}: PersonalWechatSetupGuideProps): React.ReactElement {
|
||||||
const runtimeUnavailable = senderStatus?.state === 'runtime_missing'
|
const runtimeUnavailable = senderStatus?.state === 'runtime_missing'
|
||||||
const runtimeLabel = '发送运行时'
|
const runtimeLabel = '发送运行时'
|
||||||
@@ -64,7 +76,7 @@ export function PersonalWechatSetupGuide({
|
|||||||
<div>
|
<div>
|
||||||
<span className="personal-wechat-eyebrow">首次使用</span>
|
<span className="personal-wechat-eyebrow">首次使用</span>
|
||||||
<h2>先准备好微信消息功能</h2>
|
<h2>先准备好微信消息功能</h2>
|
||||||
<p>只需几步,TraceMemo 就能在当前会话中生成并发送语音。</p>
|
<p>只需几步,TraceMemo 就能具备微信消息发送能力。</p>
|
||||||
</div>
|
</div>
|
||||||
{allReady && <span className="personal-wechat-setup-complete">已完成</span>}
|
{allReady && <span className="personal-wechat-setup-complete">已完成</span>}
|
||||||
</div>
|
</div>
|
||||||
@@ -76,7 +88,7 @@ export function PersonalWechatSetupGuide({
|
|||||||
<strong>准备 {runtimeLabel}</strong>
|
<strong>准备 {runtimeLabel}</strong>
|
||||||
<p>
|
<p>
|
||||||
{runtimeUnavailable
|
{runtimeUnavailable
|
||||||
? `个人微信发送需要${runtimeLabel},授权后即可使用。`
|
? '当前版本没有微信发送能力。'
|
||||||
: `${runtimeLabel}随 TraceMemo 一起提供,无需额外安装。`}
|
: `${runtimeLabel}随 TraceMemo 一起提供,无需额外安装。`}
|
||||||
</p>
|
</p>
|
||||||
{runtimeReady ? (
|
{runtimeReady ? (
|
||||||
@@ -89,68 +101,86 @@ export function PersonalWechatSetupGuide({
|
|||||||
</div>
|
</div>
|
||||||
</li>
|
</li>
|
||||||
|
|
||||||
<li
|
{showBindAction ? (
|
||||||
className={
|
<li
|
||||||
connected
|
className={
|
||||||
? 'is-complete'
|
connected
|
||||||
: binding
|
? 'is-complete'
|
||||||
? 'is-active'
|
: binding
|
||||||
: runtimeReady
|
? 'is-active'
|
||||||
? 'is-current'
|
: runtimeReady
|
||||||
: 'is-pending'
|
? 'is-current'
|
||||||
}
|
: 'is-pending'
|
||||||
>
|
}
|
||||||
<span className="personal-wechat-step-number">{connected ? '✓' : '2'}</span>
|
>
|
||||||
<div className="personal-wechat-step-content">
|
<span className="personal-wechat-step-number">{connected ? '✓' : '2'}</span>
|
||||||
<strong>绑定个人微信</strong>
|
<div className="personal-wechat-step-content">
|
||||||
<p>请保持微信未登录窗口状态,点击“绑定微信”后,再点击微信窗口登录。</p>
|
<strong>绑定个人微信</strong>
|
||||||
{connected ? (
|
<p>
|
||||||
<span className="personal-wechat-step-status">✓ 微信已绑定</span>
|
4.1.13以下请保持微信未登录窗口状态,点击“绑定微信”后,再点击微信窗口登录。
|
||||||
) : (
|
|
||||||
<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">
|
|
||||||
绑定微信可能导致当前微信异常闪退,这是正常现象。若微信退出,请重新启动微信后,再回到这里重新检测/绑定。
|
|
||||||
<br />
|
<br />
|
||||||
微信总是自动更新?请在微信左下角打开“设置 →
|
4.1.13以上登录状态微信直接点击“绑定微信”
|
||||||
通用”,取消勾选“有更新时自动升级微信”,否则版本变化后可能无法绑定。
|
|
||||||
</p>
|
</p>
|
||||||
)}
|
{connected ? (
|
||||||
</div>
|
<span className="personal-wechat-step-status">✓ 微信已绑定</span>
|
||||||
</li>
|
) : (
|
||||||
|
<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'}>
|
<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">
|
<div className="personal-wechat-step-content">
|
||||||
<strong>初始化发送能力</strong>
|
<strong>初始化发送能力</strong>
|
||||||
<p>绑定微信后,TraceMemo 会自动完成文字、图片和语音发送所需的初始化。</p>
|
<p>每个微信进程只能绑定一次</p>
|
||||||
|
{showBindingInstructionsInInitialization && (
|
||||||
|
<>
|
||||||
|
<p>4.1.13以下请保持微信未登录窗口状态,点击“绑定微信”后,再点击微信窗口登录。</p>
|
||||||
|
<p>4.1.13以上登录状态微信直接点击“绑定微信”</p>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
{initializing && (
|
{initializing && (
|
||||||
<p className="personal-wechat-step-hint" role="status">
|
<p className="personal-wechat-step-hint" role="status">
|
||||||
{detecting ? '正在初始化发送能力…' : '正在等待发送运行时完成初始化…'}
|
{detecting
|
||||||
|
? '正在初始化发送能力…'
|
||||||
|
: runtimeReady
|
||||||
|
? '微信已绑定,正在等待发送能力完成初始化…'
|
||||||
|
: '正在等待发送运行时完成初始化…'}
|
||||||
</p>
|
</p>
|
||||||
)}
|
)}
|
||||||
{senderStatus?.state === 'error' && (
|
{senderStatus?.state === 'error' && (
|
||||||
@@ -161,37 +191,43 @@ export function PersonalWechatSetupGuide({
|
|||||||
</div>
|
</div>
|
||||||
</li>
|
</li>
|
||||||
|
|
||||||
<li className={allReady ? 'is-complete' : initializing ? 'is-current' : 'is-pending'}>
|
{showCapabilityStatus ? (
|
||||||
<span className="personal-wechat-step-number">{allReady ? '✓' : '4'}</span>
|
<li className={allReady ? 'is-complete' : initializing ? 'is-current' : 'is-pending'}>
|
||||||
<div className="personal-wechat-step-content">
|
<span className="personal-wechat-step-number">
|
||||||
<strong>能力检测</strong>
|
{allReady ? '✓' : showBindAction ? '4' : '3'}
|
||||||
<div className="personal-wechat-capabilities" aria-label="微信消息能力">
|
</span>
|
||||||
{[
|
<div className="personal-wechat-step-content">
|
||||||
['文字消息', Boolean(senderStatus?.canSendText)],
|
<strong>能力检测</strong>
|
||||||
['图片消息', Boolean(senderStatus?.canSendImage)],
|
<div className="personal-wechat-capabilities" aria-label="微信消息能力">
|
||||||
['语音消息', canSendVoice]
|
{[
|
||||||
].map(([label, ready]) => (
|
['文字消息', Boolean(senderStatus?.canSendText)],
|
||||||
<span key={String(label)} className={ready ? 'is-ready' : ''}>
|
['图片消息', Boolean(senderStatus?.canSendImage)],
|
||||||
<b aria-hidden>{ready ? '✓' : '−'}</b>
|
['语音消息', canSendVoice]
|
||||||
{label}
|
].map(([label, ready]) => (
|
||||||
<small>{capabilityLabel(Boolean(ready), initializing)}</small>
|
<span key={String(label)} className={ready ? 'is-ready' : ''}>
|
||||||
</span>
|
<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>
|
</div>
|
||||||
{allReady ? (
|
</li>
|
||||||
<>
|
) : null}
|
||||||
<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>
|
|
||||||
</ol>
|
</ol>
|
||||||
|
|
||||||
{!runtimeReady && runtimeUnavailable && onOpenTextToSpeechSettings && (
|
{!runtimeReady && runtimeUnavailable && onOpenTextToSpeechSettings && (
|
||||||
|
|||||||
@@ -27,6 +27,7 @@ import {
|
|||||||
buildContactSearchIndex,
|
buildContactSearchIndex,
|
||||||
filterContactSearchIndex
|
filterContactSearchIndex
|
||||||
} from '../../../../shared/contact-search'
|
} from '../../../../shared/contact-search'
|
||||||
|
import { loadExportPreferences, saveExportPreferences } from './exportPreferences'
|
||||||
|
|
||||||
const ALL_CONTACT_TYPES: ExportContactType[] = ['group', 'user']
|
const ALL_CONTACT_TYPES: ExportContactType[] = ['group', 'user']
|
||||||
const contactTypeKey = (types: ExportContactType[] | undefined): string =>
|
const contactTypeKey = (types: ExportContactType[] | undefined): string =>
|
||||||
@@ -44,6 +45,8 @@ export function ExportWorkspace({
|
|||||||
onCancelExport
|
onCancelExport
|
||||||
}: ExportWorkspaceProps): React.ReactElement {
|
}: ExportWorkspaceProps): React.ReactElement {
|
||||||
const initialSelection = initialContact || contacts[0] || null
|
const initialSelection = initialContact || contacts[0] || null
|
||||||
|
const defaultNameMode = initialSelection?.type === 'group' ? 'groupNickname' : 'remark'
|
||||||
|
const [savedPreferences] = useState(() => loadExportPreferences(defaultNameMode))
|
||||||
const runningAllTask = exportTasks.find(
|
const runningAllTask = exportTasks.find(
|
||||||
(task) => task.scope === 'all' && task.status === 'running'
|
(task) => task.scope === 'all' && task.status === 'running'
|
||||||
)
|
)
|
||||||
@@ -64,24 +67,30 @@ export function ExportWorkspace({
|
|||||||
const contactSearchIndex = useMemo(() => buildContactSearchIndex(contacts), [contacts])
|
const contactSearchIndex = useMemo(() => buildContactSearchIndex(contacts), [contacts])
|
||||||
const [activeContactId, setActiveContactId] = useState(initialSelection?.md5 || '')
|
const [activeContactId, setActiveContactId] = useState(initialSelection?.md5 || '')
|
||||||
const [previewByContact, setPreviewByContact] = useState<Record<string, Message[]>>({})
|
const [previewByContact, setPreviewByContact] = useState<Record<string, Message[]>>({})
|
||||||
const [range, setRange] = useState<ExportRange>(() => (runningAllTask ? 'all' : 'today'))
|
const [range, setRange] = useState<ExportRange>(() => savedPreferences.range)
|
||||||
const [startDate, setStartDate] = useState('')
|
const [startDate, setStartDate] = useState(() => savedPreferences.startDate)
|
||||||
const [endDate, setEndDate] = useState('')
|
const [endDate, setEndDate] = useState(() => savedPreferences.endDate)
|
||||||
const [selectedKinds, setSelectedKinds] = useState<Set<string>>(() => new Set(['text']))
|
const [selectedKinds, setSelectedKinds] = useState<Set<string>>(
|
||||||
const [nameMode, setNameMode] = useState<ExportNameMode>(
|
() => new Set(savedPreferences.selectedKinds)
|
||||||
initialSelection?.type === 'group' ? 'groupNickname' : 'remark'
|
)
|
||||||
|
const [nameMode, setNameMode] = useState<ExportNameMode>(() => savedPreferences.nameMode)
|
||||||
|
const [includeMedia, setIncludeMedia] = useState(() => savedPreferences.includeMedia)
|
||||||
|
const [includeVoiceTranscripts, setIncludeVoiceTranscripts] = useState(
|
||||||
|
() => savedPreferences.includeVoiceTranscripts
|
||||||
)
|
)
|
||||||
const [includeMedia, setIncludeMedia] = useState(true)
|
|
||||||
const [includeVoiceTranscripts, setIncludeVoiceTranscripts] = useState(true)
|
|
||||||
const [voiceModelStatus, setVoiceModelStatus] = useState<VoiceModelStatus | null>(null)
|
const [voiceModelStatus, setVoiceModelStatus] = useState<VoiceModelStatus | null>(null)
|
||||||
const [includeAvatars, setIncludeAvatars] = useState(true)
|
const [includeAvatars, setIncludeAvatars] = useState(() => savedPreferences.includeAvatars)
|
||||||
const [preferOriginal, setPreferOriginal] = useState(true)
|
const [preferOriginal, setPreferOriginal] = useState(() => savedPreferences.preferOriginal)
|
||||||
const [fallbackThumbnail, setFallbackThumbnail] = useState(true)
|
const [fallbackThumbnail, setFallbackThumbnail] = useState(
|
||||||
const [keepMissing, setKeepMissing] = useState(true)
|
() => savedPreferences.fallbackThumbnail
|
||||||
const [format, setFormat] = useState<ExportFormat>(() => runningAllTask?.format || 'csv')
|
)
|
||||||
const [zip, setZip] = useState(() => runningAllTask?.zip === true)
|
const [keepMissing, setKeepMissing] = useState(() => savedPreferences.keepMissing)
|
||||||
const [fileName, setFileName] = useState('')
|
const [format, setFormat] = useState<ExportFormat>(
|
||||||
const [outputDirectory, setOutputDirectory] = useState('')
|
() => runningAllTask?.format || savedPreferences.format
|
||||||
|
)
|
||||||
|
const [zip, setZip] = useState(() => runningAllTask?.zip ?? savedPreferences.zip)
|
||||||
|
const [fileName, setFileName] = useState(() => savedPreferences.fileName)
|
||||||
|
const [outputDirectory, setOutputDirectory] = useState(() => savedPreferences.outputDirectory)
|
||||||
const [status, setStatus] = useState<ExportStatus>('idle')
|
const [status, setStatus] = useState<ExportStatus>('idle')
|
||||||
const [jobId, setJobId] = useState('')
|
const [jobId, setJobId] = useState('')
|
||||||
const [progress, setProgress] = useState<ExportJobProgress | null>(null)
|
const [progress, setProgress] = useState<ExportJobProgress | null>(null)
|
||||||
@@ -92,6 +101,42 @@ export function ExportWorkspace({
|
|||||||
const [taskCenterOpen, setTaskCenterOpen] = useState(false)
|
const [taskCenterOpen, setTaskCenterOpen] = useState(false)
|
||||||
const selectionLimit = 5
|
const selectionLimit = 5
|
||||||
|
|
||||||
|
React.useEffect(() => {
|
||||||
|
saveExportPreferences({
|
||||||
|
format,
|
||||||
|
range,
|
||||||
|
startDate,
|
||||||
|
endDate,
|
||||||
|
selectedKinds: Array.from(selectedKinds) as ExportRequest['kinds'],
|
||||||
|
nameMode,
|
||||||
|
includeMedia,
|
||||||
|
includeVoiceTranscripts,
|
||||||
|
includeAvatars,
|
||||||
|
preferOriginal,
|
||||||
|
fallbackThumbnail,
|
||||||
|
keepMissing,
|
||||||
|
zip,
|
||||||
|
fileName,
|
||||||
|
outputDirectory
|
||||||
|
})
|
||||||
|
}, [
|
||||||
|
endDate,
|
||||||
|
fallbackThumbnail,
|
||||||
|
fileName,
|
||||||
|
format,
|
||||||
|
includeAvatars,
|
||||||
|
includeMedia,
|
||||||
|
includeVoiceTranscripts,
|
||||||
|
keepMissing,
|
||||||
|
nameMode,
|
||||||
|
outputDirectory,
|
||||||
|
preferOriginal,
|
||||||
|
range,
|
||||||
|
selectedKinds,
|
||||||
|
startDate,
|
||||||
|
zip
|
||||||
|
])
|
||||||
|
|
||||||
React.useEffect(() => {
|
React.useEffect(() => {
|
||||||
if (selectedContacts.length > 0) return
|
if (selectedContacts.length > 0) return
|
||||||
const candidate = initialContact || contacts[0]
|
const candidate = initialContact || contacts[0]
|
||||||
@@ -206,7 +251,6 @@ export function ExportWorkspace({
|
|||||||
const handleSelectContact = (contact: Contact): void => {
|
const handleSelectContact = (contact: Contact): void => {
|
||||||
if (exportAll) {
|
if (exportAll) {
|
||||||
setExportAll(false)
|
setExportAll(false)
|
||||||
setRange('today')
|
|
||||||
}
|
}
|
||||||
if (!selectionMode) {
|
if (!selectionMode) {
|
||||||
setSelectedContacts([contact])
|
setSelectedContacts([contact])
|
||||||
@@ -236,7 +280,6 @@ export function ExportWorkspace({
|
|||||||
setExportAll(true)
|
setExportAll(true)
|
||||||
setAllContactTypes([...ALL_CONTACT_TYPES])
|
setAllContactTypes([...ALL_CONTACT_TYPES])
|
||||||
setSelectionMode(false)
|
setSelectionMode(false)
|
||||||
setRange('all')
|
|
||||||
setStatus('idle')
|
setStatus('idle')
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -417,6 +460,7 @@ export function ExportWorkspace({
|
|||||||
setSelectedKinds(new Set(['text']))
|
setSelectedKinds(new Set(['text']))
|
||||||
setNameMode(contact?.type === 'group' ? 'groupNickname' : 'remark')
|
setNameMode(contact?.type === 'group' ? 'groupNickname' : 'remark')
|
||||||
setIncludeMedia(true)
|
setIncludeMedia(true)
|
||||||
|
setIncludeVoiceTranscripts(true)
|
||||||
setIncludeAvatars(true)
|
setIncludeAvatars(true)
|
||||||
setPreferOriginal(true)
|
setPreferOriginal(true)
|
||||||
setFallbackThumbnail(true)
|
setFallbackThumbnail(true)
|
||||||
@@ -424,6 +468,7 @@ export function ExportWorkspace({
|
|||||||
setFormat('csv')
|
setFormat('csv')
|
||||||
setZip(false)
|
setZip(false)
|
||||||
setFileName('')
|
setFileName('')
|
||||||
|
setOutputDirectory('')
|
||||||
setStatus('idle')
|
setStatus('idle')
|
||||||
setJobId('')
|
setJobId('')
|
||||||
setProgress(null)
|
setProgress(null)
|
||||||
@@ -492,7 +537,7 @@ export function ExportWorkspace({
|
|||||||
selectionMode={selectionMode}
|
selectionMode={selectionMode}
|
||||||
exportContactCount={exportContacts.length}
|
exportContactCount={exportContacts.length}
|
||||||
format={format}
|
format={format}
|
||||||
range={range}
|
range={exportAll ? 'all' : range}
|
||||||
startDate={startDate}
|
startDate={startDate}
|
||||||
endDate={endDate}
|
endDate={endDate}
|
||||||
selectedKinds={selectedKinds}
|
selectedKinds={selectedKinds}
|
||||||
|
|||||||
@@ -0,0 +1,115 @@
|
|||||||
|
import type { ExportFormat, ExportMessageKind, ExportNameMode } from '../../../../shared/export'
|
||||||
|
import type { ExportRange } from './exportTypes'
|
||||||
|
|
||||||
|
export interface ExportPreferences {
|
||||||
|
format: ExportFormat
|
||||||
|
range: ExportRange
|
||||||
|
startDate: string
|
||||||
|
endDate: string
|
||||||
|
selectedKinds: ExportMessageKind[]
|
||||||
|
nameMode: ExportNameMode
|
||||||
|
includeMedia: boolean
|
||||||
|
includeVoiceTranscripts: boolean
|
||||||
|
includeAvatars: boolean
|
||||||
|
preferOriginal: boolean
|
||||||
|
fallbackThumbnail: boolean
|
||||||
|
keepMissing: boolean
|
||||||
|
zip: boolean
|
||||||
|
fileName: string
|
||||||
|
outputDirectory: string
|
||||||
|
}
|
||||||
|
|
||||||
|
export const EXPORT_PREFERENCES_STORAGE_KEY = 'tracememo_export_preferences'
|
||||||
|
|
||||||
|
const formats: ExportFormat[] = ['html', 'csv', 'json', 'markdown']
|
||||||
|
const ranges: ExportRange[] = ['all', 'today', 'threeDays', 'sevenDays', 'custom']
|
||||||
|
const messageKinds: ExportMessageKind[] = [
|
||||||
|
'text',
|
||||||
|
'image',
|
||||||
|
'video',
|
||||||
|
'voice',
|
||||||
|
'sticker',
|
||||||
|
'file',
|
||||||
|
'share',
|
||||||
|
'location',
|
||||||
|
'system'
|
||||||
|
]
|
||||||
|
const nameModes: ExportNameMode[] = ['groupNickname', 'remark', 'wechatNickname']
|
||||||
|
|
||||||
|
export function loadExportPreferences(defaultNameMode: ExportNameMode): ExportPreferences {
|
||||||
|
const defaults: ExportPreferences = {
|
||||||
|
format: 'csv',
|
||||||
|
range: 'today',
|
||||||
|
startDate: '',
|
||||||
|
endDate: '',
|
||||||
|
selectedKinds: ['text'],
|
||||||
|
nameMode: defaultNameMode,
|
||||||
|
includeMedia: true,
|
||||||
|
includeVoiceTranscripts: true,
|
||||||
|
includeAvatars: true,
|
||||||
|
preferOriginal: true,
|
||||||
|
fallbackThumbnail: true,
|
||||||
|
keepMissing: true,
|
||||||
|
zip: false,
|
||||||
|
fileName: '',
|
||||||
|
outputDirectory: ''
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const stored = window.localStorage.getItem(EXPORT_PREFERENCES_STORAGE_KEY)
|
||||||
|
if (!stored) return defaults
|
||||||
|
const value = JSON.parse(stored) as Partial<ExportPreferences>
|
||||||
|
return {
|
||||||
|
format: formats.includes(value.format as ExportFormat)
|
||||||
|
? (value.format as ExportFormat)
|
||||||
|
: defaults.format,
|
||||||
|
range: ranges.includes(value.range as ExportRange)
|
||||||
|
? (value.range as ExportRange)
|
||||||
|
: defaults.range,
|
||||||
|
startDate: typeof value.startDate === 'string' ? value.startDate : defaults.startDate,
|
||||||
|
endDate: typeof value.endDate === 'string' ? value.endDate : defaults.endDate,
|
||||||
|
selectedKinds: Array.isArray(value.selectedKinds)
|
||||||
|
? [
|
||||||
|
...new Set(
|
||||||
|
value.selectedKinds.filter((kind): kind is ExportMessageKind =>
|
||||||
|
messageKinds.includes(kind as ExportMessageKind)
|
||||||
|
)
|
||||||
|
)
|
||||||
|
]
|
||||||
|
: defaults.selectedKinds,
|
||||||
|
nameMode: nameModes.includes(value.nameMode as ExportNameMode)
|
||||||
|
? (value.nameMode as ExportNameMode)
|
||||||
|
: defaults.nameMode,
|
||||||
|
includeMedia:
|
||||||
|
typeof value.includeMedia === 'boolean' ? value.includeMedia : defaults.includeMedia,
|
||||||
|
includeVoiceTranscripts:
|
||||||
|
typeof value.includeVoiceTranscripts === 'boolean'
|
||||||
|
? value.includeVoiceTranscripts
|
||||||
|
: defaults.includeVoiceTranscripts,
|
||||||
|
includeAvatars:
|
||||||
|
typeof value.includeAvatars === 'boolean' ? value.includeAvatars : defaults.includeAvatars,
|
||||||
|
preferOriginal:
|
||||||
|
typeof value.preferOriginal === 'boolean' ? value.preferOriginal : defaults.preferOriginal,
|
||||||
|
fallbackThumbnail:
|
||||||
|
typeof value.fallbackThumbnail === 'boolean'
|
||||||
|
? value.fallbackThumbnail
|
||||||
|
: defaults.fallbackThumbnail,
|
||||||
|
keepMissing:
|
||||||
|
typeof value.keepMissing === 'boolean' ? value.keepMissing : defaults.keepMissing,
|
||||||
|
zip: typeof value.zip === 'boolean' ? value.zip : defaults.zip,
|
||||||
|
fileName: typeof value.fileName === 'string' ? value.fileName : defaults.fileName,
|
||||||
|
outputDirectory:
|
||||||
|
typeof value.outputDirectory === 'string' ? value.outputDirectory : defaults.outputDirectory
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
return defaults
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function saveExportPreferences(preferences: ExportPreferences): void {
|
||||||
|
try {
|
||||||
|
window.localStorage.setItem(EXPORT_PREFERENCES_STORAGE_KEY, JSON.stringify(preferences))
|
||||||
|
} catch {
|
||||||
|
// Export remains usable when browser storage is unavailable.
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -58,6 +58,67 @@ export const API_ENDPOINTS: ApiEndpoint[] = [
|
|||||||
{ key: 'q', label: '待解析标识', required: true, placeholder: '昵称、wxid 或 md5' }
|
{ key: 'q', label: '待解析标识', required: true, placeholder: '昵称、wxid 或 md5' }
|
||||||
]
|
]
|
||||||
}),
|
}),
|
||||||
|
endpoint('app-capabilities', {
|
||||||
|
name: '应用能力',
|
||||||
|
description: '查看数据库、Query、Automation 与运行环境的能力状态。'
|
||||||
|
}),
|
||||||
|
endpoint('group-exit-monitor', {
|
||||||
|
name: '退群监控状态',
|
||||||
|
description: '查看监控开关、监控群范围、事件数量和运行状态。'
|
||||||
|
}),
|
||||||
|
endpoint('group-exit-monitor-update', {
|
||||||
|
name: '配置退群监控',
|
||||||
|
description: '设置监控群范围或启用/关闭退群监控,不会修改退群通知 Automation。',
|
||||||
|
body: true
|
||||||
|
}),
|
||||||
|
endpoint('group-exit-events', {
|
||||||
|
name: '退群事件历史',
|
||||||
|
description: '按群和时间窗口查询退群事件,最多返回 200 条。',
|
||||||
|
parameters: [
|
||||||
|
{ key: 'conversationId', label: '群会话 ID', placeholder: 'xxx@chatroom' },
|
||||||
|
{ key: 'since', label: '开始时间', placeholder: '2026-10-01T00:00:00+07:00' },
|
||||||
|
{ key: 'until', label: '结束时间', placeholder: '2026-10-02T23:59:59+07:00' },
|
||||||
|
{ key: 'limit', label: '数量上限', placeholder: '50,最大 200' }
|
||||||
|
]
|
||||||
|
}),
|
||||||
|
endpoint('group-member-stats', {
|
||||||
|
name: '群成员活跃统计',
|
||||||
|
description: '查询指定群在时间窗口内的活跃成员、沉默成员和数据完整性。',
|
||||||
|
parameters: [
|
||||||
|
{ key: 'conversationId', label: '群会话 ID', required: true, placeholder: 'xxx@chatroom' },
|
||||||
|
{ key: 'start', label: '开始时间', required: true, placeholder: '2026-10-01T00:00:00+07:00' },
|
||||||
|
{ key: 'end', label: '结束时间', required: true, placeholder: '2026-10-02T23:59:59+07:00' }
|
||||||
|
]
|
||||||
|
}),
|
||||||
|
endpoint('automations', {
|
||||||
|
name: '自动化规则',
|
||||||
|
description: '列出自动化规则,可按类型和启用状态筛选。',
|
||||||
|
parameters: [
|
||||||
|
{ key: 'type', label: '规则类型', placeholder: 'daily_report / scheduled_report / leave_notification' },
|
||||||
|
{ key: 'enabled', label: '启用状态', placeholder: 'true 或 false' }
|
||||||
|
]
|
||||||
|
}),
|
||||||
|
endpoint('automation-create', {
|
||||||
|
name: '创建自动化规则',
|
||||||
|
description: '创建一条默认停用的自动化规则。',
|
||||||
|
body: true
|
||||||
|
}),
|
||||||
|
endpoint('automation-validate', {
|
||||||
|
name: '校验自动化规则',
|
||||||
|
description: '检查规则字段、目标标识和预计影响,不保存也不执行。',
|
||||||
|
body: true
|
||||||
|
}),
|
||||||
|
endpoint('automation-executions', {
|
||||||
|
name: '自动化执行记录',
|
||||||
|
description: '分页上限内查询执行结果,可按规则、状态和时间筛选。',
|
||||||
|
parameters: [
|
||||||
|
{ key: 'ruleId', label: '规则 ID', placeholder: 'ruleId' },
|
||||||
|
{ key: 'status', label: '状态', placeholder: 'running / success / failed' },
|
||||||
|
{ key: 'since', label: '开始时间', placeholder: '2026-10-01T00:00:00+07:00' },
|
||||||
|
{ key: 'until', label: '结束时间', placeholder: '2026-10-02T23:59:59+07:00' },
|
||||||
|
{ key: 'limit', label: '数量上限', placeholder: '50,最大 200' }
|
||||||
|
]
|
||||||
|
}),
|
||||||
endpoint('report', {
|
endpoint('report', {
|
||||||
name: '群聊日报导出',
|
name: '群聊日报导出',
|
||||||
description: '通过内置模板导出群聊日报 HTML 与 PNG。',
|
description: '通过内置模板导出群聊日报 HTML 与 PNG。',
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
export type ApiMethod = 'GET' | 'POST'
|
export type ApiMethod = 'GET' | 'POST' | 'PATCH'
|
||||||
export type { ApiTokenStatus } from '../../../../../shared/local-api-auth'
|
export type { ApiTokenStatus } from '../../../../../shared/local-api-auth'
|
||||||
|
|
||||||
export interface ApiParameter {
|
export interface ApiParameter {
|
||||||
|
|||||||
@@ -4,8 +4,19 @@ export function buildApiUrl(
|
|||||||
path: string,
|
path: string,
|
||||||
params: Record<string, string>
|
params: Record<string, string>
|
||||||
): string {
|
): string {
|
||||||
const url = new URL(path, `http://${host}:${port}`)
|
let resolvedPath = path
|
||||||
|
const pathParameterKeys = new Set(
|
||||||
|
Object.keys(params).filter((key) => path.includes(`{${key}}`))
|
||||||
|
)
|
||||||
Object.entries(params).forEach(([key, value]) => {
|
Object.entries(params).forEach(([key, value]) => {
|
||||||
|
const normalized = value.trim()
|
||||||
|
if (normalized && resolvedPath.includes(`{${key}}`)) {
|
||||||
|
resolvedPath = resolvedPath.replace(`{${key}}`, encodeURIComponent(normalized))
|
||||||
|
}
|
||||||
|
})
|
||||||
|
const url = new URL(resolvedPath, `http://${host}:${port}`)
|
||||||
|
Object.entries(params).forEach(([key, value]) => {
|
||||||
|
if (pathParameterKeys.has(key)) return
|
||||||
if (value.trim()) url.searchParams.set(key, value.trim())
|
if (value.trim()) url.searchParams.set(key, value.trim())
|
||||||
})
|
})
|
||||||
return url.toString()
|
return url.toString()
|
||||||
|
|||||||
@@ -7,13 +7,13 @@ function requestHost(host: string): string {
|
|||||||
function opening(target: AgentInstallTarget): string {
|
function opening(target: AgentInstallTarget): string {
|
||||||
switch (target) {
|
switch (target) {
|
||||||
case 'codex':
|
case 'codex':
|
||||||
return '请将本地目录中的 TraceMemo Reader Skill 安装到当前 Codex 项目或用户 Skill 目录:'
|
return '请将本地目录中的 TraceMemo Reader Skill 安装或更新到当前 Codex 项目或用户 Skill 目录:'
|
||||||
case 'claude-code':
|
case 'claude-code':
|
||||||
return '请安装以下本地 TraceMemo Reader Skill,并按照 SKILL.md 调用本地 HTTP API:'
|
return '请安装或更新以下本地 TraceMemo Reader Skill,并按照 SKILL.md 调用本地 HTTP API:'
|
||||||
case 'openclaw':
|
case 'openclaw':
|
||||||
return '请将以下本地目录作为 TraceMemo Reader Skill 安装,并阅读其中的 SKILL.md:'
|
return '请将以下本地目录作为 TraceMemo Reader Skill 安装或更新,并阅读其中的 SKILL.md:'
|
||||||
default:
|
default:
|
||||||
return '请读取并安装以下 TraceMemo Reader Skill:'
|
return '请读取并安装(或更新)以下 TraceMemo Reader Skill:'
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -32,8 +32,11 @@ export function buildSkillInstallInstruction({
|
|||||||
const sourceText =
|
const sourceText =
|
||||||
source.type === 'local'
|
source.type === 'local'
|
||||||
? `${opening(target)}\n\n${source.directoryPath}\n\n请先阅读该目录中的 SKILL.md,然后调用:`
|
? `${opening(target)}\n\n${source.directoryPath}\n\n请先阅读该目录中的 SKILL.md,然后调用:`
|
||||||
: `请从以下地址安装 TraceMemo Reader Skill:\n\n${source.installUrl}\n\n阅读 SKILL.md 后,调用:`
|
: `请安装或更新 TraceMemo Reader Skill,来源:\n\n${source.installUrl}\n\n阅读 SKILL.md 后,调用:`
|
||||||
return `${sourceText}\n\n${healthUrl}\n\n先调用公开的 health 接口验证服务。然后请用户在 TraceMemo → API Center → API Token 中点击“复制 Token”,并把 Token 配置为 Agent 本机环境变量 TRACEMEMO_API_TOKEN。读取联系人、会话或聊天记录时,必须发送 Authorization: Bearer $TRACEMEMO_API_TOKEN。若旧配置尚未升级,可兼容读取 WECHATEXPLORER_API_TOKEN,但新配置必须优先使用 TRACEMEMO_API_TOKEN。此服务是 Local HTTP API,不是 MCP Server。安装完成后告诉我验证结果。`
|
const versionNote = source.version
|
||||||
|
? `\n\n这一份的 Skill 版本是 ${source.version}。如果目标位置已经有旧版本,请用这一份覆盖;安装完成后记住该版本号,之后每次会话开始时按 SKILL.md 的「版本自检」与 health 返回的 skill.version 比对,不一致就提醒用户重新安装。`
|
||||||
|
: ''
|
||||||
|
return `${sourceText}\n\n${healthUrl}${versionNote}\n\n先调用公开的 health 接口验证服务。然后请用户在 TraceMemo → API Center → API Token 中点击“复制 Token”,并把 Token 配置为 Agent 本机环境变量 TRACEMEMO_API_TOKEN。读取联系人、会话或聊天记录时,必须发送 Authorization: Bearer $TRACEMEMO_API_TOKEN。若旧配置尚未升级,可兼容读取 WECHATEXPLORER_API_TOKEN,但新配置必须优先使用 TRACEMEMO_API_TOKEN。此服务是 Local HTTP API,不是 MCP Server。安装完成后告诉我验证结果,并说明你的本机 Skill 版本与 health 返回的 skill.version 是否一致。`
|
||||||
}
|
}
|
||||||
|
|
||||||
export function buildSkillVerificationPrompt(): string {
|
export function buildSkillVerificationPrompt(): string {
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import { useState } from 'react'
|
import { useEffect, useState } from 'react'
|
||||||
import {
|
import {
|
||||||
AlertDialog,
|
AlertDialog,
|
||||||
AlertDialogAction,
|
AlertDialogAction,
|
||||||
@@ -21,14 +21,53 @@ export function AppUpdatePrompt({
|
|||||||
}): React.ReactElement {
|
}): React.ReactElement {
|
||||||
const update = useAppUpdateState()
|
const update = useAppUpdateState()
|
||||||
const [dismissedVersion, setDismissedVersion] = useState<string>()
|
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 =
|
const shouldPrompt =
|
||||||
update.status === 'available' &&
|
update.status === 'available' &&
|
||||||
update.source === 'startup' &&
|
update.source === 'startup' &&
|
||||||
Boolean(update.version) &&
|
Boolean(update.version) &&
|
||||||
|
ignoredVersion !== null &&
|
||||||
|
update.version !== ignoredVersion &&
|
||||||
update.version !== dismissedVersion
|
update.version !== dismissedVersion
|
||||||
|
|
||||||
const dismiss = (): void => setDismissedVersion(update.version)
|
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> => {
|
const continueUpdate = async (): Promise<void> => {
|
||||||
dismiss()
|
dismiss()
|
||||||
if (update.delivery === 'release-page') {
|
if (update.delivery === 'release-page') {
|
||||||
@@ -55,6 +94,9 @@ export function AppUpdatePrompt({
|
|||||||
</AlertDialogDescription>
|
</AlertDialogDescription>
|
||||||
</AlertDialogHeader>
|
</AlertDialogHeader>
|
||||||
<AlertDialogFooter>
|
<AlertDialogFooter>
|
||||||
|
<Button variant="ghost" className="sm:mr-auto" onClick={() => void ignoreVersion()}>
|
||||||
|
忽略此版本
|
||||||
|
</Button>
|
||||||
<AlertDialogCancel asChild>
|
<AlertDialogCancel asChild>
|
||||||
<Button variant="outline" onClick={dismiss}>
|
<Button variant="outline" onClick={dismiss}>
|
||||||
取消
|
取消
|
||||||
|
|||||||
@@ -24,6 +24,7 @@ import {
|
|||||||
AutomationRuleTypeTabs,
|
AutomationRuleTypeTabs,
|
||||||
type AutomationRuleTabType
|
type AutomationRuleTabType
|
||||||
} from './AutomationRuleTypeTabs'
|
} from './AutomationRuleTypeTabs'
|
||||||
|
import { MessageInsertSwitches } from './MessageInsertSwitches'
|
||||||
import { ScheduledReportEditor } from './ScheduledReportEditor'
|
import { ScheduledReportEditor } from './ScheduledReportEditor'
|
||||||
import { ScheduledReportRuleList } from './ScheduledReportRuleList'
|
import { ScheduledReportRuleList } from './ScheduledReportRuleList'
|
||||||
import { ScheduledReportNotificationPanel } from './ScheduledReportNotificationPanel'
|
import { ScheduledReportNotificationPanel } from './ScheduledReportNotificationPanel'
|
||||||
@@ -483,16 +484,20 @@ export function AutomationWorkspace({
|
|||||||
<h1>自动化</h1>
|
<h1>自动化</h1>
|
||||||
<p>当群里出现符合条件的消息时,TraceMemo 会自动执行你配置的动作。</p>
|
<p>当群里出现符合条件的消息时,TraceMemo 会自动执行你配置的动作。</p>
|
||||||
</div>
|
</div>
|
||||||
{tab === 'rules' && !showEditor ? (
|
<div className="automation-page-header-actions">
|
||||||
<Button
|
{/* 微信消息插入开关:控制 TraceMemo 能在微信会话里插入哪些消息 */}
|
||||||
onClick={() => {
|
<MessageInsertSwitches />
|
||||||
lastDailyTargetRef.current = null
|
{tab === 'rules' && !showEditor ? (
|
||||||
setEditor({ mode: 'create', rule: null, ruleType: 'daily_report' })
|
<Button
|
||||||
}}
|
onClick={() => {
|
||||||
>
|
lastDailyTargetRef.current = null
|
||||||
新建自动化
|
setEditor({ mode: 'create', rule: null, ruleType: 'daily_report' })
|
||||||
</Button>
|
}}
|
||||||
) : null}
|
>
|
||||||
|
新建自动化
|
||||||
|
</Button>
|
||||||
|
) : null}
|
||||||
|
</div>
|
||||||
</header>
|
</header>
|
||||||
|
|
||||||
{!apiAvailable ? (
|
{!apiAvailable ? (
|
||||||
|
|||||||
@@ -0,0 +1,286 @@
|
|||||||
|
import * as React from 'react'
|
||||||
|
import {
|
||||||
|
MSG_INSERT_SWITCH_LABELS,
|
||||||
|
type MsgInsertApplyResult,
|
||||||
|
type MsgInsertSwitchName,
|
||||||
|
type MsgInsertSwitchStatus,
|
||||||
|
type MsgInsertSwitchesSnapshot
|
||||||
|
} from '../../../../shared/msg-insert-switch'
|
||||||
|
import { Switch, Spinner, useToast } from '../../components/ui'
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 「微信消息插入开关」—— 自动化页右上角的两个开关。
|
||||||
|
*
|
||||||
|
* 分工:
|
||||||
|
* 开关值存在 native 侧(每个消息分片 `_tm_config` 表),真正干活的是挂在
|
||||||
|
* `Msg_<md5(roomId)>` 表上的规则;写入由主进程 spawn 一次性 helper 完成。
|
||||||
|
* 这里只负责展示与触发,不做任何平台判断。
|
||||||
|
*
|
||||||
|
* 三个状态都要如实展示,不能只画一个 boolean:
|
||||||
|
* desiredEnabled 用户意图(开关值)
|
||||||
|
* effectiveEnabled 是否真的生效(目标会话规则齐 + 开关值落到相关分片)
|
||||||
|
* ready / total 目标会话的覆盖情况
|
||||||
|
*
|
||||||
|
* 打开时先 loading、成功才 ON、失败回滚;写失败与「规则没装齐」是两种不同的
|
||||||
|
* 提示,不混成一句「设置失败」。
|
||||||
|
*/
|
||||||
|
/* 首次拉取失败时的有界重试:2s 一次,最多 20 次(约 40s)。连上即停。 */
|
||||||
|
const BLOCKED_RETRY_LIMIT = 20
|
||||||
|
const BLOCKED_RETRY_INTERVAL_MS = 2000
|
||||||
|
|
||||||
|
/** 运行期刷新的低频兜底间隔。开销说明见 `refreshQuietly`:指纹没变时只是一次本地读。 */
|
||||||
|
const REFRESH_INTERVAL_MS = 5 * 60 * 1000
|
||||||
|
|
||||||
|
export function MessageInsertSwitches(): React.JSX.Element {
|
||||||
|
const { toast } = useToast()
|
||||||
|
const [snapshot, setSnapshot] = React.useState<MsgInsertSwitchesSnapshot | null>(null)
|
||||||
|
const [pending, setPending] = React.useState<MsgInsertSwitchName | null>(null)
|
||||||
|
const [blockedReason, setBlockedReason] = React.useState<string | null>(null)
|
||||||
|
const [loading, setLoading] = React.useState(true)
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 拉一次状态。返回是否成功 —— 调用方据此决定要不要重试。
|
||||||
|
*/
|
||||||
|
const refresh = React.useCallback(async (): Promise<boolean> => {
|
||||||
|
const api = window.api
|
||||||
|
if (!api?.getMsgInsertSwitches) {
|
||||||
|
setBlockedReason('当前版本不支持微信消息插入开关')
|
||||||
|
setLoading(false)
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
const result = await api.getMsgInsertSwitches()
|
||||||
|
setSnapshot(result)
|
||||||
|
/* 数据库没连上时不能假装能改;但已经有数据时不要把界面打回禁用态。 */
|
||||||
|
setBlockedReason(result.success ? null : result.detail || '微信数据库尚未连接')
|
||||||
|
return result.success
|
||||||
|
} catch (error) {
|
||||||
|
setBlockedReason(error instanceof Error ? error.message : String(error))
|
||||||
|
return false
|
||||||
|
} finally {
|
||||||
|
setLoading(false)
|
||||||
|
}
|
||||||
|
}, [])
|
||||||
|
|
||||||
|
/*
|
||||||
|
* 首次拉取失败要**有界重试**。
|
||||||
|
*
|
||||||
|
* 自动化页常常在微信库还没连上的时候就被打开(冷启动、刚切库、微信还没起来),
|
||||||
|
* 这时只拉一次就会把开关永久置灰 —— 用户看到的是「灰的」,但真实原因只是「还没连上」,
|
||||||
|
* 而且切走再回来才会恢复。所以这里连上就停、连不上退避重试,最多 20 次(约 40s)。
|
||||||
|
*
|
||||||
|
* 不轮询:一旦拿到 success=true 就彻底停,不会有常驻定时器。
|
||||||
|
*/
|
||||||
|
React.useEffect(() => {
|
||||||
|
let cancelled = false
|
||||||
|
let timer: ReturnType<typeof setTimeout> | undefined
|
||||||
|
let attempt = 0
|
||||||
|
const run = async (): Promise<void> => {
|
||||||
|
const ok = await refresh()
|
||||||
|
if (cancelled || ok || attempt >= BLOCKED_RETRY_LIMIT) return
|
||||||
|
attempt += 1
|
||||||
|
timer = setTimeout(() => void run(), BLOCKED_RETRY_INTERVAL_MS)
|
||||||
|
}
|
||||||
|
void run()
|
||||||
|
return () => {
|
||||||
|
cancelled = true
|
||||||
|
if (timer) clearTimeout(timer)
|
||||||
|
}
|
||||||
|
}, [refresh])
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 运行期刷新:**窗口重新聚焦** + **低频兜底**。
|
||||||
|
*
|
||||||
|
* 只在挂载时拉一次不够用:微信运行期间会新建 `message_N.db`,目标会话集合随之变化,
|
||||||
|
* 而规则补齐只在启动时跑过一次 —— 于是 `ready / total` 会一直差着几个。
|
||||||
|
*
|
||||||
|
* 刻意不做高频轮询:主进程侧会先比对消息分片清单指纹,没变就只做纯读立刻返回,
|
||||||
|
* 变了才 spawn 一次 helper,所以这一次调用的实际开销通常只是一次本地读。
|
||||||
|
*/
|
||||||
|
const refreshQuietly = React.useCallback(async (): Promise<void> => {
|
||||||
|
const api = window.api
|
||||||
|
if (!api?.refreshMsgInsertSwitches) return
|
||||||
|
try {
|
||||||
|
const result = await api.refreshMsgInsertSwitches()
|
||||||
|
setSnapshot(result)
|
||||||
|
if (result.success) setBlockedReason(null)
|
||||||
|
} catch {
|
||||||
|
/* 静默:一次后台刷新失败不应该把已经可用的界面打回禁用态。 */
|
||||||
|
}
|
||||||
|
}, [])
|
||||||
|
|
||||||
|
React.useEffect(() => {
|
||||||
|
const timer = window.setInterval(() => void refreshQuietly(), REFRESH_INTERVAL_MS)
|
||||||
|
const onFocus = (): void => void refreshQuietly()
|
||||||
|
window.addEventListener('focus', onFocus)
|
||||||
|
return () => {
|
||||||
|
window.clearInterval(timer)
|
||||||
|
window.removeEventListener('focus', onFocus)
|
||||||
|
}
|
||||||
|
}, [refreshQuietly])
|
||||||
|
|
||||||
|
/** 把结果里的失败原因翻成人话;native code 只进日志。 */
|
||||||
|
const humanize = React.useCallback((result: MsgInsertApplyResult): string => {
|
||||||
|
const status = result.status
|
||||||
|
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) {
|
||||||
|
return `设置失败:${status.failedShards} 个消息库写入失败`
|
||||||
|
}
|
||||||
|
if (
|
||||||
|
status &&
|
||||||
|
status.totalInstallableRooms > 0 &&
|
||||||
|
status.readyInstallableRooms < status.totalInstallableRooms
|
||||||
|
) {
|
||||||
|
return `开启失败:${
|
||||||
|
status.totalInstallableRooms - status.readyInstallableRooms
|
||||||
|
} 个会话的消息规则安装失败`
|
||||||
|
}
|
||||||
|
return result.message || '设置失败,请稍后重试'
|
||||||
|
}, [])
|
||||||
|
|
||||||
|
const handleToggle = React.useCallback(
|
||||||
|
async (name: MsgInsertSwitchName, next: boolean): Promise<void> => {
|
||||||
|
const api = window.api
|
||||||
|
if (!api?.setMsgInsertSwitch || pending) return
|
||||||
|
setPending(name)
|
||||||
|
try {
|
||||||
|
const result = await api.setMsgInsertSwitch(name, next)
|
||||||
|
/* 不乐观更新:写的是微信库里的规则 + 开关,失败必须回滚到真实状态。
|
||||||
|
* 先拿主进程只读复核的结果,再决定开关画成什么。 */
|
||||||
|
setSnapshot((prev) =>
|
||||||
|
prev ? { ...prev, switches: { ...prev.switches, [name]: result.status } } : prev
|
||||||
|
)
|
||||||
|
if (!result.success) {
|
||||||
|
toast({ description: humanize(result), variant: 'destructive', duration: 4000 })
|
||||||
|
/* 复核一次,确保界面与库里真实状态一致(而不是停在乐观值上)。 */
|
||||||
|
await refresh()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if (result.detail) console.warn('[MsgInsert]', result.detail)
|
||||||
|
await refresh()
|
||||||
|
} catch (error) {
|
||||||
|
toast({
|
||||||
|
description: error instanceof Error ? error.message : '设置失败',
|
||||||
|
variant: 'destructive',
|
||||||
|
duration: 4000
|
||||||
|
})
|
||||||
|
await refresh()
|
||||||
|
} finally {
|
||||||
|
setPending(null)
|
||||||
|
}
|
||||||
|
},
|
||||||
|
[humanize, pending, refresh, toast]
|
||||||
|
)
|
||||||
|
|
||||||
|
/* 开启要全绿,关闭永远放行——授权过期后关不掉比开不了更糟。 */
|
||||||
|
const capability = snapshot?.capability
|
||||||
|
const helperMissing = snapshot?.helperAvailable === false
|
||||||
|
|
||||||
|
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={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 =
|
||||||
|
status?.desiredEnabled === true &&
|
||||||
|
status.totalInstallableRooms > 0 &&
|
||||||
|
status.readyInstallableRooms < status.totalInstallableRooms
|
||||||
|
/* 内部口径(roomsWithoutTable 之类的「暂无消息表」计数)不面向普通用户,
|
||||||
|
* 只留在诊断/tooltip 里,不上主界面。 */
|
||||||
|
const scopeHint =
|
||||||
|
status?.mode === 'event' && (status.monitoredRoomCount || 0) > 0
|
||||||
|
? `覆盖全部群聊(${status.monitoredRoomCount} 个)`
|
||||||
|
: null
|
||||||
|
return (
|
||||||
|
/* 刻意用 span 而不是 label:<label> 会把点击转发给里面的 Switch,
|
||||||
|
于是「点文字」也会切换开关。写微信库的开关不该这么容易被误触。 */
|
||||||
|
<span
|
||||||
|
key={name}
|
||||||
|
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 子进程 + 装规则,耗时以秒计。
|
||||||
|
只把开关置灰会让人以为卡死,所以显式给「处理中」。 */}
|
||||||
|
{busy ? (
|
||||||
|
<span className="automation-msg-insert-switch-busy">
|
||||||
|
<Spinner />
|
||||||
|
处理中…
|
||||||
|
</span>
|
||||||
|
) : null}
|
||||||
|
<Switch
|
||||||
|
checked={desired}
|
||||||
|
disabled={switchDisabled}
|
||||||
|
onCheckedChange={(checked) => void handleToggle(name, checked === true)}
|
||||||
|
aria-label={label}
|
||||||
|
/>
|
||||||
|
{status && showCoverage ? (
|
||||||
|
<span
|
||||||
|
className={`automation-msg-insert-switch-count ${partial ? 'is-warning' : ''}`}
|
||||||
|
title="已就绪 / 可安装"
|
||||||
|
>
|
||||||
|
{partial ? '⚠ ' : ''}
|
||||||
|
{status.readyInstallableRooms} / {status.totalInstallableRooms} 已启用
|
||||||
|
</span>
|
||||||
|
) : null}
|
||||||
|
{scopeHint ? (
|
||||||
|
<span className="automation-msg-insert-switch-scope" title="覆盖范围,不是规则覆盖率">
|
||||||
|
{scopeHint}
|
||||||
|
</span>
|
||||||
|
) : null}
|
||||||
|
</span>
|
||||||
|
)
|
||||||
|
})}
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -129,7 +129,11 @@ function SendCapabilityStatus({
|
|||||||
* 退群监控只产生退群事实,不再持有通知模板 —— 两处可编辑必然漂移。
|
* 退群监控只产生退群事实,不再持有通知模板 —— 两处可编辑必然漂移。
|
||||||
*/
|
*/
|
||||||
|
|
||||||
function GroupAvatar({ contact }: { contact: Contact }): React.ReactElement {
|
const GroupAvatar = React.memo(function GroupAvatar({
|
||||||
|
contact
|
||||||
|
}: {
|
||||||
|
contact: Contact
|
||||||
|
}): React.ReactElement {
|
||||||
const name = contactDisplayName(contact)
|
const name = contactDisplayName(contact)
|
||||||
const initial = name.charAt(0) || '?'
|
const initial = name.charAt(0) || '?'
|
||||||
return (
|
return (
|
||||||
@@ -137,7 +141,7 @@ function GroupAvatar({ contact }: { contact: Contact }): React.ReactElement {
|
|||||||
{contact.avatar ? <img src={contact.avatar} alt="" aria-hidden="true" /> : initial}
|
{contact.avatar ? <img src={contact.avatar} alt="" aria-hidden="true" /> : initial}
|
||||||
</span>
|
</span>
|
||||||
)
|
)
|
||||||
}
|
})
|
||||||
|
|
||||||
interface ManageGroupsProps {
|
interface ManageGroupsProps {
|
||||||
groups: Contact[]
|
groups: Contact[]
|
||||||
@@ -155,7 +159,14 @@ interface ManageGroupsProps {
|
|||||||
onCancel: () => void
|
onCancel: () => void
|
||||||
}
|
}
|
||||||
|
|
||||||
function ManageGroups({
|
/**
|
||||||
|
* 管理群聊页。
|
||||||
|
*
|
||||||
|
* 必须 `memo`:这个页面**不消费退群监控状态** —— 列表数据来自 `contacts`、选中来自本地 state,
|
||||||
|
* 而父层会因为监控状态推送反复重渲染(实测约 5 次/秒,且推送间隔 350ms 去抖)。
|
||||||
|
* 没有 memo 时 200+ 行会跟着每次推送重建,用户看到的就是"列表一直在刷新"。
|
||||||
|
*/
|
||||||
|
const ManageGroups = React.memo(function ManageGroups({
|
||||||
groups,
|
groups,
|
||||||
selectedRoomIds,
|
selectedRoomIds,
|
||||||
sendCapability,
|
sendCapability,
|
||||||
@@ -294,7 +305,8 @@ function ManageGroups({
|
|||||||
|
|
||||||
<footer className="exit-monitor-manage-footer">
|
<footer className="exit-monitor-manage-footer">
|
||||||
<span>
|
<span>
|
||||||
保存后将从新的成员快照开始记录退群动态;退群通知发到哪里,请在「自动化 → 退群通知」里配置。
|
保存后将从新的成员快照开始记录退群动态;退群通知发到哪里,请在「自动化 →
|
||||||
|
退群通知」里配置。
|
||||||
</span>
|
</span>
|
||||||
<div>
|
<div>
|
||||||
<Button variant="ghost" onClick={onCancel} disabled={saving}>
|
<Button variant="ghost" onClick={onCancel} disabled={saving}>
|
||||||
@@ -307,7 +319,7 @@ function ManageGroups({
|
|||||||
</footer>
|
</footer>
|
||||||
</div>
|
</div>
|
||||||
)
|
)
|
||||||
}
|
})
|
||||||
|
|
||||||
export function GroupExitMonitorWorkspace({
|
export function GroupExitMonitorWorkspace({
|
||||||
dbReady,
|
dbReady,
|
||||||
@@ -354,6 +366,7 @@ export function GroupExitMonitorWorkspace({
|
|||||||
}, [contacts])
|
}, [contacts])
|
||||||
|
|
||||||
React.useEffect(() => {
|
React.useEffect(() => {
|
||||||
|
if (view !== 'events') return
|
||||||
const api = typeof window !== 'undefined' ? window.api : undefined
|
const api = typeof window !== 'undefined' ? window.api : undefined
|
||||||
if (!api || typeof api.getGroupExitMonitorState !== 'function') return
|
if (!api || typeof api.getGroupExitMonitorState !== 'function') return
|
||||||
let disposed = false
|
let disposed = false
|
||||||
@@ -372,7 +385,7 @@ export function GroupExitMonitorWorkspace({
|
|||||||
disposed = true
|
disposed = true
|
||||||
unsubscribe?.()
|
unsubscribe?.()
|
||||||
}
|
}
|
||||||
}, [])
|
}, [view])
|
||||||
|
|
||||||
React.useEffect(() => {
|
React.useEffect(() => {
|
||||||
const api = typeof window !== 'undefined' ? window.api : undefined
|
const api = typeof window !== 'undefined' ? window.api : undefined
|
||||||
@@ -536,7 +549,13 @@ export function GroupExitMonitorWorkspace({
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const saveGroups = async (): Promise<void> => {
|
/**
|
||||||
|
* 保存监控范围。
|
||||||
|
*
|
||||||
|
* `useCallback` 是给 `ManageGroups` 的 `memo` 用的:函数引用不稳定时,
|
||||||
|
* 每次状态推送都会让 200+ 行的列表跟着重渲染。
|
||||||
|
*/
|
||||||
|
const saveGroups = React.useCallback(async (): Promise<void> => {
|
||||||
const api = window.api
|
const api = window.api
|
||||||
if (saving || !dbReady || typeof api.setGroupExitMonitorGroups !== 'function') return
|
if (saving || !dbReady || typeof api.setGroupExitMonitorGroups !== 'function') return
|
||||||
setSaving(true)
|
setSaving(true)
|
||||||
@@ -554,7 +573,7 @@ export function GroupExitMonitorWorkspace({
|
|||||||
} finally {
|
} finally {
|
||||||
setSaving(false)
|
setSaving(false)
|
||||||
}
|
}
|
||||||
}
|
}, [dbReady, groups, saving, selectedManageRoomIds])
|
||||||
|
|
||||||
const setMonitorEnabled = async (enabled: boolean): Promise<void> => {
|
const setMonitorEnabled = async (enabled: boolean): Promise<void> => {
|
||||||
const api = window.api
|
const api = window.api
|
||||||
@@ -570,16 +589,16 @@ export function GroupExitMonitorWorkspace({
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const toggleManageGroup = (roomId: string): void => {
|
const toggleManageGroup = React.useCallback((roomId: string): void => {
|
||||||
setSelectedManageRoomIds((current) => {
|
setSelectedManageRoomIds((current) => {
|
||||||
const next = new Set(current)
|
const next = new Set(current)
|
||||||
if (next.has(roomId)) next.delete(roomId)
|
if (next.has(roomId)) next.delete(roomId)
|
||||||
else next.add(roomId)
|
else next.add(roomId)
|
||||||
return next
|
return next
|
||||||
})
|
})
|
||||||
}
|
}, [])
|
||||||
|
|
||||||
const toggleAllManageGroups = (): void => {
|
const toggleAllManageGroups = React.useCallback((): void => {
|
||||||
const allRoomIds = groups.map(contactRoomId)
|
const allRoomIds = groups.map(contactRoomId)
|
||||||
const shouldSelect = allRoomIds.some((roomId) => !selectedManageRoomIds.has(roomId))
|
const shouldSelect = allRoomIds.some((roomId) => !selectedManageRoomIds.has(roomId))
|
||||||
setSelectedManageRoomIds((current) => {
|
setSelectedManageRoomIds((current) => {
|
||||||
@@ -590,7 +609,10 @@ export function GroupExitMonitorWorkspace({
|
|||||||
})
|
})
|
||||||
return next
|
return next
|
||||||
})
|
})
|
||||||
}
|
}, [groups, selectedManageRoomIds])
|
||||||
|
|
||||||
|
/** 退出管理页返回事件列表。同样为了 `ManageGroups` 的 memo 保持稳定引用。 */
|
||||||
|
const cancelManage = React.useCallback((): void => setView('events'), [])
|
||||||
|
|
||||||
if (view === 'manage') {
|
if (view === 'manage') {
|
||||||
return (
|
return (
|
||||||
@@ -606,8 +628,8 @@ export function GroupExitMonitorWorkspace({
|
|||||||
onListFilterChange={setManageFilter}
|
onListFilterChange={setManageFilter}
|
||||||
onToggle={toggleManageGroup}
|
onToggle={toggleManageGroup}
|
||||||
onToggleAll={toggleAllManageGroups}
|
onToggleAll={toggleAllManageGroups}
|
||||||
onSave={() => void saveGroups()}
|
onSave={saveGroups}
|
||||||
onCancel={() => setView('events')}
|
onCancel={cancelManage}
|
||||||
/>
|
/>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
@@ -616,11 +638,11 @@ export function GroupExitMonitorWorkspace({
|
|||||||
? '数据库未连接'
|
? '数据库未连接'
|
||||||
: !state.enabled
|
: !state.enabled
|
||||||
? '监控已暂停'
|
? '监控已暂停'
|
||||||
: state.running && state.nativeMonitorActive
|
: state.running && state.nativeMonitorActive
|
||||||
? '实时监听已启用'
|
? '实时监听已启用'
|
||||||
: state.running
|
: state.running
|
||||||
? '已连接,等待原生监听'
|
? '已连接,等待原生监听'
|
||||||
: '等待启动'
|
: '等待启动'
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="exit-monitor-page">
|
<div className="exit-monitor-page">
|
||||||
|
|||||||
@@ -13,7 +13,12 @@ import {
|
|||||||
} from '../../components/ui'
|
} from '../../components/ui'
|
||||||
|
|
||||||
type StatusFilter = 'all' | WechatActionStatus
|
type StatusFilter = 'all' | WechatActionStatus
|
||||||
type PurposeFilter = 'all' | 'leave_notification' | 'scheduled_report' | 'other'
|
type PurposeFilter =
|
||||||
|
| 'all'
|
||||||
|
| 'leave_notification'
|
||||||
|
| 'scheduled_report'
|
||||||
|
| 'automation_report'
|
||||||
|
| 'other'
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 「退群通知」的发送用途。
|
* 「退群通知」的发送用途。
|
||||||
@@ -32,7 +37,10 @@ const LEAVE_NOTIFICATION_PURPOSES: readonly string[] = [
|
|||||||
const sourceLabel = (source: ActionLogEntry['source']): string => {
|
const sourceLabel = (source: ActionLogEntry['source']): string => {
|
||||||
if (source === 'member_monitor') return '退群监控'
|
if (source === 'member_monitor') return '退群监控'
|
||||||
if (source === 'scheduled_report') return '定时日报'
|
if (source === 'scheduled_report') return '定时日报'
|
||||||
|
// 消息型自动化「@我生成日报」发出的动作。少了这一条会直接显示英文原文 `automation`。
|
||||||
|
if (source === 'automation') return '自动化'
|
||||||
if (source === 'user_tts') return '文字转语音'
|
if (source === 'user_tts') return '文字转语音'
|
||||||
|
if (source === 'user_manual') return '手动发送'
|
||||||
if (source === 'unknown') return '未知来源'
|
if (source === 'unknown') return '未知来源'
|
||||||
return source || '未知来源'
|
return source || '未知来源'
|
||||||
}
|
}
|
||||||
@@ -40,9 +48,21 @@ const sourceLabel = (source: ActionLogEntry['source']): string => {
|
|||||||
const triggerLabel = (triggerType: ActionLogEntry['triggerType']): string =>
|
const triggerLabel = (triggerType: ActionLogEntry['triggerType']): string =>
|
||||||
triggerType === 'user' ? '用户触发' : '自动化'
|
triggerType === 'user' ? '用户触发' : '自动化'
|
||||||
|
|
||||||
|
/**
|
||||||
|
* purpose → 中文。
|
||||||
|
*
|
||||||
|
* **每一个有生产者的 purpose 都必须在这里有分支**:`WechatActionPurpose` 是字符串联合,
|
||||||
|
* 漏掉谁,那类记录就会顶着英文原文出现在列表里(筛选项里也找不到对应项)——
|
||||||
|
* 「@我生成日报」的发送记录此前就是这样被用户当成"压根没有"的。
|
||||||
|
* 未知值仍回落到原文,好让将来新增 purpose 时一眼能看出漏了映射。
|
||||||
|
*/
|
||||||
const purposeLabel = (purpose: WechatActionPurpose): string => {
|
const purposeLabel = (purpose: WechatActionPurpose): string => {
|
||||||
if (LEAVE_NOTIFICATION_PURPOSES.includes(purpose)) return '退群通知'
|
if (LEAVE_NOTIFICATION_PURPOSES.includes(purpose)) return '退群通知'
|
||||||
if (purpose === 'scheduled_report') return '定时日报'
|
if (purpose === 'scheduled_report') return '定时日报'
|
||||||
|
if (purpose === 'automation_report') return '生成日报(@我)'
|
||||||
|
if (purpose === 'automation_reply') return '回复确认(@我)'
|
||||||
|
if (purpose === 'manual_report_image') return '日报图片(手动发送)'
|
||||||
|
if (purpose === 'manual_report_postfix') return '日报后置词(手动发送)'
|
||||||
if (purpose === 'tts_voice') return '文字转语音'
|
if (purpose === 'tts_voice') return '文字转语音'
|
||||||
return purpose || '其它动作'
|
return purpose || '其它动作'
|
||||||
}
|
}
|
||||||
@@ -65,8 +85,11 @@ const statusDetails = (entry: ActionLogEntry): { label: string; className: strin
|
|||||||
const matchesPurpose = (entry: ActionLogEntry, filter: PurposeFilter): boolean => {
|
const matchesPurpose = (entry: ActionLogEntry, filter: PurposeFilter): boolean => {
|
||||||
if (filter === 'all') return true
|
if (filter === 'all') return true
|
||||||
if (filter === 'other') {
|
if (filter === 'other') {
|
||||||
|
// 「其它动作」= 剩下的。独立筛选项必须在这里排掉,否则同一条记录会同时出现在两组里。
|
||||||
return (
|
return (
|
||||||
!LEAVE_NOTIFICATION_PURPOSES.includes(entry.purpose) && entry.purpose !== 'scheduled_report'
|
!LEAVE_NOTIFICATION_PURPOSES.includes(entry.purpose) &&
|
||||||
|
entry.purpose !== 'scheduled_report' &&
|
||||||
|
entry.purpose !== 'automation_report'
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
if (filter === 'leave_notification') {
|
if (filter === 'leave_notification') {
|
||||||
@@ -154,6 +177,7 @@ export function LogsWorkspace(): React.ReactElement {
|
|||||||
<SelectItem value="all">全部类型</SelectItem>
|
<SelectItem value="all">全部类型</SelectItem>
|
||||||
<SelectItem value="leave_notification">退群通知</SelectItem>
|
<SelectItem value="leave_notification">退群通知</SelectItem>
|
||||||
<SelectItem value="scheduled_report">定时日报</SelectItem>
|
<SelectItem value="scheduled_report">定时日报</SelectItem>
|
||||||
|
<SelectItem value="automation_report">生成日报(@我)</SelectItem>
|
||||||
<SelectItem value="other">其它动作</SelectItem>
|
<SelectItem value="other">其它动作</SelectItem>
|
||||||
</SelectContent>
|
</SelectContent>
|
||||||
</Select>
|
</Select>
|
||||||
|
|||||||
@@ -4,11 +4,36 @@ function DiagnosticIcon({ status }: { status: DiagnosticStatus }): React.ReactEl
|
|||||||
if (status === 'checking') {
|
if (status === 'checking') {
|
||||||
return <span className="settings-diagnostic-icon checking" aria-label="检测中" />
|
return <span className="settings-diagnostic-icon checking" aria-label="检测中" />
|
||||||
}
|
}
|
||||||
const symbol =
|
|
||||||
status === 'success' ? '✓' : status === 'warning' ? '!' : status === 'error' ? '×' : '—'
|
const icon =
|
||||||
|
status === 'success' ? (
|
||||||
|
<path d="m5 12.5 4.5 4.5L19 7" />
|
||||||
|
) : status === 'warning' ? (
|
||||||
|
<>
|
||||||
|
<path d="M12 6v7" />
|
||||||
|
<circle cx="12" cy="17" r="1.5" fill="currentColor" stroke="none" />
|
||||||
|
</>
|
||||||
|
) : status === 'error' ? (
|
||||||
|
<path d="m7 7 10 10M17 7 7 17" />
|
||||||
|
) : (
|
||||||
|
<path d="M6 12h12" />
|
||||||
|
)
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<span className={`settings-diagnostic-icon ${status}`} aria-hidden="true">
|
<span className={`settings-diagnostic-icon ${status}`} aria-hidden="true">
|
||||||
{symbol}
|
<svg
|
||||||
|
viewBox="0 0 24 24"
|
||||||
|
width="12"
|
||||||
|
height="12"
|
||||||
|
fill="none"
|
||||||
|
stroke="currentColor"
|
||||||
|
strokeWidth="2.5"
|
||||||
|
strokeLinecap="round"
|
||||||
|
strokeLinejoin="round"
|
||||||
|
focusable="false"
|
||||||
|
>
|
||||||
|
{icon}
|
||||||
|
</svg>
|
||||||
</span>
|
</span>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -25,8 +25,11 @@ export function DatabaseKeyAutoDetect({
|
|||||||
const environment = state.environment
|
const environment = state.environment
|
||||||
const platform = environment?.platform || runtimePlatform
|
const platform = environment?.platform || runtimePlatform
|
||||||
const isMac = platform === 'darwin'
|
const isMac = platform === 'darwin'
|
||||||
const isIntelMac = platform === 'darwin' && environment?.architecture === 'x64'
|
// 与连接页同源:读主进程给出的 macKeyFlow,不在这里重新推断硬件。
|
||||||
const isAppleSiliconMac = isMac && !isIntelMac
|
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 supported = environment?.autoDetectSupported ?? (platform === 'win32' || isMac)
|
||||||
const phases = isAppleSiliconMac ? MAC_LOGIN_PHASES : DEFAULT_PHASES
|
const phases = isAppleSiliconMac ? MAC_LOGIN_PHASES : DEFAULT_PHASES
|
||||||
if (!supported) {
|
if (!supported) {
|
||||||
@@ -41,20 +44,43 @@ export function DatabaseKeyAutoDetect({
|
|||||||
}
|
}
|
||||||
return (
|
return (
|
||||||
<section className="settings-card database-key-auto">
|
<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 className="database-key-auto-heading">
|
||||||
<div>
|
<div>
|
||||||
<strong>
|
<strong>
|
||||||
{isIntelMac ? 'Intel Mac 自动获取' : isMac ? 'macOS 自动获取' : 'Windows 自动获取'}
|
{isArchMismatch
|
||||||
|
? '架构不匹配'
|
||||||
|
: isIntelMac
|
||||||
|
? 'Intel Mac 自动获取'
|
||||||
|
: isMac
|
||||||
|
? 'macOS 自动获取'
|
||||||
|
: 'Windows 自动获取'}
|
||||||
</strong>
|
</strong>
|
||||||
<p>
|
<p>
|
||||||
{isIntelMac
|
{isArchMismatch
|
||||||
? '请让微信停在未登录界面,按页面提示操作即可。'
|
? '当前应用的运行架构与这台 Mac 的芯片不匹配,自动获取已停用。'
|
||||||
: isAppleSiliconMac
|
: isIntelMac
|
||||||
? '执行时会请求管理员授权;授权后在微信登录界面点击“登录”即可,已有登录凭据时通常不需要扫码。监听最长两分钟,结束后会明确显示结果。'
|
? '请让微信停在未登录界面,按页面提示操作即可。'
|
||||||
: 'TraceMemo 可在微信桌面端正在运行时,通过本机内存扫描尝试获取数据库密钥。'}
|
: isAppleSiliconMac
|
||||||
|
? '执行时会请求管理员授权;授权后在微信登录界面点击“登录”即可,已有登录凭据时通常不需要扫码。监听最长两分钟,结束后会明确显示结果。'
|
||||||
|
: 'TraceMemo 可在微信桌面端正在运行时,通过本机内存扫描尝试获取数据库密钥。'}
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
<Button variant="outline" onClick={onDetect} disabled={disabled}>
|
<Button
|
||||||
|
variant="outline"
|
||||||
|
onClick={onDetect}
|
||||||
|
disabled={disabled || isArchMismatch}
|
||||||
|
>
|
||||||
{state.status === 'auto-detecting' ? '正在获取…' : '自动获取密钥'}
|
{state.status === 'auto-detecting' ? '正在获取…' : '自动获取密钥'}
|
||||||
</Button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import { useMemo, useState } from 'react'
|
import { useEffect, useMemo, useState } from 'react'
|
||||||
import { Button, Progress } from '../../../components/ui'
|
import { Button, Progress } from '../../../components/ui'
|
||||||
import { useAppUpdateState } from '../../app-update/useAppUpdateState'
|
import { useAppUpdateState } from '../../app-update/useAppUpdateState'
|
||||||
|
|
||||||
@@ -19,6 +19,30 @@ export function AboutPage({
|
|||||||
}): React.ReactElement {
|
}): React.ReactElement {
|
||||||
const update = useAppUpdateState()
|
const update = useAppUpdateState()
|
||||||
const [busy, setBusy] = useState(false)
|
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(() => {
|
const action = useMemo(() => {
|
||||||
if (update.status === 'available') {
|
if (update.status === 'available') {
|
||||||
@@ -153,6 +177,20 @@ export function AboutPage({
|
|||||||
</div>
|
</div>
|
||||||
</section>
|
</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>
|
<h2 className="settings-section-heading">支持</h2>
|
||||||
<section className="settings-card about-links-card">
|
<section className="settings-card about-links-card">
|
||||||
<a href={RELEASES_URL} target="_blank" rel="noreferrer">
|
<a href={RELEASES_URL} target="_blank" rel="noreferrer">
|
||||||
|
|||||||
@@ -2,6 +2,8 @@ import { useEffect, useState } from 'react'
|
|||||||
import { RadioGroup, RadioGroupItem, Switch } from '../../../components/ui'
|
import { RadioGroup, RadioGroupItem, Switch } from '../../../components/ui'
|
||||||
|
|
||||||
export type AppearanceTheme = 'system' | 'light' | 'dark'
|
export type AppearanceTheme = 'system' | 'light' | 'dark'
|
||||||
|
/** 关闭主窗口时的行为。与主进程 settings-store 的 `CloseAction` 保持一致。 */
|
||||||
|
export type CloseAction = 'ask' | 'tray' | 'quit'
|
||||||
|
|
||||||
export function AppearancePage({
|
export function AppearancePage({
|
||||||
onNotice,
|
onNotice,
|
||||||
@@ -13,6 +15,7 @@ export function AppearancePage({
|
|||||||
const [theme, setTheme] = useState<AppearanceTheme>('system')
|
const [theme, setTheme] = useState<AppearanceTheme>('system')
|
||||||
const [compactMode, setCompactMode] = useState(false)
|
const [compactMode, setCompactMode] = useState(false)
|
||||||
const [showStartupProgress, setShowStartupProgress] = useState(true)
|
const [showStartupProgress, setShowStartupProgress] = useState(true)
|
||||||
|
const [closeAction, setCloseAction] = useState<CloseAction>('ask')
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
let active = true
|
let active = true
|
||||||
@@ -21,6 +24,7 @@ export function AppearancePage({
|
|||||||
setTheme(result.settings.appearanceTheme)
|
setTheme(result.settings.appearanceTheme)
|
||||||
setCompactMode(result.settings.compactMode)
|
setCompactMode(result.settings.compactMode)
|
||||||
setShowStartupProgress(result.settings.showStartupProgress)
|
setShowStartupProgress(result.settings.showStartupProgress)
|
||||||
|
setCloseAction(result.settings.closeAction)
|
||||||
onAppearanceChange({
|
onAppearanceChange({
|
||||||
theme: result.settings.appearanceTheme,
|
theme: result.settings.appearanceTheme,
|
||||||
compactMode: result.settings.compactMode
|
compactMode: result.settings.compactMode
|
||||||
@@ -35,11 +39,13 @@ export function AppearancePage({
|
|||||||
appearanceTheme?: AppearanceTheme
|
appearanceTheme?: AppearanceTheme
|
||||||
compactMode?: boolean
|
compactMode?: boolean
|
||||||
showStartupProgress?: boolean
|
showStartupProgress?: boolean
|
||||||
|
closeAction?: CloseAction
|
||||||
}): Promise<void> => {
|
}): Promise<void> => {
|
||||||
const result = await window.api.setSettings(patch)
|
const result = await window.api.setSettings(patch)
|
||||||
setTheme(result.settings.appearanceTheme)
|
setTheme(result.settings.appearanceTheme)
|
||||||
setCompactMode(result.settings.compactMode)
|
setCompactMode(result.settings.compactMode)
|
||||||
setShowStartupProgress(result.settings.showStartupProgress)
|
setShowStartupProgress(result.settings.showStartupProgress)
|
||||||
|
setCloseAction(result.settings.closeAction)
|
||||||
onAppearanceChange({
|
onAppearanceChange({
|
||||||
theme: result.settings.appearanceTheme,
|
theme: result.settings.appearanceTheme,
|
||||||
compactMode: result.settings.compactMode
|
compactMode: result.settings.compactMode
|
||||||
@@ -118,6 +124,45 @@ export function AppearancePage({
|
|||||||
/>
|
/>
|
||||||
</label>
|
</label>
|
||||||
</section>
|
</section>
|
||||||
|
|
||||||
|
<h2 className="settings-section-heading">关闭窗口时</h2>
|
||||||
|
<section className="settings-card settings-option-card">
|
||||||
|
<RadioGroup
|
||||||
|
className="settings-choice-grid"
|
||||||
|
value={closeAction}
|
||||||
|
onValueChange={(value) => {
|
||||||
|
if (value === 'ask' || value === 'tray' || value === 'quit')
|
||||||
|
void save({ closeAction: value })
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{(
|
||||||
|
[
|
||||||
|
['ask', '每次询问', '每次关闭窗口都弹出选择框'],
|
||||||
|
['tray', '最小化到托盘', '窗口隐藏,应用继续在后台运行'],
|
||||||
|
['quit', '退出应用', '直接结束整个 TraceMemo 进程']
|
||||||
|
] as const
|
||||||
|
).map(([value, label, hint]) => (
|
||||||
|
<label
|
||||||
|
className={`settings-choice ${closeAction === value ? 'active' : ''}`}
|
||||||
|
key={value}
|
||||||
|
htmlFor={`appearance-close-${value}`}
|
||||||
|
>
|
||||||
|
<RadioGroupItem
|
||||||
|
id={`appearance-close-${value}`}
|
||||||
|
value={value}
|
||||||
|
className="mt-0.5"
|
||||||
|
/>
|
||||||
|
<span>
|
||||||
|
<b>{label}</b>
|
||||||
|
<small>{hint}</small>
|
||||||
|
</span>
|
||||||
|
</label>
|
||||||
|
))}
|
||||||
|
</RadioGroup>
|
||||||
|
<p className="settings-option-hint">
|
||||||
|
选择「每次询问」时,关闭弹窗里勾选「记住我的选择」会自动切换到这里对应的项。
|
||||||
|
</p>
|
||||||
|
</section>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -1,9 +1,27 @@
|
|||||||
import { useCallback, useEffect, useState, type ReactElement } from 'react'
|
import { useCallback, useEffect, useRef, useState, type ReactElement } from 'react'
|
||||||
import type {
|
import type {
|
||||||
PersonalWechatSendCapability,
|
PersonalWechatSendCapability,
|
||||||
PersonalWechatSenderStatus
|
PersonalWechatSenderStatus
|
||||||
} from '../../../../../shared/personal-wechat'
|
} 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 { PersonalWechatSetupGuide } from '../../../components/chat/PersonalWechatSetupGuide'
|
||||||
import { isMac, isWindows } from '../../../utils/runtime-environment'
|
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
|
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 {
|
function boundToCurrentWechat(status: PersonalWechatSenderStatus | null): boolean {
|
||||||
if (!status) return false
|
if (!status) return false
|
||||||
return (
|
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({
|
export function PersonalWechatSendPage({
|
||||||
onNotice,
|
onNotice,
|
||||||
onOpenTextToSpeechSettings
|
onOpenTextToSpeechSettings
|
||||||
@@ -79,6 +308,37 @@ export function PersonalWechatSendPage({
|
|||||||
const [windowsPortInput, setWindowsPortInput] = useState('')
|
const [windowsPortInput, setWindowsPortInput] = useState('')
|
||||||
const [windowsDetectedPort, setWindowsDetectedPort] = useState('')
|
const [windowsDetectedPort, setWindowsDetectedPort] = useState('')
|
||||||
const [windowsEndpointBusy, setWindowsEndpointBusy] = useState(false)
|
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> => {
|
const refresh = useCallback(async (): Promise<void> => {
|
||||||
if (isWindows) {
|
if (isWindows) {
|
||||||
setLoading(false)
|
setLoading(false)
|
||||||
@@ -101,9 +361,68 @@ export function PersonalWechatSendPage({
|
|||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (isWindows) return
|
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])
|
}, [refresh])
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!isMac) return undefined
|
||||||
|
void refreshMac4290PortStatus()
|
||||||
|
const timer = window.setInterval(() => void refreshMac4290PortStatus(), 5_000)
|
||||||
|
return () => window.clearInterval(timer)
|
||||||
|
}, [refreshMac4290PortStatus])
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (isWindows || !senderStatus || senderStatus.canSend || senderStatus.state === 'error') {
|
if (isWindows || !senderStatus || senderStatus.canSend || senderStatus.state === 'error') {
|
||||||
return undefined
|
return undefined
|
||||||
@@ -148,6 +467,9 @@ export function PersonalWechatSendPage({
|
|||||||
try {
|
try {
|
||||||
const nextStatus = await window.api.rebindPersonalWechatSender()
|
const nextStatus = await window.api.rebindPersonalWechatSender()
|
||||||
setSenderStatus(nextStatus)
|
setSenderStatus(nextStatus)
|
||||||
|
if (boundToCurrentWechat(nextStatus)) {
|
||||||
|
setMacWechatRebindRequired(false)
|
||||||
|
}
|
||||||
const nextCapability = await window.api.getPersonalWechatSendCapability()
|
const nextCapability = await window.api.getPersonalWechatSendCapability()
|
||||||
setCapability(nextCapability)
|
setCapability(nextCapability)
|
||||||
if (nextStatus.state === 'error' && nextStatus.message) setError(nextStatus.message)
|
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 normalizedWindowsPort = normalizeWindowsPort(windowsPortInput)
|
||||||
const windowsCanSave = Boolean(
|
const windowsCanSave = Boolean(
|
||||||
normalizedWindowsPort &&
|
normalizedWindowsPort &&
|
||||||
@@ -266,7 +681,28 @@ export function PersonalWechatSendPage({
|
|||||||
const pageMessage = isWindows
|
const pageMessage = isWindows
|
||||||
? windowsSenderStatus?.message || '请输入端口并检测 Windows 微信发送能力'
|
? windowsSenderStatus?.message || '请输入端口并检测 Windows 微信发送能力'
|
||||||
: capability?.message || '微信发送能力暂不可用'
|
: 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 (
|
return (
|
||||||
<>
|
<>
|
||||||
@@ -279,7 +715,13 @@ export function PersonalWechatSendPage({
|
|||||||
<span
|
<span
|
||||||
className={`settings-status-badge ${loading ? 'checking' : pageReady ? '' : pageStatus === 'unsupported' ? 'unavailable' : 'warning'}`}
|
className={`settings-status-badge ${loading ? 'checking' : pageReady ? '' : pageStatus === 'unsupported' ? 'unavailable' : 'warning'}`}
|
||||||
>
|
>
|
||||||
{loading ? '检测中' : macUnavailable ? '暂不可用' : capabilityLabel[pageStatus]}
|
{loading
|
||||||
|
? '检测中'
|
||||||
|
: macUnavailable
|
||||||
|
? '没有微信发送能力'
|
||||||
|
: macComponentError
|
||||||
|
? '发送组件异常'
|
||||||
|
: capabilityLabel[pageStatus]}
|
||||||
</span>
|
</span>
|
||||||
</header>
|
</header>
|
||||||
<div className="settings-page-scroll">
|
<div className="settings-page-scroll">
|
||||||
@@ -407,18 +849,194 @@ export function PersonalWechatSendPage({
|
|||||||
</>
|
</>
|
||||||
) : isMac ? (
|
) : isMac ? (
|
||||||
<>
|
<>
|
||||||
<h2 className="settings-section-heading">配置状态</h2>
|
{/* 发送能力授权卡片:仅在加载了发送组件的档位渲染。
|
||||||
<PersonalWechatSetupGuide
|
OSS(runtime_missing)下不渲染,保证免费版不出现授权入口。 */}
|
||||||
senderStatus={senderStatus}
|
{macRuntimeAvailability?.state === 'available' ? (
|
||||||
binding={binding}
|
<MacNativeLicenseCard
|
||||||
detecting={detecting}
|
onNotice={onNotice}
|
||||||
sessionBound={boundToCurrentWechat(senderStatus)}
|
onStatusChange={setMacLicenseStatus}
|
||||||
onBind={() => void bindWechat()}
|
/>
|
||||||
onStartSending={() =>
|
) : null}
|
||||||
onNotice('微信消息发送能力已就绪,请在档案中选择会话开始发送。')
|
<section
|
||||||
}
|
className="settings-card mac-wechat-environment-card"
|
||||||
onOpenTextToSpeechSettings={onOpenTextToSpeechSettings}
|
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}
|
) : null}
|
||||||
</>
|
</>
|
||||||
@@ -426,6 +1044,43 @@ export function PersonalWechatSendPage({
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</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>
|
||||||
</>
|
</>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
@@ -42,6 +42,74 @@
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* 右上角操作区:微信消息插入开关 + 新建自动化 */
|
||||||
|
.automation-page-header-actions {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 18px;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
padding-top: 6px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.automation-msg-insert-switches {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 16px;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
}
|
||||||
|
|
||||||
|
.automation-msg-insert-switch {
|
||||||
|
display: inline-flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 8px;
|
||||||
|
font-size: 12px;
|
||||||
|
line-height: 20px;
|
||||||
|
color: var(--wxex-text-secondary);
|
||||||
|
/* 容器本身不可点(点了不切换),所以不要给 pointer 光标误导用户。 */
|
||||||
|
cursor: default;
|
||||||
|
user-select: none;
|
||||||
|
|
||||||
|
&.is-disabled {
|
||||||
|
opacity: 0.5;
|
||||||
|
cursor: not-allowed;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.automation-msg-insert-switch-label {
|
||||||
|
white-space: nowrap;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* 处理中:把「正在写微信库」这件事显式说出来,避免用户以为界面卡死。
|
||||||
|
宽度不锁死会带着开关一起抖,所以这里只用固定行高、不加弹性布局。 */
|
||||||
|
.automation-msg-insert-switch-busy {
|
||||||
|
display: inline-flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 4px;
|
||||||
|
white-space: nowrap;
|
||||||
|
color: var(--wxex-accent, var(--wxex-text-secondary));
|
||||||
|
}
|
||||||
|
|
||||||
|
/* 中性提示:既不表示失败,也不参与「是否生效」判定 → 不用警告色。 */
|
||||||
|
.automation-msg-insert-switch-scope {
|
||||||
|
white-space: nowrap;
|
||||||
|
font-variant-numeric: tabular-nums;
|
||||||
|
color: var(--wxex-text-tertiary, var(--wxex-text-secondary));
|
||||||
|
opacity: 0.7;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* 覆盖情况(已就绪 / 可安装)。规则没装齐时给出可读的警示,而不是只留一个 ON。 */
|
||||||
|
.automation-msg-insert-switch-count {
|
||||||
|
white-space: nowrap;
|
||||||
|
font-variant-numeric: tabular-nums;
|
||||||
|
color: var(--wxex-text-tertiary, var(--wxex-text-secondary));
|
||||||
|
opacity: 0.85;
|
||||||
|
|
||||||
|
&.is-warning {
|
||||||
|
color: var(--wxex-warning, #d97706);
|
||||||
|
opacity: 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
.automation-notice {
|
.automation-notice {
|
||||||
margin: 0;
|
margin: 0;
|
||||||
padding: 10px 14px;
|
padding: 10px 14px;
|
||||||
|
|||||||
@@ -1739,8 +1739,11 @@
|
|||||||
}
|
}
|
||||||
|
|
||||||
.quoted-sender {
|
.quoted-sender {
|
||||||
flex: 0 1 auto;
|
// 名字优先:两个 flex 项都按比例收缩时,长引用会把名字压成半个字(只剩一个冒号),
|
||||||
|
// 所以名字固定不参与收缩,只用 max-width 限制它最多占六成,剩下的留给正文。
|
||||||
|
flex: 0 0 auto;
|
||||||
min-width: 0;
|
min-width: 0;
|
||||||
|
max-width: 60%;
|
||||||
font-weight: 600;
|
font-weight: 600;
|
||||||
overflow: hidden;
|
overflow: hidden;
|
||||||
text-overflow: ellipsis;
|
text-overflow: ellipsis;
|
||||||
@@ -1752,7 +1755,12 @@
|
|||||||
}
|
}
|
||||||
|
|
||||||
.quoted-text {
|
.quoted-text {
|
||||||
flex: 0 0 auto;
|
// 收缩全部落在正文上(名字已固定),单行省略;全文由引用框的 title 兜底。
|
||||||
|
flex: 0 1 auto;
|
||||||
|
min-width: 0;
|
||||||
|
overflow: hidden;
|
||||||
|
text-overflow: ellipsis;
|
||||||
|
white-space: nowrap;
|
||||||
}
|
}
|
||||||
|
|
||||||
.quote-reply {
|
.quote-reply {
|
||||||
@@ -2150,6 +2158,36 @@
|
|||||||
word-break: break-word;
|
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 {
|
.database-login-diagnostics {
|
||||||
margin: 0;
|
margin: 0;
|
||||||
border-top: 1px solid #e2e7e4;
|
border-top: 1px solid #e2e7e4;
|
||||||
|
|||||||
@@ -546,6 +546,13 @@
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.settings-option-hint {
|
||||||
|
margin: 12px 0 0;
|
||||||
|
color: var(--wxex-text-muted);
|
||||||
|
font-size: 10px;
|
||||||
|
line-height: 15px;
|
||||||
|
}
|
||||||
|
|
||||||
.settings-toggle-list {
|
.settings-toggle-list {
|
||||||
display: grid;
|
display: grid;
|
||||||
gap: 0;
|
gap: 0;
|
||||||
|
|||||||
@@ -249,6 +249,248 @@
|
|||||||
background: var(--wxex-bg-elevated);
|
background: var(--wxex-bg-elevated);
|
||||||
padding: 24px 26px;
|
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 {
|
.settings-account-overview {
|
||||||
display: grid;
|
display: grid;
|
||||||
grid-template-columns: minmax(190px, 1fr) minmax(220px, 1fr) auto;
|
grid-template-columns: minmax(190px, 1fr) minmax(220px, 1fr) auto;
|
||||||
@@ -416,8 +658,9 @@
|
|||||||
border: 1px solid #929a96;
|
border: 1px solid #929a96;
|
||||||
border-radius: 50%;
|
border-radius: 50%;
|
||||||
color: #929a96;
|
color: #929a96;
|
||||||
font-size: 11px;
|
}
|
||||||
font-weight: 700;
|
.settings-diagnostic-icon svg {
|
||||||
|
display: block;
|
||||||
}
|
}
|
||||||
.settings-diagnostic-icon.success {
|
.settings-diagnostic-icon.success {
|
||||||
border-color: #2e8b68;
|
border-color: #2e8b68;
|
||||||
|
|||||||
@@ -0,0 +1,445 @@
|
|||||||
|
import {
|
||||||
|
AUTOMATION_REPLY_DELAY_MAX_SECONDS,
|
||||||
|
SCHEDULED_REPORT_MAX_TIMEOUT_SECONDS,
|
||||||
|
SCHEDULED_REPORT_MIN_TIMEOUT_SECONDS,
|
||||||
|
SCHEDULED_REPORT_POSTFIX_MAX_LENGTH,
|
||||||
|
normalizeRuleDraft,
|
||||||
|
type AutomationRuleDraft,
|
||||||
|
type AutomationRuleType
|
||||||
|
} from '../automation'
|
||||||
|
import { validateGroupExitNotificationTemplate } from '../group-exit-monitor'
|
||||||
|
import { isSelectableReportTemplateId } from '../report-templates'
|
||||||
|
import {
|
||||||
|
type ScheduledReportMemberNameMode,
|
||||||
|
type ScheduledReportMessageType,
|
||||||
|
type ScheduledReportRange
|
||||||
|
} from '../scheduled-report'
|
||||||
|
import type { AgentAutomationValidationIssue } from './contracts'
|
||||||
|
|
||||||
|
type JsonRecord = Record<string, unknown>
|
||||||
|
|
||||||
|
const RULE_TYPES: AutomationRuleType[] = ['daily_report', 'scheduled_report', 'leave_notification']
|
||||||
|
const SCOPES = ['group', 'direct', 'all'] as const
|
||||||
|
const KEYWORD_MODES = ['contains', 'exact', 'prefix'] as const
|
||||||
|
const ACTION_TYPES = ['replyText', 'generateReport', 'sendReportImage'] as const
|
||||||
|
const SCHEDULE_RANGES: ScheduledReportRange[] = ['today', 'yesterday', '7days', 'recent24h']
|
||||||
|
const MESSAGE_TYPES: ScheduledReportMessageType[] = [
|
||||||
|
'text',
|
||||||
|
'image',
|
||||||
|
'sticker',
|
||||||
|
'video',
|
||||||
|
'voice',
|
||||||
|
'share',
|
||||||
|
'system'
|
||||||
|
]
|
||||||
|
const MEMBER_NAME_MODES: ScheduledReportMemberNameMode[] = [
|
||||||
|
'groupNickname',
|
||||||
|
'wechatNickname',
|
||||||
|
'remark'
|
||||||
|
]
|
||||||
|
const TARGET_TYPES = ['source_chat', 'self', 'file_transfer', 'contact'] as const
|
||||||
|
|
||||||
|
function asRecord(value: unknown): JsonRecord | undefined {
|
||||||
|
return value !== null && typeof value === 'object' && !Array.isArray(value)
|
||||||
|
? (value as JsonRecord)
|
||||||
|
: undefined
|
||||||
|
}
|
||||||
|
|
||||||
|
function addIssue(
|
||||||
|
issues: AgentAutomationValidationIssue[],
|
||||||
|
path: string,
|
||||||
|
code: string,
|
||||||
|
message: string
|
||||||
|
): void {
|
||||||
|
issues.push({ path, code, message })
|
||||||
|
}
|
||||||
|
|
||||||
|
function checkObject(
|
||||||
|
value: unknown,
|
||||||
|
path: string,
|
||||||
|
allowedKeys: readonly string[],
|
||||||
|
issues: AgentAutomationValidationIssue[]
|
||||||
|
): JsonRecord | undefined {
|
||||||
|
const record = asRecord(value)
|
||||||
|
if (!record) {
|
||||||
|
addIssue(issues, path, 'invalid_type', '必须是 JSON 对象')
|
||||||
|
return undefined
|
||||||
|
}
|
||||||
|
for (const key of Object.keys(record)) {
|
||||||
|
if (!allowedKeys.includes(key)) {
|
||||||
|
addIssue(issues, `${path}.${key}`, 'unknown_field', '不支持此字段')
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return record
|
||||||
|
}
|
||||||
|
|
||||||
|
function checkString(
|
||||||
|
value: unknown,
|
||||||
|
path: string,
|
||||||
|
issues: AgentAutomationValidationIssue[],
|
||||||
|
options: { required?: boolean; max?: number; allowEmpty?: boolean } = {}
|
||||||
|
): value is string {
|
||||||
|
if (typeof value !== 'string') {
|
||||||
|
if (options.required || value !== undefined) {
|
||||||
|
addIssue(issues, path, 'invalid_type', '必须是字符串')
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
const trimmed = value.trim()
|
||||||
|
if (options.required && !trimmed) addIssue(issues, path, 'required', '不能为空')
|
||||||
|
if (!options.allowEmpty && !options.required && value.length > 0 && !trimmed) {
|
||||||
|
addIssue(issues, path, 'invalid_value', '不能只包含空白字符')
|
||||||
|
}
|
||||||
|
if (options.max !== undefined && value.length > options.max) {
|
||||||
|
addIssue(issues, path, 'too_long', `最多 ${options.max} 个字符`)
|
||||||
|
}
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
function checkBoolean(
|
||||||
|
value: unknown,
|
||||||
|
path: string,
|
||||||
|
issues: AgentAutomationValidationIssue[],
|
||||||
|
required = false
|
||||||
|
): void {
|
||||||
|
if (value === undefined && !required) return
|
||||||
|
if (typeof value !== 'boolean') addIssue(issues, path, 'invalid_type', '必须是布尔值')
|
||||||
|
}
|
||||||
|
|
||||||
|
function checkInteger(
|
||||||
|
value: unknown,
|
||||||
|
path: string,
|
||||||
|
issues: AgentAutomationValidationIssue[],
|
||||||
|
min: number,
|
||||||
|
max: number,
|
||||||
|
required = false
|
||||||
|
): void {
|
||||||
|
if (value === undefined && !required) return
|
||||||
|
if (!Number.isInteger(value) || Number(value) < min || Number(value) > max) {
|
||||||
|
addIssue(issues, path, 'out_of_range', `必须是 ${min} 到 ${max} 之间的整数`)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function checkEnum(
|
||||||
|
value: unknown,
|
||||||
|
path: string,
|
||||||
|
values: readonly string[],
|
||||||
|
issues: AgentAutomationValidationIssue[],
|
||||||
|
required = false
|
||||||
|
): void {
|
||||||
|
if (value === undefined && !required) return
|
||||||
|
if (typeof value !== 'string' || !values.includes(value)) {
|
||||||
|
addIssue(issues, path, 'invalid_enum', `仅支持:${values.join(', ')}`)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function validateDailyReport(raw: JsonRecord, issues: AgentAutomationValidationIssue[]): void {
|
||||||
|
const conditions = checkObject(
|
||||||
|
raw.conditions,
|
||||||
|
'conditions',
|
||||||
|
['requireMentionMe', 'keyword', 'keywordMatchMode', 'conversationIds', 'ignoreSelf'],
|
||||||
|
issues
|
||||||
|
)
|
||||||
|
if (conditions) {
|
||||||
|
checkBoolean(conditions.requireMentionMe, 'conditions.requireMentionMe', issues, true)
|
||||||
|
checkBoolean(conditions.ignoreSelf, 'conditions.ignoreSelf', issues, true)
|
||||||
|
if (conditions.keyword === undefined) {
|
||||||
|
addIssue(issues, 'conditions.keyword', 'required', '必须是字符串')
|
||||||
|
} else {
|
||||||
|
checkString(conditions.keyword, 'conditions.keyword', issues, { max: 200, allowEmpty: true })
|
||||||
|
}
|
||||||
|
checkEnum(
|
||||||
|
conditions.keywordMatchMode,
|
||||||
|
'conditions.keywordMatchMode',
|
||||||
|
KEYWORD_MODES,
|
||||||
|
issues,
|
||||||
|
true
|
||||||
|
)
|
||||||
|
if (!Array.isArray(conditions.conversationIds)) {
|
||||||
|
addIssue(issues, 'conditions.conversationIds', 'invalid_type', '必须是 ID 数组')
|
||||||
|
} else {
|
||||||
|
if (conditions.conversationIds.length > 100) {
|
||||||
|
addIssue(issues, 'conditions.conversationIds', 'too_many_items', '最多支持 100 个会话')
|
||||||
|
}
|
||||||
|
conditions.conversationIds.forEach((id, index) =>
|
||||||
|
checkString(id, `conditions.conversationIds[${index}]`, issues, {
|
||||||
|
required: true,
|
||||||
|
max: 300
|
||||||
|
})
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!Array.isArray(raw.actions)) {
|
||||||
|
addIssue(issues, 'actions', 'invalid_type', '必须是动作数组')
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if (raw.actions.length > 3) addIssue(issues, 'actions', 'too_many_items', '最多支持 3 个动作')
|
||||||
|
const seen = new Set<string>()
|
||||||
|
raw.actions.forEach((actionValue, index) => {
|
||||||
|
const path = `actions[${index}]`
|
||||||
|
const action = checkObject(actionValue, path, ['type', 'enabled', 'text'], issues)
|
||||||
|
if (!action) return
|
||||||
|
checkEnum(action.type, `${path}.type`, ACTION_TYPES, issues, true)
|
||||||
|
checkBoolean(action.enabled, `${path}.enabled`, issues, true)
|
||||||
|
if (typeof action.type === 'string') {
|
||||||
|
if (seen.has(action.type))
|
||||||
|
addIssue(issues, `${path}.type`, 'duplicate_action', '动作不能重复')
|
||||||
|
seen.add(action.type)
|
||||||
|
if (action.type === 'replyText') {
|
||||||
|
checkString(action.text, `${path}.text`, issues, {
|
||||||
|
required: action.enabled === true,
|
||||||
|
max: 2_000,
|
||||||
|
allowEmpty: action.enabled !== true
|
||||||
|
})
|
||||||
|
} else if (action.text !== undefined) {
|
||||||
|
addIssue(issues, `${path}.text`, 'unknown_field', '此动作不支持 text')
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
function validateTarget(
|
||||||
|
value: unknown,
|
||||||
|
path: string,
|
||||||
|
issues: AgentAutomationValidationIssue[]
|
||||||
|
): void {
|
||||||
|
const target = checkObject(value, path, ['type', 'contactId'], issues)
|
||||||
|
if (!target) return
|
||||||
|
checkEnum(target.type, `${path}.type`, TARGET_TYPES, issues, true)
|
||||||
|
if (target.type === 'contact') {
|
||||||
|
checkString(target.contactId, `${path}.contactId`, issues, { required: true, max: 300 })
|
||||||
|
} else if (target.contactId !== undefined) {
|
||||||
|
addIssue(issues, `${path}.contactId`, 'unexpected_field', '仅 contact 目标可设置 contactId')
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function validateScheduledReport(raw: JsonRecord, issues: AgentAutomationValidationIssue[]): void {
|
||||||
|
checkBoolean(raw.targetNeedsReview, 'scheduledReport.targetNeedsReview', issues)
|
||||||
|
if (raw.targetNeedsReview === true) {
|
||||||
|
addIssue(
|
||||||
|
issues,
|
||||||
|
'scheduledReport.targetNeedsReview',
|
||||||
|
'target_needs_review',
|
||||||
|
'发送目标需要在 TraceMemo 中重新确认'
|
||||||
|
)
|
||||||
|
}
|
||||||
|
if (raw.postfixText !== undefined) {
|
||||||
|
checkString(raw.postfixText, 'scheduledReport.postfixText', issues, {
|
||||||
|
max: SCHEDULED_REPORT_POSTFIX_MAX_LENGTH,
|
||||||
|
allowEmpty: true
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
const schedule = checkObject(raw.schedule, 'scheduledReport.schedule', ['time'], issues)
|
||||||
|
if (schedule) {
|
||||||
|
if (typeof schedule.time !== 'string' || !/^(?:[01]\d|2[0-3]):[0-5]\d$/.test(schedule.time)) {
|
||||||
|
addIssue(issues, 'scheduledReport.schedule.time', 'invalid_time', '时间必须使用 HH:mm 格式')
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const report = checkObject(
|
||||||
|
raw.report,
|
||||||
|
'scheduledReport.report',
|
||||||
|
[
|
||||||
|
'sourceConversationId',
|
||||||
|
'range',
|
||||||
|
'messageTypes',
|
||||||
|
'templateId',
|
||||||
|
'memberNameMode',
|
||||||
|
'timeoutSeconds'
|
||||||
|
],
|
||||||
|
issues
|
||||||
|
)
|
||||||
|
if (report) {
|
||||||
|
checkString(
|
||||||
|
report.sourceConversationId,
|
||||||
|
'scheduledReport.report.sourceConversationId',
|
||||||
|
issues,
|
||||||
|
{
|
||||||
|
required: true,
|
||||||
|
max: 300
|
||||||
|
}
|
||||||
|
)
|
||||||
|
checkEnum(report.range, 'scheduledReport.report.range', SCHEDULE_RANGES, issues, true)
|
||||||
|
if (!Array.isArray(report.messageTypes) || report.messageTypes.length === 0) {
|
||||||
|
addIssue(issues, 'scheduledReport.report.messageTypes', 'required', '至少选择一种消息类型')
|
||||||
|
} else {
|
||||||
|
report.messageTypes.forEach((type, index) =>
|
||||||
|
checkEnum(
|
||||||
|
type,
|
||||||
|
`scheduledReport.report.messageTypes[${index}]`,
|
||||||
|
MESSAGE_TYPES,
|
||||||
|
issues,
|
||||||
|
true
|
||||||
|
)
|
||||||
|
)
|
||||||
|
}
|
||||||
|
if (!isSelectableReportTemplateId(report.templateId)) {
|
||||||
|
addIssue(issues, 'scheduledReport.report.templateId', 'invalid_template', '模板 ID 不受支持')
|
||||||
|
}
|
||||||
|
checkEnum(
|
||||||
|
report.memberNameMode,
|
||||||
|
'scheduledReport.report.memberNameMode',
|
||||||
|
MEMBER_NAME_MODES,
|
||||||
|
issues,
|
||||||
|
true
|
||||||
|
)
|
||||||
|
checkInteger(
|
||||||
|
report.timeoutSeconds,
|
||||||
|
'scheduledReport.report.timeoutSeconds',
|
||||||
|
issues,
|
||||||
|
SCHEDULED_REPORT_MIN_TIMEOUT_SECONDS,
|
||||||
|
SCHEDULED_REPORT_MAX_TIMEOUT_SECONDS,
|
||||||
|
true
|
||||||
|
)
|
||||||
|
}
|
||||||
|
validateTarget(raw.target, 'scheduledReport.target', issues)
|
||||||
|
}
|
||||||
|
|
||||||
|
function validateLeaveNotification(
|
||||||
|
raw: JsonRecord,
|
||||||
|
issues: AgentAutomationValidationIssue[]
|
||||||
|
): void {
|
||||||
|
checkBoolean(raw.targetNeedsReview, 'leaveNotification.targetNeedsReview', issues)
|
||||||
|
if (raw.targetNeedsReview === true) {
|
||||||
|
addIssue(
|
||||||
|
issues,
|
||||||
|
'leaveNotification.targetNeedsReview',
|
||||||
|
'target_needs_review',
|
||||||
|
'发送目标需要在 TraceMemo 中重新确认'
|
||||||
|
)
|
||||||
|
}
|
||||||
|
validateTarget(raw.target, 'leaveNotification.target', issues)
|
||||||
|
checkEnum(raw.notifyScope, 'leaveNotification.notifyScope', ['all', 'selected'], issues, true)
|
||||||
|
if (!Array.isArray(raw.notifyRoomIds)) {
|
||||||
|
addIssue(issues, 'leaveNotification.notifyRoomIds', 'invalid_type', '必须是群聊 ID 数组')
|
||||||
|
} else {
|
||||||
|
if (raw.notifyRoomIds.length > 500) {
|
||||||
|
addIssue(issues, 'leaveNotification.notifyRoomIds', 'too_many_items', '最多支持 500 个群聊')
|
||||||
|
}
|
||||||
|
raw.notifyRoomIds.forEach((id, index) =>
|
||||||
|
checkString(id, `leaveNotification.notifyRoomIds[${index}]`, issues, {
|
||||||
|
required: true,
|
||||||
|
max: 300
|
||||||
|
})
|
||||||
|
)
|
||||||
|
}
|
||||||
|
checkString(raw.template, 'leaveNotification.template', issues, { required: true, max: 2_000 })
|
||||||
|
const templateResult = validateGroupExitNotificationTemplate(raw.template)
|
||||||
|
if (!templateResult.valid) {
|
||||||
|
addIssue(
|
||||||
|
issues,
|
||||||
|
'leaveNotification.template',
|
||||||
|
'invalid_template',
|
||||||
|
templateResult.error || '模板无效'
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Strict structural validation before the existing tolerant Store normalizer is called. */
|
||||||
|
export function validateAutomationDraftShape(input: unknown): {
|
||||||
|
valid: boolean
|
||||||
|
issues: AgentAutomationValidationIssue[]
|
||||||
|
normalized?: AutomationRuleDraft
|
||||||
|
} {
|
||||||
|
const issues: AgentAutomationValidationIssue[] = []
|
||||||
|
const raw = checkObject(
|
||||||
|
input,
|
||||||
|
'draft',
|
||||||
|
[
|
||||||
|
'name',
|
||||||
|
'enabled',
|
||||||
|
'ruleType',
|
||||||
|
'trigger',
|
||||||
|
'scope',
|
||||||
|
'conditions',
|
||||||
|
'actions',
|
||||||
|
'cooldownSeconds',
|
||||||
|
'replyDelaySeconds',
|
||||||
|
'leaveNotification',
|
||||||
|
'scheduledReport'
|
||||||
|
],
|
||||||
|
issues
|
||||||
|
)
|
||||||
|
if (!raw) return { valid: false, issues }
|
||||||
|
|
||||||
|
checkString(raw.name, 'name', issues, { required: true, max: 100 })
|
||||||
|
checkEnum(raw.ruleType, 'ruleType', RULE_TYPES, issues, true)
|
||||||
|
if (raw.enabled !== undefined) checkBoolean(raw.enabled, 'enabled', issues, true)
|
||||||
|
if (raw.enabled === true) {
|
||||||
|
addIssue(
|
||||||
|
issues,
|
||||||
|
'enabled',
|
||||||
|
'use_enable_operation',
|
||||||
|
'创建和校验不能启用规则,请使用 enable 操作'
|
||||||
|
)
|
||||||
|
}
|
||||||
|
checkEnum(raw.trigger, 'trigger', ['message'], issues, false)
|
||||||
|
checkEnum(raw.scope, 'scope', SCOPES, issues, false)
|
||||||
|
checkInteger(raw.cooldownSeconds, 'cooldownSeconds', issues, 0, 86_400)
|
||||||
|
checkInteger(
|
||||||
|
raw.replyDelaySeconds,
|
||||||
|
'replyDelaySeconds',
|
||||||
|
issues,
|
||||||
|
0,
|
||||||
|
AUTOMATION_REPLY_DELAY_MAX_SECONDS
|
||||||
|
)
|
||||||
|
|
||||||
|
if (raw.ruleType !== 'scheduled_report' && raw.scheduledReport !== undefined) {
|
||||||
|
addIssue(issues, 'scheduledReport', 'unexpected_field', '此规则类型不支持 scheduledReport')
|
||||||
|
}
|
||||||
|
if (raw.ruleType !== 'leave_notification' && raw.leaveNotification !== undefined) {
|
||||||
|
addIssue(issues, 'leaveNotification', 'unexpected_field', '此规则类型不支持 leaveNotification')
|
||||||
|
}
|
||||||
|
|
||||||
|
if (raw.ruleType === 'daily_report') validateDailyReport(raw, issues)
|
||||||
|
if (raw.ruleType === 'scheduled_report') {
|
||||||
|
if (raw.scheduledReport === undefined) {
|
||||||
|
addIssue(issues, 'scheduledReport', 'required', '必须提供定时日报配置')
|
||||||
|
} else {
|
||||||
|
const scheduled = checkObject(
|
||||||
|
raw.scheduledReport,
|
||||||
|
'scheduledReport',
|
||||||
|
['schedule', 'report', 'target', 'postfixText', 'targetNeedsReview'],
|
||||||
|
issues
|
||||||
|
)
|
||||||
|
if (scheduled) validateScheduledReport(scheduled, issues)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (raw.ruleType === 'leave_notification') {
|
||||||
|
if (raw.leaveNotification === undefined) {
|
||||||
|
addIssue(issues, 'leaveNotification', 'required', '必须提供退群通知配置')
|
||||||
|
} else {
|
||||||
|
const leave = checkObject(
|
||||||
|
raw.leaveNotification,
|
||||||
|
'leaveNotification',
|
||||||
|
['target', 'template', 'notifyScope', 'notifyRoomIds', 'targetNeedsReview'],
|
||||||
|
issues
|
||||||
|
)
|
||||||
|
if (leave) validateLeaveNotification(leave, issues)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (issues.length) return { valid: false, issues }
|
||||||
|
const ruleType = raw.ruleType as AutomationRuleType
|
||||||
|
const normalized = normalizeRuleDraft({
|
||||||
|
...raw,
|
||||||
|
enabled: false,
|
||||||
|
...(ruleType === 'daily_report'
|
||||||
|
? {}
|
||||||
|
: {
|
||||||
|
scope: 'group',
|
||||||
|
conditions: {
|
||||||
|
requireMentionMe: false,
|
||||||
|
keyword: '',
|
||||||
|
keywordMatchMode: 'contains',
|
||||||
|
conversationIds: [],
|
||||||
|
ignoreSelf: true
|
||||||
|
},
|
||||||
|
actions: [],
|
||||||
|
cooldownSeconds: 0
|
||||||
|
})
|
||||||
|
})
|
||||||
|
return { valid: true, issues: [], normalized: { ...normalized, enabled: false } }
|
||||||
|
}
|
||||||
@@ -0,0 +1,70 @@
|
|||||||
|
import type { AutomationExecution, AutomationRuleType } from '../automation'
|
||||||
|
|
||||||
|
export interface AgentApiErrorBody {
|
||||||
|
error: {
|
||||||
|
code: string
|
||||||
|
message: string
|
||||||
|
details?: unknown
|
||||||
|
}
|
||||||
|
requestId: string
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface CapabilityAvailability {
|
||||||
|
supported: boolean
|
||||||
|
available: boolean
|
||||||
|
reason?: string
|
||||||
|
operations?: string[]
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ApplicationCapabilities {
|
||||||
|
version: string
|
||||||
|
apiVersion: 'v1'
|
||||||
|
database: { ready: boolean }
|
||||||
|
query: CapabilityAvailability
|
||||||
|
automations: CapabilityAvailability & {
|
||||||
|
ruleTypes: AutomationRuleType[]
|
||||||
|
operations: string[]
|
||||||
|
}
|
||||||
|
groupExitMonitor: CapabilityAvailability
|
||||||
|
groupStats: CapabilityAvailability
|
||||||
|
wechat: {
|
||||||
|
personal: CapabilityAvailability & {
|
||||||
|
status: string
|
||||||
|
content: { text: boolean; image: boolean; voice: boolean }
|
||||||
|
}
|
||||||
|
ilink: CapabilityAvailability & { status: string }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface AgentAutomationValidationIssue {
|
||||||
|
path: string
|
||||||
|
code: string
|
||||||
|
message: string
|
||||||
|
details?: unknown
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface AgentAutomationValidationResult {
|
||||||
|
valid: boolean
|
||||||
|
issues: AgentAutomationValidationIssue[]
|
||||||
|
normalized?: unknown
|
||||||
|
effects?: Record<string, unknown>
|
||||||
|
nextRunAt?: string | null
|
||||||
|
capabilities?: Record<string, unknown>
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface AgentAutomationExecution extends Pick<
|
||||||
|
AutomationExecution,
|
||||||
|
| 'executionId'
|
||||||
|
| 'ruleId'
|
||||||
|
| 'ruleName'
|
||||||
|
| 'trigger'
|
||||||
|
| 'status'
|
||||||
|
| 'triggerTime'
|
||||||
|
| 'durationMs'
|
||||||
|
| 'sourceDisplayName'
|
||||||
|
> {
|
||||||
|
ruleType?: AutomationRuleType
|
||||||
|
startedAt: string
|
||||||
|
finishedAt: string | null
|
||||||
|
error?: string
|
||||||
|
}
|
||||||
Loaded 100 of 163 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user