diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 7dc4643..0320e8c 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -15,6 +15,9 @@ jobs: steps: - uses: actions/checkout@v4 + with: + # 版本漂移检查需要与基准分支比较 SKILL.md,浅克隆拿不到基准。 + fetch-depth: 0 - uses: pnpm/action-setup@v4 with: @@ -46,6 +49,9 @@ jobs: - name: Skill installation instruction tests run: pnpm test:skill-install + - name: Reader Skill version drift check + run: pnpm check:skill-version + - name: Build Electron test application run: pnpm test:e2e:build diff --git a/.gitignore b/.gitignore index ea465ae..e15d7c9 100644 --- a/.gitignore +++ b/.gitignore @@ -26,3 +26,5 @@ skills-lock.json findings.md progress.md task_plan.md + +*tm-wcdb-config-helper* diff --git a/README.md b/README.md index 5c72535..9c69f35 100644 --- a/README.md +++ b/README.md @@ -79,7 +79,7 @@ TraceMemo(迹忆)原名 **WechatExplorer** 是一款本地优先的微信数 ## 💻 平台支持 -TraceMemo 2.5.0 支持: +TraceMemo 2.5.1 支持: - **Windows x64** - **macOS Apple Silicon(M 系列 / arm64)** diff --git a/docs/agent/api.md b/docs/agent/api.md index 36424ef..315c17c 100644 --- a/docs/agent/api.md +++ b/docs/agent/api.md @@ -8,7 +8,9 @@ - API 前缀:`/api/v1` - 默认只监听 loopback;不要把它当作公网服务。 - `/api/v1/health` 无需 Token;其他端点需要 `Authorization: Bearer `。 -- 请求体使用 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/skill/tracememo-reader` | 当前 Reader Skill 的版本与全文 | 无(需 Token) | | GET | `/api/v1/current_time` | 本机时间、时区和 Unix 时间戳 | 无 | | GET | `/api/v1/contact` | 联系人和群聊列表 | `filter`、`type=user\|group` | | GET | `/api/v1/chatroom` | 群聊列表 | `keyword` | @@ -55,10 +58,130 @@ Token 由应用生成并保存在本机,**不接受用环境变量覆盖**:A | POST | `/api/v1/scheduled-reports/{id}/disable` | 暂停定时日报任务 | 无 | | POST | `/api/v1/scheduled-reports/{id}/run` | 立即执行一次并返回 execution | 无 | | GET | `/api/v1/scheduled-reports/{id}/executions` | 查询某个任务的执行记录 | 无 | -| POST | `/api/v1/scheduled-reports/executions/{executionId}/retry-send` | 复用已有 PNG 重试发送 | 无 | +| 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)。 +## 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、微信连接器和数据库状态; @@ -215,3 +338,102 @@ curl -X POST -H "$AUTH" -H 'Content-Type: application/json' "$BASE/query/convers 调用方**必须**把 `coverage` 当真:`coverage.state` 不是 `complete` 且 `evidence` 为空时,只能说明"这段范围暂时无法确认",**不能**下"没有找到"的结论。索引落后时服务端会自动请求一次追赶同步,但不会让请求无限等待;`freshness.catchUp` 为 `pending` 表示追赶仍在后台进行,稍后重试即可拿到更新的覆盖。 `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.3.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.0", + "skill": { "name": "tracememo-reader", "version": "1.3.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.3.0", + "contentHash": "", + "modifiedAt": "2026-10-13T08:37:30.000Z", + "markdown": "---\nname: tracememo-reader\nversion: 1.3.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` 会在"只改文档、不升版本"时失败,避免再次出现"文档改了两轮、版本号纹丝不动"的情况。 diff --git a/docs/agent/reader-skill.md b/docs/agent/reader-skill.md index 45ec8a8..c1f9196 100644 --- a/docs/agent/reader-skill.md +++ b/docs/agent/reader-skill.md @@ -26,6 +26,21 @@ Reader Skill 只负责“外部 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 的读取顺序 当用户使用“今天”“昨天”“本周”等相对时间时: @@ -55,7 +70,8 @@ Reader Skill 可以指导 Agent 使用: - 结构化日报渲染和按群聊生成总结图片; - 定时日报任务的查询、创建、修改、启停、删除、立即执行和执行记录;删除不可逆,Skill 要求先列出唯一任务并取得用户明确确认; - 个人微信发送能力状态查询(`/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 自动监听微信消息。 注意这个 API 不只是只读的:`/report`、`/agent/send` 和 `/scheduled-reports*` 会写入状态或真的发出微信消息。 diff --git a/docs/development/agent-api-capability-audit.md b/docs/development/agent-api-capability-audit.md new file mode 100644 index 0000000..0b2df5e --- /dev/null +++ b/docs/development/agent-api-capability-audit.md @@ -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 能力需在后续实现集成测试中验证;静态代码审计无法替代真实数据库/微信连接的运行时验证。 diff --git a/docs/platform/macos.md b/docs/platform/macos.md index 585a0be..072ef67 100644 --- a/docs/platform/macos.md +++ b/docs/platform/macos.md @@ -13,6 +13,34 @@ TraceMemo 需要读取微信本地数据。macOS 会根据系统版本、微信 不要直接复制网上针对其他微信版本的命令。系统授权失败时,记录 macOS 版本、微信版本和页面错误,再按[排障文档](../user-guide/troubleshooting.md#连接微信失败)处理。 +## 提示「无法读取微信数据库」时 + +**这是故障恢复步骤,不是安装前置条件。** 能正常连接的用户不需要做任何权限设置。 + +如果你在连接页看到「最近验证结果:无法读取微信数据库」(错误码 `DATABASE_PERMISSION_DENIED`),并且已经确认微信数据目录**实际存在**(例如在终端里能列出 `db_storage/session/session.db`),那说明是 **TraceMemo 这个进程**读不到,而不是文件缺失。 + +macOS 27 及更高版本对其他应用的容器数据有更严格的访问控制。给 TraceMemo 授予「完全磁盘访问权限」: + +1. 打开 **系统设置 → 隐私与安全性 → 完全磁盘访问权限** +2. 找到 **TraceMemo**,打开开关 +3. **重新启动 TraceMemo**(该授权只在进程下次启动时生效) +4. 回到连接页重试 + +### 为什么终端能读、TraceMemo 读不了 + +macOS 的隐私权限按**应用进程的身份**判定,而不是按文件系统的用户身份。同一个用户在终端里能读到文件内容,不代表 TraceMemo 进程也有权限 —— 两者走的是不同的授权判定。所以「终端能读」不能用来排除权限问题。 + +### 不要做的事 + +上面这条路径**只涉及给 TraceMemo 授权**。以下做法都不需要,而且有风险: + +- 关闭 SIP +- `chmod` / `chown` 整个微信目录 +- 用 `sudo` 启动 TraceMemo +- 修改微信数据库文件权限 + +「无法读取微信数据库」与 SIP 不是同一个问题;改动微信数据目录的权限还可能影响微信自身的正常运行。 + ## SIP 风险 关闭 System Integrity Protection 会降低 macOS 对系统文件和进程的保护。它不是日常使用 TraceMemo 的功能开关,也不应长期保持关闭。只有在你理解风险、确认页面要求且完成必要操作时才处理;完成后按 Apple 官方方式重新启用。 diff --git a/docs/skill/tracememo-reader/SKILL.md b/docs/skill/tracememo-reader/SKILL.md index 620dad7..2b0176f 100644 --- a/docs/skill/tracememo-reader/SKILL.md +++ b/docs/skill/tracememo-reader/SKILL.md @@ -1,5 +1,6 @@ --- name: tracememo-reader +version: 1.3.0 description: 通过 TraceMemo 本地 HTTP API 按需读取用户有权访问的微信聊天数据和图片媒体,并管理定时日报任务。当用户要求查看微信消息、查找联系人或群聊、总结聊天、查看或理解图片、生成群聊总结、查询或修改定时日报时使用。此 Skill 由本机 TraceMemo 提供数据,不是 MCP Server。 --- @@ -17,6 +18,35 @@ description: 通过 TraceMemo 本地 HTTP API 按需读取用户有权访问的 - 不要把 Token 放到 URL、回答、日志、Skill 文件或仓库。 - 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`,确认服务和数据库状态。 @@ -29,7 +59,8 @@ description: 通过 TraceMemo 本地 HTTP API 按需读取用户有权访问的 | 方法 | 路径 | 用途 | | ------ | ------------------------------------------------------- | ------------------------------------------------- | -| GET | `/health` | 健康和数据库状态 | +| GET | `/health` | 健康和数据库状态 + 当前 Skill 版本 | +| GET | `/skill/tracememo-reader` | 当前 SKILL.md 全文与版本号(自助更新用) | | GET | `/current_time` | 本机时间与时区 | | GET | `/contact` | 联系人/群聊列表;可传 `filter`、`type` | | GET | `/chatroom` | 群聊列表;可传 `keyword` | @@ -42,6 +73,7 @@ description: 通过 TraceMemo 本地 HTTP API 按需读取用户有权访问的 | POST | `/query/search` | 受限语义关键词检索(依赖本地索引,见 freshness) | | POST | `/query/message-context` | 用 `messageRef` 取某条消息的前后文 | | POST | `/query/conversation-overview` | 按会话与时间范围提取可总结的证据 | +| POST | `/query/voice-transcribe` | 把指定语音消息转成文字(本机离线识别) | | GET | `/query/capabilities` | Query 端点能力目录 | | GET | `/wechat-personal/send-capability` | 个人微信发送能力状态(文字 / 图片 / 语音) | | GET | `/scheduled-reports` | 查询全部定时日报任务 | @@ -118,6 +150,7 @@ description: 通过 TraceMemo 本地 HTTP API 按需读取用户有权访问的 - `query/search`:受限语义关键词检索,依赖本地索引; - `query/message-context`:用返回的 `messageRef` 取前后文; - `query/conversation-overview`:按会话与时间范围提取可总结的证据。 +- `query/voice-transcribe`:把指定语音消息的 `messageRef` 转成文字。 两个要点: @@ -147,6 +180,18 @@ description: 通过 TraceMemo 本地 HTTP API 按需读取用户有权访问的 不要只根据 `[图片]` 猜测内容,不要把一次 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 的数据策略。 diff --git a/docs/user-guide/export.md b/docs/user-guide/export.md index 96dd694..04dc980 100644 --- a/docs/user-guide/export.md +++ b/docs/user-guide/export.md @@ -24,6 +24,12 @@ ZIP 是 HTML 资源包的压缩选项,不是第五种内容格式。 5. 设置文件名并开始导出。 6. 在导出任务中心查看读取、解析、媒体处理、转写、写入和压缩进度;完成后打开文件位置。 +## 导出设置会被记住 + +TraceMemo 会记住上一次使用的导出设置,下次打开导出页面时自动恢复,减少重复选择。包括格式、时间范围、消息类型、名称显示方式、媒体选项(原图/缩略图、头像)、语音转写、缺失资源处理、ZIP、文件名和输出目录。 + +这些偏好保存在本机,不会随账号同步到其他设备。 + ## 多会话和增量导出 HTML 支持把最多五个会话合并到一个档案中;选择多个会话后,其他格式会不可用。再次使用相同名称导出 HTML 时,可以把新消息增量合并到已有档案;这不会删除之前已导出的消息。 diff --git a/docs/user-guide/troubleshooting.md b/docs/user-guide/troubleshooting.md index 87d9a88..102b857 100644 --- a/docs/user-guide/troubleshooting.md +++ b/docs/user-guide/troubleshooting.md @@ -31,6 +31,14 @@ 重新输入密钥或断开连接不会删除微信原始数据库。macOS 的 SIP 和授权说明见[平台说明](../platform/macos.md)。 +### 提示「无法读取微信数据库」但文件确实存在 + +这是**权限问题,不是文件缺失** —— 如果你在终端里能列出 `db_storage/session/session.db`,说明数据目录是完整的,只是 TraceMemo 这个进程读不到。 + +macOS 27 及更高版本需要给 TraceMemo 授予「完全磁盘访问权限」。注意:**终端能读到文件不代表 TraceMemo 有权限** —— macOS 的隐私权限按应用进程的身份判定,两者走的是不同的授权。 + +处理步骤见 [macOS 数据访问与系统权限 → 提示「无法读取微信数据库」时](../platform/macos.md#提示无法读取微信数据库时)。 + 仍然失败时,记录 **macOS 版本、CPU 架构(Apple Silicon / Intel)、微信版本、TraceMemo 版本和页面错误提示**后 扫码 README 文档二维码进群提交消息, 或者提交 Issue。 ## 连接成功但没有联系人或消息 @@ -92,3 +100,15 @@ Agent Hub 和外部 Agent 是两条路径。机器人异常时依次确认: 5. 需要总结或自然语言理解时,AI Provider 是否可用。 当前机器人不支持群发、定时任务或与文字同等的图片、语音、文件和视频理解。详细边界见[Agent Hub](../agent/agent-hub.md)。 + +## 点击关闭后应用没有退出 + +「关闭窗口时」可能被配置为**最小化到托盘** —— 窗口隐藏,应用仍在后台运行。 + +到「设置 → 外观与行为 → 关闭窗口时」可以改成: + +- **每次询问**:每次关闭都弹窗确认; +- **最小化到托盘**:窗口隐藏,应用继续在后台运行; +- **退出应用**:直接结束 TraceMemo 进程。 + +选择「每次询问」时,在关闭弹窗里勾选「记住我的选择,下次不再询问」会自动切换到这里对应的项。 diff --git a/electron-builder.win.yml b/electron-builder.win.yml index b08db0b..7d6c0ec 100644 --- a/electron-builder.win.yml +++ b/electron-builder.win.yml @@ -38,6 +38,7 @@ extraResources: - key/win32/x64/** - runtime/win32/** - wcdb/win32/x64/** + - '!wcdb/**/tm-wcdb-config-helper*' - from: docs/skill/tracememo-reader to: skill/tracememo-reader filter: diff --git a/electron-builder.yml b/electron-builder.yml index 49a1292..5e1352f 100644 --- a/electron-builder.yml +++ b/electron-builder.yml @@ -35,6 +35,7 @@ extraResources: filter: - '**/*' - '!runtime/darwin-arm64/**' + - '!wcdb/**/tm-wcdb-config-helper*' - from: docs/skill/tracememo-reader to: skill/tracememo-reader filter: diff --git a/package.json b/package.json index 07c9304..a24165b 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "tracememo", - "version": "2.5.0", + "version": "2.5.1", "packageManager": "pnpm@7.33.7", "description": "TraceMemo(迹忆)是一款本地优先、可追溯的 AI 微信知识与分析工作台。 原名 WechatExplorer,支持聊天记录搜索、知识库、微信群聊总结和 Agent 助手。", "keywords": [ @@ -33,6 +33,7 @@ "typecheck": "npm run typecheck:node && npm run typecheck:web && npm run typecheck:test", "typecheck:test": "node scripts/typecheck-tests.cjs", "test:skill-install": "node scripts/test-skill-install-instruction.cjs", + "check:skill-version": "node scripts/check-skill-version-drift.cjs", "cp: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", diff --git a/public/二维码.jpg b/public/二维码.jpg index 9060993..69ce88e 100644 Binary files a/public/二维码.jpg and b/public/二维码.jpg differ diff --git a/resources/trayTemplate.png b/resources/trayTemplate.png new file mode 100644 index 0000000..d0fc06b Binary files /dev/null and b/resources/trayTemplate.png differ diff --git a/resources/trayTemplate.svg b/resources/trayTemplate.svg new file mode 100644 index 0000000..6fffd2f --- /dev/null +++ b/resources/trayTemplate.svg @@ -0,0 +1,13 @@ + + + + diff --git a/resources/trayTemplate@2x.png b/resources/trayTemplate@2x.png new file mode 100644 index 0000000..7140283 Binary files /dev/null and b/resources/trayTemplate@2x.png differ diff --git a/resources/wcdb/macos/arm64/libwcdb_api.dylib b/resources/wcdb/macos/arm64/libwcdb_api.dylib index 3bab03e..eda2136 100755 Binary files a/resources/wcdb/macos/arm64/libwcdb_api.dylib and b/resources/wcdb/macos/arm64/libwcdb_api.dylib differ diff --git a/resources/wcdb/macos/x64/libwcdb_api.dylib b/resources/wcdb/macos/x64/libwcdb_api.dylib index d076466..fcdf6ba 100755 Binary files a/resources/wcdb/macos/x64/libwcdb_api.dylib and b/resources/wcdb/macos/x64/libwcdb_api.dylib differ diff --git a/resources/wcdb/win32/x64/wcdb_api.dll b/resources/wcdb/win32/x64/wcdb_api.dll index d57cc18..9bf8a0e 100644 Binary files a/resources/wcdb/win32/x64/wcdb_api.dll and b/resources/wcdb/win32/x64/wcdb_api.dll differ diff --git a/scripts/check-skill-version-drift.cjs b/scripts/check-skill-version-drift.cjs new file mode 100644 index 0000000..0fef69b --- /dev/null +++ b/scripts/check-skill-version-drift.cjs @@ -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})。` +) diff --git a/scripts/test-skill-install-instruction.cjs b/scripts/test-skill-install-instruction.cjs index 225bc45..3b32403 100644 --- a/scripts/test-skill-install-instruction.cjs +++ b/scripts/test-skill-install-instruction.cjs @@ -67,4 +67,34 @@ assert.match( /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') diff --git a/src/main/http-server.ts b/src/main/http-server.ts index e90193a..1a55837 100644 --- a/src/main/http-server.ts +++ b/src/main/http-server.ts @@ -1,5 +1,6 @@ import crypto from 'crypto' import http, { IncomingMessage, ServerResponse, Server } from 'http' +import { app } from 'electron' import { isReady, listContacts, @@ -7,7 +8,8 @@ import { listMessages, getGroupSnapshot, listRecentChat, - resolveMd5 + resolveMd5, + type FormattedMessage } from './services/chat-service' import { exportGroupReport } from './group-report-service' import { GroupReportExportRequest } from '../shared/group-report' @@ -26,8 +28,21 @@ import type { import { agentHubService } from './services/agent-hub-service' import { safeError, safeLog, safeWarn } from './safe-log' import { apiTokenStore } from './api-token-store' +import { READER_SKILL_NAME, skillResourceService } from './services/skill-resource-service' import { HttpMediaError, readImageMedia, type HttpImageResult } from './http-media-service' import { LocalQueryApiService } from './services/local-query-api-service' +import { automationRuleStore, AutomationRulePersistenceError } from './services/automation-rule-store' +import { automationExecutionLogService } from './services/automation-execution-log-service' +import { groupExitMonitorService } from './services/group-exit-monitor-service' +import { LocalAgentApiError, LocalAgentApiService } from './services/local-agent-api-service' +import type { GroupStatsService } from './services/group-stats-service' +import { encodeMessageRef } from '../shared/local-query-api' +import type { + VoiceMessageReference, + VoiceTranscriptSnapshot, + VoiceTranscriptState +} from '../shared/voice-recognition' +import { voiceMessageReferenceOf } from './voice-pipeline/voice-message-identity' export const DEFAULT_HTTP_HOST = '127.0.0.1' export const DEFAULT_HTTP_PORT = 6131 @@ -45,6 +60,11 @@ interface RouteContext { body?: unknown } +type HttpMethod = 'GET' | 'HEAD' | 'POST' | 'PATCH' | 'DELETE' +type RouteHandler = ((ctx: RouteContext) => void | Promise) & { + allowedMethods: readonly HttpMethod[] +} + export interface HttpServerOptions { tokenProvider?: () => string | null mediaProvider?: (messageId: string) => Promise @@ -54,21 +74,85 @@ export interface HttpServerOptions { scheduledReportDatabaseReadyProvider?: ScheduledReportApiDependencies['isDatabaseReady'] scheduledReportPlatform?: NodeJS.Platform queryApiService?: LocalQueryApiService + agentApiService?: LocalAgentApiService + groupStatsService?: Pick + appVersionProvider?: () => string } let configuredQueryApiService: LocalQueryApiService | undefined +let configuredGroupStatsService: Pick | undefined export function setLocalQueryApiService(service: LocalQueryApiService | undefined): void { configuredQueryApiService = service } -type RouteHandler = (ctx: RouteContext) => void | Promise +export function setLocalGroupStatsService( + service: Pick | undefined +): void { + configuredGroupStatsService = service +} + +let configuredVoiceTranscriptSnapshot: + | ((reference: VoiceMessageReference) => VoiceTranscriptSnapshot) + | undefined +export function setLocalVoiceTranscriptSnapshotProvider( + provider: ((reference: VoiceMessageReference) => VoiceTranscriptSnapshot) | undefined +): void { + configuredVoiceTranscriptSnapshot = provider +} + +/** + * chatlog 的语音消息补上本地已有的转写(只读缓存,不触发识别)与 messageRef, + * 调用方据 `voiceTranscriptState` 决定是否调用 query/voice-transcribe。 + */ +function withChatlogVoiceTranscript( + conversationId: string, + message: FormattedMessage +): FormattedMessage & { messageRef?: string; voiceTranscriptState?: VoiceTranscriptState } { + const reference = voiceMessageReferenceOf(message) + if (!reference || !configuredVoiceTranscriptSnapshot) return message + const snapshot = configuredVoiceTranscriptSnapshot(reference) + const transcript = snapshot.state === 'transcribed' ? snapshot.transcript?.trim() : undefined + return { + ...message, + messageRef: encodeMessageRef(conversationId, message.id), + voiceTranscriptState: snapshot.state, + ...(transcript ? { voiceTranscript: transcript } : {}) + } +} + +const MAX_JSON_BODY_BYTES = 1024 * 1024 + +class RequestBodyTooLargeError extends Error { + constructor() { + super('Request body exceeds the maximum size') + this.name = 'RequestBodyTooLargeError' + } +} + +function withMethods( + methods: readonly HttpMethod[], + handler: (ctx: RouteContext) => void | Promise +): RouteHandler { + return Object.assign(handler, { allowedMethods: methods }) +} + +function sendMethodNotAllowed(res: ServerResponse, methods: readonly HttpMethod[]): void { + res.setHeader('Allow', methods.join(', ')) + sendError(res, 405, `请求方法不受支持;允许的方法:${methods.join(', ')}`) +} function sendJson(res: ServerResponse, status: number, payload: unknown): void { - const body = JSON.stringify(payload, null, 2) + const requestId = String(res.getHeader('X-Request-Id') || '') + let responsePayload = payload + if (status >= 400 && payload && typeof payload === 'object' && !('requestId' in payload)) { + responsePayload = { ...(payload as Record), requestId } + } + const body = JSON.stringify(responsePayload, null, 2) res.writeHead(status, { 'Content-Type': 'application/json; charset=utf-8', 'Content-Length': Buffer.byteLength(body), - 'Cache-Control': 'no-store' + 'Cache-Control': 'no-store', + ...(requestId ? { 'X-Request-Id': requestId } : {}) }) res.end(body) } @@ -91,8 +175,8 @@ function applyCorsHeaders(req: IncomingMessage, res: ServerResponse): boolean { if (!isAllowedCorsOrigin(origin)) return false res.setHeader('Access-Control-Allow-Origin', origin) res.setHeader('Vary', 'Origin') - res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PATCH, DELETE, OPTIONS') - res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization') + res.setHeader('Access-Control-Allow-Methods', 'GET, HEAD, POST, PATCH, DELETE, OPTIONS') + res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization, X-Request-Id') return true } @@ -112,6 +196,20 @@ function sendUnauthorized(res: ServerResponse): void { }) } +function sendAgentHttpError( + res: ServerResponse, + status: number, + code: string, + message: string, + details?: unknown +): void { + const requestId = String(res.getHeader('X-Request-Id') || '') + sendJson(res, status, { + error: { code, message, ...(details !== undefined ? { details } : {}) }, + requestId + }) +} + function sendError(res: ServerResponse, status: number, message: string, extra?: unknown): void { sendJson(res, status, { error: message, status, ...(extra ? { details: extra } : {}) }) } @@ -121,7 +219,8 @@ function sendBinary(res: ServerResponse, status: number, result: HttpImageResult 'Content-Type': result.mimeType, 'Content-Length': result.buffer.length, 'Cache-Control': 'private, no-store', - 'X-Content-Type-Options': 'nosniff' + 'X-Content-Type-Options': 'nosniff', + 'X-Request-Id': String(res.getHeader('X-Request-Id') || '') }) res.end(result.buffer) } @@ -136,10 +235,37 @@ function sanitizeChatlogMessage(message: Record): Record { +function readBody(req: IncomingMessage, maxBytes = MAX_JSON_BODY_BYTES): Promise { return new Promise((resolve, reject) => { + const contentLength = Number(req.headers['content-length']) + if (Number.isFinite(contentLength) && contentLength > maxBytes) { + /* + * 拒收,但**要先把请求体排空**。 + * + * 直接 `pause()` 会让剩余数据留在 socket 缓冲里,而我们紧接着就会 + * 发 413 + `Connection: close` —— 客户端此时仍在写,收到连接关闭后会以 + * 传输层错误收场(undici 报 `ECONNRESET`;Windows 的 TCP 栈比 macOS + * 更倾向回 RST,所以先在那里暴露)。改成 `resume()`:不再收集数据, + * 只是把客户端已经/正在发的字节丢掉,让它正常写完并读到这个 413。 + * 上限仍是 maxBytes,所以不会有人靠超大 body 拖住我们。 + */ + req.resume() + reject(new RequestBodyTooLargeError()) + return + } const chunks: Buffer[] = [] - req.on('data', (chunk: Buffer) => chunks.push(chunk)) + let size = 0 + req.on('data', (chunk: Buffer) => { + size += chunk.length + if (size > maxBytes) { + chunks.length = 0 + // 同上:排空而不是暂停,否则客户端拿不到这个 413。 + req.resume() + reject(new RequestBodyTooLargeError()) + return + } + chunks.push(chunk) + }) req.on('end', () => resolve(Buffer.concat(chunks).toString('utf-8'))) req.on('error', reject) }) @@ -208,18 +334,50 @@ function parseNumeric(value: string | null, fallback: number): number { return Number.isFinite(n) ? n : fallback } +function getApplicationVersion(): string { + try { + return typeof app.getVersion === 'function' ? app.getVersion() : 'unknown' + } catch { + return 'unknown' + } +} + const routes: Record = { - '/api/v1/health': ({ res }) => { + '/api/v1/health': withMethods(['GET'], ({ res }) => { + const skill = skillResourceService.getStatus() sendJson(res, 200, { ok: true, ready: isReady(), service: 'TraceMemo Reader', - version: '1.0.0', + version: getApplicationVersion(), + skill: { + name: skill.name || READER_SKILL_NAME, + version: skill.version || null, + available: skill.available + }, timestamp: new Date().toISOString() }) - }, + }), - '/api/v1/current_time': ({ res }) => { + // 外部 Agent 的版本自检与自助更新入口:返回当前 SKILL.md 全文,不返回本地路径。 + '/api/v1/skill/tracememo-reader': withMethods(['GET'], ({ res }) => { + const document = skillResourceService.getDocument() + if (!document) { + return sendJson(res, 503, { + error: 'skill_unavailable', + message: '未找到本机 TraceMemo Reader Skill 文件,请确认应用安装是否完整。' + }) + } + sendJson(res, 200, { + name: document.name, + version: document.version || null, + contentHash: document.contentHash, + modifiedAt: document.modifiedAt, + markdown: document.markdown + }) + }), + + '/api/v1/current_time': withMethods(['GET'], ({ res }) => { const now = new Date() sendJson(res, 200, { time: now.toISOString(), @@ -229,9 +387,9 @@ const routes: Record = { now.getDate() ).padStart(2, '0')}` }) - }, + }), - '/api/v1/contact': async ({ res, url }) => { + '/api/v1/contact': withMethods(['GET'], async ({ res, url }) => { if (!isReady()) return sendError(res, 503, 'TraceMemo 数据库未初始化') const filter = url.searchParams.get('filter') || undefined const type = url.searchParams.get('type') || undefined @@ -243,9 +401,9 @@ const routes: Record = { contacts = contacts.filter((c) => c.type === type) } sendJson(res, 200, { count: contacts.length, contacts }) - }, + }), - '/api/v1/chatroom': async ({ res, url }) => { + '/api/v1/chatroom': withMethods(['GET'], async ({ res, url }) => { if (!isReady()) return sendError(res, 503, 'TraceMemo 数据库未初始化') const keyword = url.searchParams.get('keyword') || '' // Same hydration requirement as /api/v1/contact: group display names are @@ -260,16 +418,16 @@ const routes: Record = { ) } sendJson(res, 200, { count: groups.length, chatrooms: groups }) - }, + }), - '/api/v1/recent_chat': ({ res, url }) => { + '/api/v1/recent_chat': withMethods(['GET'], ({ res, url }) => { if (!isReady()) return sendError(res, 503, 'TraceMemo 数据库未初始化') const limit = parseNumeric(url.searchParams.get('limit'), 50) const items = listRecentChat(limit) sendJson(res, 200, { count: items.length, items }) - }, + }), - '/api/v1/chatlog': ({ res, url }) => { + '/api/v1/chatlog': withMethods(['GET'], ({ res, url }) => { if (!isReady()) return sendError(res, 503, 'TraceMemo 数据库未初始化') const talker = url.searchParams.get('talker') if (!talker) return sendError(res, 400, '缺少必要参数 talker') @@ -304,30 +462,32 @@ const routes: Record = { query: { talker, time: timeParam, startTime, endTime }, count: messages.length, messages: messages.map((message) => - sanitizeChatlogMessage(message as unknown as Record) + sanitizeChatlogMessage( + withChatlogVoiceTranscript(resolved.md5, message) as unknown as Record + ) ) }) - }, + }), - '/api/v1/group_snapshot': ({ res, url }) => { + '/api/v1/group_snapshot': withMethods(['GET'], ({ res, url }) => { if (!isReady()) return sendError(res, 503, 'TraceMemo 数据库未初始化') const md5 = url.searchParams.get('md5') if (!md5) return sendError(res, 400, '缺少必要参数 md5') const snapshot = getGroupSnapshot(md5) if (!snapshot) return sendError(res, 404, `未找到群聊: ${md5}`) sendJson(res, 200, snapshot) - }, + }), - '/api/v1/resolve': ({ res, url }) => { + '/api/v1/resolve': withMethods(['GET'], ({ res, url }) => { if (!isReady()) return sendError(res, 503, 'TraceMemo 数据库未初始化') const q = url.searchParams.get('q') if (!q) return sendError(res, 400, '缺少必要参数 q') const contact = resolveMd5(q) if (!contact) return sendError(res, 404, `未匹配到联系人: ${q}`) sendJson(res, 200, contact) - }, + }), - '/api/v1/report': async ({ req, res, body }) => { + '/api/v1/report': withMethods(['POST'], async ({ req, res, body }) => { if (req.method !== 'POST') return sendError(res, 405, '需要 POST 请求') if (!isReady()) return sendError(res, 503, 'TraceMemo 数据库未初始化') if (typeof body !== 'string' || !body.trim()) { @@ -354,9 +514,9 @@ const routes: Record = { } const result = await exportGroupReport(request) sendJson(res, result.success ? 200 : 500, result) - }, + }), - '/api/v1/agent/group-report': async ({ req, res, body }) => { + '/api/v1/agent/group-report': withMethods(['POST'], async ({ req, res, body }) => { if (req.method !== 'POST') return sendError(res, 405, '需要 POST 请求') if (!isReady()) return sendError(res, 503, 'TraceMemo 数据库未初始化') let request: { group?: string; range?: 'today' | 'yesterday' | '7days' } @@ -370,9 +530,9 @@ const routes: Record = { range: request.range }) sendJson(res, result.success ? 200 : 400, result) - }, + }), - '/api/v1/agent/status': ({ res }) => { + '/api/v1/agent/status': withMethods(['GET'], ({ res }) => { const status = agentHubService.getStatus() sendJson(res, 200, { ok: status.hub === 'online' && status.connector === 'online', @@ -382,9 +542,9 @@ const routes: Record = { databaseReady: status.databaseReady, accountId: status.accountId }) - }, + }), - '/api/v1/agent/send': async ({ req, res, body }) => { + '/api/v1/agent/send': withMethods(['POST'], async ({ req, res, body }) => { if (req.method !== 'POST') return sendError(res, 405, '需要 POST 请求') let request: { to?: string; text?: string; media_url?: string } try { @@ -398,7 +558,7 @@ const routes: Record = { mediaUrl: request.media_url }) sendJson(res, result.success ? 200 : result.status === 'token_expired' ? 401 : 503, result) - } + }) } const SCHEDULED_REPORTS_ROUTE = '/api/v1/scheduled-reports' @@ -448,18 +608,18 @@ function createScheduledReportRoute( api: ScheduledReportApiService ): RouteHandler | undefined { if (pathname === WECHAT_SEND_CAPABILITY_ROUTE) { - return async ({ req, res }) => { + return withMethods(['GET'], async ({ req, res }) => { if (req.method !== 'GET') return sendError(res, 405, '需要 GET 请求') try { sendJson(res, 200, { capability: await api.getCapability() }) } catch (error) { sendScheduledError(res, error) } - } + }) } if (pathname === SCHEDULED_REPORTS_ROUTE) { - return async ({ req, res, body }) => { + return withMethods(['GET', 'POST'], async ({ req, res, body }) => { try { if (req.method === 'GET') { const tasks = await api.list() @@ -475,7 +635,7 @@ function createScheduledReportRoute( } catch (error) { sendScheduledError(res, error) } - } + }) } const retryPrefix = `${SCHEDULED_REPORTS_ROUTE}/executions/` @@ -488,7 +648,7 @@ function createScheduledReportRoute( } catch { return undefined } - return async ({ req, res }) => { + return withMethods(['POST'], async ({ req, res }) => { if (req.method !== 'POST') return sendError(res, 405, '需要 POST 请求') try { const execution = await api.retrySend(executionId) @@ -496,7 +656,7 @@ function createScheduledReportRoute( } catch (error) { sendScheduledError(res, error) } - } + }) } const prefix = `${SCHEDULED_REPORTS_ROUTE}/` @@ -510,8 +670,15 @@ function createScheduledReportRoute( return undefined } const action = segments[1] + if (action && !['enable', 'disable', 'run', 'executions'].includes(action)) return undefined - return async ({ req, res, body }) => { + const methods: HttpMethod[] = !action + ? ['GET', 'PATCH', 'DELETE'] + : action === 'executions' + ? ['GET'] + : ['POST'] + + return withMethods(methods, async ({ req, res, body }) => { try { if (!action && req.method === 'GET') { sendJson(res, 200, { task: await api.get(taskId) }) @@ -551,7 +718,7 @@ function createScheduledReportRoute( } catch (error) { sendScheduledError(res, error) } - } + }) } const MEDIA_ROUTE_PREFIX = '/api/v1/media/' @@ -562,46 +729,58 @@ function queryStatusCode(status: string): number { if (status === 'contact_not_found') return 404 if (status === 'ambiguous_contact') return 409 if (status === 'knowledge_unavailable') return 503 + if (status === 'voice_model_not_ready' || status === 'voice_transcription_unavailable') return 503 + if (status === 'busy') return 429 if (status === 'retrieval_incomplete') return 206 return 400 } -function createQueryRoute(api: LocalQueryApiService): RouteHandler | undefined { - return async ({ req, res, body }) => { - const pathname = new URL(req.url || '/', 'http://localhost').pathname - if (pathname === '/api/v1/query/capabilities') { - if (req.method !== 'GET') return sendError(res, 405, '需要 GET 请求') +function createQueryRoute(pathname: string, api: LocalQueryApiService): RouteHandler | undefined { + if (pathname === '/api/v1/query/capabilities') { + return withMethods(['GET'], ({ res }) => { return sendJson(res, 200, api.capabilities()) - } - if (req.method !== 'POST') return sendError(res, 405, '需要 POST 请求') - let payload: any + }) + } + type QueryOperationResult = + | Awaited> + | Awaited> + | Awaited> + | Awaited> + | Awaited> + const operations: Record Promise> = { + '/api/v1/query/messages': (payload) => + api.messages(payload as Parameters[0]), + '/api/v1/query/search': (payload) => + api.search(payload as Parameters[0]), + '/api/v1/query/message-context': (payload) => + api.context(payload as Parameters[0]), + '/api/v1/query/conversation-overview': (payload) => + api.overview(payload as Parameters[0]), + '/api/v1/query/voice-transcribe': (payload) => + api.transcribeVoice(payload as Parameters[0]) + } + const operation = operations[pathname] + if (!operation) return undefined + return withMethods(['POST'], async ({ res, body }) => { + let payload: unknown try { payload = JSON.parse(typeof body === 'string' ? body : '') } catch { return sendError(res, 400, 'invalid_request') } if (!payload || typeof payload !== 'object') return sendError(res, 400, 'invalid_request') try { - const result = pathname === '/api/v1/query/messages' - ? await api.messages(payload) - : pathname === '/api/v1/query/search' - ? await api.search(payload) - : pathname === '/api/v1/query/message-context' - ? await api.context(payload) - : pathname === '/api/v1/query/conversation-overview' - ? await api.overview(payload) - : undefined - if (!result) return sendError(res, 404, `端点不存在: ${pathname}`) + const result = await operation(payload) + if ('retryAfterSeconds' in result && typeof result.retryAfterSeconds === 'number') { + res.setHeader('Retry-After', String(result.retryAfterSeconds)) + } return sendJson(res, queryStatusCode(result.status), result) } catch (error) { return sendError(res, 400, error instanceof Error ? error.message : 'invalid_request') } - } + }) } function createMediaRoute( mediaProvider: (messageId: string) => Promise ): RouteHandler { - return async ({ req, res, url }) => { - if (req.method !== 'GET' && req.method !== 'HEAD') { - return sendError(res, 405, '需要 GET 请求') - } + return withMethods(['GET', 'HEAD'], async ({ req, res, url }) => { const encodedMessageId = url.pathname.slice(MEDIA_ROUTE_PREFIX.length) let messageId: string try { @@ -640,7 +819,218 @@ function createMediaRoute( safeError('[HttpServer] media request failed:', error) return sendError(res, 500, '图片读取失败') } + }) +} + +function createAgentApiService(options: HttpServerOptions): LocalAgentApiService { + const groupStats = options.groupStatsService || configuredGroupStatsService + return options.agentApiService || new LocalAgentApiService({ + automationRuleStore, + automationExecutionLogService, + listContacts: listContactsAsync, + isDatabaseReady: isReady, + getVersion: options.appVersionProvider || getApplicationVersion, + getPersonalWechatCapability: () => + personalWechatCapabilityService.getPersonalWechatSendCapability(), + getAgentHubStatus: () => agentHubService.getStatus(), + getGroupExitMonitorState: () => { + const state = groupExitMonitorService.getState() + return { ...state, monitoredRoomIds: state.monitoredRoomIds || [] } + }, + configureGroupExitMonitor: (configuration) => + groupExitMonitorService.configure(configuration), + setGroupExitMonitorRoomIds: (roomIds) => groupExitMonitorService.setMonitoredRoomIds(roomIds), + setGroupExitMonitorEnabled: (enabled) => groupExitMonitorService.setEnabled(enabled), + listGroupExitMonitorEvents: (query) => groupExitMonitorService.listEvents(query), + ...(groupStats ? { getGroupMemberStats: (query) => groupStats.getMemberStats(query) } : {}) + }) +} + +function sendAgentApiError(res: ServerResponse, error: unknown): void { + const requestId = String(res.getHeader('X-Request-Id') || '') + if (error instanceof LocalAgentApiError) { + sendAgentHttpError(res, error.status, error.code, error.message, error.details) + return } + if (error instanceof AutomationRulePersistenceError) { + sendAgentHttpError(res, 500, 'PERSISTENCE_FAILED', '自动化规则未能保存到本地') + return + } + safeError(`[HttpServer requestId=${requestId}] Agent API request failed:`, error) + sendAgentHttpError(res, 500, 'INTERNAL_ERROR', 'Agent API 请求失败') +} + +async function handleAgentApi( + res: ServerResponse, + operation: () => Promise | T, + respond: (value: T) => void +): Promise { + try { + respond(await operation()) + } catch (error) { + sendAgentApiError(res, error) + } +} + +function parseAgentJson(body: unknown): unknown { + if (typeof body !== 'string' || !body.trim()) { + throw new LocalAgentApiError(400, 'INVALID_ARGUMENT', '请求体不能为空') + } + try { + return JSON.parse(body) + } catch { + throw new LocalAgentApiError(400, 'INVALID_ARGUMENT', '请求体 JSON 格式无效') + } +} + +function createAgentApiRoute( + pathname: string, + api: LocalAgentApiService +): RouteHandler | undefined { + if (pathname === '/api/v1/capabilities') { + return withMethods(['GET'], ({ res }) => + void handleAgentApi(res, () => api.getCapabilities(), (capabilities) => + sendJson(res, 200, capabilities) + ) + ) + } + + const groupExitMonitorPath = '/api/v1/monitors/group-exits' + if (pathname === groupExitMonitorPath) { + return withMethods(['GET', 'PATCH'], async ({ req, res, body }) => { + if (req.method === 'GET') { + await handleAgentApi(res, () => api.getGroupExitMonitorState(), (state) => + sendJson(res, 200, state) + ) + return + } + await handleAgentApi(res, () => api.updateGroupExitMonitor(parseAgentJson(body)), (state) => + sendJson(res, 200, state) + ) + }) + } + + if (pathname === `${groupExitMonitorPath}/events`) { + return withMethods(['GET'], ({ res, url }) => + void handleAgentApi(res, () => api.listGroupExitMonitorEvents(url.searchParams), (result) => + sendJson(res, 200, result) + ) + ) + } + + const groupStatsPrefix = '/api/v1/groups/' + if (pathname.startsWith(groupStatsPrefix)) { + const segments = pathname.slice(groupStatsPrefix.length).split('/') + if (segments.length === 2 && segments[1] === 'member-stats' && segments[0]) { + let conversationId: string + try { + conversationId = decodeURIComponent(segments[0]) + } catch { + return undefined + } + return withMethods(['GET'], ({ res, url }) => + void handleAgentApi( + res, + () => api.getGroupMemberStats(conversationId, url.searchParams), + (result) => sendJson(res, 200, result) + ) + ) + } + } + + const automationCollection = '/api/v1/automations' + if (pathname === automationCollection) { + return withMethods(['GET', 'POST'], async ({ req, res, url, body }) => { + if (req.method === 'GET') { + await handleAgentApi( + res, + () => api.listAutomations({ + type: url.searchParams.get('type'), + enabled: url.searchParams.get('enabled') + }), + (rules) => sendJson(res, 200, { count: rules.length, rules }) + ) + return + } + await handleAgentApi(res, () => api.createAutomation(parseAgentJson(body)), (rule) => + sendJson(res, 201, { created: true, rule }) + ) + }) + } + + if (pathname === `${automationCollection}/validate`) { + return withMethods(['POST'], async ({ res, body }) => { + await handleAgentApi(res, () => api.validateAutomation(parseAgentJson(body)), (result) => + sendJson(res, 200, result) + ) + }) + } + + if (pathname === `${automationCollection}/executions`) { + return withMethods(['GET'], ({ res, url }) => + void handleAgentApi(res, () => api.listExecutions(url.searchParams), (result) => + sendJson(res, 200, result) + ) + ) + } + + const prefix = `${automationCollection}/` + if (!pathname.startsWith(prefix)) return undefined + const segments = pathname.slice(prefix.length).split('/').filter(Boolean) + if (segments.length < 1 || segments.length > 2) return undefined + let id: string + try { + id = decodeURIComponent(segments[0]) + } catch { + return undefined + } + if (!id || id.includes('/') || id.includes('\\')) return undefined + const action = segments[1] + if (action && action !== 'enable' && action !== 'disable') return undefined + + if (action) { + return withMethods(['POST'], ({ res }) => + void handleAgentApi(res, () => api.setAutomationEnabled(id, action === 'enable'), (rule) => + sendJson(res, 200, { updated: true, rule }) + ) + ) + } + + return withMethods(['GET', 'PATCH', 'DELETE'], async ({ req, res, body }) => { + if (req.method === 'GET') { + await handleAgentApi(res, () => api.getAutomation(id), (rule) => + sendJson(res, 200, { rule }) + ) + return + } + if (req.method === 'PATCH') { + await handleAgentApi( + res, + () => api.updateAutomation(id, parseAgentJson(body)), + (rule) => sendJson(res, 200, { updated: true, rule }) + ) + return + } + await handleAgentApi(res, () => api.deleteAutomation(id), (result) => + sendJson(res, 200, { deleted: true, ...result }) + ) + }) +} + +function requestIdFor(req: IncomingMessage): string { + const incoming = req.headers['x-request-id'] + return typeof incoming === 'string' && /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/.test(incoming) + ? incoming + : crypto.randomUUID() +} + +function isAgentApiPath(pathname: string): boolean { + return pathname === '/api/v1/capabilities' || + pathname === '/api/v1/monitors/group-exits' || + pathname.startsWith('/api/v1/monitors/group-exits/') || + pathname.startsWith('/api/v1/groups/') || + pathname === '/api/v1/automations' || + pathname.startsWith('/api/v1/automations/') } export function startHttpServer( @@ -652,11 +1042,19 @@ export function startHttpServer( const mediaProvider = options.mediaProvider || readImageMedia const scheduledReportApi = createScheduledReportApi(options) const queryApi = options.queryApiService || configuredQueryApiService || new LocalQueryApiService() + const agentApi = createAgentApiService(options) return new Promise((resolve, reject) => { const server: Server = http.createServer(async (req, res) => { + const requestId = requestIdFor(req) + res.setHeader('X-Request-Id', requestId) + let agentApiRequest = false try { const url = new URL(req.url || '/', `http://${host}:${port}`) + agentApiRequest = isAgentApiPath(url.pathname) if (!applyCorsHeaders(req, res)) { + if (agentApiRequest) { + return sendAgentHttpError(res, 403, 'FORBIDDEN', 'Origin 不允许访问本地 API') + } return sendError(res, 403, 'Origin 不允许访问本地 API') } if (req.method === 'OPTIONS') { @@ -665,15 +1063,37 @@ export function startHttpServer( } const handler = routes[url.pathname] || + createAgentApiRoute(url.pathname, agentApi) || createScheduledReportRoute(url.pathname, scheduledReportApi) || - (url.pathname.startsWith(QUERY_ROUTE_PREFIX) ? createQueryRoute(queryApi) : undefined) || + (url.pathname.startsWith(QUERY_ROUTE_PREFIX) + ? createQueryRoute(url.pathname, queryApi) + : undefined) || (url.pathname.startsWith(MEDIA_ROUTE_PREFIX) ? createMediaRoute(mediaProvider) : undefined) if (!handler) { + if (agentApiRequest) { + return sendAgentHttpError(res, 404, 'NOT_FOUND', `端点不存在: ${url.pathname}`) + } return sendError(res, 404, `端点不存在: ${url.pathname}`) } + if (!handler.allowedMethods.includes(req.method as HttpMethod)) { + if (agentApiRequest) { + res.setHeader('Allow', handler.allowedMethods.join(', ')) + return sendAgentHttpError( + res, + 405, + 'METHOD_NOT_ALLOWED', + `请求方法不受支持;允许的方法:${handler.allowedMethods.join(', ')}`, + { allowedMethods: handler.allowedMethods } + ) + } + return sendMethodNotAllowed(res, handler.allowedMethods) + } if (url.pathname !== '/api/v1/health' && !isAuthorized(req, tokenProvider())) { + if (agentApiRequest) { + return sendAgentHttpError(res, 401, 'UNAUTHORIZED', 'Valid API token required') + } return sendUnauthorized(res) } let body: string | undefined @@ -683,8 +1103,22 @@ export function startHttpServer( const ctx: RouteContext = { req, res, url, body } await handler(ctx) } catch (error) { - safeError('[HttpServer] 请求处理失败:', error) + if (error instanceof RequestBodyTooLargeError) { + res.setHeader('Connection', 'close') + res.shouldKeepAlive = false + if (agentApiRequest) { + sendAgentHttpError(res, 413, 'PAYLOAD_TOO_LARGE', '请求体不能超过 1 MiB') + return + } + sendError(res, 413, '请求体不能超过 1 MiB') + return + } + safeError(`[HttpServer requestId=${requestId}] 请求处理失败:`, error) if (!res.headersSent) { + if (agentApiRequest) { + sendAgentHttpError(res, 500, 'INTERNAL_ERROR', 'Agent API 请求失败') + return + } sendError(res, 500, error instanceof Error ? error.message : String(error)) } } diff --git a/src/main/index.ts b/src/main/index.ts index 8cc1012..faae0bf 100644 --- a/src/main/index.ts +++ b/src/main/index.ts @@ -1,3 +1,4 @@ +import path from 'node:path' import { isLegacyMigrationHelper, isUserDataIsolated, @@ -21,7 +22,10 @@ import { dirname, extname, join } from 'path' import { existsSync, promises as fsPromises } from 'fs' import { electronApp, optimizer, is } from '@electron-toolkit/utils' import icon from '../../resources/icon.png?asset' +import trayTemplateIcon from '../../resources/trayTemplate.png?asset' +import trayTemplateRetinaIcon from '../../resources/trayTemplate@2x.png?asset' import { WechatDb } from './wechat-db' +import { createTrayImage } from './tray-icon' import { bootstrapWcdbNativeAsync, Wcdb4Client } from './wcdb4-client' import { VoiceService } from './voice-service' import { StickerService } from './sticker-service' @@ -73,7 +77,12 @@ import type { SystemOcrCapability, SystemOcrRequest, SystemOcrResult } from '../ import { KeyServiceMac } from './key-service-mac' import { KeyService as KeyServiceWin } from './key-service-win' import * as chat from './services/chat-service' -import { apiServer, setLocalQueryApiService } from './http-server' +import { + apiServer, + setLocalGroupStatsService, + setLocalQueryApiService, + setLocalVoiceTranscriptSnapshotProvider +} from './http-server' import { skillResourceService } from './services/skill-resource-service' import { buildLocalApiCurlCommand, testLocalApiRequest } from './services/local-api-test-service' import { isWechatRunning } from './services/wechat-process-status' @@ -85,6 +94,7 @@ import type { SaveImageKeyRequest, TestImageDecryptionRequest } from '../shared/ import { loadSettings, saveSettings, + updateSettings, getSettingsPath, AppSettings, validateDbRoot @@ -121,7 +131,243 @@ import { MessageListenerService } from './services/message-listener-service' import { automationRuleStore } from './services/automation-rule-store' import { automationExecutionLogService } from './services/automation-execution-log-service' import { initAutomationService, getAutomationService } from './services/automation-service' +import { + applyMsgInsertSwitch, + emptyMsgInsertStatus, + eventModeStatus, + readMsgInsertSwitches, + reconcileMsgInsertRules, + resolveHelperPath, + resolveTargetRooms, + type MsgInsertScopeInput, + type MsgInsertSwitchName, + type MsgInsertSwitchesSnapshot +} from './services/msg-insert-switch-service' import { GroupStatsService } from './services/group-stats-service' +import { + configureWechatLocalExitNotice, + wechatLocalExitNoticeService +} from './services/wechat-local-exit-notice-service' + +/** 「微信内退群监控消息」覆盖的群聊数(开关卡片的范围说明用,不是覆盖率)。 */ +function exitNoticeGroupCount(): number { + return groupExitMonitorService.getNoticeGroupCount() +} + +/** + * 把「微信内退群监控消息」的开关状态同步给退群监控。 + * + * 注入的只是**开关**:群清单由 monitor 自己在刷新群名时一并更新, + * 这里不维护第二份。检测范围会成为「勾选的群 ∪ 全部群聊」,两个消费者都能拿到事件。 + */ +function syncExitNoticeScope(): void { + try { + groupExitMonitorService.setNoticeEnabled(wechatLocalExitNoticeService.isEnabled()) + } catch (error) { + console.warn('[MsgInsert] 同步退群内提示范围失败:', error) + } +} + +/** + * 微信消息插入开关的作用面输入。 + * + * 防撤回用「全部可定位会话」;退群监控的勾选只服务自动化通知,不再是内提示的范围。 + * 数据库没连上时返回 null,调用方据此禁用写入而不是假装能改。 + */ +function resolveMsgInsertScopeInput(): MsgInsertScopeInput | null { + const client = chat.getChatDb()?.getWcdb4Client() + if (!client) return null + return { + client, + monitoredRoomIds: groupExitMonitorService.getState().monitoredRoomIds || [] + } +} + +/** + * 组装「微信消息插入开关」的快照。**纯读**:不写微信库、不触发 DDL。 + * + * 抽出来是为了让 GET 与「运行期刷新」共用同一份展示口径(含退群提示这个本地事件开关), + * 避免两处各拼一遍导致漂移。 + */ +function buildMsgInsertSwitchesSnapshot(): MsgInsertSwitchesSnapshot { + const scope = resolveMsgInsertScopeInput() + if (scope) { + const snapshot = readMsgInsertSwitches(scope) + /* 退群提示的开关状态来自本地设置(事件驱动,不装规则), + * 不是微信库里的 _tm_config。 */ + snapshot.switches.group_exit_notice = eventModeStatus( + 'group_exit_notice', + wechatLocalExitNoticeService.isEnabled(), + exitNoticeGroupCount() + ) + return snapshot + } + return { + success: false, + switches: { + recall_notice: emptyMsgInsertStatus('recall_notice'), + group_exit_notice: eventModeStatus( + 'group_exit_notice', + wechatLocalExitNoticeService.isEnabled() + ) + }, + helperAvailable: resolveHelperPath() !== null, + detail: '微信数据库尚未连接' + } +} + +/** + * 轻量 reconciliation —— 把退群监控选中的群缺失的规则补齐,不动开关值。 + * + * 触发点:连库完成后 / 退群监控群列表变化后 / 用户打开开关时(那条在 service 里)。 + * 不轮询。微信新建 message_4.db 并把目标群的新表放进去时,下一次触发就会补上。 + */ +let lastMsgInsertReconciledShards = '' + +/** + * 启动时补齐 —— 防撤回 reconciliation 的入口之一。 + * + * 只在**持久化的开关已经是开**的时候跑(说明用户上次明确打开过)。开关是关的 + * 就什么都不做,避免每次启动都扫一遍目标会话。 + * + * 顺带覆盖「已启用时检测到新 shard / 新表」:分片清单变了就重新补齐,并把新的 + * 清单记下来。渲染层读状态**不会**走到这里 —— GET 必须是纯读。 + */ +async function reconcileMsgInsertRulesOnStart(): Promise { + const scope = resolveMsgInsertScopeInput() + const client = chat.getChatDb()?.getWcdb4Client() + if (!scope || !client) return + + let enabled = false + try { + const shards = client.listMessageShardPaths() + const shardSignature = shards.map((item) => path.basename(item)).join(',') + if (lastMsgInsertReconciledShards && lastMsgInsertReconciledShards !== shardSignature) { + /* 微信新建了 message_N.db(或清理了旧的)—— 分片集合变了就重新补齐。 */ + console.log('[MsgInsert] 检测到消息分片变化,重新补齐规则') + } + lastMsgInsertReconciledShards = shardSignature + for (const shardPath of shards) { + const read = client.getMsgInsertSwitches(shardPath) + if (read.success && read.switches?.recall_notice) { + enabled = true + break + } + } + } catch (error) { + console.warn('[MsgInsert] 启动检查失败:', error) + return + } + if (!enabled) return + await reconcileMsgInsertRulesNow(recallRoomsForReconcile(scope)) +} + +/** + * 防撤回的作用面 = 全部可定位会话(群聊 + 私聊)。 + * + * native 侧有「定义漂移就 DROP + 重建」的能力,但只有显式复核时才会跑; + * 规则定义变了不自动铺开,用户就得手动关-开一次开关。 + */ +function recallRoomsForReconcile(scope: MsgInsertScopeInput): string[] { + return resolveTargetRooms(scope, 'recall_notice').rooms +} + +async function reconcileMsgInsertRulesNow(extraRooms: string[] = []): Promise { + const scope = resolveMsgInsertScopeInput() + const client = chat.getChatDb()?.getWcdb4Client() + if (!scope || !client) return false + try { + const result = await reconcileMsgInsertRules({ + ...scope, + extraRooms, + myWxid: String(chat.getSelfAccountInfo()?.wxid || ''), + databaseKey: client.getKey() + }) + if (result.rooms === 0) { + // 群列表还没就绪(或用户本来就没选群)—— 不算跑过,让下一次触发重试。 + return false + } + if (!result.done) { + console.warn(`[MsgInsert] reconcile 未完成 errorCode=${result.errorCode || 'UNKNOWN'}`) + } + return true + } catch (error) { + console.warn('[MsgInsert] reconcile 失败:', error) + return true + } +} + +/** + * 清理老版防撤回保护(recall journal)留在微信库里的 `_wxe_capture_*` 触发器。 + * + * 那批触发器装进库里就没人卸载(应用关闭该功能时直接 return),会一直抓取;而且它 + * 和新机制的触发器挂在同一张 `Msg_*` 表上抢事件。 + * + * 边界:先只读扫描、有残留才写库;只删触发器、不删老日志表(表里是微信已删、可能 + * 只剩一份的副本);日志只记数量(对象名含 sha1(会话表名) 派生的稳定标识)。 + */ +async function cleanupLegacyRecallResidueOnStart(): Promise { + const client = chat.getChatDb()?.getWcdb4Client() + if (!client) return + try { + const report = client.scanLegacyRecallResidue() + if (!report.found) return + + console.log( + `[RecallResidue] 检测到老版防撤回残留 shards=${report.shards.length} triggers=${report.triggerCount}` + + ` journals=${report.journalCount} blockingDelete=${report.blockingDeleteCount}` + + ` blockingInsert=${report.blockingInsertCount} passive=${report.passiveCount}` + ) + appLogger.write({ + level: 'warn', + scope: 'recall-residue', + message: '检测到老版防撤回残留,开始清理', + details: { + shards: report.shards.length, + triggers: report.triggerCount, + journals: report.journalCount, + blockingDelete: report.blockingDeleteCount, + blockingInsert: report.blockingInsertCount, + passive: report.passiveCount + } + }) + + /* + * 删除必须借 helper 的可写连接:本进程对分片只有只读连接,自己发 DROP 一定失败。 + * helper 那条链路会在装规则时顺手清掉残留,顺带把新规则铺到所有会话。 + */ + const scope = resolveMsgInsertScopeInput() + const applied = scope ? await reconcileMsgInsertRulesNow(recallRoomsForReconcile(scope)) : false + + /* 收尾结论以「重新扫描」为准,不采信 helper 的自述。 */ + const after = client.scanLegacyRecallResidue() + const cleared = after.triggerCount === 0 + console.log( + `[RecallResidue] 清理${cleared ? '完成' : '未完成'} applied=${applied} remainingTriggers=${after.triggerCount}` + + ` remainingJournals=${after.journalCount}` + ) + appLogger.write({ + level: cleared ? 'info' : 'warn', + scope: 'recall-residue', + message: cleared ? '老版防撤回残留清理完成' : '老版防撤回残留清理未完成', + details: { + requested: report.triggerCount, + remainingTriggers: after.triggerCount, + remainingJournals: after.journalCount, + helperApplied: applied + } + }) + } catch (error) { + /* 清理失败绝不能挡住启动 —— 它只是收尾工作。 */ + console.warn('[RecallResidue] 清理失败:', error) + appLogger.write({ + level: 'warn', + scope: 'recall-residue', + message: '老版防撤回残留清理失败', + details: { reason: error instanceof Error ? error.message : String(error) } + }) + } +} import { wechatActionLogService } from './services/wechat-action-log-service' import { toPersonalWechatSendResult, wechatActionGateway } from './services/wechat-action-gateway' import { personalWechatSendService } from './services/personal-wechat-send-service' @@ -167,6 +413,7 @@ import type { ExportRequest } from '../shared/export' import { discoverAccounts } from './services/account-discovery' import { VoiceRecognitionUseCase } from './voice-pipeline/voice-recognition-use-case' import { VoiceBatchService } from './voice-pipeline/voice-batch-service' +import { VoiceTranscriptionGateway } from './voice-pipeline/voice-transcription-gateway' import type { VoiceBatchRequest, VoiceMessageReference } from '../shared/voice-recognition' import type { AiSearchPipelineRequest } from '../shared/ai-search' import type { @@ -323,6 +570,11 @@ function configureRecallProtection( recallJournalTimer = null } configureRecallArchive(enabled ? accountRoot : '') + /* + * 读取路径必须跟开关一起走:老 recall journal 的合并以前是无条件的, + * 于是「关掉防撤回」对用户等于没关(消息照样在,且不带撤回标记)。 + */ + wcdb4Client.setRecallJournalEnabled(enabled) if (!enabled) return const monitor = new RecallArchiveMonitor( @@ -370,6 +622,18 @@ function configureRecallProtection( const packagedIconPath = join(process.resourcesPath, 'resources', 'icon.png') const appIconPath = existsSync(packagedIconPath) ? packagedIconPath : icon +const packagedTrayTemplateIconPath = join(process.resourcesPath, 'resources', 'trayTemplate.png') +const packagedTrayTemplateRetinaIconPath = join( + process.resourcesPath, + 'resources', + 'trayTemplate@2x.png' +) +const trayTemplateIconPath = existsSync(packagedTrayTemplateIconPath) + ? packagedTrayTemplateIconPath + : trayTemplateIcon +const trayTemplateRetinaIconPath = existsSync(packagedTrayTemplateRetinaIconPath) + ? packagedTrayTemplateRetinaIconPath + : trayTemplateRetinaIcon protocol.registerSchemesAsPrivileged([ { @@ -542,8 +806,27 @@ function createWindow(): void { mainWindow.show() }) + /** 隐藏到托盘。关闭弹窗的"最小化"与"已记住托盘"两条路径共用同一套副作用。 */ + const minimizeToTray = (): void => { + setupTray() + mainWindow.hide() + if (process.platform === 'darwin') app.dock?.hide() + } + mainWindow.on('close', (event) => { if (isQuitting || appShutdownRequested) return + // 用户在关闭弹窗里勾过"记住我的选择"就照做,不再每次都弹。 + const remembered = loadSettings().closeAction + if (remembered === 'quit') { + isQuitting = true + app.quit() + return + } + if (remembered === 'tray') { + event.preventDefault() + minimizeToTray() + return + } event.preventDefault() if (closePromptInFlight) return closePromptInFlight = true @@ -556,16 +839,19 @@ function createWindow(): void { buttons: ['最小化到系统托盘', '关闭进程', '取消'], defaultId: 0, cancelId: 2, + // 勾了就记住这次的选择,之后不再弹窗;设置页里随时可以改回来。 + checkboxLabel: '记住我的选择,下次不再询问', + checkboxChecked: false, noLink: true }) - .then(({ response }) => { + .then(({ response, checkboxChecked }) => { if (response === 0) { - setupTray() - mainWindow.hide() - if (process.platform === 'darwin') app.dock?.hide() + if (checkboxChecked) updateSettings({ closeAction: 'tray' }) + minimizeToTray() return } if (response === 1) { + if (checkboxChecked) updateSettings({ closeAction: 'quit' }) isQuitting = true app.quit() } @@ -790,6 +1076,7 @@ app.whenReady().then(async () => { // 群员统计复用同一个 Knowledge 实例:它只是「读派生库 + 读成员名单」的编排, // 不持有自己的数据库,也不新建索引。 groupStatsService = new GroupStatsService(knowledgeSearchService) + setLocalGroupStatsService(groupStatsService) // 图片文字索引覆盖度是**独立覆盖维度**:接到 search_messages 的 tool result 上, // 让 Query Agent 在图片索引没做完时不能凭 0 条证据断言"没有"。 localQueryApiService.setImageTextCoverageProvider(() => @@ -807,6 +1094,15 @@ app.whenReady().then(async () => { localQueryApiService.setImageOcrEntryProvider((conversationId, messageId) => imageTextIndexService.getConversationOcr(conversationId).get(messageId) ) + /** + * 语音转写:读消息时只读缓存快照;只有 query/voice-transcribe 会真正排队识别, + * 识别仍走同一个 VoiceRecognitionUseCase(同一份缓存、同一条串行队列)。 + */ + const voiceTranscriptionGateway = new VoiceTranscriptionGateway(voiceRecognition) + localQueryApiService.setVoiceTranscriptionGateway(voiceTranscriptionGateway) + setLocalVoiceTranscriptSnapshotProvider((reference) => + voiceTranscriptionGateway.snapshot(reference) + ) setLocalQueryApiService(localQueryApiService) // Query Agent:生产 Runtime 只在这里实例化一次,桌面问问微信与 Agent Hub 共用同一个实例。 queryAgentService = new QueryAgentService( @@ -921,8 +1217,6 @@ app.whenReady().then(async () => { // 设置应用程序用户模型 ID electronApp.setAppUserModelId('com.tracememo.app') - if (process.platform === 'darwin') app.dock?.setIcon(appIconPath) - // 开发环境中默认使用 F12 打开或关闭 DevTools // 生产环境中忽略 CommandOrControl + R // 参见 https://github.com/alex8088/electron-toolkit/tree/master/packages/utils @@ -1073,7 +1367,43 @@ app.whenReady().then(async () => { * `handleGroupExit` 自己吞掉异常,这里再兜一层 `.catch` 是防御性的 —— * 未捕获的 rejection 会污染监控循环,而退群事实早就已经记录成功了。 */ + /* 退群本地提示的运行时依赖:密钥 / wxid / 账号目录都由主进程提供, + * 服务自己不依赖 chat-service 的具体形态。 */ + configureWechatLocalExitNotice({ + resolveDatabaseKey: () => chat.getChatDb()?.getWcdb4Client()?.getKey() || '', + resolveMyWxid: () => String(chat.getSelfAccountInfo()?.wxid || ''), + resolveAccountRoot: () => { + const shards = chat.getChatDb()?.getWcdb4Client()?.listMessageShardPaths() || [] + if (shards.length > 0) return path.dirname(path.dirname(path.dirname(shards[0]))) + return String(chat.getCurrentAccountRoot() || '') + } + }) + + /* + * 防撤回 reconciliation 的启动入口:只有当持久化的开关已经是「开」时才会跑。 + * 渲染层读状态、群列表变化都不会触发 DDL。 + */ + void reconcileMsgInsertRulesOnStart() + /* + * 老防撤回残留收尾:只读扫描 → 有残留才写库(清理走 helper 的可写通道, + * 判定规则与边界见函数注释)。 + */ + void cleanupLegacyRecallResidueOnStart() + groupExitMonitorService.setGroupExitHandler((event) => { + /* + * 同一个退群事件按**各自的范围**分发给两个消费者: + * + * - 微信内退群监控消息:范围 = 全部群聊(开关开着就全覆盖); + * - 自动化退群通知:范围 = 退群监控里勾选的群。 + * + * 两者互不依赖:内提示不抛异常、不 await(handleExitEvent 内部兜底), + * 插入失败不会影响自动化通知,反之亦然。 + */ + if (groupExitMonitorService.isNoticeRoom(event.conversationId)) { + void wechatLocalExitNoticeService.handleExitEvent(event) + } + if (!groupExitMonitorService.isMonitoredRoom(event.conversationId)) return undefined try { return getAutomationService() .handleGroupExit(event) @@ -1093,6 +1423,8 @@ app.whenReady().then(async () => { return undefined } }) + /* 把「微信内退群监控消息」的开关交给 monitor:开着时检测范围扩到全部群聊。 */ + syncExitNoticeScope() messageListener.onMessage((message) => { // 日志只允许出现「类型 / 群或私聊 / 是否自己发 / @ 数量」这类不可逆标识, // 不含 wxid、昵称、群名、正文与 source。 @@ -1679,6 +2011,8 @@ app.whenReady().then(async () => { * 只有一个参数:旧版第二个参数(通知群聊)已经迁到「自动化 → 退群通知」, * 退群监控不再持有任何通知配置。 */ + /* 监控范围变化不再触发任何规则补齐:防撤回的目标是「全部有消息表的会话」, + * 与退群监控选中的群无关;退群提示也已经改成事件驱动、不依赖 per-room 规则。 */ ipcMain.handle('group-exit-monitor:setGroups', (_, roomIds: string[]) => groupExitMonitorService.setMonitoredRoomIds(Array.isArray(roomIds) ? roomIds : []) ) @@ -1743,6 +2077,107 @@ app.whenReady().then(async () => { }) ipcMain.handle('automation:clearExecutions', () => automationExecutionLogService.clear()) ipcMain.handle('automation:listGroups', () => tryAutomationService()?.listGroups() ?? []) + /** + * 微信消息插入开关 —— 读取。 + * + * 只走本进程只读路径(分片目录 + 开关值),不持有任何写权限。 + * 状态里同时给出 desiredEnabled / effectiveEnabled:开关值写成功不等于功能 + * 真的生效(规则可能没装齐),渲染层不能只看前者。 + */ + ipcMain.handle('automation:getMsgInsertSwitches', () => { + /* 🔴 纯读:任何 get/status 都不允许写微信库、不允许触发 DDL。 + * 需要顺带补齐规则的场景走 automation:refreshMsgInsertSwitches。 */ + return buildMsgInsertSwitchesSnapshot() + }) + /** + * 微信消息插入开关 —— **运行期刷新**(允许在分片集合变化时补一次规则)。 + * + * 与 GET 的分工:GET 必须纯读;但"微信运行期间新建了 message_N.db"这种情况需要补规则, + * 否则新分片里的会话永远显示未就绪 —— 而规则补齐只在**启动时**跑过一次。 + * 用户侧看到的表现就是"计数变了,但分子追不上分母"。 + * + * 成本控制:分片清单指纹没变 → 只做纯读立刻返回;变了才 spawn 一次 helper。 + */ + ipcMain.handle('automation:refreshMsgInsertSwitches', async () => { + const scope = resolveMsgInsertScopeInput() + const client = chat.getChatDb()?.getWcdb4Client() + if (scope && client) { + try { + const signature = client + .listMessageShardPaths() + .map((item) => path.basename(item)) + .join(',') + if (signature !== lastMsgInsertReconciledShards) { + lastMsgInsertReconciledShards = signature + console.log('[MsgInsert] 运行期检测到消息分片变化,重新补齐规则') + await reconcileMsgInsertRulesNow(recallRoomsForReconcile(scope)) + } + } catch (error) { + console.warn('[MsgInsert] 运行期补齐失败:', error) + } + } + return buildMsgInsertSwitchesSnapshot() + }) + /** + * 微信消息插入开关 —— 写入。 + * + * 绝不使用本进程的 WCDB 句柄写(只读池会把它钉死)。这里 spawn 一次性 helper: + * 先补齐目标会话的规则 → 再写开关值 → 读回校验 → 本进程只读复核。 + * 失败不伪装成功:partial 会带 failedShards / notReadyRooms 回渲染层。 + */ + ipcMain.handle('automation:setMsgInsertSwitch', async (_, input: unknown) => { + const payload = (input || {}) as { name?: unknown; enabled?: unknown } + const name = String(payload.name || '') as MsgInsertSwitchName + if (name !== 'recall_notice' && name !== 'group_exit_notice') { + return { + success: false, + status: emptyMsgInsertStatus('recall_notice'), + errorCode: 'UNSUPPORTED_SWITCH', + message: '未知的开关' + } + } + /* + * 退群提示是**事件驱动**的(GroupExitMonitorService 发事件 → 一次性插一条), + * 不装任何 per-room 规则。所以它的开关只是本地设置: + * 既不 spawn helper,也不碰微信库。 + */ + if (name === 'group_exit_notice') { + const toggled = wechatLocalExitNoticeService.setEnabled(payload.enabled === true) + if (toggled.error) { + return { + success: false, + status: eventModeStatus(name, toggled.enabled, exitNoticeGroupCount()), + errorCode: 'UNKNOWN', + message: '保存开关状态失败' + } + } + /* 开关一变,检测范围随之变(开 → 全部群聊;关 → 只剩勾选的群)。 */ + syncExitNoticeScope() + return { + success: true, + status: eventModeStatus(name, toggled.enabled, exitNoticeGroupCount()) + } + } + + const scope = resolveMsgInsertScopeInput() + const client = chat.getChatDb()?.getWcdb4Client() + if (!scope || !client) { + return { + success: false, + status: emptyMsgInsertStatus(name), + errorCode: 'DATABASE_UNAVAILABLE', + message: '微信数据库尚未连接' + } + } + return applyMsgInsertSwitch({ + ...scope, + name, + enabled: payload.enabled === true, + myWxid: String(chat.getSelfAccountInfo()?.wxid || ''), + /* 密钥只在这里读一次,随后直接进 helper 的 stdin,绝不落盘 / 进 argv */ + databaseKey: client.getKey() + }) + }) /** * 保存「退群通知」规则(singleton upsert)。 * @@ -2875,11 +3310,12 @@ function buildTrayMenu(): Menu { function setupTray(): void { if (tray) return try { - const image = nativeImage.createFromPath(appIconPath) - const traySize = process.platform === 'darwin' ? 20 : 24 - const trayImage = image.isEmpty() - ? nativeImage.createEmpty() - : image.resize({ width: traySize, height: traySize, quality: 'best' }) + const trayImage = createTrayImage( + process.platform, + appIconPath, + { oneX: trayTemplateIconPath, twoX: trayTemplateRetinaIconPath }, + nativeImage + ) tray = new Tray(trayImage) tray.setToolTip('TraceMemo') // macOS may show a Tray context menu on a primary click when it is set diff --git a/src/main/runtime-mode.ts b/src/main/runtime-mode.ts index df787bd..42f0c4a 100644 --- a/src/main/runtime-mode.ts +++ b/src/main/runtime-mode.ts @@ -5,8 +5,13 @@ import { join } from 'path' export function isPackagedRuntime(): boolean { if (app.isPackaged) return true + // 非 Electron 进程(例如单元/集成测试)里 process.resourcesPath 不存在, + // 此时 join 会抛错。没有 resources 目录就必然不是打包运行时。 + const resourcesPath = process.resourcesPath + if (!resourcesPath) return false + return ( - existsSync(join(process.resourcesPath, 'app.asar')) && - existsSync(join(process.resourcesPath, 'app-update.yml')) + existsSync(join(resourcesPath, 'app.asar')) && + existsSync(join(resourcesPath, 'app-update.yml')) ) } diff --git a/src/main/services/agent-hub-routing.ts b/src/main/services/agent-hub-routing.ts index 7334100..a37a1c4 100644 --- a/src/main/services/agent-hub-routing.ts +++ b/src/main/services/agent-hub-routing.ts @@ -148,12 +148,48 @@ export function resolveInboundRoute(text: string): InboundRoute { /** 查询大脑不可用时的统一文案(不暴露 stack / provider raw response / 内部 id)。 */ 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 结果映射成**微信文字回复**。 * 只输出用户可读文本;Tool trace / temporalBasis / Evidence / 诊断字段一律不下发。 */ 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 // Agent Hub 没有 Legacy runner,不会产生 legacy 结果;真出现时按服务不可用处理,不暴露内部结构。 return QUERY_AGENT_UNAVAILABLE_TEXT diff --git a/src/main/services/agent-hub-service.ts b/src/main/services/agent-hub-service.ts index fd09afc..06e1167 100644 --- a/src/main/services/agent-hub-service.ts +++ b/src/main/services/agent-hub-service.ts @@ -17,6 +17,7 @@ import { QueryAgentService } from './query-agent-service' import { AskWechatService } from './ask-wechat-service' import { QUERY_AGENT_UNAVAILABLE_TEXT, + formatWechatReplyText, queryAgentReplyText, resolveInboundRoute, type GroupMemberChatIntent, @@ -700,7 +701,7 @@ export class AgentHubService { { requestId: `agent-hub-${Date.now()}-${this.nextLogId}`, text }, conversationKey ) - await this.sendToConversation(conversation, this.formatAIReply(queryAgentReplyText(result))) + await this.sendToConversation(conversation, formatWechatReplyText(queryAgentReplyText(result))) this.addLog('agent-hub', 'info', `查询回答已发送(${result.status})`) } catch (error) { this.addLog('agent-hub', 'error', `查询处理失败:${this.errorMessage(error)}`) @@ -834,7 +835,7 @@ export class AgentHubService { } await this.sendToConversation( conversation, - this.formatAIReply( + formatWechatReplyText( `${displayName}在“${group.m_nsNickName}”的发言总结(共 ${messages.length} 条):\n\n${summary.data.trim().slice(0, 3500)}` ) ) @@ -850,15 +851,6 @@ export class AgentHubService { 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( conversation: AgentHubTarget, intent: GroupReportIntent diff --git a/src/main/services/automation-action-runner.ts b/src/main/services/automation-action-runner.ts index ad5229d..ad1ff2e 100644 --- a/src/main/services/automation-action-runner.ts +++ b/src/main/services/automation-action-runner.ts @@ -337,6 +337,19 @@ export class AutomationActionRunner { return { steps, status: 'failed', errorSummary: reportStep.error } } 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()) } @@ -369,6 +382,61 @@ export class AutomationActionRunner { 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) } + } + } + /** * 定时日报:把一次「到点触发 / 手动立即执行」跑成一次生成 + 一次发送。 * diff --git a/src/main/services/automation-rule-store.ts b/src/main/services/automation-rule-store.ts index 06212c3..a4ded57 100644 --- a/src/main/services/automation-rule-store.ts +++ b/src/main/services/automation-rule-store.ts @@ -50,6 +50,13 @@ const LEGACY_SCHEDULED_TASKS_FILE = 'tasks.json' const SCHEDULED_MIGRATION_BACKUP_FILE = 'scheduled-report-migration-backup.json' const CURRENT_VERSION = 4 +export class AutomationRulePersistenceError extends Error { + constructor() { + super('自动化规则保存失败') + this.name = 'AutomationRulePersistenceError' + } +} + interface StoredRules { version: number /** 内置「@我生成日报」是否已经播种过。**即使随后被删除也保持 true**。 */ @@ -231,7 +238,8 @@ export class AutomationRuleStore { this.legacyConversationResolver = resolver if (!this.loaded) 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, updatedAt: timestamp } - this.state.rules = [...this.state.rules, rule] - this.persist() + this.commitRules([...this.state.rules, rule]) return structuredClone(rule) } @@ -316,8 +323,7 @@ export class AutomationRuleStore { } else { delete rule.leaveNotification } - this.state.rules = this.state.rules.map((item, at) => (at === index ? rule : item)) - this.persist() + this.commitRules(this.state.rules.map((item, at) => (at === index ? rule : item))) return structuredClone(rule) } @@ -346,8 +352,7 @@ export class AutomationRuleStore { createdAt: timestamp, updatedAt: timestamp } - this.state.rules = [...this.state.rules, rule] - this.persist() + this.commitRules([...this.state.rules, rule]) return structuredClone(rule) } @@ -355,9 +360,9 @@ export class AutomationRuleStore { this.ensureLoaded() const key = String(id || '').trim() const before = this.state.rules.length - this.state.rules = this.state.rules.filter((rule) => rule.id !== key) - if (this.state.rules.length === before) return false - this.persist() + const rules = this.state.rules.filter((rule) => rule.id !== key) + if (rules.length === before) return false + this.commitRules(rules) return true } @@ -394,8 +399,7 @@ export class AutomationRuleStore { }, updatedAt: this.now() } - this.state.rules = this.state.rules.map((item, at) => (at === index ? next : item)) - this.persist() + this.commitRules(this.state.rules.map((item, at) => (at === index ? next : item))) return structuredClone(next) } @@ -428,7 +432,11 @@ export class AutomationRuleStore { this.runScheduledReportMigration(stored) stored.version = CURRENT_VERSION 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( `[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 } } } diff --git a/src/main/services/chat-service.ts b/src/main/services/chat-service.ts index c15cc15..c2ed545 100644 --- a/src/main/services/chat-service.ts +++ b/src/main/services/chat-service.ts @@ -14,6 +14,7 @@ import { isWindowsVcRuntimeMissingError, WINDOWS_VC_RUNTIME_ERROR_MESSAGE } from '../../shared/windows-runtime' +import { hasPermissionDeniedText, isPermissionDeniedError } from './path-access-probe' import { mergeRecallArchiveMessages, recordRecallArchiveMessages } from './recall-archive-service' import type { ExportImageQuality } from '../../shared/image-quality' import type { ImageMessageCountProbe } from '../../shared/image-text-index' @@ -1238,12 +1239,11 @@ export function testConnection(key: string, accountRoot?: string): DatabaseKeyVa messages: { available: true, count: messages.length } } } catch (error) { - const detail = error instanceof Error ? error.message : String(error) - const code = mapConnectionError(detail) + const code = mapConnectionError(error) return { success: false, code, - error: DATABASE_KEY_ERROR_MESSAGES[code] + error: databaseKeyErrorMessage(code) } } finally { try { @@ -1256,20 +1256,79 @@ export function testConnection(key: string, accountRoot?: string): DatabaseKeyVa } } -const DATABASE_KEY_ERROR_MESSAGES: Record = { +/** + * 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 = { INVALID_FORMAT: '密钥格式不正确', DATABASE_OPEN_FAILED: '无法打开数据库', ACCOUNT_MISMATCH: '密钥与当前账号不匹配', ROOT_UNAVAILABLE: '当前数据库目录不可用', DATABASE_FILE_MISSING: '数据库文件缺失', + DATABASE_PERMISSION_DENIED: DATABASE_PERMISSION_HINT_GENERIC, VC_RUNTIME_MISSING: WINDOWS_VC_RUNTIME_ERROR_MESSAGE, 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] +} + +/** + * 把底层抛出物归类成机器可读的错误码。 + * + * 顺序是有约束的,别随意调整: + * 1. VC runtime —— Windows 专属,特征明确,先摘掉; + * 2. 账号不匹配 —— `-1005` 是 native 给出的确定信号; + * 3. **权限不足** —— 必须排在"文件缺失"之前。原因见下; + * 4. 文件缺失 / 根目录不可用 / 打开失败 —— 按文本兜底。 + * + * 为什么权限要排在缺失之前:底层探测用的是 `fs.existsSync()`,它对 EPERM 也返回 + * `false`,所以走到这里时错误文本常常已经变成「未找到 … session.db」这种**缺失**措辞。 + * 只按文本判断就会永远归到 `DATABASE_FILE_MISSING`,把用户指向错误的方向。 + * 因此 errno 优先(调用方在探测层用 `statSync` 补问过),文本特征只作兜底。 + * + * 判断文本时逐个列举显式模式,不用 `includes('permission')` 这类过宽匹配 —— + * 那会把 "permission config not found" 之类无关错误也算进来。 + * + * 导出是为了让分类规则本身可被回归测试钉住:这条链路上任何一处顺序调整都会让 + * 权限问题重新落回"文件缺失",而那正是本函数要防的回归。 + * `platform` 可注入,否则 Windows 专属分支在测试里无法触发(`process.platform` 是只读的)。 + */ +export function mapConnectionError( + error: unknown, + platform: NodeJS.Platform = process.platform +): DatabaseKeyValidationCode { + const detail = error instanceof Error ? error.message : String(error) const normalized = detail.toLowerCase() - if (isWindowsVcRuntimeMissingError(detail, process.platform)) return 'VC_RUNTIME_MISSING' + if (isWindowsVcRuntimeMissingError(detail, platform)) return 'VC_RUNTIME_MISSING' 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('数据库文件')) { return 'DATABASE_FILE_MISSING' } diff --git a/src/main/services/group-exit-monitor-service.ts b/src/main/services/group-exit-monitor-service.ts index 26f5780..5130ea0 100644 --- a/src/main/services/group-exit-monitor-service.ts +++ b/src/main/services/group-exit-monitor-service.ts @@ -101,6 +101,15 @@ class GroupExitMonitorService { private events: GroupExitMonitorEvent[] = [] private monitorSelectionConfigured = true private monitoredRoomIds = new Set() + /* + * 「微信内退群监控消息」的范围:**全部群聊**,与退群监控勾选的群无关。 + * + * 勾选只决定「哪些群的退群走自动化通知」;内提示是面向全体的展示能力。 + * 所以这里只持有开关状态 + 全部群 id(随群名刷新一起更新), + * 检测范围取两者的并集 —— 两个消费者都要拿到事件。 + */ + private noticeEnabled = false + private allGroupRoomIds = new Set() private loaded = false private accountRoot = '' private groupNamesByRoomId = new Map() @@ -131,6 +140,11 @@ class GroupExitMonitorService { /** 永久保留的事件总数(`events` 只是最新的一批)。 */ totalEventCount: this.events.length, enabled: this.enabled, + /* + * 这里仍然按「用户勾选的那套监控」报状态,不掺内提示的范围: + * `running` 同时是本地 Agent API 的可用性判据,改语义会波及它。 + * 注意:内提示开着时检测其实也在跑(见 detectionEnabled),只是不算「退群监控在跑」。 + */ running: this.enabled && this.active && chat.isReady(), nativeMonitorActive: this.nativeMonitorActive, monitoredGroupCount: this.snapshots.size, @@ -168,7 +182,7 @@ class GroupExitMonitorService { this.active = true this.nativeMonitorActive = nativeMonitorActive this.checkQueued = false - if (!this.enabled) { + if (!this.detectionEnabled()) { this.save() this.broadcast() 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 { + 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 { this.active = false this.nativeMonitorActive = false @@ -208,7 +293,7 @@ class GroupExitMonitorService { } notifyDatabaseChanged(rawPayload: string): void { - if (!this.enabled || !this.active || !isContactEvent(rawPayload)) return + if (!this.detectionEnabled() || !this.active || !isContactEvent(rawPayload)) return try { chat.getChatDb()?.getWcdb4Client().invalidateGroupNicknameCache() } catch { @@ -224,7 +309,7 @@ class GroupExitMonitorService { async checkNow(): Promise { this.ensureLoaded() - if (!this.enabled) return this.getState() + if (!this.detectionEnabled()) return this.getState() if (!this.active && chat.isReady()) await this.start(false) await this.check() return this.getState() @@ -237,49 +322,66 @@ class GroupExitMonitorService { * 本服务不再持有任何通知配置。 */ async setMonitoredRoomIds(roomIds: string[]): Promise { + 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 { this.ensureLoaded() - this.eventSequence += 1 - this.scopeGeneration += 1 - this.monitorSelectionConfigured = true - const nextMonitoredRoomIds = normalizeRoomIds(roomIds) - for (const roomId of this.snapshots.keys()) { - if (!nextMonitoredRoomIds.has(roomId)) this.snapshots.delete(roomId) + const hasScope = configuration.monitoredRoomIds !== undefined + const hasEnabled = configuration.enabled !== undefined + if (!hasScope && !hasEnabled) return this.getState() + if (hasEnabled && !hasScope && this.enabled === configuration.enabled) return this.getState() + + 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.broadcast() - // 建立基线放到后台,保存配置可以立即返回。 - if (this.enabled && this.active) void this.check() + // 仅修改范围时保持原有的后台基线行为;涉及 enabled 的 PATCH 等待一次检查, + // 让调用方拿到的是最终运行状态。 + if (this.enabled && this.active && chat.isReady()) { + if (hasEnabled) await this.check() + else void this.check() + } return this.getState() } async setEnabled(enabled: boolean): Promise { - this.ensureLoaded() - 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() + return this.configure({ enabled }) } /** @@ -371,7 +473,12 @@ class GroupExitMonitorService { const result = await this.readMemberships() const membershipCostMs = Date.now() - startedAt 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) } console.log( @@ -383,7 +490,7 @@ class GroupExitMonitorService { private async readMemberships(): Promise { await this.refreshGroupNamesIfNeeded() const database = chat.getChatDb() - const roomIds = Array.from(this.monitoredRoomIds) + const roomIds = Array.from(this.detectionRoomIds()) const batchAvailable = chat.isGroupMemberIdsBatchAvailable() const mode: MembershipMode = batchAvailable ? 'batch' : 'legacy' if (!database) return { mode, groupCount: roomIds.length, groups: null } @@ -513,7 +620,7 @@ class GroupExitMonitorService { } this.hydrationQueue.delete(roomId) const baseline = this.snapshots.get(roomId) - if (!baseline || !this.monitoredRoomIds.has(roomId)) { + if (!baseline || !this.detectionRoomIds().has(roomId)) { this.startNextSnapshotHydration() return } @@ -587,6 +694,9 @@ class GroupExitMonitorService { const resolved = normalizeKnownGroupName(roomId, name) if (resolved) this.groupNamesByRoomId.set(roomId, resolved) } + /* 内提示覆盖的「全部群聊」与群名同源、同频刷新(都是会话表里的群聊), + * 这样群变动后自然跟上,上层不需要再维护第二份群清单。 */ + this.allGroupRoomIds = new Set(Object.keys(names || {})) } catch { // Session 群名是展示信息;读取失败时继续使用快照中的已知群名。 } diff --git a/src/main/services/local-agent-api-service.ts b/src/main/services/local-agent-api-service.ts new file mode 100644 index 0000000..34d262d --- /dev/null +++ b/src/main/services/local-agent-api-service.ts @@ -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 +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 + isDatabaseReady: () => boolean + getVersion: () => string + getPersonalWechatCapability: () => Promise + getAgentHubStatus: () => { connector: string } + getGroupExitMonitorState: () => GroupExitMonitorStateSource + /** Preferred atomic monitor configuration operation. */ + configureGroupExitMonitor?: ( + configuration: GroupExitMonitorConfiguration + ) => Promise | GroupExitMonitorStateSource + setGroupExitMonitorRoomIds?: (roomIds: string[]) => Promise + setGroupExitMonitorEnabled?: (enabled: boolean) => Promise + listGroupExitMonitorEvents?: (query: GroupExitMonitorEventQuery) => GroupExitMonitorEvent[] + getGroupMemberStats?: (query: GroupMemberStatsQuery) => Promise +} + +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 | undefined { + return value !== null && typeof value === 'object' && !Array.isArray(value) + ? (value as Record) + : 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 +): Record { + const next: Record = { ...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).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).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 { + 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 { + 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() + 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 { + 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 { + 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 { + 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 { + 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 { + 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 { + 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 { + 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 { + 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 { + 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 { + 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' + ) + } + } +} diff --git a/src/main/services/local-api-test-service.ts b/src/main/services/local-api-test-service.ts index a088dea..1d5c34f 100644 --- a/src/main/services/local-api-test-service.ts +++ b/src/main/services/local-api-test-service.ts @@ -46,6 +46,21 @@ function parseBody(bodyText: string, contentType?: string): { json?: unknown; bo return { bodyText } } +function materializeEndpointPath(pathname: string, query: Record): 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): { success: boolean command?: string @@ -71,18 +86,17 @@ export function buildLocalApiCurlCommand(payload: unknown): { const service = apiServer.getState() const targetHost = requestHost(service.host) const hostPart = targetHost.includes(':') ? `[${targetHost}]` : targetHost - const url = new URL(endpoint.path, `http://${hostPart}:${service.port}`) - entries.forEach(([key, value]) => { - if (value.trim()) url.searchParams.set(key, value.trim()) - }) + const endpointPath = materializeEndpointPath(endpoint.path, query as Record) + const url = new URL(endpointPath, `http://${hostPart}:${service.port}`) + appendQueryParameters(url, endpoint.path, entries) const token = endpointId === 'health' ? null : apiTokenStore.getTokenForAuthentication() if (endpointId !== 'health' && !token) { return { success: false, error: 'API Token 安全存储不可用,请在 API Center 检查 Token 状态' } } const authHeader = token ? ` -H 'Authorization: Bearer ${token}'` : '' const command = - endpoint.method === 'POST' - ? `curl -X POST '${url.toString()}'${authHeader} -H 'Content-Type: application/json' -d '${body.replaceAll("'", "\\'")}'` + endpoint.method === 'POST' || endpoint.method === 'PATCH' + ? `curl -X ${endpoint.method} '${url.toString()}'${authHeader} -H 'Content-Type: application/json' -d '${body.replaceAll("'", "\\'")}'` : `curl '${url.toString()}'${authHeader}` return { success: true, command } } @@ -110,10 +124,9 @@ export async function testLocalApiRequest(payload: unknown): Promise { - if (value.trim()) url.searchParams.set(key, value.trim()) - }) + const endpointPath = materializeEndpointPath(endpoint.path, query as Record) + const url = new URL(endpointPath, `http://${hostPart}:${targetPort}`) + appendQueryParameters(url, endpoint.path, entries) if (!service.running) { return { @@ -150,7 +163,9 @@ export async function testLocalApiRequest(payload: unknown): Promise = {} - 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}` const request = http.request( url, @@ -208,7 +223,7 @@ export async function testLocalApiRequest(payload: unknown): Promise + +const VOICE_MODEL_NOT_READY_HINT = + '本机还没有可用的离线语音识别模型。请让用户在 TraceMemo 设置里下载语音识别模型后再试;在此之前不要重试。' + +/** + * 语音转写条目的原因码 → 给调用方(通常是 AI)的下一步建议。 + * 关键是把"还没转完 / 转不了 / 不该转"三类分开,避免模型把它们说成"语音里没内容"。 + */ +const VOICE_ITEM_HINTS: Record = { + 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): 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 { + return { status: 'invalid_tool_arguments', field, constraint, hint } +} + export class LocalQueryApiService { /** * 图片文字索引覆盖度提供者(同步、只读)。 @@ -343,8 +412,24 @@ export class LocalQueryApiService { ): void { 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 { - 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' ? this.imageOcrEntry?.(contact.md5, sourceMessageId(message)) : undefined - return toQueryMessage(contact.md5, message, contact, ocr) + return toQueryMessage(contact.md5, message, contact, ocr, this.voiceSnapshot(message)) }) 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 } : {}) } @@ -471,6 +556,7 @@ export class LocalQueryApiService { let found: Awaited> let freshness: { resynced: boolean; catchUp: 'none' | 'reused' | 'skipped' | 'completed' | 'pending' } let freshnessMs = 0 + let directFallback: { evidence: Map; scanned: number } | undefined try { found = await this.probe(probes, conversationIds, range, limit, contactByMd5, retrievalSessionId) probeMs.push(...found.probeMs) @@ -489,13 +575,38 @@ export class LocalQueryApiService { enrichmentMs += reProbe.enrichmentMs 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 { this.knowledge.endInteractiveQuery() } const requestedEnd = rangeEndMs(range, this.nowProvider().getTime()) 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 timings: QuerySearchTimings = { @@ -513,8 +624,8 @@ export class LocalQueryApiService { resolvedTimeRange: range, coverage: { state: this.searchCoverage(found, requestedEnd) }, probeCount: probes.length, - evidenceCount: found.evidence.size, - evidence: Array.from(found.evidence.values()).slice(0, limit), + evidenceCount: evidence.size, + evidence: Array.from(evidence.values()).slice(0, limit), scope: corpus.scope, indexLatestAt: found.indexLatestAt, 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; 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() + 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 检索并合并去重;同时记录派生索引的覆盖口径与真实耗时分解。 */ private async probe( probes: string[], @@ -648,12 +833,19 @@ export class LocalQueryApiService { if (lag <= worthThreshold) return { resynced: false, catchUp: 'skipped' } const request = this.knowledge.requestCatchUp(QUERY_CATCH_UP_MIN_INTERVAL_MS) - if (!request.triggered) { - // 已经在跑 → 复用;刚触发过 → 节流。两种都不阻塞本次查询,后台继续追。 - return { resynced: false, catchUp: request.inProgress ? 'reused' : 'skipped' } + // 只有在"刚刚触发过、节流窗口内"时才不等 —— 那种情况再等也没意义。 + if (!request.triggered && !request.inProgress) { + return { resynced: false, catchUp: 'skipped' } } + // 本次触发、以及**正在跑(复用)**两种都要等。 + // + // 复用场景若直接返回旧快照,就会出现**索引明明在追、查询却拿旧覆盖下结论**的表现。 + // 等待后统一 `resynced: true`:即使没等到追平,索引也可能前进了一段,值得按新覆盖重查一次。 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 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) } } + /** + * 把指定语音消息转成文字。 + * + * 这是 Query API 里**唯一会触发计算**的操作:识别在本机离线进行、结果写入语音缓存, + * 之后 query/messages 等读路径就能直接读到。并发、去重与排队上限见 VoiceTranscriptionGateway。 + */ + async transcribeVoice(request: VoiceTranscribeRequest): Promise { + 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() + const references = new Map() + const refsByConversation = new Map>() + 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() + 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 } : {}) + } + } + /** * 会话概览。 * diff --git a/src/main/services/msg-insert-switch-service.ts b/src/main/services/msg-insert-switch-service.ts new file mode 100644 index 0000000..21882d9 --- /dev/null +++ b/src/main/services/msg-insert-switch-service.ts @@ -0,0 +1,760 @@ +/** + * 微信消息插入开关 —— 主进程侧封装。 + * + * 为什么写操作不能在本进程做 + * -------------------------- + * 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_` 表上的规则。一个分片完全可能 + * 「有 _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 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_`。 + * + * ⚠️ 读路径必须用带后缀的名字去查目录,否则会得出「库里明明有规则、界面却显示 0」这种 + * 自相矛盾的结论。 + */ +function ruleName(base: string, roomId: string): string { + return `${base}_${md5Hex(roomId)}` +} + +const SWITCH_SCOPE: Record = { + // 防撤回:群聊和私聊都要覆盖,所以目标是「全部可定位会话」 + recall_notice: 'all_sessions', + // 退群提示:任意群有人退出都要提示,所以目标是「全部群聊」(与退群监控的勾选无关) + group_exit_notice: 'all_group_chats' +} + +interface HelperRunResult { + ok: boolean + exitCode: number | null + json?: Record + 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 = { + // 防撤回靠装规则 + 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 { + /* + * 平台/架构都要分。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 { + // /db_storage/message/message_N.db + return path.dirname(path.dirname(path.dirname(shardPath))) +} + +/** + * 跑一次 helper。**密钥只走 stdin**。 + * + * 请求体是一行 JSON:{"key":"","rooms":[...],"myWxid":"..."} + * 用 JSON 而不是 argv,是因为目标会话可能有上千个,argv 会被撑爆; + * 顺带保证密钥永远不进进程参数表。 + */ +function runHelper( + helperPath: string, + args: string[], + request: { key: string; rooms: string[]; myWxid: string }, + timeoutMs = HELPER_TIMEOUT_MS +): Promise { + return new Promise((resolve) => { + let child: ReturnType + 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 | undefined + try { + json = JSON.parse(lines[lines.length - 1] || '') as Record + } 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): 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 { + 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 + ruleTables: Map +} + +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((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 + + 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>() + 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() + 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 { + /* + * 防御:事件驱动型开关(退群提示)**不允许**走规则路径。 + * + * 它没有 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: '数据库密钥不可用,请先连接微信数据库' + } + } + + 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 }> { + 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' + } +} diff --git a/src/main/services/path-access-probe.ts b/src/main/services/path-access-probe.ts new file mode 100644 index 0000000..33d0157 --- /dev/null +++ b/src/main/services/path-access-probe.ts @@ -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)) +} diff --git a/src/main/services/query-agent-service.ts b/src/main/services/query-agent-service.ts index 743bd10..dcc4325 100644 --- a/src/main/services/query-agent-service.ts +++ b/src/main/services/query-agent-service.ts @@ -299,6 +299,8 @@ const SYSTEM_PROMPT = `你是 TraceMemo 的本地聊天查询助手,只能使 - indexCoverage.covered 为 false 时,说明这段时间还没进索引:此时即使结果为 0 也只能说"索引尚未覆盖这段时间,暂时无法确认",**绝不能**说成"没有"。必须如实引用结论里的索引更新时间。 - 已经检索到 Evidence 时,只有当这个覆盖边界真的会影响结论时才补一句说明,不要机械附加警告。 - 只有 coverage.state 为 complete(indexCoverage.covered 为 true)且结果为 0,才可以下"没有找到"的结论。不要自己把 partial 说成 complete。 +- 结论句说"暂时无法确认"时**不能只停在那里**:必须同时给出可执行的下一步 —— 明确告诉用户「指定某个群或联系人、再加上时间再问一次」,这类精确查询读的是原始聊天记录,**不受索引进度影响**。索引在后台追赶可以如实说明,但那是背景,不是结论的终点。 +- 结论句若说"已改用直读原始记录补齐",表示这段**已经查过原始记录了**:直接按检索结果回答即可,**不要**再让用户换问法,也不要再说"暂时无法确认"。 图片文字索引:search_messages 的 imageOcrCoverage 是**独立于文字索引**的覆盖维度,只针对“图片里的文字”(截图、报价图、公告截图、海报)。规则: - 文字消息索引完整**不代表**图片里的文字搜得到。不要把这两个维度混着说。 - 问题涉及图片里的文字、而 imageOcrCoverage.state 不是 complete 时:即使图片证据为 0,也**绝不能**回答“没有”或“没找到”。必须如实引用 imageOcrCoverage.summary,说明图片文字索引尚未完成、当前无法确认全部历史图片。 diff --git a/src/main/services/scheduled-report-service.ts b/src/main/services/scheduled-report-service.ts index fa3dff6..3eeed20 100644 --- a/src/main/services/scheduled-report-service.ts +++ b/src/main/services/scheduled-report-service.ts @@ -613,7 +613,10 @@ export class ScheduledReportService { payload?.severity || notification.severity, payload?.title || notification.title, payload?.message || notification.message, - payload?.suggestedAction + payload?.suggestedAction, + // 用**失败发生时刻**而不是发送时刻:pending 通知会跨天补发, + // 同一批里几条文案完全相同的失败,只有这个时间能区分开。 + notification.createdAt ) }) if (result.success) { @@ -679,17 +682,20 @@ export class ScheduledReportService { severity: ScheduledReportNotificationSeverity, title: string, message: string, - suggestedAction?: string + suggestedAction?: string, + occurredAt?: string ): string { const icon = severity === 'error' ? '❌' : severity === 'warning' ? '⚠️' : '✅' + const stamp = formatNotificationTimestamp(occurredAt) return [ - `${icon} ${ruleName}`, + `${icon} ${ruleName}${stamp ? ` · ${stamp}` : ''}`, title, message, suggestedAction ? `建议:${suggestedAction}` : '' ] .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 = (value: unknown): T[] => (Array.isArray(value) ? (value as T[]) : []) const executionStatuses = new Set([ diff --git a/src/main/services/settings-store.ts b/src/main/services/settings-store.ts index 9f77bf1..85eed4c 100644 --- a/src/main/services/settings-store.ts +++ b/src/main/services/settings-store.ts @@ -20,6 +20,8 @@ function redirectLegacyWeChatFilesToXwechat(candidate: string): string { return candidate } +export type CloseAction = 'ask' | 'tray' | 'quit' + export interface AppSettings { dbRoot: string apiEnabled: boolean @@ -47,6 +49,17 @@ export interface AppSettings { * 不在用户界面暴露实验性名称)。 */ queryAgentEnabled: boolean + /** + * 关闭主窗口时的行为。 + * + * - `ask`:每次弹窗询问(默认,保持既有行为) + * - `tray`:直接最小化到系统托盘,应用继续在后台跑 + * - `quit`:直接退出整个进程 + * + * 只有用户在关闭弹窗里勾了"记住我的选择"才会离开 `ask`; + * 设置页随时可以改回来。 + */ + closeAction: CloseAction } function getDefaultDbRoot(): string { @@ -131,7 +144,8 @@ const DEFAULT_SETTINGS: AppSettings = { ttsModel: 's2.1-pro-free', windowsWechatPort: '', reportImagePostfixText: '今日日报', - queryAgentEnabled: true + queryAgentEnabled: true, + closeAction: 'ask' } const SETTINGS_FILE = path.join( @@ -176,6 +190,11 @@ export function loadSettings(): AppSettings { if (cache.dbRoot) { cache.dbRoot = redirectLegacyWeChatFilesToXwechat(cache.dbRoot) } + // 关闭行为可能来自旧版本或手改过的 settings.json —— 非法值一律收敛回 `ask`。 + // 放任非法值会造成最难排查的一种表现:点关闭窗口什么也不发生。 + if (cache.closeAction !== 'ask' && cache.closeAction !== 'tray' && cache.closeAction !== 'quit') { + cache.closeAction = 'ask' + } // 防撤回已下线(设置入口已隐藏):历史版本可能把它持久化为 true。 // 这里强制收敛为 false 并回写磁盘,确保旧的撤回监听与撤回日志不会继续运行。 if (cache.recallProtectionEnabled || retiredKeepProcess !== undefined) { diff --git a/src/main/services/skill-resource-service.ts b/src/main/services/skill-resource-service.ts index d182fc7..b09ec7c 100644 --- a/src/main/services/skill-resource-service.ts +++ b/src/main/services/skill-resource-service.ts @@ -1,5 +1,6 @@ +import { createHash } from 'crypto' 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 { isPackagedRuntime } from '../runtime-mode' @@ -8,7 +9,8 @@ const SKILL_RELATIVE_PATHS = [ join('skill', 'wechatexplorer-reader', 'SKILL.md') ] 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' @@ -27,7 +29,9 @@ interface SkillCandidate { export interface SkillResourceStatus { available: boolean + name?: string version?: string + contentHash?: string filePath?: string directoryPath?: string source: SkillResourceSource @@ -35,6 +39,27 @@ export interface SkillResourceStatus { 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 { return { 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[] { const runtime = environment || currentEnvironment() const developmentPaths = SKILL_RELATIVE_PATHS.flatMap((relativePath) => [ @@ -82,26 +182,40 @@ export function getSkillCandidates(environment?: SkillPathEnvironment): SkillCan export function resolveSkillResourceStatus( environment?: SkillPathEnvironment ): SkillResourceStatus { - const candidates = getSkillCandidates(environment) - const resolved = candidates.find((candidate) => existsSync(candidate.path)) - const filePath = resolved?.path || candidates[0].path - const source = resolved?.source || candidates[0].source - const directoryPath = dirname(filePath) - if (!resolved) { - return { - available: false, - source, - githubUrl: GITHUB_URL, - error: `未找到 TraceMemo Reader Skill 文件(已检查:${candidates.map((item) => item.path).join(';')})` + let candidates: SkillCandidate[] = [] + let source: SkillResourceSource = environment?.packaged ? 'bundled' : 'development' + try { + candidates = getSkillCandidates(environment) + const resolved = candidates.find((candidate) => existsSync(candidate.path)) + if (resolved) { + const filePath = resolved.path + const status: SkillResourceStatus = { + available: true, + filePath, + 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 { - available: true, - version: SKILL_VERSION, - filePath, - directoryPath, + available: false, 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 = { 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 }> { const status = this.getStatus() if (!status.available || !status.filePath) return { success: false, error: status.error } diff --git a/src/main/services/wechat-local-exit-notice-service.ts b/src/main/services/wechat-local-exit-notice-service.ts new file mode 100644 index 0000000..0480d8f --- /dev/null +++ b/src/main/services/wechat-local-exit-notice-service.ts @@ -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 { findResource } from '../resource-paths' + +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_NAME = 'tm-wcdb-config-helper' +const HELPER_TIMEOUT_MS = 20_000 +/** 最近若干次插入结果,只用于诊断展示,不参与判定 */ +const RECENT_LIMIT = 50 + +function helperPath(): string | null { + /* 与 msg-insert-switch-service 的 resolveHelperPath 保持一致: + * Windows 走 wcdb/win32// 且文件名带 .exe。 */ + const arch = process.arch === 'x64' ? 'x64' : 'arm64' + const other = arch === 'arm64' ? 'x64' : 'arm64' + const platformDir = process.platform === 'win32' ? 'win32' : 'macos' + const suffix = process.platform === 'win32' ? '.exe' : '' + for (const candidate of [ + `wcdb/${platformDir}/${arch}/${HELPER_NAME}${suffix}`, + `wcdb/${platformDir}/${other}/${HELPER_NAME}${suffix}`, + `wcdb/${platformDir}/${HELPER_NAME}${suffix}` + ]) { + const resolved = findResource(candidate) + if (resolved) return resolved + } + return null +} + +/** + * 退群本地提示服务。 + * + * 与 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 { + 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' }) + 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 | null> { + return new Promise((resolve) => { + let child: ReturnType + 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 | 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) + } catch { + finish(null) + } + }) + try { + child.stdin?.write(`${payload}\n`) + child.stdin?.end() + } catch { + finish(null) + } + }) +} diff --git a/src/main/tray-icon.ts b/src/main/tray-icon.ts new file mode 100644 index 0000000..65eaa37 --- /dev/null +++ b/src/main/tray-icon.ts @@ -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 { + 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( + platform: NodeJS.Platform, + appIconPath: string, + templateIconPaths: TrayTemplateIconPaths, + nativeImage: TrayNativeImageFactory, + 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) +} diff --git a/src/main/voice-pipeline/voice-message-identity.ts b/src/main/voice-pipeline/voice-message-identity.ts index cca357e..e22090d 100644 --- a/src/main/voice-pipeline/voice-message-identity.ts +++ b/src/main/voice-pipeline/voice-message-identity.ts @@ -23,3 +23,30 @@ export function voiceAccountIdentity(accountRoot: string): string { ) .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 + } +} diff --git a/src/main/voice-pipeline/voice-transcription-gateway.ts b/src/main/voice-pipeline/voice-transcription-gateway.ts new file mode 100644 index 0000000..7019f18 --- /dev/null +++ b/src/main/voice-pipeline/voice-transcription-gateway.ts @@ -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>() + + 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 { + 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 { + 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() + 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 => { + 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 { + 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 + } + // 被交互请求抢占:账号没变就重新排队,与批量转写的处理一致。 + } + } +} diff --git a/src/main/wcdb4-client.ts b/src/main/wcdb4-client.ts index 4a1c848..6fcb7ad 100644 --- a/src/main/wcdb4-client.ts +++ b/src/main/wcdb4-client.ts @@ -6,6 +6,7 @@ import { createRequire } from 'module' import { createConnection, Socket } from 'net' import { getResourceRoots } from './resource-paths' import { wcdbDebugLog } from './wcdb-debug' +import { looksLikePermissionDenied, PathAccessDeniedError } from './services/path-access-probe' import type { ImageMessageCountProbe } from '../shared/image-text-index' import { imageTextWindowToSeconds } from '../shared/image-text-index' @@ -54,6 +55,7 @@ export interface WindowsNativePathBridgeOptions { type Wcdb4MessageStore = { tableName: string dbPath: string + senderTableName?: string } export interface Wcdb4GroupMember { @@ -457,6 +459,41 @@ export function parseMonitorEvent(rawPayload: string): Wcdb4MonitorEvent { } } +/** 老版「防撤回保护」在某个消息分片上留下的残留。 */ +export interface LegacyRecallResidueShard { + /** 分片文件名,如 `message_0.db`(不含会话信息,可以进日志)。 */ + shard: string + dbPath: string + /** 本应用自己装的抓取触发器:`_wxe_capture_` */ + triggers: string[] + /** 老日志表:`_wxe_recall_journal_` */ + 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 { static readonly defaultRoot = Wcdb4Client.findExistingDefaultRoot() @@ -525,6 +562,16 @@ export class Wcdb4Client { private wcdbGetGroupMembersBatch: | ((handle: number, chatroomIdsJson: string, outJson: WcdbVoidOut) => number) | 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 wcdbMsgInsertListShardCatalog: + | ((handle: number, outJson: WcdbVoidOut) => number) + | null = null private wcdbGetGroupNicknames: | ((handle: number, chatroomId: string, outJson: WcdbVoidOut) => number) | null = null @@ -585,6 +632,18 @@ export class Wcdb4Client { this.sessionDbPath = this.findSessionDb() 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}`) } } @@ -598,6 +657,8 @@ export class Wcdb4Client { return target } if (!fs.existsSync(target)) { + // 同 session.db:existsSync 分不出"不存在"与"读不了",追问一次再下结论。 + if (looksLikePermissionDenied(target)) throw new PathAccessDeniedError(target) throw new Error(`未找到微信 4.0 数据目录: ${target}`) } const candidates = fs @@ -614,6 +675,8 @@ export class Wcdb4Client { static findLatestAccountRoot(): string { const root = Wcdb4Client.defaultRoot if (!fs.existsSync(root)) { + // 默认根目录读不了同样要区分:macOS 上这就是"没授权"的表现,不是"没装微信"。 + if (looksLikePermissionDenied(root)) throw new PathAccessDeniedError(root) throw new Error(`未找到微信 4.0 数据目录: ${root}`) } @@ -1180,7 +1243,12 @@ export class Wcdb4Client { try { const cursorMessages = this.getMessagesByCursor(username, startTime, endTime, maxRows) 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) console.log( `[WCDB4] getMessages cursor ok username=${username} rows=${mergedMessages.length} recovered=${recoveredMessages.length} cost=${Date.now() - startedAt}ms` @@ -1623,7 +1691,7 @@ export class Wcdb4Client { try { const order = limit ? 'DESC' : 'ASC' 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[]>((handle, outJson) => this.wcdbExecQuery!(handle, 'message', table.dbPath, sql, outJson) ) @@ -1699,7 +1767,7 @@ export class Wcdb4Client { // `local_id` 参与排序:`create_time` 同秒的消息需要一个稳定次序, // 否则多次读取的行序可能不同,调用方无法做稳定游标。 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 rows = await this.callJsonAsync[]>( this.wcdbExecQuery as unknown as KoffiAsyncFunction, @@ -1771,7 +1839,7 @@ export class Wcdb4Client { let successfulTables = 0 for (const table of tables) { 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 rows = await this.callJsonAsync[]>( this.wcdbExecQuery as unknown as KoffiAsyncFunction, @@ -1803,6 +1871,122 @@ export class Wcdb4Client { return result } + /** + * 列出账号目录下所有消息分片路径(message_.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 + error?: string + } { + if (!this.wcdbMsgInsertGetSwitches) { + return { success: false, error: '当前 WCDB 服务不支持微信消息插入开关' } + } + try { + const switches = this.callJson>((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) } + } + } + + /** + * 读取「微信消息插入规则」的分片目录(只读)。 + * + * 每个分片只跑两条查询(表清单 + 规则清单),拿回来之后调用方可以在本地用 + * md5(roomId) 匹配出「每个会话落在哪些分片、规则齐不齐」。这样即使会话很多, + * 判断全部会话的状态也只是一次目录读取,不需要按会话逐个查库。 + */ + listMsgInsertShardCatalog(): { + success: boolean + catalog?: { + shardCount: number + shards: Array<{ + shard: string + dbPath: string + configTable: boolean + storeTables: { capture: boolean; names: boolean; queue: boolean } + tables: string[] + rules: Array<{ name: string; table: string }> + }> + } + error?: string + } { + if (!this.wcdbMsgInsertListShardCatalog) { + return { success: false, error: '当前 WCDB 服务不支持消息插入规则目录' } + } + try { + const catalog = this.callJson<{ + shardCount: number + shards: Array<{ + shard: string + dbPath: string + configTable: boolean + storeTables: { capture: boolean; names: boolean; queue: boolean } + tables: string[] + rules: Array<{ name: string; table: string }> + }> + }>((handle, outJson) => this.wcdbMsgInsertListShardCatalog!(handle, outJson)) + return { success: true, catalog } + } 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 } { const stores = new Map() for (const username of this.uniq(usernames)) { @@ -1847,7 +2031,7 @@ export class Wcdb4Client { 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 { @@ -1863,7 +2047,7 @@ export class Wcdb4Client { 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[]): Wcdb4MessageStore[] { @@ -1875,12 +2059,17 @@ export class Wcdb4Client { .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 pattern = username.startsWith('gh_') + ? /^biz_message(?:_\d+)?\.db$/i + : /^message(?:_\d+)?\.db$/i try { return fs .readdirSync(messageRoot) - .filter((name) => /^biz_message(?:_\d+)?\.db$/i.test(name)) + .filter((name) => pattern.test(name)) .sort() .map((name) => path.join(messageRoot, name)) } catch { @@ -1888,51 +2077,71 @@ export class Wcdb4Client { } } - private listBizMessageStores(username: string): Wcdb4MessageStore[] { - if (!this.wcdbExecQuery || !username.startsWith('gh_')) return [] + private listFallbackMessageStores(username: string): Wcdb4MessageStore[] { + if (!this.wcdbExecQuery) return [] const tableName = `Msg_${this.md5(username)}` const escapedTableName = tableName.replace(/'/g, "''") const stores: Wcdb4MessageStore[] = [] - for (const dbPath of this.getBizMessageDatabasePaths()) { + for (const dbPath of this.getMessageDatabasePaths(username)) { try { const rows = this.callJson[]>((handle, outJson) => this.wcdbExecQuery!( handle, 'message', 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 ) ) - 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 { - // 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 } - private async listBizMessageStoresAsync(username: string): Promise { - if (!this.wcdbExecQuery || !username.startsWith('gh_')) return [] + private async listFallbackMessageStoresAsync(username: string): Promise { + if (!this.wcdbExecQuery) return [] const tableName = `Msg_${this.md5(username)}` const escapedTableName = tableName.replace(/'/g, "''") const stores: Wcdb4MessageStore[] = [] - for (const dbPath of this.getBizMessageDatabasePaths()) { + for (const dbPath of this.getMessageDatabasePaths(username)) { try { const rows = await this.callJsonAsync[]>( this.wcdbExecQuery as unknown as KoffiAsyncFunction, 'message', 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 { - // 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 } + 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[] { if (!this.wcdbExecQuery) throw new Error('当前 WCDB 数据服务不支持 SQL 通道') const rows = this.callJson[]>((handle, outJson) => @@ -2056,6 +2265,92 @@ export class Wcdb4Client { .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[] { + 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[]>((handle, outJson) => + this.wcdbExecQuery!(handle, 'message', dbPath, sql, outJson) + ) + return Array.isArray(rows) ? rows : [] + } + getMyAvatarUrl(): string | undefined { const candidates = this.getMyUsernameCandidates() this.hydrateAvatarUrls(candidates) @@ -2985,6 +3280,30 @@ export class Wcdb4Client { 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 { + this.wcdbMsgInsertListShardCatalog = lib.func( + 'int32 wcdb_msg_insert_list_shard_catalog(int64 handle, _Out_ void** outJson)' + ) as (handle: number, outJson: WcdbVoidOut) => number + } catch { + this.wcdbMsgInsertListShardCatalog = null + } + try { this.wcdbGetGroupNicknames = lib.func( 'int32 wcdb_get_group_nicknames(int64 handle, const char* chatroomId, _Out_ void** outJson)' diff --git a/src/preload/index.d.ts b/src/preload/index.d.ts index 9cfda07..dda28e7 100644 --- a/src/preload/index.d.ts +++ b/src/preload/index.d.ts @@ -105,6 +105,11 @@ import type { ScheduledRuleRunOutcome } from '../shared/automation' import type { ActionLogEntry } from '../shared/action-log' +import type { + MsgInsertApplyResult, + MsgInsertSwitchName, + MsgInsertSwitchesSnapshot +} from '../shared/msg-insert-switch' import type { AppUpdateCheckResult, AppUpdateInstallResult, @@ -326,6 +331,24 @@ declare global { saveLeaveNotificationRule: (draft: AutomationRuleDraft) => Promise /** 「指定好友」的可选项;已在 main 侧过滤掉群聊 / 公众号 / 文件传输助手 / 自己。 */ listSendableContacts: () => Promise> + /** + * 微信消息插入开关:读取当前状态。 + * + * 逐目标会话返回 desiredEnabled / effectiveEnabled —— 开关值写成功不等于 + * 功能真的生效(规则可能没装齐),界面不能只看前者。 + */ + getMsgInsertSwitches: () => Promise + refreshMsgInsertSwitches: () => Promise + /** + * 微信消息插入开关:打开 / 关闭。 + * + * 开的时候先补规则再写值;写入由一次性 helper 子进程完成, + * 失败会带 failedShards / notReadyRooms 回来,不伪装成功。 + */ + setMsgInsertSwitch: ( + name: MsgInsertSwitchName, + enabled: boolean + ) => Promise onGroupExitMonitorState: (callback: (state: GroupExitMonitorState) => void) => () => void search: (keyword: string) => Promise searchKnowledge: (request: KnowledgeSearchIpcRequest) => Promise @@ -539,6 +562,7 @@ declare global { appearanceTheme: 'system' | 'light' | 'dark' compactMode: boolean showStartupProgress: boolean + closeAction: 'ask' | 'tray' | 'quit' ttsSelectedVoiceId: string ttsModel: import('../shared/text-to-speech').TextToSpeechModel windowsWechatPort: string @@ -580,6 +604,7 @@ declare global { appearanceTheme: 'system' | 'light' | 'dark' compactMode: boolean showStartupProgress: boolean + closeAction: 'ask' | 'tray' | 'quit' ttsSelectedVoiceId: string ttsModel: import('../shared/text-to-speech').TextToSpeechModel windowsWechatPort: string @@ -604,6 +629,7 @@ declare global { appearanceTheme: 'system' | 'light' | 'dark' compactMode: boolean showStartupProgress: boolean + closeAction: 'ask' | 'tray' | 'quit' ttsSelectedVoiceId: string ttsModel: import('../shared/text-to-speech').TextToSpeechModel windowsWechatPort: string @@ -626,6 +652,7 @@ declare global { appearanceTheme: 'system' | 'light' | 'dark' compactMode: boolean showStartupProgress: boolean + closeAction: 'ask' | 'tray' | 'quit' windowsWechatPort: string imageXorKey: string imageAesKey: string diff --git a/src/preload/index.ts b/src/preload/index.ts index bd6e74a..c660d18 100644 --- a/src/preload/index.ts +++ b/src/preload/index.ts @@ -75,6 +75,11 @@ import type { } from '../shared/automation' import type { GroupMemberStatsQuery, GroupMemberStatsResult } from '../shared/group-stats' 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 { ExportRequest, ExportJobProgress } from '../shared/export' import type { ImageDecoderSelectionResult, ImageDecoderStatus } from '../shared/image-decryption' @@ -222,6 +227,30 @@ const api = { */ listSendableContacts: (): Promise> => ipcRenderer.invoke('automation:listSendableContacts'), + /** + * 微信消息插入开关 —— 读取当前状态。 + * + * 返回的是**逐目标会话**的状态:desiredEnabled(开关值)与 effectiveEnabled + * (真的会生效)是两个概念,界面不能只看前者。数据库未连接时 `success=false`。 + */ + getMsgInsertSwitches: (): Promise => + ipcRenderer.invoke('automation:getMsgInsertSwitches'), + /** 运行期刷新:允许在消息分片集合变化时补一次规则,再返回最新状态。 */ + refreshMsgInsertSwitches: (): Promise => + ipcRenderer.invoke('automation:refreshMsgInsertSwitches'), + /** + * 微信消息插入开关 —— 打开 / 关闭。 + * + * 开的时候会先把目标会话的规则补齐、确认 ready 才写开关值;写不进本进程, + * 由一次性 helper 子进程完成。失败不伪装成功:`status.failedShards > 0` + * 表示真的有分片写失败,`status.readyTargetRooms < status.totalTargetRooms` + * 表示只是规则没装齐。 + */ + setMsgInsertSwitch: ( + name: MsgInsertSwitchName, + enabled: boolean + ): Promise => + ipcRenderer.invoke('automation:setMsgInsertSwitch', { name, enabled }), onGroupExitMonitorState: (callback: (state: GroupExitMonitorState) => void) => { const listener = (_event: Electron.IpcRendererEvent, state: GroupExitMonitorState): void => callback(state) diff --git a/src/renderer/src/components/account/AccountSummary.tsx b/src/renderer/src/components/account/AccountSummary.tsx index 06d905d..a0b0687 100644 --- a/src/renderer/src/components/account/AccountSummary.tsx +++ b/src/renderer/src/components/account/AccountSummary.tsx @@ -26,11 +26,7 @@ export function AccountSummary({ const displayName = showAccount && selfInfo ? selfInfo.nickname || selfInfo.wxid || '当前账号' : '未连接' const subtitle = showAccount && selfInfo ? selfInfo.wxid : '打开设置' - const statusText = dbReady - ? '数据库已连接' - : dbConnecting - ? '正在连接数据库' - : '数据库未连接' + const statusText = dbReady ? '数据库已连接' : dbConnecting ? '正在连接数据库' : '数据库未连接' const statusClass = dbReady ? 'ready' : dbConnecting ? 'connecting' : '' const initial = (displayName || '?').charAt(0) const title = `${displayName}\n${subtitle}` @@ -66,8 +62,8 @@ export function AccountSummary({ diff --git a/src/renderer/src/components/export/ExportWorkspace.tsx b/src/renderer/src/components/export/ExportWorkspace.tsx index cb03865..0faf994 100644 --- a/src/renderer/src/components/export/ExportWorkspace.tsx +++ b/src/renderer/src/components/export/ExportWorkspace.tsx @@ -27,6 +27,7 @@ import { buildContactSearchIndex, filterContactSearchIndex } from '../../../../shared/contact-search' +import { loadExportPreferences, saveExportPreferences } from './exportPreferences' const ALL_CONTACT_TYPES: ExportContactType[] = ['group', 'user'] const contactTypeKey = (types: ExportContactType[] | undefined): string => @@ -44,6 +45,8 @@ export function ExportWorkspace({ onCancelExport }: ExportWorkspaceProps): React.ReactElement { const initialSelection = initialContact || contacts[0] || null + const defaultNameMode = initialSelection?.type === 'group' ? 'groupNickname' : 'remark' + const [savedPreferences] = useState(() => loadExportPreferences(defaultNameMode)) const runningAllTask = exportTasks.find( (task) => task.scope === 'all' && task.status === 'running' ) @@ -64,24 +67,30 @@ export function ExportWorkspace({ const contactSearchIndex = useMemo(() => buildContactSearchIndex(contacts), [contacts]) const [activeContactId, setActiveContactId] = useState(initialSelection?.md5 || '') const [previewByContact, setPreviewByContact] = useState>({}) - const [range, setRange] = useState(() => (runningAllTask ? 'all' : 'today')) - const [startDate, setStartDate] = useState('') - const [endDate, setEndDate] = useState('') - const [selectedKinds, setSelectedKinds] = useState>(() => new Set(['text'])) - const [nameMode, setNameMode] = useState( - initialSelection?.type === 'group' ? 'groupNickname' : 'remark' + const [range, setRange] = useState(() => savedPreferences.range) + const [startDate, setStartDate] = useState(() => savedPreferences.startDate) + const [endDate, setEndDate] = useState(() => savedPreferences.endDate) + const [selectedKinds, setSelectedKinds] = useState>( + () => new Set(savedPreferences.selectedKinds) + ) + const [nameMode, setNameMode] = useState(() => 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(null) - const [includeAvatars, setIncludeAvatars] = useState(true) - const [preferOriginal, setPreferOriginal] = useState(true) - const [fallbackThumbnail, setFallbackThumbnail] = useState(true) - const [keepMissing, setKeepMissing] = useState(true) - const [format, setFormat] = useState(() => runningAllTask?.format || 'csv') - const [zip, setZip] = useState(() => runningAllTask?.zip === true) - const [fileName, setFileName] = useState('') - const [outputDirectory, setOutputDirectory] = useState('') + const [includeAvatars, setIncludeAvatars] = useState(() => savedPreferences.includeAvatars) + const [preferOriginal, setPreferOriginal] = useState(() => savedPreferences.preferOriginal) + const [fallbackThumbnail, setFallbackThumbnail] = useState( + () => savedPreferences.fallbackThumbnail + ) + const [keepMissing, setKeepMissing] = useState(() => savedPreferences.keepMissing) + const [format, setFormat] = 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('idle') const [jobId, setJobId] = useState('') const [progress, setProgress] = useState(null) @@ -92,6 +101,42 @@ export function ExportWorkspace({ const [taskCenterOpen, setTaskCenterOpen] = useState(false) 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(() => { if (selectedContacts.length > 0) return const candidate = initialContact || contacts[0] @@ -206,7 +251,6 @@ export function ExportWorkspace({ const handleSelectContact = (contact: Contact): void => { if (exportAll) { setExportAll(false) - setRange('today') } if (!selectionMode) { setSelectedContacts([contact]) @@ -236,7 +280,6 @@ export function ExportWorkspace({ setExportAll(true) setAllContactTypes([...ALL_CONTACT_TYPES]) setSelectionMode(false) - setRange('all') setStatus('idle') } @@ -417,6 +460,7 @@ export function ExportWorkspace({ setSelectedKinds(new Set(['text'])) setNameMode(contact?.type === 'group' ? 'groupNickname' : 'remark') setIncludeMedia(true) + setIncludeVoiceTranscripts(true) setIncludeAvatars(true) setPreferOriginal(true) setFallbackThumbnail(true) @@ -424,6 +468,7 @@ export function ExportWorkspace({ setFormat('csv') setZip(false) setFileName('') + setOutputDirectory('') setStatus('idle') setJobId('') setProgress(null) @@ -492,7 +537,7 @@ export function ExportWorkspace({ selectionMode={selectionMode} exportContactCount={exportContacts.length} format={format} - range={range} + range={exportAll ? 'all' : range} startDate={startDate} endDate={endDate} selectedKinds={selectedKinds} diff --git a/src/renderer/src/components/export/exportPreferences.ts b/src/renderer/src/components/export/exportPreferences.ts new file mode 100644 index 0000000..a58d6d6 --- /dev/null +++ b/src/renderer/src/components/export/exportPreferences.ts @@ -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 + 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. + } +} diff --git a/src/renderer/src/features/api-center/model/apiEndpoints.ts b/src/renderer/src/features/api-center/model/apiEndpoints.ts index f5dc8b9..a527d4c 100644 --- a/src/renderer/src/features/api-center/model/apiEndpoints.ts +++ b/src/renderer/src/features/api-center/model/apiEndpoints.ts @@ -58,6 +58,67 @@ export const API_ENDPOINTS: ApiEndpoint[] = [ { 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', { name: '群聊日报导出', description: '通过内置模板导出群聊日报 HTML 与 PNG。', diff --git a/src/renderer/src/features/api-center/model/types.ts b/src/renderer/src/features/api-center/model/types.ts index 5288d70..e917c28 100644 --- a/src/renderer/src/features/api-center/model/types.ts +++ b/src/renderer/src/features/api-center/model/types.ts @@ -1,4 +1,4 @@ -export type ApiMethod = 'GET' | 'POST' +export type ApiMethod = 'GET' | 'POST' | 'PATCH' export type { ApiTokenStatus } from '../../../../../shared/local-api-auth' export interface ApiParameter { diff --git a/src/renderer/src/features/api-center/utils/buildApiUrl.ts b/src/renderer/src/features/api-center/utils/buildApiUrl.ts index 6b500cf..92f9efa 100644 --- a/src/renderer/src/features/api-center/utils/buildApiUrl.ts +++ b/src/renderer/src/features/api-center/utils/buildApiUrl.ts @@ -4,8 +4,19 @@ export function buildApiUrl( path: string, params: Record ): 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]) => { + 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()) }) return url.toString() diff --git a/src/renderer/src/features/api-center/utils/buildSkillInstallInstruction.ts b/src/renderer/src/features/api-center/utils/buildSkillInstallInstruction.ts index b2e2aac..05432bf 100644 --- a/src/renderer/src/features/api-center/utils/buildSkillInstallInstruction.ts +++ b/src/renderer/src/features/api-center/utils/buildSkillInstallInstruction.ts @@ -7,13 +7,13 @@ function requestHost(host: string): string { function opening(target: AgentInstallTarget): string { switch (target) { case 'codex': - return '请将本地目录中的 TraceMemo Reader Skill 安装到当前 Codex 项目或用户 Skill 目录:' + return '请将本地目录中的 TraceMemo Reader Skill 安装或更新到当前 Codex 项目或用户 Skill 目录:' case 'claude-code': - return '请安装以下本地 TraceMemo Reader Skill,并按照 SKILL.md 调用本地 HTTP API:' + return '请安装或更新以下本地 TraceMemo Reader Skill,并按照 SKILL.md 调用本地 HTTP API:' case 'openclaw': - return '请将以下本地目录作为 TraceMemo Reader Skill 安装,并阅读其中的 SKILL.md:' + return '请将以下本地目录作为 TraceMemo Reader Skill 安装或更新,并阅读其中的 SKILL.md:' default: - return '请读取并安装以下 TraceMemo Reader Skill:' + return '请读取并安装(或更新)以下 TraceMemo Reader Skill:' } } @@ -32,8 +32,11 @@ export function buildSkillInstallInstruction({ const sourceText = source.type === 'local' ? `${opening(target)}\n\n${source.directoryPath}\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。安装完成后告诉我验证结果。` + : `请安装或更新 TraceMemo Reader Skill,来源:\n\n${source.installUrl}\n\n阅读 SKILL.md 后,调用:` + 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 { diff --git a/src/renderer/src/features/automation/AutomationWorkspace.tsx b/src/renderer/src/features/automation/AutomationWorkspace.tsx index bd4fc40..aa1c3c5 100644 --- a/src/renderer/src/features/automation/AutomationWorkspace.tsx +++ b/src/renderer/src/features/automation/AutomationWorkspace.tsx @@ -24,6 +24,7 @@ import { AutomationRuleTypeTabs, type AutomationRuleTabType } from './AutomationRuleTypeTabs' +import { MessageInsertSwitches } from './MessageInsertSwitches' import { ScheduledReportEditor } from './ScheduledReportEditor' import { ScheduledReportRuleList } from './ScheduledReportRuleList' import { ScheduledReportNotificationPanel } from './ScheduledReportNotificationPanel' @@ -483,16 +484,20 @@ export function AutomationWorkspace({

自动化

当群里出现符合条件的消息时,TraceMemo 会自动执行你配置的动作。

- {tab === 'rules' && !showEditor ? ( - - ) : null} +
+ {/* 微信消息插入开关:控制 TraceMemo 能在微信会话里插入哪些消息 */} + + {tab === 'rules' && !showEditor ? ( + + ) : null} +
{!apiAvailable ? ( diff --git a/src/renderer/src/features/automation/MessageInsertSwitches.tsx b/src/renderer/src/features/automation/MessageInsertSwitches.tsx new file mode 100644 index 0000000..2e70b39 --- /dev/null +++ b/src/renderer/src/features/automation/MessageInsertSwitches.tsx @@ -0,0 +1,254 @@ +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_` 表上的规则;写入由主进程 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(null) + const [pending, setPending] = React.useState(null) + const [blockedReason, setBlockedReason] = React.useState(null) + const [loading, setLoading] = React.useState(true) + + /** + * 拉一次状态。返回是否成功 —— 调用方据此决定要不要重试。 + */ + const refresh = React.useCallback(async (): Promise => { + 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 | undefined + let attempt = 0 + const run = async (): Promise => { + 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 => { + 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 => { + 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] + ) + + /* + * helper 缺失时**提前**禁用,而不是等用户点了再弹「缺少写入组件」。 + * 写开关必须靠那个一次性子进程,缺了它这个开关根本没法工作 —— + * 让人点了才失败是最差的一种交互。 + */ + /* + * 写入组件缺失 = **这个能力还没开放**,不是安装坏了。 + * + * 主进程对微信库只有只读连接,任何写入都要 spawn 那个一次性写入组件;当前分发的 + * 安装包不带它(它随发送运行时按需分发),所以「微信内防撤回提示」与 + * 「微信内退群监控消息」一律按"下个版本开放"呈现 —— 不该让用户去排查自己的安装。 + * (machine-readable 的原因仍然是 snapshot.helperAvailable,授权层可以据此判断。) + */ + const helperMissing = snapshot?.helperAvailable === false + const blocked = blockedReason ?? (helperMissing ? '该能力将在下个版本开放' : null) + const disabled = blocked !== null + + return ( +
+ {loading ? : null} + {MSG_INSERT_SWITCH_LABELS.map(({ name, label, hint }) => { + const status: MsgInsertSwitchStatus | undefined = snapshot?.switches?.[name] + const busy = pending === name + /* 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:
+ ) +} diff --git a/src/renderer/src/features/group-exit-monitor/GroupExitMonitorWorkspace.tsx b/src/renderer/src/features/group-exit-monitor/GroupExitMonitorWorkspace.tsx index 773cc93..5812be5 100644 --- a/src/renderer/src/features/group-exit-monitor/GroupExitMonitorWorkspace.tsx +++ b/src/renderer/src/features/group-exit-monitor/GroupExitMonitorWorkspace.tsx @@ -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 initial = name.charAt(0) || '?' return ( @@ -137,7 +141,7 @@ function GroupAvatar({ contact }: { contact: Contact }): React.ReactElement { {contact.avatar ? : initial} ) -} +}) interface ManageGroupsProps { groups: Contact[] @@ -155,7 +159,14 @@ interface ManageGroupsProps { onCancel: () => void } -function ManageGroups({ +/** + * 管理群聊页。 + * + * 必须 `memo`:这个页面**不消费退群监控状态** —— 列表数据来自 `contacts`、选中来自本地 state, + * 而父层会因为监控状态推送反复重渲染(实测约 5 次/秒,且推送间隔 350ms 去抖)。 + * 没有 memo 时 200+ 行会跟着每次推送重建,用户看到的就是"列表一直在刷新"。 + */ +const ManageGroups = React.memo(function ManageGroups({ groups, selectedRoomIds, sendCapability, @@ -294,7 +305,8 @@ function ManageGroups({
- 保存后将从新的成员快照开始记录退群动态;退群通知发到哪里,请在「自动化 → 退群通知」里配置。 + 保存后将从新的成员快照开始记录退群动态;退群通知发到哪里,请在「自动化 → + 退群通知」里配置。
) -} +}) export function GroupExitMonitorWorkspace({ dbReady, @@ -354,6 +366,7 @@ export function GroupExitMonitorWorkspace({ }, [contacts]) React.useEffect(() => { + if (view !== 'events') return const api = typeof window !== 'undefined' ? window.api : undefined if (!api || typeof api.getGroupExitMonitorState !== 'function') return let disposed = false @@ -372,7 +385,7 @@ export function GroupExitMonitorWorkspace({ disposed = true unsubscribe?.() } - }, []) + }, [view]) React.useEffect(() => { const api = typeof window !== 'undefined' ? window.api : undefined @@ -536,7 +549,13 @@ export function GroupExitMonitorWorkspace({ } } - const saveGroups = async (): Promise => { + /** + * 保存监控范围。 + * + * `useCallback` 是给 `ManageGroups` 的 `memo` 用的:函数引用不稳定时, + * 每次状态推送都会让 200+ 行的列表跟着重渲染。 + */ + const saveGroups = React.useCallback(async (): Promise => { const api = window.api if (saving || !dbReady || typeof api.setGroupExitMonitorGroups !== 'function') return setSaving(true) @@ -554,7 +573,7 @@ export function GroupExitMonitorWorkspace({ } finally { setSaving(false) } - } + }, [dbReady, groups, saving, selectedManageRoomIds]) const setMonitorEnabled = async (enabled: boolean): Promise => { 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) => { const next = new Set(current) if (next.has(roomId)) next.delete(roomId) else next.add(roomId) return next }) - } + }, []) - const toggleAllManageGroups = (): void => { + const toggleAllManageGroups = React.useCallback((): void => { const allRoomIds = groups.map(contactRoomId) const shouldSelect = allRoomIds.some((roomId) => !selectedManageRoomIds.has(roomId)) setSelectedManageRoomIds((current) => { @@ -590,7 +609,10 @@ export function GroupExitMonitorWorkspace({ }) return next }) - } + }, [groups, selectedManageRoomIds]) + + /** 退出管理页返回事件列表。同样为了 `ManageGroups` 的 memo 保持稳定引用。 */ + const cancelManage = React.useCallback((): void => setView('events'), []) if (view === 'manage') { return ( @@ -606,8 +628,8 @@ export function GroupExitMonitorWorkspace({ onListFilterChange={setManageFilter} onToggle={toggleManageGroup} onToggleAll={toggleAllManageGroups} - onSave={() => void saveGroups()} - onCancel={() => setView('events')} + onSave={saveGroups} + onCancel={cancelManage} /> ) } @@ -616,11 +638,11 @@ export function GroupExitMonitorWorkspace({ ? '数据库未连接' : !state.enabled ? '监控已暂停' - : state.running && state.nativeMonitorActive - ? '实时监听已启用' - : state.running - ? '已连接,等待原生监听' - : '等待启动' + : state.running && state.nativeMonitorActive + ? '实时监听已启用' + : state.running + ? '已连接,等待原生监听' + : '等待启动' return (
diff --git a/src/renderer/src/features/logs/LogsWorkspace.tsx b/src/renderer/src/features/logs/LogsWorkspace.tsx index 36602d3..dfde556 100644 --- a/src/renderer/src/features/logs/LogsWorkspace.tsx +++ b/src/renderer/src/features/logs/LogsWorkspace.tsx @@ -13,7 +13,12 @@ import { } from '../../components/ui' 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 => { if (source === 'member_monitor') return '退群监控' if (source === 'scheduled_report') return '定时日报' + // 消息型自动化「@我生成日报」发出的动作。少了这一条会直接显示英文原文 `automation`。 + if (source === 'automation') return '自动化' if (source === 'user_tts') return '文字转语音' + if (source === 'user_manual') return '手动发送' if (source === 'unknown') return '未知来源' return source || '未知来源' } @@ -40,9 +48,21 @@ const sourceLabel = (source: ActionLogEntry['source']): string => { const triggerLabel = (triggerType: ActionLogEntry['triggerType']): string => triggerType === 'user' ? '用户触发' : '自动化' +/** + * purpose → 中文。 + * + * **每一个有生产者的 purpose 都必须在这里有分支**:`WechatActionPurpose` 是字符串联合, + * 漏掉谁,那类记录就会顶着英文原文出现在列表里(筛选项里也找不到对应项)—— + * 「@我生成日报」的发送记录此前就是这样被用户当成"压根没有"的。 + * 未知值仍回落到原文,好让将来新增 purpose 时一眼能看出漏了映射。 + */ const purposeLabel = (purpose: WechatActionPurpose): string => { if (LEAVE_NOTIFICATION_PURPOSES.includes(purpose)) 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 '文字转语音' return purpose || '其它动作' } @@ -65,8 +85,11 @@ const statusDetails = (entry: ActionLogEntry): { label: string; className: strin const matchesPurpose = (entry: ActionLogEntry, filter: PurposeFilter): boolean => { if (filter === 'all') return true if (filter === 'other') { + // 「其它动作」= 剩下的。独立筛选项必须在这里排掉,否则同一条记录会同时出现在两组里。 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') { @@ -154,6 +177,7 @@ export function LogsWorkspace(): React.ReactElement { 全部类型 退群通知 定时日报 + 生成日报(@我) 其它动作 diff --git a/src/renderer/src/features/settings/account-database/ConnectionHealthSection.tsx b/src/renderer/src/features/settings/account-database/ConnectionHealthSection.tsx index a460193..30a43c2 100644 --- a/src/renderer/src/features/settings/account-database/ConnectionHealthSection.tsx +++ b/src/renderer/src/features/settings/account-database/ConnectionHealthSection.tsx @@ -4,11 +4,36 @@ function DiagnosticIcon({ status }: { status: DiagnosticStatus }): React.ReactEl if (status === 'checking') { return } - const symbol = - status === 'success' ? '✓' : status === 'warning' ? '!' : status === 'error' ? '×' : '—' + + const icon = + status === 'success' ? ( + + ) : status === 'warning' ? ( + <> + + + + ) : status === 'error' ? ( + + ) : ( + + ) + return ( ) } diff --git a/src/renderer/src/features/settings/pages/AppearancePage.tsx b/src/renderer/src/features/settings/pages/AppearancePage.tsx index 51ec108..0422367 100644 --- a/src/renderer/src/features/settings/pages/AppearancePage.tsx +++ b/src/renderer/src/features/settings/pages/AppearancePage.tsx @@ -2,6 +2,8 @@ import { useEffect, useState } from 'react' import { RadioGroup, RadioGroupItem, Switch } from '../../../components/ui' export type AppearanceTheme = 'system' | 'light' | 'dark' +/** 关闭主窗口时的行为。与主进程 settings-store 的 `CloseAction` 保持一致。 */ +export type CloseAction = 'ask' | 'tray' | 'quit' export function AppearancePage({ onNotice, @@ -13,6 +15,7 @@ export function AppearancePage({ const [theme, setTheme] = useState('system') const [compactMode, setCompactMode] = useState(false) const [showStartupProgress, setShowStartupProgress] = useState(true) + const [closeAction, setCloseAction] = useState('ask') useEffect(() => { let active = true @@ -21,6 +24,7 @@ export function AppearancePage({ setTheme(result.settings.appearanceTheme) setCompactMode(result.settings.compactMode) setShowStartupProgress(result.settings.showStartupProgress) + setCloseAction(result.settings.closeAction) onAppearanceChange({ theme: result.settings.appearanceTheme, compactMode: result.settings.compactMode @@ -35,11 +39,13 @@ export function AppearancePage({ appearanceTheme?: AppearanceTheme compactMode?: boolean showStartupProgress?: boolean + closeAction?: CloseAction }): Promise => { const result = await window.api.setSettings(patch) setTheme(result.settings.appearanceTheme) setCompactMode(result.settings.compactMode) setShowStartupProgress(result.settings.showStartupProgress) + setCloseAction(result.settings.closeAction) onAppearanceChange({ theme: result.settings.appearanceTheme, compactMode: result.settings.compactMode @@ -118,6 +124,45 @@ export function AppearancePage({ /> + +

关闭窗口时

+
+ { + if (value === 'ask' || value === 'tray' || value === 'quit') + void save({ closeAction: value }) + }} + > + {( + [ + ['ask', '每次询问', '每次关闭窗口都弹出选择框'], + ['tray', '最小化到托盘', '窗口隐藏,应用继续在后台运行'], + ['quit', '退出应用', '直接结束整个 TraceMemo 进程'] + ] as const + ).map(([value, label, hint]) => ( + + ))} + +

+ 选择「每次询问」时,关闭弹窗里勾选「记住我的选择」会自动切换到这里对应的项。 +

+
diff --git a/src/renderer/src/styles/automation.scss b/src/renderer/src/styles/automation.scss index 16089bc..c29d7f1 100644 --- a/src/renderer/src/styles/automation.scss +++ b/src/renderer/src/styles/automation.scss @@ -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 { margin: 0; padding: 10px 14px; diff --git a/src/renderer/src/styles/settings-preferences.scss b/src/renderer/src/styles/settings-preferences.scss index 7d6f3c1..6964520 100644 --- a/src/renderer/src/styles/settings-preferences.scss +++ b/src/renderer/src/styles/settings-preferences.scss @@ -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 { display: grid; gap: 0; diff --git a/src/renderer/src/styles/settings.scss b/src/renderer/src/styles/settings.scss index 610dd8a..a571ef6 100644 --- a/src/renderer/src/styles/settings.scss +++ b/src/renderer/src/styles/settings.scss @@ -416,8 +416,9 @@ border: 1px solid #929a96; border-radius: 50%; color: #929a96; - font-size: 11px; - font-weight: 700; +} +.settings-diagnostic-icon svg { + display: block; } .settings-diagnostic-icon.success { border-color: #2e8b68; diff --git a/src/shared/agent-api/automation-validation.ts b/src/shared/agent-api/automation-validation.ts new file mode 100644 index 0000000..fb0363e --- /dev/null +++ b/src/shared/agent-api/automation-validation.ts @@ -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 + +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() + 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 } } +} diff --git a/src/shared/agent-api/contracts.ts b/src/shared/agent-api/contracts.ts new file mode 100644 index 0000000..7925e77 --- /dev/null +++ b/src/shared/agent-api/contracts.ts @@ -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 + nextRunAt?: string | null + capabilities?: Record +} + +export interface AgentAutomationExecution extends Pick< + AutomationExecution, + | 'executionId' + | 'ruleId' + | 'ruleName' + | 'trigger' + | 'status' + | 'triggerTime' + | 'durationMs' + | 'sourceDisplayName' +> { + ruleType?: AutomationRuleType + startedAt: string + finishedAt: string | null + error?: string +} diff --git a/src/shared/agent-api/group-exit-monitor.ts b/src/shared/agent-api/group-exit-monitor.ts new file mode 100644 index 0000000..99247f9 --- /dev/null +++ b/src/shared/agent-api/group-exit-monitor.ts @@ -0,0 +1,28 @@ +export interface AgentGroupExitMonitorState { + enabled: boolean + running: boolean + nativeMonitorActive: boolean + monitoredConversationIds: string[] + monitoredGroupCount: number + monitorSelectionConfigured: boolean + lastCheckedAt: string | null + lastReadAt: string | null + eventCount: number + unreadCount: number +} + +export interface AgentGroupExitMonitorEvent { + eventId: string + conversationId: string + groupName: string + memberId: string + memberName: string + wechatName: string + groupRemark: string + contactRemark: string + previousCount: number + currentCount: number + delta: number + message: string + detectedAt: string +} diff --git a/src/shared/agent-api/group-stats.ts b/src/shared/agent-api/group-stats.ts new file mode 100644 index 0000000..62b7d9f --- /dev/null +++ b/src/shared/agent-api/group-stats.ts @@ -0,0 +1,32 @@ +export interface AgentGroupMemberStats { + conversation: { + id: string + name: string + } + conversationId: string + range: { + start: string + end: string + } + memberCount: number + activeMemberCount: number + silentMemberCount: number + activeMembers: Array<{ + memberId: string + displayName: string + groupNickname: string + messageCount: number + lastMessageAt: string | null + }> + silentMembers: Array<{ + memberId: string + displayName: string + groupNickname: string + }> + freshness: 'fresh' | 'stale' | 'unknown' + complete: boolean + limitations: string[] + unattributedMessages: number + excludedSystemMessages: number + firstMessageAt: string | null +} diff --git a/src/shared/database-key.ts b/src/shared/database-key.ts index 2670d10..9a04c00 100644 --- a/src/shared/database-key.ts +++ b/src/shared/database-key.ts @@ -4,6 +4,14 @@ export type DatabaseKeyValidationCode = | 'ACCOUNT_MISMATCH' | 'ROOT_UNAVAILABLE' | 'DATABASE_FILE_MISSING' + /** + * 路径存在、但**当前进程无权读取**(macOS 的完全磁盘访问权限是最常见的成因)。 + * + * 与 `DATABASE_FILE_MISSING` 分开,是因为两者的下一步动作完全不同: + * 文件真的不存在要用户去查路径 / 重装,而权限不足要用户去系统设置授权。 + * 合成一个码会把用户指向错误的排查方向。 + */ + | 'DATABASE_PERMISSION_DENIED' | 'VC_RUNTIME_MISSING' | 'UNKNOWN_VALIDATION_ERROR' diff --git a/src/shared/local-api-test.ts b/src/shared/local-api-test.ts index 08c2c81..60cfe38 100644 --- a/src/shared/local-api-test.ts +++ b/src/shared/local-api-test.ts @@ -21,6 +21,39 @@ export const LOCAL_API_ENDPOINTS = { path: '/api/v1/scheduled-reports', queryKeys: [] }, + 'app-capabilities': { method: 'GET', path: '/api/v1/capabilities', queryKeys: [] }, + automations: { + method: 'GET', + path: '/api/v1/automations', + queryKeys: ['type', 'enabled'] + }, + 'automation-create': { method: 'POST', path: '/api/v1/automations', queryKeys: [] }, + 'automation-validate': { method: 'POST', path: '/api/v1/automations/validate', queryKeys: [] }, + 'automation-executions': { + method: 'GET', + path: '/api/v1/automations/executions', + queryKeys: ['ruleId', 'status', 'since', 'until', 'limit'] + }, + 'group-exit-monitor': { + method: 'GET', + path: '/api/v1/monitors/group-exits', + queryKeys: [] + }, + 'group-exit-monitor-update': { + method: 'PATCH', + path: '/api/v1/monitors/group-exits', + queryKeys: [] + }, + 'group-exit-events': { + method: 'GET', + path: '/api/v1/monitors/group-exits/events', + queryKeys: ['conversationId', 'since', 'until', 'limit'] + }, + 'group-member-stats': { + method: 'GET', + path: '/api/v1/groups/{conversationId}/member-stats', + queryKeys: ['conversationId', 'start', 'end'] + }, report: { method: 'POST', path: '/api/v1/report', queryKeys: [] }, 'agent-status': { method: 'GET', path: '/api/v1/agent/status', queryKeys: [] }, 'agent-group-report': { method: 'POST', path: '/api/v1/agent/group-report', queryKeys: [] }, diff --git a/src/shared/local-query-api.ts b/src/shared/local-query-api.ts index 2be8bb7..9c52552 100644 --- a/src/shared/local-query-api.ts +++ b/src/shared/local-query-api.ts @@ -1,4 +1,5 @@ import type { KnowledgeDerivedSource, KnowledgeEvidence, KnowledgeVoiceCoverage } from './knowledge' +import type { VoiceTranscriptState } from './voice-recognition' export type QueryDirection = 'any' | 'from_target' | 'to_target' export type QueryOrder = 'asc' | 'desc' @@ -254,6 +255,21 @@ export interface QueryMessage { * `empty` 也不允许被当成"可以凭画面猜内容"(OCR 不是 Vision)。 */ imageTextState?: 'indexed' | 'empty' | 'not_indexed' + /** + * 语音转写派生文本(**仅**语音消息、且本地已转写时存在)。 + * + * 与 `imageOcrText` 同理不并入 `text`:语音消息的正文仍是 `[语音消息]`, + * 这段文字来自本地离线识别,`derivedSource` 为 `voice_transcript`。 + */ + voiceTranscript?: string + /** + * 这条语音消息的本地转写状态(仅语音消息)。 + * + * - `transcribed`:已转写(此时 `voiceTranscript` 有值) + * - `pending`:尚未转写 —— 不能当成"语音里没说话",可调用 `query/voice-transcribe` + * - `failed`:之前识别失败 + */ + voiceTranscriptState?: VoiceTranscriptState } export interface QueryMessagesResponse { status: string @@ -275,7 +291,13 @@ export interface QueryMessagesResponse { imageOcrCoverage?: QueryImageTextCoverage } export interface SearchMessagesRequest { - target: QueryTarget + /** + * 目标会话。**可选** —— 省略表示"在 `scope` 描述的整个搜索范围内做跨会话检索"。 + * + * 实现侧一直是这么用的(`request.target?.query`),Tool schema 也是这么声明的; + * 只有这里漏了 `?`,于是所有"省略 target 的跨会话检索"在类型层面都成了错误。 + */ + target?: QueryTarget timeRange: QueryTimeRange query: string variants?: string[] @@ -419,7 +441,39 @@ export interface MessageContextResponse { before?: QueryMessage[] after?: QueryMessage[] } -export interface ConversationOverviewRequest { target: QueryTarget; timeRange: QueryTimeRange; scope?: QueryCorpusScope } +/** 单次 `query/voice-transcribe` 最多处理多少条语音。 */ +export const VOICE_TRANSCRIBE_MAX_REFS = 20 +/** 同步等待的默认值与上限(毫秒);超时的条目返回 `pending`,识别继续在后台进行。 */ +export const VOICE_TRANSCRIBE_DEFAULT_WAIT_MS = 15_000 +export const VOICE_TRANSCRIBE_MAX_WAIT_MS = 60_000 +export interface VoiceTranscribeRequest { + /** 来自 `query/messages` / `query/message-context` / `chatlog` 的语音消息 `messageRef`。 */ + messageRefs: string[] + /** 忽略已有转写与失败记录,重新识别。 */ + force?: boolean + /** 最多同步等待多久;0 = 只排队不等待。 */ + waitMs?: number +} +export interface VoiceTranscribeItem { + messageRef: string + state: VoiceTranscriptState + transcript?: string + cached?: boolean + durationMs?: number + /** 机器可读的原因,仅 `pending` / `failed` 时存在。 */ + code?: string + error?: string + /** 给调用方(通常是 AI)的下一步建议。 */ + hint?: string +} +export interface VoiceTranscribeResponse { + status: string + items?: VoiceTranscribeItem[] + summary?: { transcribed: number; pending: number; failed: number } + retryAfterSeconds?: number + hint?: string +} +export interface ConversationOverviewRequest { target?: QueryTarget; timeRange: QueryTimeRange; scope?: QueryCorpusScope } export interface ConversationOverviewResponse { status: string target?: { displayName: string; type: 'user' | 'group' } diff --git a/src/shared/msg-insert-switch.ts b/src/shared/msg-insert-switch.ts new file mode 100644 index 0000000..62a9cbd --- /dev/null +++ b/src/shared/msg-insert-switch.ts @@ -0,0 +1,173 @@ +/** + * 微信消息插入开关 —— 跨进程共享的类型与常量。 + * + * 开关本体存在 native 侧(每个消息分片 `_tm_config` 表),但**开关值写成功不等于 + * 功能真的生效**:真正干活的是挂在 `Msg_` 表上的规则,而某个分片 + * 完全可能「有 _tm_config 却没规则」。所以对外状态一律区分三件事: + * + * desiredEnabled 用户意图(开关值有没有写下去) + * effectiveEnabled 是否真的生效(目标会话的规则全齐 + 开关值落到相关分片) + * operationOk 写入层面有没有失败 + * + * 判断「生效」按**目标会话**算,不按分片算 —— 一个会话可能横跨 2~4 个分片, + * 只有当它命中的**每一个**分片都 ready,这个会话才算 ready。 + */ + +/** native 侧白名单里的开关名 */ +export const MSG_INSERT_SWITCHES = ['recall_notice', 'group_exit_notice'] as const + +export type MsgInsertSwitchName = (typeof MSG_INSERT_SWITCHES)[number] + +/** 目标会话的集合口径 */ +export const MSG_INSERT_SCOPES = [ + /** 退群监控里勾选的群(只服务自动化通知) */ + 'monitored_rooms', + /** 全部可定位会话(群聊 + 私聊) */ + 'all_sessions', + /** 全部群聊(微信内退群提示的口径,与勾选无关) */ + 'all_group_chats' +] as const +export type MsgInsertScope = (typeof MSG_INSERT_SCOPES)[number] + +export interface MsgInsertRoomIssue { + roomId: string + reason: 'rules-missing' | 'table-not-found' + matchedShards: string[] + notReadyShards: string[] +} + +export interface MsgInsertShardIssue { + shard: string + errorCode: number + error: string +} + +/** 开关的实现形态 */ +export type MsgInsertSwitchMode = + /** 靠微信库里的 persistent 规则实现:需要按会话装规则 → 有 room / shard 维度 */ + | 'rules' + /** 靠事件驱动的一次性插入实现:没有 room / shard 维度 */ + | 'event' + +/** 单个开关的完整状态 */ +export interface MsgInsertSwitchStatus { + switch: MsgInsertSwitchName + scope: MsgInsertScope + /** rules = 装规则(防撤回);event = 事件驱动一次性插入(退群提示) */ + mode: MsgInsertSwitchMode + + /** 用户意图:开关值当前是否处于「开」 */ + desiredEnabled: boolean + /** 是否真的生效 */ + effectiveEnabled: boolean + /** 写入层面是否全部成功 */ + operationOk: boolean + + /** + * 目标会话总数(**分母**)。 + * + * ⚠️ 这是「**有消息表、可安装规则**的会话数」,不是全部会话数。 + * 公众号 / 服务号 / 系统会话根本没有 `Msg_` 表,装不了规则,它们是中性 pending, + * 拿它们当分母只会让开关永远显示「部分成功」。 + */ + totalInstallableRooms: number + /** 规则已就绪的可安装会话数(分子) */ + readyInstallableRooms: number + /** + * 微信库里找不到消息表的会话数。 + * + * **中性 pending,不是失败**:这类会话通常还没收发过消息。它们不会进 + * notReadyRooms,也不会阻止 effectiveEnabled。UI 单独显示为「暂无消息表」。 + */ + roomsWithoutTable: number + /** 事件驱动型开关用:该开关覆盖的群聊数(只是范围,不是覆盖率) */ + monitoredRoomCount?: number + + totalShards: number + /** 目标会话实际落在的分片数 */ + targetShards: number + /** 开关值已落到「开」的分片数 */ + configuredShards: number + /** 开关值对且目标规则齐的分片数 */ + readyShards: number + /** 值对了但目标规则不齐的分片数(不是失败) */ + notReadyShards: number + /** 写不进去 / 读回校验不过的分片数(真失败) */ + failedShards: number + + notReadyRooms?: MsgInsertRoomIssue[] + failures?: MsgInsertShardIssue[] + + /** 机器可读的错误分类,见 MsgInsertErrorCode */ + errorCode?: MsgInsertErrorCode + /** 给人看的一句话;UI 直接展示这个 */ + message?: string +} + +export interface MsgInsertSwitchesSnapshot { + success: boolean + switches: Record + /** helper 是否可用(不可用时只能读不能写) */ + /** + * **能力标志**:本机是否存在「微信内消息写入组件」(那个一次性 helper)。 + * + * 这是「微信内防撤回提示」和「微信内退群监控消息」的**唯一硬门槛**: + * 主进程对微信库只持只读连接,任何写入都必须 spawn 那个组件,没有它两个功能都做不了。 + * + * 语义上它是 **capability(能力)**,不是 error(错误)—— + * 缺失时 UI 显示「暂无法使用」,而不是「请重新安装」。 + * + * ⚠️ 它是**唯一**的能力判据,不要再新增第二份(曾经因为 native 与 TS 各存一份判据 + * 而出现 946 里莫名少 323 的假象)。将来的授权/付费门禁应当**并列**加在它旁边 + * (capability && entitlement),而不是替换它。 + */ + helperAvailable: boolean + /** native code 只放这里,不往 UI 上抛 */ + detail?: string +} + +/** 打开/关闭一个开关的结果 */ +export interface MsgInsertApplyResult { + success: boolean + status: MsgInsertSwitchStatus + errorCode?: MsgInsertErrorCode + message?: string + detail?: string +} + +/** + * 错误分类。底层码(-2002 / -3004 / exit code)一律进 detail, + * 不给普通用户看。 + */ +export type MsgInsertErrorCode = + | 'HELPER_NOT_FOUND' + | 'HELPER_START_FAILED' + | 'HELPER_TIMEOUT' + | 'HELPER_BAD_OUTPUT' + | 'HELPER_EXIT_NONZERO' + | 'SHARD_WRITE_FAILED' + | 'SHARD_VERIFY_FAILED' + | 'RULE_MISSING' + | 'PARTIAL_SUCCESS' + | 'UNSUPPORTED_SWITCH' + | 'NO_TARGET_ROOMS' + | 'DATABASE_UNAVAILABLE' + | 'UNKNOWN' + +/** 界面上要展示的两个开关(顺序即展示顺序) */ +export const MSG_INSERT_SWITCH_LABELS: Array<{ + name: MsgInsertSwitchName + label: string + hint: string +}> = [ + { + name: 'recall_notice', + label: '微信内防撤回提示', + hint: '别人撤回消息时,在微信会话里保留原消息并提示你撤回了什么' + }, + { + name: 'group_exit_notice', + label: '微信内退群监控消息', + hint: '任意群有人退出时,在微信会话里插入一条退出提示(范围 = 全部群聊;自动化退群通知仍按退群监控勾选的群)' + } +] diff --git a/src/shared/report-history.ts b/src/shared/report-history.ts index 88626aa..52e378a 100644 --- a/src/shared/report-history.ts +++ b/src/shared/report-history.ts @@ -7,7 +7,17 @@ import type { ReportTemplateSelectionId } from './report-templates' import type { ReportTemplateRef } from './report-template-package' export type ReportAssetStatus = 'ready' | 'missing' -export type GeneratedReportSource = 'manual' | 'scheduled' +/** + * 日报的产出方式。 + * + * - `manual`:用户在日报页手动生成; + * - `scheduled`:定时日报(自动化里的时间驱动规则); + * - `automation`:消息型自动化「@我生成日报」触发产出。 + * + * 三种都写进**同一条日报历史**(`report-history-service` 是唯一出口), + * 这个字段只用于区分「谁触发的」,不参与任何可见性判断。 + */ +export type GeneratedReportSource = 'manual' | 'scheduled' | 'automation' export interface GeneratedReportRecord { id: string diff --git a/tests/component/account-database-controls.test.tsx b/tests/component/account-database-controls.test.tsx index 160945a..1725859 100644 --- a/tests/component/account-database-controls.test.tsx +++ b/tests/component/account-database-controls.test.tsx @@ -1,7 +1,10 @@ import { render, screen } from '@testing-library/react' import userEvent from '@testing-library/user-event' import { describe, expect, it, vi } from 'vitest' +import { AccountSummary } from '../../src/renderer/src/components/account/AccountSummary' import { AccountOverview } from '../../src/renderer/src/features/settings/account-database/AccountOverview' +import { ConnectionHealthSection } from '../../src/renderer/src/features/settings/account-database/ConnectionHealthSection' +import type { ConnectionDiagnostic } from '../../src/renderer/src/features/settings/account-database/types' import { TooltipProvider } from '../../src/renderer/src/components/ui' describe('account database controls', () => { @@ -61,4 +64,54 @@ describe('account database controls', () => { expect(screen.getByRole('button', { name: '打开账号目录' })).toBeDisabled() expect(screen.getByRole('button', { name: '复制账号目录' })).toBeDisabled() }) + + it('renders connection states with SVG glyphs and keeps checking accessible', () => { + const diagnostics: ConnectionDiagnostic[] = [ + { id: 'db-key', label: '数据库密钥', status: 'success', result: '已用于当前连接' }, + { id: 'contacts', label: '联系人索引', status: 'warning', result: '索引待更新' }, + { id: 'messages', label: '消息数据库', status: 'error', result: '读取失败' }, + { id: 'identity', label: '账号身份', status: 'idle', result: '尚未检测' }, + { id: 'image-key', label: '图片解密密钥', status: 'unavailable', result: '未配置' } + ] + const { container, rerender } = render() + + const icons = container.querySelectorAll('.settings-diagnostic-icon:not(.checking)') + expect(icons).toHaveLength(diagnostics.length) + icons.forEach((icon) => { + expect(icon).toHaveAttribute('aria-hidden', 'true') + expect(icon.querySelector('svg')).toHaveAttribute('viewBox', '0 0 24 24') + }) + expect(container.textContent).not.toMatch(/[✓!×—]/) + + rerender( + + ) + expect(screen.getByLabelText('检测中')).toHaveClass('checking') + expect(container.querySelector('.checking svg')).toBeNull() + }) + + it('keeps the account settings button clickable with a centered-viewBox SVG', async () => { + const user = userEvent.setup() + const onClick = vi.fn() + render( + + ) + + const button = screen.getByRole('button', { name: '设置' }) + expect(button.querySelector('svg')).toHaveAttribute('viewBox', '0 0 24 24') + expect(button.querySelector('svg circle')).toHaveAttribute('cx', '12') + expect(button.querySelector('svg circle')).toHaveAttribute('cy', '12') + await user.click(button) + expect(onClick).toHaveBeenCalledOnce() + }) }) diff --git a/tests/component/export-workspace.test.tsx b/tests/component/export-workspace.test.tsx index 79348df..b8d9d5d 100644 --- a/tests/component/export-workspace.test.tsx +++ b/tests/component/export-workspace.test.tsx @@ -25,6 +25,7 @@ const previewMessage = (contact: Contact): Message => ({ describe('ExportWorkspace multi-chat selection', () => { beforeEach(() => { + localStorage.clear() Object.defineProperty(window, 'api', { configurable: true, value: { @@ -41,9 +42,9 @@ describe('ExportWorkspace multi-chat selection', () => { const renderWorkspace = ( onStartExport = vi.fn(async () => ({ success: false })), exportTasks: ExportTaskRecord[] = [] - ): { loadPreviewMessages: ReturnType } => { + ): { loadPreviewMessages: ReturnType; unmount: () => void } => { const loadPreviewMessages = vi.fn(async (contact: Contact) => [previewMessage(contact)]) - render( + const workspace = render( { onCancelExport={vi.fn(async () => undefined)} /> ) - return { loadPreviewMessages } + return { loadPreviewMessages, unmount: workspace.unmount } } it('defaults to one chat, forces HTML after adding another, merges the preview, and resets locally', async () => { @@ -221,6 +222,93 @@ describe('ExportWorkspace multi-chat selection', () => { endTime: Math.floor(new Date('2026-08-02T18:45').getTime() / 1000) }) }) + + it('restores export preferences after leaving and reopening the workspace', async () => { + const { unmount } = renderWorkspace() + + await userEvent.click( + within(screen.getByRole('radiogroup', { name: '导出格式' })).getByRole('radio', { + name: /HTML/ + }) + ) + await userEvent.click( + within(screen.getByRole('radiogroup', { name: '时间范围' })).getByRole('radio', { + name: '自定义时间' + }) + ) + await userEvent.type(screen.getByLabelText('开始时间'), '2026-08-01T09:30') + await userEvent.type(screen.getByLabelText('结束时间'), '2026-08-02T18:45') + await userEvent.click(screen.getByRole('checkbox', { name: '文字' })) + await userEvent.click(screen.getByRole('checkbox', { name: '语音' })) + await userEvent.click( + within(screen.getByRole('radiogroup', { name: '消息显示名称' })).getByRole('radio', { + name: '微信名' + }) + ) + await userEvent.click( + within(screen.getByRole('radiogroup', { name: 'HTML 打包方式' })).getByRole('radio', { + name: 'HTML 资源包并压缩为 ZIP' + }) + ) + await userEvent.click(screen.getByRole('checkbox', { name: '优先导出原图' })) + await userEvent.type(screen.getByLabelText('文件名称'), '持续更新的聊天档案') + await userEvent.click(screen.getByRole('button', { name: '选择位置' })) + expect(await screen.findByText('/fixture/export/持续更新的聊天档案.zip')).toBeVisible() + + unmount() + renderWorkspace() + + expect( + within(screen.getByRole('radiogroup', { name: '导出格式' })).getByRole('radio', { + name: /HTML/ + }) + ).toBeChecked() + expect( + within(screen.getByRole('radiogroup', { name: '时间范围' })).getByRole('radio', { + name: '自定义时间' + }) + ).toBeChecked() + expect(screen.getByLabelText('开始时间')).toHaveValue('2026-08-01T09:30') + expect(screen.getByLabelText('结束时间')).toHaveValue('2026-08-02T18:45') + expect(screen.getByRole('checkbox', { name: '文字' })).not.toBeChecked() + expect(screen.getByRole('checkbox', { name: '语音' })).toBeChecked() + expect( + within(screen.getByRole('radiogroup', { name: '消息显示名称' })).getByRole('radio', { + name: '微信名' + }) + ).toBeChecked() + expect( + within(screen.getByRole('radiogroup', { name: 'HTML 打包方式' })).getByRole('radio', { + name: 'HTML 资源包并压缩为 ZIP' + }) + ).toBeChecked() + expect(screen.getByRole('checkbox', { name: '优先导出原图' })).not.toBeChecked() + expect(screen.getByLabelText('文件名称')).toHaveValue('持续更新的聊天档案') + expect(screen.getByText('/fixture/export/持续更新的聊天档案.zip')).toBeVisible() + }) + + it('preserves the selected range while switching to and from all export', async () => { + renderWorkspace() + + await userEvent.click( + within(screen.getByRole('radiogroup', { name: '时间范围' })).getByRole('radio', { + name: '最近 7 天' + }) + ) + await userEvent.click(screen.getByRole('button', { name: /全部导出/ })) + expect( + within(screen.getByRole('radiogroup', { name: '时间范围' })).getByRole('radio', { + name: '全部时间' + }) + ).toBeChecked() + + await userEvent.click(screen.getByRole('button', { name: /聊天 A/ })) + expect( + within(screen.getByRole('radiogroup', { name: '时间范围' })).getByRole('radio', { + name: '最近 7 天' + }) + ).toBeChecked() + }) }) describe('ExportTaskCenter details', () => { diff --git a/tests/component/group-exit-monitor-workspace.test.tsx b/tests/component/group-exit-monitor-workspace.test.tsx index 6c499a9..e6ec94a 100644 --- a/tests/component/group-exit-monitor-workspace.test.tsx +++ b/tests/component/group-exit-monitor-workspace.test.tsx @@ -149,9 +149,22 @@ describe('GroupExitMonitorWorkspace', () => { monitoredRoomIds: ['研发群@chatroom'], monitoredGroupCount: 1 } - const setGroups = vi.fn().mockResolvedValue(savedState) + const setGroups = vi.fn(async (roomIds: string[]) => { + current = { + ...configuredState, + monitoredRoomIds: roomIds, + monitoredGroupCount: roomIds.length + } + return current + }) + /** + * 真实服务的 `getState()` 返回的是**内存里的当前状态** —— 保存之后再拉一次, + * 拿到的必然是保存后的值。mock 用可变变量体现这一点: + * 否则"切回事件页时重新拉取"会把它覆盖成保存前的旧值,那是 mock 的失真,不是实现的问题。 + */ + let current: GroupExitMonitorState = configuredState window.api = { - getGroupExitMonitorState: vi.fn().mockResolvedValue(configuredState), + getGroupExitMonitorState: vi.fn(async () => current), onGroupExitMonitorState: vi.fn(() => () => undefined), setGroupExitMonitorGroups: setGroups, checkGroupExitMonitorNow: vi.fn().mockResolvedValue(savedState), diff --git a/tests/component/leave-notification-ui.test.tsx b/tests/component/leave-notification-ui.test.tsx index 8c9c59a..c1379e5 100644 --- a/tests/component/leave-notification-ui.test.tsx +++ b/tests/component/leave-notification-ui.test.tsx @@ -240,8 +240,13 @@ describe('退群通知 · 真实数据', () => { it('规则级启停只有一个开关,没有第二个「发送退群通知」', async () => { await openLeaveNotificationEditor() - expect(screen.getAllByRole('switch')).toHaveLength(1) - expect(screen.getByRole('switch', { name: '启用这条自动化' })).toBeVisible() + /* 作用域收敛到规则编辑器本体(.automation-editor)。页面右上角的 + * 「微信消息插入开关」是页面级控件,不属于这条规则的编辑器, + * 不该被本断言计入 —— 否则页面级功能一增加,这里就会假失败。 */ + const editor = document.querySelector('.automation-editor') as HTMLElement + expect(editor).not.toBeNull() + expect(within(editor).getAllByRole('switch')).toHaveLength(1) + expect(within(editor).getByRole('switch', { name: '启用这条自动化' })).toBeVisible() expect(screen.queryByText('发送退群通知')).toBeNull() }) }) diff --git a/tests/component/message-insert-switches.test.tsx b/tests/component/message-insert-switches.test.tsx new file mode 100644 index 0000000..3c0287e --- /dev/null +++ b/tests/component/message-insert-switches.test.tsx @@ -0,0 +1,110 @@ +import { act, render, waitFor } from '@testing-library/react' +import { afterEach, describe, expect, it, vi } from 'vitest' + +import { ToastProvider } from '../../src/renderer/src/components/ui' +import { MessageInsertSwitches } from '../../src/renderer/src/features/automation/MessageInsertSwitches' +import type { MsgInsertSwitchesSnapshot } from '../../src/shared/msg-insert-switch' + +/** + * 自动化页右上角的两个开关 —— 只钉**运行期刷新时机**。 + * + * 背景:微信运行期间会新建 `message_N.db`,目标会话集合随之变化,而规则补齐此前 + * 只在启动时跑过一次。渲染层如果只在挂载时拉一次,用户看到的就是"计数对不上、 + * 而且不会自己变好"。所以要在窗口重新聚焦时问一次(主进程侧再用分片指纹决定要不要补)。 + */ +function makeSnapshot(ready: number, total: number): MsgInsertSwitchesSnapshot { + return { + success: true, + helperAvailable: true, + switches: { + recall_notice: { + name: 'recall_notice', + mode: 'rules', + desiredEnabled: true, + effectiveEnabled: ready === total, + readyInstallableRooms: ready, + totalInstallableRooms: total, + notReadyRooms: [], + totalShards: 1, + targetShards: 1 + }, + group_exit_notice: { + name: 'group_exit_notice', + mode: 'event', + desiredEnabled: true, + effectiveEnabled: true, + readyInstallableRooms: 1, + totalInstallableRooms: 1, + notReadyRooms: [], + totalShards: 0, + targetShards: 0 + } + } + } as unknown as MsgInsertSwitchesSnapshot +} + +function renderSwitches(): void { + render( + + + + ) +} + +describe('微信消息插入开关 · 运行期刷新', () => { + afterEach(() => { + vi.restoreAllMocks() + }) + + it('挂载只用 GET,不额外触发刷新', async () => { + const get = vi.fn().mockResolvedValue(makeSnapshot(1, 2)) + const refresh = vi.fn().mockResolvedValue(makeSnapshot(2, 2)) + window.api = { + getMsgInsertSwitches: get, + refreshMsgInsertSwitches: refresh + } as unknown as typeof window.api + + renderSwitches() + + await waitFor(() => expect(get).toHaveBeenCalled()) + expect(refresh).not.toHaveBeenCalled() + }) + + it('窗口重新聚焦时刷新一次,并画出更新后的计数', async () => { + const get = vi.fn().mockResolvedValue(makeSnapshot(1, 2)) + const refresh = vi.fn().mockResolvedValue(makeSnapshot(2, 2)) + window.api = { + getMsgInsertSwitches: get, + refreshMsgInsertSwitches: refresh + } as unknown as typeof window.api + + renderSwitches() + await waitFor(() => expect(document.body.textContent).toContain('1 / 2 已启用')) + + await act(async () => { + window.dispatchEvent(new Event('focus')) + }) + + await waitFor(() => expect(refresh).toHaveBeenCalledTimes(1)) + await waitFor(() => expect(document.body.textContent).toContain('2 / 2 已启用')) + }) + + it('刷新失败时保持已有状态,不打回禁用态', async () => { + const get = vi.fn().mockResolvedValue(makeSnapshot(1, 2)) + const refresh = vi.fn().mockRejectedValue(new Error('boom')) + window.api = { + getMsgInsertSwitches: get, + refreshMsgInsertSwitches: refresh + } as unknown as typeof window.api + + renderSwitches() + await waitFor(() => expect(document.body.textContent).toContain('1 / 2 已启用')) + + await act(async () => { + window.dispatchEvent(new Event('focus')) + }) + + await waitFor(() => expect(refresh).toHaveBeenCalled()) + expect(document.body.textContent).toContain('1 / 2 已启用') + }) +}) diff --git a/tests/integration/agent-api-phase2.test.ts b/tests/integration/agent-api-phase2.test.ts new file mode 100644 index 0000000..9edef6d --- /dev/null +++ b/tests/integration/agent-api-phase2.test.ts @@ -0,0 +1,287 @@ +import { afterAll, afterEach, describe, expect, it, vi } from 'vitest' + +const fixture = vi.hoisted(() => ({ + root: `/tmp/tracememo-agent-api-phase2-${process.pid}`, + contacts: [ + { + m_nsUsrName: 'room@chatroom', + m_nsNickName: '产品群', + md5: 'room-md5', + type: 'group' as const + }, + { + m_nsUsrName: 'wxid_friend', + m_nsNickName: 'Alice', + md5: 'friend-md5', + type: 'user' as const, + wxid: 'wxid_friend' + } + ], + state: { + enabled: true, + running: true, + nativeMonitorActive: true, + monitoredRoomIds: ['room@chatroom'], + monitoredGroupCount: 1, + monitorSelectionConfigured: true, + totalEventCount: 2, + lastCheckedAt: 1_728_000_000_000, + lastReadAt: 1_727_000_000_000, + unreadCount: 1 + }, + events: [ + { + id: 'event-2', + contactId: 'room-md5', + roomId: 'room@chatroom', + groupName: '产品群', + memberWxid: 'wxid_b', + memberName: '乙', + wechatName: '乙', + groupRemark: '群乙', + contactRemark: '', + previousCount: 3, + currentCount: 2, + delta: -1, + message: '乙退出了产品群', + detectedAt: 1_728_000_000_000 + }, + { + id: 'event-1', + contactId: 'room-md5', + roomId: 'room@chatroom', + groupName: '产品群', + memberWxid: 'wxid_a', + memberName: '甲', + wechatName: '甲', + groupRemark: '', + contactRemark: '', + previousCount: 4, + currentCount: 3, + delta: -1, + message: '甲退出了产品群', + detectedAt: 1_727_000_000_000 + } + ] +})) + +vi.mock('electron', () => ({ + app: { getPath: () => fixture.root, getVersion: () => 'test-version' }, + safeStorage: { + isEncryptionAvailable: () => true, + encryptString: (value: string) => Buffer.from(value), + decryptString: (value: Buffer) => value.toString() + } +})) + +vi.mock('../../src/main/services/chat-service', () => ({ + isReady: () => true, + listContacts: () => fixture.contacts, + listContactsAsync: async () => fixture.contacts, + listMessages: () => [], + getGroupSnapshot: () => null, + listRecentChat: () => [], + resolveMd5: () => null +})) +vi.mock('../../src/main/group-report-service', () => ({ exportGroupReport: vi.fn() })) +vi.mock('../../src/main/services/agent-group-report-service', () => ({ + generateAgentGroupReport: vi.fn() +})) +vi.mock('../../src/main/services/agent-hub-service', () => ({ + agentHubService: { getStatus: () => ({ connector: 'offline' }) } +})) + +import { LocalAgentApiService } from '../../src/main/services/local-agent-api-service' +import { startHttpServer, type HttpServerHandle } from '../../src/main/http-server' +import type { GroupMemberStatsResult } from '../../src/shared/group-stats' + +const TOKEN = 'T'.repeat(43) +const handles: HttpServerHandle[] = [] + +function createApi(): LocalAgentApiService { + const monitorState = fixture.state + return new LocalAgentApiService({ + automationRuleStore: { + listRules: () => [], + getRule: () => undefined, + createRule: () => { throw new Error('not used') }, + updateRule: () => undefined, + deleteRule: () => false, + setRuleEnabled: () => undefined + } as never, + automationExecutionLogService: { list: () => [] } as never, + listContacts: async () => fixture.contacts, + isDatabaseReady: () => true, + getVersion: () => 'test-version', + getPersonalWechatCapability: async () => ({ + supported: true, + ready: false, + status: 'needs_binding', + capabilities: { text: false, image: false, voice: false } + } as never), + getAgentHubStatus: () => ({ connector: 'offline' }), + getGroupExitMonitorState: () => ({ ...monitorState }), + configureGroupExitMonitor: async (configuration) => { + if (configuration.monitoredRoomIds !== undefined) { + monitorState.monitoredRoomIds = [...configuration.monitoredRoomIds] + monitorState.monitoredGroupCount = monitorState.monitoredRoomIds.length + } + if (configuration.enabled !== undefined) monitorState.enabled = configuration.enabled + monitorState.running = monitorState.enabled + return { ...monitorState } + }, + listGroupExitMonitorEvents: ({ roomId, sinceMs, untilMs, limit }) => + fixture.events + .filter((event) => !roomId || event.roomId === roomId) + .filter((event) => sinceMs === undefined || event.detectedAt >= sinceMs) + .filter((event) => untilMs === undefined || event.detectedAt <= untilMs) + .sort((left, right) => left.detectedAt - right.detectedAt) + .slice(-limit!), + getGroupMemberStats: async (query): Promise => ({ + conversationId: query.userMd5, + startTime: query.startTime, + endTime: query.endTime, + freshness: 'stale', + complete: false, + memberCount: 2, + activeMemberCount: 1, + silentMemberCount: 1, + activeMembers: [{ + senderId: 'wxid_a', + displayName: '甲', + groupNickname: '群甲', + messageCount: 3, + lastMessageTime: 1_728_000_000_000 + }], + silentMembers: [{ senderId: 'wxid_b', displayName: '乙', groupNickname: '' }], + unattributedMessages: 4, + excludedSystemMessages: 5, + firstMessageTime: 1_727_000_000_000, + limitations: ['本地索引尚未完全同步,以下结果可能不完整。'] + }) + }) +} + +async function startServer(): Promise { + const handle = await startHttpServer('127.0.0.1', 0, { + tokenProvider: () => TOKEN, + agentApiService: createApi() + }) + handles.push(handle) + return handle +} + +async function request( + handle: HttpServerHandle, + pathname: string, + method = 'GET', + body?: unknown +): Promise { + return fetch(`http://${handle.host}:${handle.port}${pathname}`, { + method, + headers: { + Authorization: `Bearer ${TOKEN}`, + ...(body === undefined ? {} : { 'Content-Type': 'application/json' }) + }, + ...(body === undefined ? {} : { body: JSON.stringify(body) }) + }) +} + +describe('Agent API Phase 2', () => { + afterEach(async () => { + await Promise.all(handles.splice(0).map((handle) => handle.close())) + }) + + afterAll(async () => { + await Promise.all(handles.splice(0).map((handle) => handle.close())) + }) + + it('advertises only the Phase 2 monitor and stats operations', async () => { + const handle = await startServer() + const response = await request(handle, '/api/v1/capabilities') + const body = await response.json() + + expect(response.status).toBe(200) + expect(body.groupExitMonitor.operations).toEqual([ + 'read_state', + 'configure_scope', + 'enable', + 'disable', + 'list_events' + ]) + expect(body.groupStats.operations).toEqual(['member_stats']) + }) + + it('validates the complete monitor patch before changing scope', async () => { + const handle = await startServer() + const invalid = await request(handle, '/api/v1/monitors/group-exits', 'PATCH', { + enabled: false, + monitoredConversationIds: ['room@chatroom', 'missing@chatroom'] + }) + + expect(invalid.status).toBe(422) + expect(fixture.state.enabled).toBe(true) + expect(fixture.state.monitoredRoomIds).toEqual(['room@chatroom']) + + const updated = await request(handle, '/api/v1/monitors/group-exits', 'PATCH', { + enabled: false, + monitoredConversationIds: [] + }) + expect(updated.status).toBe(200) + expect(await updated.json()).toMatchObject({ + enabled: false, + monitoredConversationIds: [], + eventCount: 2 + }) + }) + + it('returns stable event DTOs with time filters and ascending order', async () => { + const handle = await startServer() + const response = await request( + handle, + '/api/v1/monitors/group-exits/events?conversationId=room%40chatroom&since=2024-10-01T00%3A00%3A00%2B07%3A00&limit=1' + ) + const body = await response.json() + + expect(response.status).toBe(200) + expect(body).toMatchObject({ count: 1 }) + expect(body.events[0]).toMatchObject({ + eventId: 'event-2', + conversationId: 'room@chatroom', + memberId: 'wxid_b', + detectedAt: new Date(1_728_000_000_000).toISOString() + }) + expect(body.events[0].read).toBeUndefined() + }) + + it('adapts stable group IDs and preserves stats freshness diagnostics', async () => { + const handle = await startServer() + const response = await request( + handle, + '/api/v1/groups/room%40chatroom/member-stats?start=2026-10-01T00%3A00%3A00%2B07%3A00&end=2026-10-02T00%3A00%3A00%2B07%3A00' + ) + const body = await response.json() + + expect(response.status).toBe(200) + expect(body).toMatchObject({ + conversation: { id: 'room@chatroom', name: '产品群' }, + conversationId: 'room@chatroom', + freshness: 'stale', + complete: false, + unattributedMessages: 4, + excludedSystemMessages: 5, + firstMessageAt: new Date(1_727_000_000_000).toISOString() + }) + expect(body.activeMembers[0]).toMatchObject({ + memberId: 'wxid_a', + lastMessageAt: new Date(1_728_000_000_000).toISOString() + }) + + const direct = await request( + handle, + '/api/v1/groups/wxid_friend/member-stats?start=2026-10-01T00%3A00%3A00%2B07%3A00&end=2026-10-02T00%3A00%3A00%2B07%3A00' + ) + expect(direct.status).toBe(422) + expect((await direct.json()).error.code).toBe('NOT_GROUP_CONVERSATION') + }) +}) diff --git a/tests/integration/local-agent-api.test.ts b/tests/integration/local-agent-api.test.ts new file mode 100644 index 0000000..945e5be --- /dev/null +++ b/tests/integration/local-agent-api.test.ts @@ -0,0 +1,645 @@ +import fs from 'fs-extra' +import path from 'node:path' +import { afterAll, afterEach, beforeEach, describe, expect, it, vi } from 'vitest' + +const root = vi.hoisted(() => { + // eslint-disable-next-line @typescript-eslint/no-require-imports + const fs = require('node:fs') as typeof import('node:fs') + // eslint-disable-next-line @typescript-eslint/no-require-imports + const os = require('node:os') as typeof import('node:os') + // eslint-disable-next-line @typescript-eslint/no-require-imports + const path = require('node:path') as typeof import('node:path') + return fs.mkdtempSync(path.join(os.tmpdir(), 'tracememo-agent-api-')) +}) + +vi.mock('electron', () => ({ + app: { getPath: () => root, getVersion: () => 'test-version' }, + safeStorage: { + isEncryptionAvailable: () => true, + encryptString: (value: string) => Buffer.from(value, 'utf8'), + decryptString: (value: Buffer) => value.toString('utf8') + } +})) + +vi.mock('../../src/main/services/chat-service', () => ({ + isReady: () => true, + listContacts: () => [], + listContactsAsync: async () => [], + listMessages: () => [], + getGroupSnapshot: () => null, + listRecentChat: () => [], + resolveMd5: () => null +})) + +vi.mock('../../src/main/group-report-service', () => ({ exportGroupReport: vi.fn() })) +vi.mock('../../src/main/services/agent-group-report-service', () => ({ + generateAgentGroupReport: vi.fn() +})) +vi.mock('../../src/main/services/agent-hub-service', () => ({ + agentHubService: { + getStatus: () => ({ connector: 'offline' }), + testSend: vi.fn() + } +})) +vi.mock('../../src/main/services/group-exit-monitor-service', () => ({ + groupExitMonitorService: { + getState: () => ({ enabled: false, running: false, monitoredRoomIds: [] }) + } +})) + +import { + BUILTIN_DAILY_REPORT_RULE_ID, + BUILTIN_LEAVE_NOTIFICATION_RULE_ID +} from '../../src/shared/automation' +import { GROUP_EXIT_NOTIFICATION_TEMPLATE } from '../../src/shared/group-exit-monitor' +import type { Contact } from '../../src/shared/types' +import type { PersonalWechatSendCapability } from '../../src/shared/personal-wechat' +import { AutomationExecutionLogService } from '../../src/main/services/automation-execution-log-service' +import { AutomationRuleStore } from '../../src/main/services/automation-rule-store' +import { LocalAgentApiService } from '../../src/main/services/local-agent-api-service' +import { + apiServer, + startHttpServer, + type HttpServerHandle, + type HttpServerOptions +} from '../../src/main/http-server' +import type { LocalQueryApiService } from '../../src/main/services/local-query-api-service' + +const TOKEN = 'T'.repeat(43) +const handles: HttpServerHandle[] = [] +type TestDailyDraft = { + name: string + ruleType: string + scope: string + conditions: { + requireMentionMe: boolean + keyword: string + keywordMatchMode: string + conversationIds: string[] + ignoreSelf: boolean + } + actions: Array<{ type: string; enabled: boolean; text?: string }> + cooldownSeconds: number + replyDelaySeconds: number +} +type TestScheduledDraft = { + name: string + ruleType: string + scheduledReport: { + schedule: { time: string } + report: { + sourceConversationId: string + range: string + messageTypes: string[] + templateId: string + memberNameMode: string + timeoutSeconds: number + } + target: { type: string; contactId: string } + postfixText: string + } +} +type TestLeaveNotificationDraft = { + name: string + ruleType: string + leaveNotification: { + target: { type: string } + template: string + notifyScope: string + notifyRoomIds: string[] + targetNeedsReview?: boolean + } +} +const contacts: Contact[] = [ + { + m_nsUsrName: 'room@chatroom', + m_nsNickName: '产品群', + md5: 'group-md5', + type: 'group' + }, + { + m_nsUsrName: 'wxid_friend', + wxid: 'wxid_friend', + m_nsNickName: 'Alice', + md5: 'friend-md5', + type: 'user' + } +] + +let databaseReady = true +let personalReady = false +let currentStore: AutomationRuleStore +let currentExecutionLog: AutomationExecutionLogService + +function createApiService( + store = currentStore, + executionLog = currentExecutionLog +): LocalAgentApiService { + const personal = { + supported: true, + ready: personalReady, + status: personalReady ? 'ready' : 'needs_binding', + capabilities: { text: personalReady, image: false, voice: false }, + senderStatus: { executablePath: '/private/wechat/runtime' } + } as unknown as PersonalWechatSendCapability + return new LocalAgentApiService({ + automationRuleStore: store, + automationExecutionLogService: executionLog, + listContacts: async () => contacts, + isDatabaseReady: () => databaseReady, + getVersion: () => 'test-version', + getPersonalWechatCapability: async () => personal, + getAgentHubStatus: () => ({ connector: 'offline' }), + getGroupExitMonitorState: () => ({ enabled: false, running: false, monitoredRoomIds: [] }) + }) +} + +async function startServer( + api = createApiService(), + queryApiService?: HttpServerOptions['queryApiService'] +): Promise { + const handle = await startHttpServer('127.0.0.1', 0, { + tokenProvider: () => TOKEN, + agentApiService: api, + queryApiService + }) + handles.push(handle) + return handle +} + +function url(handle: HttpServerHandle, pathName: string): string { + return `http://${handle.host}:${handle.port}${pathName}` +} + +async function request( + handle: HttpServerHandle, + pathName: string, + method = 'GET', + body?: unknown, + headers: Record = {} +): Promise { + return fetch(url(handle, pathName), { + method, + headers: { + Authorization: `Bearer ${TOKEN}`, + ...(body !== undefined ? { 'Content-Type': 'application/json' } : {}), + ...headers + }, + ...(body !== undefined ? { body: JSON.stringify(body) } : {}) + }) +} + +const validDailyDraft = (): TestDailyDraft => ({ + name: '产品群日报自动化', + ruleType: 'daily_report', + scope: 'group', + conditions: { + requireMentionMe: true, + keyword: '日报', + keywordMatchMode: 'contains', + conversationIds: ['room@chatroom'], + ignoreSelf: true + }, + actions: [{ type: 'replyText', enabled: true, text: '收到' }], + cooldownSeconds: 60, + replyDelaySeconds: 0 +}) + +const validScheduledDraft = (): TestScheduledDraft => ({ + name: '产品群每日日报', + ruleType: 'scheduled_report', + scheduledReport: { + schedule: { time: '20:00' }, + report: { + sourceConversationId: 'room@chatroom', + range: 'today', + messageTypes: ['text', 'image'], + templateId: 'v1', + memberNameMode: 'groupNickname', + timeoutSeconds: 300 + }, + target: { type: 'contact', contactId: 'wxid_friend' }, + postfixText: '日报已生成' + } +}) + +const validLeaveNotificationDraft = (): TestLeaveNotificationDraft => ({ + name: '退群通知', + ruleType: 'leave_notification', + leaveNotification: { + target: { type: 'file_transfer' }, + template: GROUP_EXIT_NOTIFICATION_TEMPLATE, + notifyScope: 'all', + notifyRoomIds: [] + } +}) + +describe('Local Agent API', () => { + beforeEach(() => { + fs.removeSync(path.join(root, 'automation')) + databaseReady = true + personalReady = false + currentStore = new AutomationRuleStore({ userDataPath: () => root }) + currentExecutionLog = new AutomationExecutionLogService({ userDataPath: () => root }) + }) + + afterEach(async () => { + await Promise.all(handles.splice(0).map((handle) => handle.close())) + await apiServer.stop() + }) + + afterAll(() => fs.removeSync(root)) + + it('reports application version and separates supported from runtime availability', async () => { + const handle = await startServer() + let response = await request(handle, '/api/v1/capabilities') + expect(response.status).toBe(200) + let body = await response.json() + expect(body).toMatchObject({ + version: 'test-version', + apiVersion: 'v1', + database: { ready: true }, + query: { supported: true, available: true }, + automations: { + supported: true, + available: true, + ruleTypes: ['daily_report', 'scheduled_report', 'leave_notification'] + }, + wechat: { + personal: { supported: true, available: false, status: 'needs_binding' }, + ilink: { supported: true, available: false, status: 'offline' } + } + }) + expect(JSON.stringify(body)).not.toMatch(/private\/wechat|executablePath|token|context_token/i) + + databaseReady = false + response = await request(handle, '/api/v1/capabilities') + body = await response.json() + expect(body).toMatchObject({ + database: { ready: false }, + query: { supported: true, available: false, reason: 'database_not_ready' }, + groupStats: { supported: true, available: false, reason: 'database_not_ready' } + }) + }) + + it('uses the Agent error envelope for authorization, method, missing route, and size failures', async () => { + const handle = await startServer() + const unauthorized = await fetch(url(handle, '/api/v1/capabilities')) + expect(unauthorized.status).toBe(401) + expect(await unauthorized.json()).toMatchObject({ + error: { code: 'UNAUTHORIZED' }, + requestId: expect.any(String) + }) + + const wrongMethod = await request(handle, '/api/v1/capabilities', 'POST') + expect(wrongMethod.status).toBe(405) + expect(wrongMethod.headers.get('allow')).toBe('GET') + expect(await wrongMethod.json()).toMatchObject({ + error: { code: 'METHOD_NOT_ALLOWED' }, + requestId: expect.any(String) + }) + + const missingRoute = await request(handle, '/api/v1/automations/rule-1/run') + expect(missingRoute.status).toBe(404) + expect(await missingRoute.json()).toMatchObject({ + error: { code: 'NOT_FOUND' }, + requestId: expect.any(String) + }) + + const oversized = await fetch(url(handle, '/api/v1/automations'), { + method: 'POST', + headers: { + Authorization: `Bearer ${TOKEN}`, + 'Content-Type': 'application/json' + }, + body: JSON.stringify('x'.repeat(1024 * 1024 + 1)) + }) + expect(oversized.status).toBe(413) + expect(oversized.headers.get('x-request-id')).toEqual(expect.any(String)) + expect(await oversized.json()).toMatchObject({ + error: { code: 'PAYLOAD_TOO_LARGE' }, + requestId: expect.any(String) + }) + }) + + it('preserves the existing Query operation request and response contract', async () => { + const queryApi = { + messages: vi.fn(async (payload: unknown) => ({ status: 'completed', payload })) + } as unknown as LocalQueryApiService + const handle = await startServer(createApiService(), queryApi) + const payload = { target: { query: 'Alice' }, timeRange: { kind: 'all' } } + const response = await request(handle, '/api/v1/query/messages', 'POST', payload) + + expect(response.status).toBe(200) + expect(await response.json()).toEqual({ status: 'completed', payload }) + expect(queryApi.messages).toHaveBeenCalledWith(payload) + }) + + it('validates rule fields and resolves scheduled IDs without persisting', async () => { + const handle = await startServer() + const scheduled = validScheduledDraft() + const response = await request(handle, '/api/v1/automations/validate', 'POST', scheduled) + expect(response.status).toBe(200) + const result = await response.json() + expect(result).toMatchObject({ valid: true, normalized: { enabled: false } }) + expect(result.normalized.scheduledReport.report.sourceConversationId).toBe('room@chatroom') + expect(result.normalized.scheduledReport.target.contactId).toBe('wxid_friend') + expect(result.effects).toMatchObject({ sendsWechatMessage: true }) + expect(result.nextRunAt).toEqual(expect.any(String)) + expect(currentStore.listRules().some((rule) => rule.name === '产品群每日日报')).toBe(false) + + const mentionOnly = validDailyDraft() + mentionOnly.conditions.keyword = '' + const mentionOnlyResponse = await request( + handle, + '/api/v1/automations/validate', + 'POST', + mentionOnly + ) + expect((await mentionOnlyResponse.json()).valid).toBe(true) + + const invalidEnum = validDailyDraft() + invalidEnum.conditions.keywordMatchMode = 'regex' + const enumResponse = await request(handle, '/api/v1/automations/validate', 'POST', invalidEnum) + const enumResult = await enumResponse.json() + expect(enumResult.valid).toBe(false) + expect(enumResult.issues).toEqual( + expect.arrayContaining([ + expect.objectContaining({ path: 'conditions.keywordMatchMode', code: 'invalid_enum' }) + ]) + ) + + const invalidTime = validScheduledDraft() + invalidTime.scheduledReport.schedule.time = '29:90' + const timeResponse = await request(handle, '/api/v1/automations/validate', 'POST', invalidTime) + expect((await timeResponse.json()).issues).toEqual( + expect.arrayContaining([ + expect.objectContaining({ path: 'scheduledReport.schedule.time', code: 'invalid_time' }) + ]) + ) + + const unknownFieldResponse = await request(handle, '/api/v1/automations/validate', 'POST', { + ...validDailyDraft(), + callbackUrl: 'http://127.0.0.1' + }) + expect((await unknownFieldResponse.json()).issues).toEqual( + expect.arrayContaining([ + expect.objectContaining({ path: 'draft.callbackUrl', code: 'unknown_field' }) + ]) + ) + + const invalidRuleTypeResponse = await request(handle, '/api/v1/automations/validate', 'POST', { + ...validDailyDraft(), + ruleType: 'webhook' + }) + expect((await invalidRuleTypeResponse.json()).issues).toEqual( + expect.arrayContaining([expect.objectContaining({ path: 'ruleType', code: 'invalid_enum' })]) + ) + + const enabledInputResponse = await request(handle, '/api/v1/automations/validate', 'POST', { + ...validDailyDraft(), + enabled: true + }) + expect((await enabledInputResponse.json()).issues).toEqual( + expect.arrayContaining([ + expect.objectContaining({ path: 'enabled', code: 'use_enable_operation' }) + ]) + ) + + const invalidAllScopeRoomResponse = await request( + handle, + '/api/v1/automations/validate', + 'POST', + { + ...validLeaveNotificationDraft(), + leaveNotification: { + ...validLeaveNotificationDraft().leaveNotification, + notifyRoomIds: ['missing-room@chatroom'] + } + } + ) + expect((await invalidAllScopeRoomResponse.json()).issues).toEqual( + expect.arrayContaining([ + expect.objectContaining({ + path: 'leaveNotification.notifyRoomIds[0]', + code: 'contact_not_found' + }) + ]) + ) + }) + + it('creates disabled rules, updates them, validates on enable, and protects system rules', async () => { + const handle = await startServer() + const createResponse = await request(handle, '/api/v1/automations', 'POST', validDailyDraft(), { + 'X-Request-Id': 'agent:create-rule' + }) + expect(createResponse.status).toBe(201) + expect(createResponse.headers.get('x-request-id')).toBe('agent:create-rule') + const created = (await createResponse.json()).rule + expect(created).toMatchObject({ enabled: false, ruleType: 'daily_report' }) + expect(created.conditions.conversationIds).toEqual(['room@chatroom']) + + const getResponse = await request(handle, `/api/v1/automations/${created.id}`) + expect(getResponse.status).toBe(200) + expect((await getResponse.json()).rule.id).toBe(created.id) + + const patchResponse = await request(handle, `/api/v1/automations/${created.id}`, 'PATCH', { + name: '更新后的名称' + }) + expect((await patchResponse.json()).rule).toMatchObject({ + id: created.id, + name: '更新后的名称', + enabled: false + }) + + const immutableResponse = await request(handle, `/api/v1/automations/${created.id}`, 'PATCH', { + ruleType: 'scheduled_report' + }) + expect(immutableResponse.status).toBe(400) + expect(await immutableResponse.json()).toMatchObject({ + error: { code: 'RULE_TYPE_IMMUTABLE' }, + requestId: expect.any(String) + }) + + const metadataResponse = await request(handle, `/api/v1/automations/${created.id}`, 'PATCH', { + createdAt: 0 + }) + expect(metadataResponse.status).toBe(400) + expect((await metadataResponse.json()).error.code).toBe('IMMUTABLE_FIELD') + + databaseReady = false + const unavailableEnableResponse = await request( + handle, + `/api/v1/automations/${created.id}/enable`, + 'POST' + ) + expect(unavailableEnableResponse.status).toBe(409) + expect((await unavailableEnableResponse.json()).error.code).toBe('VALIDATION_FAILED') + expect(currentStore.getRule(created.id)?.enabled).toBe(false) + + databaseReady = true + const enableResponse = await request(handle, `/api/v1/automations/${created.id}/enable`, 'POST') + expect((await enableResponse.json()).rule.enabled).toBe(true) + const disableResponse = await request( + handle, + `/api/v1/automations/${created.id}/disable`, + 'POST' + ) + expect((await disableResponse.json()).rule.enabled).toBe(false) + + const filteredResponse = await request( + handle, + '/api/v1/automations?type=daily_report&enabled=false' + ) + const filtered = await filteredResponse.json() + expect(filtered.rules.some((rule: { id: string }) => rule.id === created.id)).toBe(true) + + const protectedDaily = await request( + handle, + `/api/v1/automations/${BUILTIN_DAILY_REPORT_RULE_ID}`, + 'DELETE' + ) + expect(protectedDaily.status).toBe(409) + expect((await protectedDaily.json()).error.code).toBe('PROTECTED_RULE') + const protectedLeave = await request( + handle, + `/api/v1/automations/${BUILTIN_LEAVE_NOTIFICATION_RULE_ID}`, + 'DELETE' + ) + expect(protectedLeave.status).toBe(409) + + const nonBuiltinLeave = currentStore.createRule(validLeaveNotificationDraft()) + const protectedNonBuiltinLeave = await request( + handle, + `/api/v1/automations/${nonBuiltinLeave.id}`, + 'DELETE' + ) + expect(protectedNonBuiltinLeave.status).toBe(409) + expect((await protectedNonBuiltinLeave.json()).error.code).toBe('PROTECTED_RULE') + + const duplicateLeave = await request(handle, '/api/v1/automations', 'POST', { + name: '第二条退群通知', + ruleType: 'leave_notification', + leaveNotification: { + target: { type: 'file_transfer' }, + template: '{groupName} {user}', + notifyScope: 'all', + notifyRoomIds: [] + } + }) + expect(duplicateLeave.status).toBe(409) + expect((await duplicateLeave.json()).error.code).toBe('SINGLETON_RULE') + + const deleteCustom = await request(handle, `/api/v1/automations/${created.id}`, 'DELETE') + expect(deleteCustom.status).toBe(200) + expect((await deleteCustom.json()).deletedId).toBe(created.id) + }) + + it('lists bounded execution records with structured filters', async () => { + const handle = await startServer() + currentExecutionLog.record({ + executionId: 'execution-1', + ruleId: BUILTIN_DAILY_REPORT_RULE_ID, + ruleName: '内置日报', + triggerTime: Date.parse('2025-01-02T03:04:05.000Z'), + trigger: 'message', + sourceDisplayName: '产品群', + status: 'failed', + durationMs: 1_250, + steps: [], + errorSummary: '日报生成失败' + }) + const response = await request( + handle, + '/api/v1/automations/executions?ruleId=builtin-mention-me-daily-report&status=failed&since=2025-01-01T00%3A00%3A00Z&until=2025-01-03T00%3A00%3A00Z&limit=10' + ) + expect(response.status).toBe(200) + expect(await response.json()).toMatchObject({ + count: 1, + executions: [ + { + executionId: 'execution-1', + ruleId: BUILTIN_DAILY_REPORT_RULE_ID, + ruleType: 'daily_report', + trigger: 'message', + status: 'failed', + startedAt: '2025-01-02T03:04:05.000Z', + finishedAt: '2025-01-02T03:04:06.250Z', + error: '日报生成失败' + } + ] + }) + const invalidLimit = await request(handle, '/api/v1/automations/executions?limit=201') + expect(invalidLimit.status).toBe(400) + expect((await invalidLimit.json()).error.code).toBe('INVALID_ARGUMENT') + }) + + it('only clears target review when a valid replacement target is supplied', async () => { + const handle = await startServer() + currentStore.saveLeaveNotificationRule({ + ...validLeaveNotificationDraft(), + enabled: false, + leaveNotification: { + ...validLeaveNotificationDraft().leaveNotification, + targetNeedsReview: true + } + }) + + const bypass = await request( + handle, + `/api/v1/automations/${BUILTIN_LEAVE_NOTIFICATION_RULE_ID}`, + 'PATCH', + { leaveNotification: { targetNeedsReview: false } } + ) + expect(bypass.status).toBe(400) + expect((await bypass.json()).error.code).toBe('IMMUTABLE_FIELD') + expect( + currentStore.getRule(BUILTIN_LEAVE_NOTIFICATION_RULE_ID)?.leaveNotification?.targetNeedsReview + ).toBe(true) + + const invalidTarget = await request( + handle, + `/api/v1/automations/${BUILTIN_LEAVE_NOTIFICATION_RULE_ID}`, + 'PATCH', + { leaveNotification: { target: {} } } + ) + expect(invalidTarget.status).toBe(422) + expect( + currentStore.getRule(BUILTIN_LEAVE_NOTIFICATION_RULE_ID)?.leaveNotification?.targetNeedsReview + ).toBe(true) + + const updated = await request( + handle, + `/api/v1/automations/${BUILTIN_LEAVE_NOTIFICATION_RULE_ID}`, + 'PATCH', + { leaveNotification: { target: { type: 'self' } } } + ) + expect(updated.status).toBe(200) + expect((await updated.json()).rule.leaveNotification).not.toHaveProperty('targetNeedsReview') + expect( + currentStore.getRule(BUILTIN_LEAVE_NOTIFICATION_RULE_ID)?.leaveNotification?.target + ).toEqual({ type: 'self' }) + }) + + it('returns a standard persistence error and rolls back the in-memory rule on write failure', async () => { + const blockedPath = path.join(root, 'not-a-directory') + fs.writeFileSync(blockedPath, 'file') + const failingStore = new AutomationRuleStore({ userDataPath: () => blockedPath }) + const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined) + const handle = await startServer(createApiService(failingStore, currentExecutionLog)) + try { + const response = await request(handle, '/api/v1/automations', 'POST', { + ...validDailyDraft(), + name: '不得假成功' + }) + expect(response.status).toBe(500) + expect(await response.json()).toMatchObject({ + error: { code: 'PERSISTENCE_FAILED' }, + requestId: expect.any(String) + }) + expect(failingStore.listRules().some((rule) => rule.name === '不得假成功')).toBe(false) + } finally { + warn.mockRestore() + } + }) +}) diff --git a/tests/integration/local-api-auth.test.ts b/tests/integration/local-api-auth.test.ts index 57d4e35..2f8642a 100644 --- a/tests/integration/local-api-auth.test.ts +++ b/tests/integration/local-api-auth.test.ts @@ -1,9 +1,11 @@ import fs from 'fs-extra' +import { join } from 'path' import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest' const fixture = vi.hoisted(() => ({ root: `/tmp/wxe-local-api-auth-${process.pid}`, storageAvailable: true, + skillVersion: '9.9.9', contacts: [ { m_nsUsrName: 'wxid_fixture', @@ -29,7 +31,16 @@ const fixture = vi.hoisted(() => ({ })) vi.mock('electron', () => ({ - app: { getPath: () => fixture.root }, + app: { + getPath: () => fixture.root, + getAppPath: () => fixture.root, + getVersion: () => 'test-version', + isPackaged: false + }, + shell: { + openPath: async () => '', + openExternal: async () => undefined + }, safeStorage: { isEncryptionAvailable: () => fixture.storageAvailable, encryptString: (value: string) => Buffer.from(`encrypted:${value}`, 'utf8'), @@ -68,7 +79,14 @@ vi.mock('../../src/main/services/agent-hub-service', () => ({ })) import { apiTokenStore } from '../../src/main/api-token-store' -import { apiServer, startHttpServer, type HttpServerHandle } from '../../src/main/http-server' +import { + apiServer, + setLocalVoiceTranscriptSnapshotProvider, + startHttpServer, + type HttpServerHandle +} from '../../src/main/http-server' +import type { LocalQueryApiService } from '../../src/main/services/local-query-api-service' +import { decodeMessageRef } from '../../src/shared/local-query-api' import { HttpMediaError } from '../../src/main/http-media-service' import { buildLocalApiCurlCommand, @@ -92,7 +110,13 @@ async function startFixtureServer( } describe('Local API authentication', () => { - beforeAll(() => fs.ensureDirSync(fixture.root)) + beforeAll(() => { + fs.ensureDirSync(fixture.root) + fs.outputFileSync( + join(fixture.root, 'docs', 'skill', 'tracememo-reader', 'SKILL.md'), + `---\nname: tracememo-reader\nversion: ${fixture.skillVersion}\ndescription: fixture\n---\n\n# TraceMemo Reader fixture\n` + ) + }) beforeEach(() => { fixture.storageAvailable = true @@ -111,7 +135,7 @@ describe('Local API authentication', () => { const health = await fetch(`${baseUrl(handle)}/api/v1/health`) expect(health.status).toBe(200) const healthBody = await health.json() - expect(healthBody).toMatchObject({ ok: true, service: 'TraceMemo Reader' }) + expect(healthBody).toMatchObject({ ok: true, service: 'TraceMemo Reader', version: 'test-version' }) expect(JSON.stringify(healthBody)).not.toMatch( /token|authorization|wxid|databasePath|provider/i ) @@ -128,6 +152,104 @@ describe('Local API authentication', () => { await expect(response.json()).resolves.toMatchObject({ count: 1 }) }) + it('advertises the Reader Skill version on health and serves SKILL.md to authenticated agents', async () => { + const handle = await startFixtureServer() + + const health = await (await fetch(`${baseUrl(handle)}/api/v1/health`)).json() + expect(health).toMatchObject({ + ok: true, + skill: { name: 'tracememo-reader', version: fixture.skillVersion, available: true } + }) + + const path = `${baseUrl(handle)}/api/v1/skill/tracememo-reader` + expect((await fetch(path)).status).toBe(401) + + const response = await fetch(path, { headers: { Authorization: `Bearer ${VALID_TOKEN}` } }) + expect(response.status).toBe(200) + const body = await response.json() + expect(body).toMatchObject({ name: 'tracememo-reader', version: fixture.skillVersion }) + expect(body.markdown).toContain(`version: ${fixture.skillVersion}`) + expect(body.contentHash).toMatch(/^[0-9a-f]{64}$/) + expect(JSON.stringify(body)).not.toMatch(/token|authorization|wxid|databasePath|provider/i) + }) + + // 外部 Agent 靠 health 上的 skill.version 判断 Skill 是否过期, + // 所以首选位置读不到时也必须正常回答(回退到下一个候选),不能整条 500。 + it('falls back to the next Skill candidate and still answers health', async () => { + const handle = await startFixtureServer() + const skillPath = join(fixture.root, 'docs', 'skill', 'tracememo-reader', 'SKILL.md') + const backup = fs.readFileSync(skillPath, 'utf-8') + fs.removeSync(skillPath) + try { + const response = await fetch(`${baseUrl(handle)}/api/v1/health`) + expect(response.status).toBe(200) + const body = await response.json() + expect(body.ok).toBe(true) + expect(body.skill).toMatchObject({ name: 'tracememo-reader', available: true }) + expect(body.skill.version).toMatch(/^\d+\.\d+\.\d+$/) + } finally { + fs.outputFileSync(skillPath, backup) + } + }) + + it.each([ + ['POST', '/api/v1/health', 'GET'], + ['PATCH', '/api/v1/current_time', 'GET'], + ['POST', '/api/v1/contact', 'GET'], + ['POST', '/api/v1/chatroom', 'GET'], + ['POST', '/api/v1/recent_chat', 'GET'], + ['POST', '/api/v1/chatlog', 'GET'], + ['POST', '/api/v1/group_snapshot', 'GET'], + ['POST', '/api/v1/resolve', 'GET'], + ['POST', '/api/v1/agent/status', 'GET'], + ['GET', '/api/v1/report', 'POST'], + ['PATCH', '/api/v1/query/capabilities', 'GET'], + ['GET', '/api/v1/query/messages', 'POST'], + ['POST', '/api/v1/media/image-1', 'GET, HEAD'] + ])('rejects unsupported methods with Allow: %s', async (method, pathname, allow) => { + const handle = await startFixtureServer() + const requestId = 'phase1:method-guard' + const response = await fetch(`${baseUrl(handle)}${pathname}`, { + method, + headers: { 'X-Request-Id': requestId } + }) + + expect(response.status).toBe(405) + expect(response.headers.get('allow')).toBe(allow) + expect(response.headers.get('x-request-id')).toBe(requestId) + await expect(response.json()).resolves.toMatchObject({ requestId }) + }) + + it('rejects oversized JSON request bodies with 413 and a request ID', async () => { + const handle = await startFixtureServer() + const requestId = 'phase1:body-limit' + const response = await fetch(`${baseUrl(handle)}/api/v1/report`, { + method: 'POST', + headers: { + Authorization: `Bearer ${VALID_TOKEN}`, + 'Content-Type': 'application/json', + 'X-Request-Id': requestId + }, + body: 'x'.repeat(1024 * 1024 + 1) + }) + + expect(response.status).toBe(413) + expect(response.headers.get('x-request-id')).toBe(requestId) + await expect(response.json()).resolves.toMatchObject({ status: 413, requestId }) + }) + + it('replaces malformed or oversized client request IDs with a server UUID', async () => { + const handle = await startFixtureServer() + const malformedId = 'x'.repeat(129) + const response = await fetch(`${baseUrl(handle)}/api/v1/health`, { + headers: { 'X-Request-Id': malformedId } + }) + + expect(response.status).toBe(200) + expect(response.headers.get('x-request-id')).toMatch(/^[0-9a-f-]{36}$/i) + expect(response.headers.get('x-request-id')).not.toBe(malformedId) + }) + it('exposes the query capability catalog only with the existing bearer token', async () => { const handle = await startFixtureServer() const path = `${baseUrl(handle)}/api/v1/query/capabilities` @@ -151,7 +273,9 @@ describe('Local API authentication', () => { ['POST', '/api/v1/agent/group-report'], ['POST', '/api/v1/agent/send'], ['GET', '/api/v1/query/capabilities'], - ['POST', '/api/v1/query/messages'] + ['POST', '/api/v1/query/messages'], + ['POST', '/api/v1/query/voice-transcribe'], + ['GET', '/api/v1/skill/tracememo-reader'] ])('protects every non-health route: %s %s', async (method, pathname) => { const handle = await startFixtureServer() const response = await fetch(`${baseUrl(handle)}${pathname}`, { @@ -181,6 +305,23 @@ describe('Local API authentication', () => { expect(JSON.stringify(response.headers)).not.toMatch(/path|token|database/i) }) + it('preserves authenticated HEAD requests for media without returning a body', async () => { + const provider = vi.fn(async () => ({ + buffer: Buffer.from([0xff, 0xd8, 0xff, 0xd9]), + mimeType: 'image/jpeg' + })) + const handle = await startFixtureServer(() => VALID_TOKEN, provider) + const response = await fetch(`${baseUrl(handle)}/api/v1/media/message-1`, { + method: 'HEAD', + headers: { Authorization: `Bearer ${VALID_TOKEN}` } + }) + + expect(response.status).toBe(200) + expect(response.headers.get('content-length')).toBe('4') + expect((await response.arrayBuffer()).byteLength).toBe(0) + expect(provider).toHaveBeenCalledOnce() + }) + it('adds media metadata to chatlog while redacting image keys', async () => { const handle = await startFixtureServer() const response = await fetch(`${baseUrl(handle)}/api/v1/chatlog?talker=测试联系人`, { @@ -199,6 +340,65 @@ describe('Local API authentication', () => { expect(body.messages[0].contentData).not.toHaveProperty('aeskey') }) + it('adds cached voice transcripts and a messageRef to chatlog voice messages', async () => { + const voice = { + id: '41', + type: '语音', + content: '[语音消息]', + sessionId: 'wxid_fixture', + localId: 41, + createTime: 1_785_895_200 + } + fixture.chatlogMessages.push(voice as never) + const snapshot = vi.fn(() => ({ state: 'transcribed' as const, transcript: '合成的转写文本' })) + setLocalVoiceTranscriptSnapshotProvider(snapshot) + try { + const handle = await startFixtureServer() + const response = await fetch(`${baseUrl(handle)}/api/v1/chatlog?talker=fixture`, { + headers: { Authorization: `Bearer ${VALID_TOKEN}` } + }) + const body = await response.json() + expect(body.messages[0]).not.toHaveProperty('voiceTranscriptState') + expect(body.messages[1]).toMatchObject({ + id: '41', + voiceTranscript: '合成的转写文本', + voiceTranscriptState: 'transcribed' + }) + expect(decodeMessageRef(body.messages[1].messageRef)).toEqual({ + conversationId: 'fixture-md5', + messageId: '41' + }) + expect(snapshot).toHaveBeenCalledWith({ + sessionId: 'wxid_fixture', + localId: 41, + createTime: 1_785_895_200, + svrId: undefined + }) + } finally { + setLocalVoiceTranscriptSnapshotProvider(undefined) + fixture.chatlogMessages.pop() + } + }) + + it('maps a full voice transcription queue to 429 with Retry-After', async () => { + const queryApiService = { + transcribeVoice: vi.fn(async () => ({ status: 'busy', retryAfterSeconds: 12, hint: '队列已满' })) + } as unknown as LocalQueryApiService + const handle = await startHttpServer('127.0.0.1', 0, { + tokenProvider: () => VALID_TOKEN, + queryApiService + }) + handles.push(handle) + const response = await fetch(`${baseUrl(handle)}/api/v1/query/voice-transcribe`, { + method: 'POST', + headers: { Authorization: `Bearer ${VALID_TOKEN}`, 'Content-Type': 'application/json' }, + body: JSON.stringify({ messageRefs: ['ref'] }) + }) + expect(response.status).toBe(429) + expect(response.headers.get('retry-after')).toBe('12') + await expect(response.json()).resolves.toMatchObject({ status: 'busy', retryAfterSeconds: 12 }) + }) + it('serves opaque media handles while preserving the chatlog message id', async () => { const mediaId = `image:${'a'.repeat(64)}` const previousUrl = fixture.chatlogMessages[0].media.url @@ -265,9 +465,10 @@ describe('Local API authentication', () => { headers: { Authorization: authorization } }) expect(response.status).toBe(401) - await expect(response.json()).resolves.toEqual({ + await expect(response.json()).resolves.toMatchObject({ error: 'unauthorized', - message: 'Valid API token required' + message: 'Valid API token required', + requestId: expect.any(String) }) } ) @@ -344,7 +545,9 @@ describe('Local API authentication', () => { expect(response.headers.get('access-control-allow-origin')).toBe(origin) expect(response.headers.get('access-control-allow-methods')).toContain('PATCH') expect(response.headers.get('access-control-allow-methods')).toContain('DELETE') - expect(response.headers.get('access-control-allow-headers')).toBe('Content-Type, Authorization') + expect(response.headers.get('access-control-allow-headers')).toBe( + 'Content-Type, Authorization, X-Request-Id' + ) }) it.each([ diff --git a/tests/integration/scheduled-report-api.test.ts b/tests/integration/scheduled-report-api.test.ts index 1715fd5..f89b2db 100644 --- a/tests/integration/scheduled-report-api.test.ts +++ b/tests/integration/scheduled-report-api.test.ts @@ -38,6 +38,7 @@ vi.mock('electron', () => ({ vi.mock('../../src/main/services/chat-service', () => ({ isReady: () => true, listContacts: () => fixture.contacts, + listContactsAsync: async () => fixture.contacts, listMessages: () => [], getGroupSnapshot: () => null, listRecentChat: () => [], diff --git a/tests/typecheck-baseline.json b/tests/typecheck-baseline.json index 915cccc..84fae6e 100644 --- a/tests/typecheck-baseline.json +++ b/tests/typecheck-baseline.json @@ -1,6 +1,6 @@ { "note": "测试文件类型检查基线:只允许下降,不允许上升。用 node scripts/typecheck-tests.cjs --update 下调。", - "total": 209, + "total": 203, "files": { "tests/component/ai-model-settings.test.tsx": 2, "tests/component/ai-search-cache-consent.test.tsx": 3, @@ -32,7 +32,6 @@ "tests/integration/image-text-index-synthetic-e2e.test.ts": 22, "tests/integration/query-agent-image-ocr-text.test.ts": 16, "tests/integration/query-agent-self-direction.test.ts": 7, - "tests/unit/agent-hub-routing.test.ts": 1, "tests/unit/ai-search-pipeline-service.test.ts": 1, "tests/unit/ai-search-provider-consent.test.ts": 5, "tests/unit/ai-search-workspace-pure-functions.test.ts": 13, @@ -40,7 +39,7 @@ "tests/unit/group-report.test.ts": 1, "tests/unit/http-media-service.test.ts": 2, "tests/unit/knowledge-freshness.test.ts": 1, - "tests/unit/local-query-api-service.test.ts": 51, + "tests/unit/local-query-api-service.test.ts": 46, "tests/unit/message-state.test.ts": 1, "tests/unit/query-agent-image-ocr-coverage.test.ts": 1, "tests/unit/query-agent-service.test.ts": 4, diff --git a/tests/unit/after-pack-signing.test.ts b/tests/unit/after-pack-signing.test.ts index 99f50fa..017f136 100644 --- a/tests/unit/after-pack-signing.test.ts +++ b/tests/unit/after-pack-signing.test.ts @@ -1,7 +1,7 @@ import { createRequire } from 'module' import { mkdirSync, mkdtempSync, rmSync, symlinkSync, writeFileSync } from 'fs' import { tmpdir } from 'os' -import { join } from 'path' +import { join, sep } from 'path' import { afterAll, describe, expect, it } from 'vitest' const nodeRequire = createRequire(import.meta.url) @@ -94,7 +94,16 @@ function fixtureApp(): string { } const app = fixtureApp() -const relative = (target: string): string => target.slice(app.length + 1) +/** + * 归一化成 POSIX 风格再断言。 + * + * `findNestedMacosCodePaths()` 返回的是**平台原生路径**(Windows runner 上是反斜杠), + * 而这一组用例验证的是**签名顺序算法** —— 谁必须排在谁前面 —— 跟分隔符毫无关系。 + * 归一化之后,层次可以直接用 `Contents/Frameworks/...` 这样的字面量表达, + * 既读得懂,也不会再出现"同一文件里一半 `join()`、一半硬编码斜杠"的混用。 + */ +const relative = (target: string): string => + target.slice(app.length + 1).split(sep).join('/') describe('macOS nested code signing order', () => { afterAll(() => rmSync(root, { recursive: true, force: true })) @@ -102,7 +111,7 @@ describe('macOS nested code signing order', () => { it('signs nested code inside-out and ignores resources and symlinks', () => { const paths = findNestedMacosCodePaths(app).map(relative) - expect(paths).toContain(join('Contents', 'MacOS', 'TraceMemo')) + expect(paths).toContain('Contents/MacOS/TraceMemo') expect(paths).not.toContain(app) expect(paths.some((entry) => entry.includes('Resources'))).toBe(false) expect(paths.some((entry) => entry.endsWith('.md'))).toBe(false) diff --git a/tests/unit/agent-hub-routing.test.ts b/tests/unit/agent-hub-routing.test.ts index 6c9b739..b3f9068 100644 --- a/tests/unit/agent-hub-routing.test.ts +++ b/tests/unit/agent-hub-routing.test.ts @@ -1,5 +1,6 @@ import { describe, expect, it } from 'vitest' import { + formatWechatReplyText, matchGroupReportIntent, matchRecentChatIntent, queryAgentReplyText, @@ -114,15 +115,46 @@ describe('Agent Hub 回复文案映射', () => { outcome: 'answered' as const } + /** + * 完整合法的 answered 结果。 + * `evidence` / `stats` 是 contract 必填字段 —— 直接写字面量会缺字段报类型错。 + */ + const answeredResult = (answer: string): AskWechatQueryResult => ({ + engine: 'query-agent', + status: 'answered', + answer, + evidence: [], + stats: { + tools: [], + reads: { messageCount: 0, matchedCount: 0, overviewSourceCount: 0, evidenceCount: 0 }, + modelCallCount: 0, + toolCallCount: 0, + totalMs: 0 + }, + diagnostics + }) + it('answered → 直接用 Query Agent 的文本回答', () => { + expect(queryAgentReplyText(answeredResult('最近聊了两件事。'))).toBe('最近聊了两件事。') + }) + + it('answered → 剥离桌面 UI 的 [E#] 引用编号(微信里点不开,只剩噪音)', () => { expect( - queryAgentReplyText({ - engine: 'query-agent', - status: 'answered', - answer: '最近聊了两件事。', - diagnostics - }) - ).toBe('最近聊了两件事。') + queryAgentReplyText( + answeredResult('第一件事先看结论、第二件事要留缓冲[E6][E14],第三件不能直接上[E16]。') + ) + ).toBe('第一件事先看结论、第二件事要留缓冲,第三件不能直接上。') + }) + + it('独占一行的 [E#] 被移除,但不会把相邻两行粘成一行', () => { + expect(queryAgentReplyText(answeredResult('第一件事[E1]\n[E2]\n第二件事[E3]'))).toBe( + '第一件事\n\n第二件事' + ) + }) + + it('整段只剩引用编号时原样兜底,绝不发空消息', () => { + // 防御分支:正常回答不会走到这里;真走到也宁可有内容,不能发一条空消息。 + expect(queryAgentReplyText(answeredResult('[E1][E2]'))).toBe('[E1][E2]') }) it('provider_unavailable / error → 使用安全文案', () => { @@ -153,3 +185,25 @@ describe('Agent Hub 回复文案映射', () => { expect(queryAgentReplyText(legacy)).toBe(QUERY_AGENT_UNAVAILABLE_TEXT) }) }) + +describe('Agent Hub 微信文本排版 — 单换行会被压成空格', () => { + it('列表项之间改用空行,否则微信里连成一整段', () => { + expect(formatWechatReplyText('结论:两件事。\n• 做饭\n• 游戏')).toBe( + '结论:两件事。\n\n• 做饭\n\n• 游戏' + ) + }) + + it('Markdown 列表标记归一成 • 后同样独立成行', () => { + expect(formatWechatReplyText('1. 先说结论\n- 做饭\n- 游戏')).toBe( + '1. 先说结论\n\n• 做饭\n\n• 游戏' + ) + }) + + it('连续空行收敛成一个,不留多余空行', () => { + expect(formatWechatReplyText('A\n\n\n\nB')).toBe('A\n\nB') + }) + + it('水平线不会被误当成列表标记', () => { + expect(formatWechatReplyText('上文\n---\n下文')).toBe('上文\n---\n下文') + }) +}) diff --git a/tests/unit/automation-action-runner.test.ts b/tests/unit/automation-action-runner.test.ts index d334f8e..3584d23 100644 --- a/tests/unit/automation-action-runner.test.ts +++ b/tests/unit/automation-action-runner.test.ts @@ -24,6 +24,10 @@ import { type AutomationStepKey } from '../../src/shared/automation' import type { WechatActionRequest, WechatActionResult } from '../../src/shared/wechat-action' +import type { + SaveGeneratedReportRequest, + SaveGeneratedReportResult +} from '../../src/shared/report-history' import { AutomationActionRunner } from '../../src/main/services/automation-action-runner' import type { AgentGroupReportResult } from '../../src/main/services/agent-group-report-service' @@ -87,13 +91,16 @@ function buildRunner(options: { executeAction?: (request: WechatActionRequest) => Promise generateReport?: () => Promise delay?: (ms: number) => Promise + saveGeneratedReport?: (request: SaveGeneratedReportRequest) => Promise }): { runner: AutomationActionRunner calls: WechatActionRequest[] reports: Array<{ group: string; range?: string }> + saved: SaveGeneratedReportRequest[] } { const calls: WechatActionRequest[] = [] const reports: Array<{ group: string; range?: string }> = [] + const saved: SaveGeneratedReportRequest[] = [] const runner = new AutomationActionRunner({ now: fakeClock(), delay: options.delay ?? noDelay, @@ -104,9 +111,18 @@ function buildRunner(options: { generateReport: async (request) => { reports.push({ group: request.group, ...(request.range ? { range: request.range } : {}) }) return options.generateReport ? options.generateReport() : { success: true, pngPath: '/tmp/report.png' } + }, + /* + * 默认**不落盘**:真实的 `saveGeneratedReport` 会往 electron 提供的 userData + * 前缀(本文件 mock 成 `/tmp/wxe-automation-runner-fixture`)下写 json, + * 单测不该产生文件副作用。落库的磁盘语义由 `report-history-service.test.ts` 覆盖。 + */ + saveGeneratedReport: async (request) => { + saved.push(request) + return options.saveGeneratedReport ? options.saveGeneratedReport(request) : { success: true } } }) - return { runner, calls, reports } + return { runner, calls, reports, saved } } const run = ( @@ -201,6 +217,42 @@ describe('AutomationActionRunner', () => { expect(calls[0].content.type).toBe('text') }) + /* + * 「@我生成日报」产出的日报必须落进**日报历史**。 + * + * 这一条是回归防线:`run()` 曾经只把 PNG 交给发送、从不落库,于是图发出去了、 + * 日报历史里却永远查不到(用户报的"执行成功但历史里没有"就是这个)。 + */ + it('生成日报后把日报写进日报历史,来源标为 automation', async () => { + const { runner, saved } = buildRunner({}) + const result = await run(runner, makeRule()) + + expect(statusOf(result, 'report')).toBe('success') + expect(saved).toHaveLength(1) + expect(saved[0].source).toBe('automation') + expect(saved[0].contactId).toBe(GROUP_ID) + expect(saved[0].pngPath).toBe('/tmp/report.png') + expect(saved[0].generatedAt).toBeTruthy() + }) + + /* + * 落库失败**不阻断发送**(图片已经在手上,扣下不发对用户没有任何好处), + * 但**也不能假装没事** —— 失败必须写进步骤细节,用户在执行详情里看得见。 + */ + it('日报历史写入失败时照常发送,但把失败如实写进步骤细节', async () => { + const { runner, saved, calls } = buildRunner({ + saveGeneratedReport: async () => ({ success: false, error: 'ENOSPC: no space left' }) + }) + const result = await run(runner, makeRule()) + + expect(saved).toHaveLength(1) + expect(statusOf(result, 'report')).toBe('success') + expect(statusOf(result, 'send')).toBe('success') + expect(result.status).toBe('success') + expect(result.steps.find((step) => step.key === 'report')?.detail).toContain('未写入日报历史') + expect(calls.some((call) => call.purpose === AUTOMATION_SEND_PURPOSE.report)).toBe(true) + }) + it('生成日报抛异常时同样记 failed 并跳过发送', async () => { const { runner } = buildRunner({ generateReport: async () => { diff --git a/tests/unit/database-permission-classification.test.ts b/tests/unit/database-permission-classification.test.ts new file mode 100644 index 0000000..fff0297 --- /dev/null +++ b/tests/unit/database-permission-classification.test.ts @@ -0,0 +1,210 @@ +import { chmodSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'fs' +import { tmpdir } from 'os' +import { join } from 'path' +import { afterEach, describe, expect, it, vi } from 'vitest' + +vi.mock('electron', () => ({ + app: { getPath: () => 'fixture-settings' }, + safeStorage: { isEncryptionAvailable: () => false } +})) + +import { databaseKeyErrorMessage, mapConnectionError } from '../../src/main/services/chat-service' +import { + isPermissionDeniedError, + looksLikePermissionDenied, + PathAccessDeniedError, + probePathAccess +} from '../../src/main/services/path-access-probe' + +/** + * macOS 未授予「完全磁盘访问权限」时的错误分类。 + * + * 背景:底层探测用的是 `fs.existsSync()`,它对 `EPERM` 同样返回 `false`, + * 于是"权限被拒绝"会被静默降级成"文件不存在",最终报出「数据库文件缺失」—— + * 用户据此去查路径和重装,而真正该做的是去系统设置授权。 + * + * 这组用例把分类规则的**顺序**钉住:权限判定必须排在文件缺失之前, + * 同时不能把真正缺失、账号不匹配、Windows VC Runtime 这些既有分类挤掉。 + */ +function errnoError(message: string, code: string): Error { + return Object.assign(new Error(message), { code }) +} + +describe('数据库错误分类 · 权限优先于文件缺失', () => { + it('EPERM 且文本里带 session.db,仍归为权限问题而不是文件缺失', () => { + const error = errnoError( + "EPERM: operation not permitted, open '/Users/fixture/xwechat_files/wxid_demo/db_storage/session/session.db'", + 'EPERM' + ) + expect(mapConnectionError(error)).toBe('DATABASE_PERMISSION_DENIED') + }) + + it('EACCES 同样归为权限问题', () => { + const error = errnoError( + "EACCES: permission denied, open '/Users/fixture/xwechat_files/wxid_demo/db_storage/session/session.db'", + 'EACCES' + ) + expect(mapConnectionError(error)).toBe('DATABASE_PERMISSION_DENIED') + }) + + it('errno 被包装层丢掉、只剩文本时仍能识别(这是真实的降级形态)', () => { + expect( + mapConnectionError(new Error("EPERM: operation not permitted, open '/x/session.db'")) + ).toBe('DATABASE_PERMISSION_DENIED') + expect(mapConnectionError(new Error("EACCES: permission denied, stat '/x/session.db'"))).toBe( + 'DATABASE_PERMISSION_DENIED' + ) + }) + + it('探测层抛出的 PathAccessDeniedError 能被通用判定识别', () => { + const error = new PathAccessDeniedError('/fixture/xwechat_files/wxid_demo/db_storage') + expect(isPermissionDeniedError(error)).toBe(true) + expect(mapConnectionError(error)).toBe('DATABASE_PERMISSION_DENIED') + }) + + it('文本匹配不过宽:permission 出现在无关语义里不会被误判', () => { + expect(mapConnectionError(new Error('permission config not found in manifest'))).not.toBe( + 'DATABASE_PERMISSION_DENIED' + ) + }) +}) + +describe('数据库错误分类 · 既有分类不被权限规则抢走', () => { + it('真正的文件缺失仍是数据库文件缺失', () => { + expect( + mapConnectionError( + new Error('未找到微信 4.0 session.db: /Users/fixture/xwechat_files/wxid_demo/db_storage') + ) + ).toBe('DATABASE_FILE_MISSING') + expect( + mapConnectionError( + errnoError("ENOENT: no such file or directory, stat '/x/session.db'", 'ENOENT') + ) + ).toBe('DATABASE_FILE_MISSING') + }) + + it('账号密钥不匹配不受影响', () => { + expect(mapConnectionError(new Error('密钥与当前账号不匹配'))).toBe('ACCOUNT_MISMATCH') + expect(mapConnectionError(new Error('wcdb_open_account failed: -1005'))).toBe( + 'ACCOUNT_MISMATCH' + ) + }) + + it('Windows VC Runtime 缺失语义不受影响', () => { + /* + * 输入必须是**底层错误文本**(DLL 加载失败),不是给用户看的那段文案 —— + * `isWindowsVcRuntimeMissingError` 匹配的是 vcruntime140.dll / win32 error 126 + * 这类特征,用户文案里没有它们。 + */ + const vcError = new Error( + 'ERR_DLOPEN_FAILED: The specified module could not be found. vcruntime140.dll (win32 error 126)' + ) + expect(mapConnectionError(vcError, 'win32')).toBe('VC_RUNTIME_MISSING') + // 同一条文本在 macOS 上不该被归成 Windows 专属错误码。 + expect(mapConnectionError(vcError, 'darwin')).not.toBe('VC_RUNTIME_MISSING') + }) + + it('根目录不可用与打开失败仍各自归类', () => { + expect(mapConnectionError(new Error('未找到包含 db_storage 的微信 4.0 账号目录: /x'))).toBe( + 'ROOT_UNAVAILABLE' + ) + expect(mapConnectionError(new Error('wcdb_open_account failed'))).toBe('DATABASE_OPEN_FAILED') + }) +}) + +describe('数据库错误分类 · 用户可见文案', () => { + it('macOS 上权限不足给出「完全磁盘访问权限」这一步,且与文件缺失文案不同', () => { + const denied = databaseKeyErrorMessage('DATABASE_PERMISSION_DENIED', 'darwin') + expect(denied).toContain('完全磁盘访问权限') + expect(denied).toContain('隐私与安全性') + expect(denied).not.toBe(databaseKeyErrorMessage('DATABASE_FILE_MISSING', 'darwin')) + }) + + it('文件缺失文案保持原样(不能因为修权限把这条改坏)', () => { + expect(databaseKeyErrorMessage('DATABASE_FILE_MISSING', 'darwin')).toBe('数据库文件缺失') + }) + + it('文案里不出现裸的技术码', () => { + const denied = databaseKeyErrorMessage('DATABASE_PERMISSION_DENIED', 'darwin') + expect(denied).not.toContain('EPERM') + expect(denied).not.toContain('EACCES') + }) + + it('非 macOS 平台不给 macOS 专属指引', () => { + const win = databaseKeyErrorMessage('DATABASE_PERMISSION_DENIED', 'win32') + expect(win).not.toContain('完全磁盘访问权限') + expect(win).not.toContain('macOS') + expect(win).toContain('无法读取微信数据库') + }) + + /** + * FDA 是**故障恢复方案**,不是安装前置条件。 + * 文案必须读起来像"读不到时怎么办",而不是"用之前必须先开"。 + */ + it('权限文案的口吻是故障恢复,不是安装前置条件', () => { + const denied = databaseKeyErrorMessage('DATABASE_PERMISSION_DENIED', 'darwin') + expect(denied).toContain('无法读取微信数据库') + expect(denied).not.toContain('使用前') + expect(denied).not.toContain('必须先') + expect(denied).not.toContain('安装') + }) + + it('只有权限码在 macOS 上分叉,其余错误码跨平台一致', () => { + for (const code of [ + 'INVALID_FORMAT', + 'DATABASE_OPEN_FAILED', + 'ACCOUNT_MISMATCH', + 'ROOT_UNAVAILABLE', + 'DATABASE_FILE_MISSING', + 'UNKNOWN_VALIDATION_ERROR' + ] as const) { + expect(databaseKeyErrorMessage(code, 'darwin')).toBe(databaseKeyErrorMessage(code, 'win32')) + } + }) +}) + +/** + * 底层探测:`existsSync` 分不出「不存在」和「读不了」,所以新增的 probe 必须能分。 + * + * 权限断言只在非 Windows 上跑:Windows 的 `chmod` 不改变实际访问能力, + * 断言在那里不成立。这是**文件系统语义本身**的平台差异,不是业务逻辑被跳过。 + */ +describe('路径可访问性探测', () => { + const roots: string[] = [] + + afterEach(() => { + for (const root of roots.splice(0)) { + try { + chmodSync(join(root, 'locked'), 0o755) + } catch { + /* 目录可能已不存在 */ + } + rmSync(root, { recursive: true, force: true }) + } + }) + + it('能区分可读 / 不存在 / 无权限', () => { + const root = mkdtempSync(join(tmpdir(), 'wxe-path-probe-')) + roots.push(root) + const locked = join(root, 'locked') + mkdirSync(locked) + writeFileSync(join(locked, 'session.db'), 'fixture') + chmodSync(locked, 0o000) + + expect(probePathAccess(root)).toBe('ok') + expect(probePathAccess(join(root, 'does-not-exist.db'))).toBe('missing') + + if (process.platform !== 'win32') { + const target = join(locked, 'session.db') + expect(probePathAccess(target)).toBe('denied') + expect(looksLikePermissionDenied(target)).toBe(true) + } + }) + + it('PathAccessDeniedError 带上与 fs errno 对齐的 code', () => { + const error = new PathAccessDeniedError('/fixture/path') + expect(error.code).toBe('EPERM') + expect(error.name).toBe('PathAccessDeniedError') + expect(isPermissionDeniedError(error)).toBe(true) + }) +}) diff --git a/tests/unit/local-query-api-service.test.ts b/tests/unit/local-query-api-service.test.ts index 0b0f15d..6c3adc8 100644 --- a/tests/unit/local-query-api-service.test.ts +++ b/tests/unit/local-query-api-service.test.ts @@ -1,4 +1,4 @@ -import { describe, expect, it, vi, beforeEach } from 'vitest' +import { describe, expect, it, vi, beforeEach, type Mock } from 'vitest' // Keep local-time label assertions deterministic; production follows the host timezone. process.env.TZ = 'Asia/Shanghai' @@ -20,6 +20,10 @@ vi.mock('../../src/main/services/chat-service', () => ({ })) import { LocalQueryApiService } from '../../src/main/services/local-query-api-service' +import { listMessagesAsync } from '../../src/main/services/chat-service' +import { encodeMessageRef } from '../../src/shared/local-query-api' +import type { VoiceMessageReference, VoiceTranscriptSnapshot } from '../../src/shared/voice-recognition' +import type { VoiceTranscriptionOutcome } from '../../src/main/voice-pipeline/voice-transcription-gateway' describe('LocalQueryApiService', () => { const knowledge = { @@ -243,7 +247,7 @@ describe('LocalQueryApiService', () => { expect(result.sourceLatestAt).toBe(NOW - 1000) expect(result.freshness).toEqual({ catchUp: 'pending' }) expect(knowledge.requestCatchUp).toHaveBeenCalledTimes(1) - expect(knowledge.waitForIndexingComplete).toHaveBeenCalledWith(2000) + expect(knowledge.waitForIndexingComplete).toHaveBeenCalledWith(15000) }) it('追赶在预算内完成 → 用新索引重新检索(不能拿同步前的结果回答)', async () => { @@ -311,7 +315,9 @@ describe('LocalQueryApiService', () => { voiceCoverage: undefined }) - const result = await service.search({ target: { query: 'BOBO' }, timeRange: { kind: 'today' }, query: '健身' }) + // 刻意**不带 target**:单会话现在会走直读兜底(结论句变成"已用直读补齐"), + // 而这条用例要守的是"索引落后且无法兜底时,结论句必须诚实说无法确认"。 + const result = await service.search({ timeRange: { kind: 'today' }, query: '健身' }) expect(result.resolvedTimeRange?.endTime).toEqual(expect.any(Number)) // 请求边界(今天)晚于索引覆盖边界 4 分钟 → 只能 partial。 @@ -320,16 +326,129 @@ describe('LocalQueryApiService', () => { expect(result.indexCoverage?.summary).toContain('暂时无法确认') }) - it('已有索引任务在跑 → 复用而不阻塞本次查询', async () => { + it('已有索引任务在跑 → 同样等一个有界预算,等不到才按旧覆盖如实回答', async () => { fixture.contacts.splice(1) knowledge.search.mockResolvedValue({ ...staleIndex(), sourceLatestAt: NOW - 1000 }) knowledge.requestCatchUp.mockReturnValue({ triggered: false, inProgress: true }) + knowledge.waitForIndexingComplete.mockResolvedValue(false) - const result = await service.search({ target: { query: 'BOBO' }, timeRange: { kind: 'all' }, query: '健身' }) + const result = await service.search({ + target: { query: 'BOBO' }, + timeRange: { kind: 'all' }, + query: '健身' + }) - expect(result.freshness).toEqual({ catchUp: 'reused' }) - expect(knowledge.waitForIndexingComplete).not.toHaveBeenCalled() - expect(result.coverage).toEqual({ state: 'partial' }) + // 复用场景必须等:直接返回旧快照会出现「索引明明在追,却拿旧覆盖下结论」。 + expect(knowledge.waitForIndexingComplete).toHaveBeenCalledWith(15000) + // 用 toMatchObject 而不是逐字段断言:search() 的返回是联合类型, + // 直接取属性会撞上这个文件既有的"未收窄"类型债(棘轮不允许新增)。 + expect(result).toMatchObject({ + freshness: { catchUp: 'reused' }, + coverage: { state: 'partial' } + }) + }) + + it('复用的索引任务在预算内追完 → 重新检索,不允许拿同步前的结果回答', async () => { + fixture.contacts.splice(1) + knowledge.search + .mockResolvedValueOnce({ ...staleIndex(), sourceLatestAt: NOW - 1000 }) + .mockResolvedValueOnce({ + state: 'ready', + indexLatestAt: NOW - 30 * 1000, + sourceLatestAt: NOW - 1000, + voiceCoverage: undefined, + evidence: [ + { + conversationId: 'md5-bobo', + messageId: 'new-1', + timestamp: NOW - 60_000, + sender: 'BOBO', + sourceKind: 'text', + text: '最近开始健身了' + } + ] + }) + knowledge.requestCatchUp.mockReturnValue({ triggered: false, inProgress: true }) + knowledge.waitForIndexingComplete.mockResolvedValue(true) + + const result = await service.search({ + target: { query: 'BOBO' }, + timeRange: { kind: 'all' }, + query: '健身' + }) + + expect(knowledge.search).toHaveBeenCalledTimes(2) + expect(result).toMatchObject({ + freshness: { catchUp: 'completed' }, + coverage: { state: 'complete' }, + evidenceCount: 1 + }) + }) + + it('索引没覆盖 + 范围恰是一个会话 → 直读原始记录兜底(微信机器人拿得到新消息)', async () => { + fixture.contacts.splice(1) + knowledge.search.mockResolvedValue({ ...staleIndex(), sourceLatestAt: NOW - 1000 }) + knowledge.requestCatchUp.mockReturnValue({ triggered: true, inProgress: true }) + knowledge.waitForIndexingComplete.mockResolvedValue(false) + const listSpy = listMessagesAsync as unknown as Mock + // 直读必须落在 begin/end 让路窗口**之内**:窗口外后台索引会抢 WCDB, + // 把直读拖成几十秒。用调用顺序固定这个不变量。 + const order: string[] = [] + knowledge.beginInteractiveQuery.mockImplementation(() => void order.push('begin')) + knowledge.endInteractiveQuery.mockImplementation(() => void order.push('end')) + listSpy.mockImplementation(async () => { + order.push('directRead') + return [ + { + id: 'm9', + type: '普通文本', + datetime: '2026/9/9 11:58:00', + content: '刚聊到过这个话题', + isSender: false, + name: 'BOBO', + createTime: Math.floor((NOW - 2 * 60 * 1000) / 1000) + } + ] + }) + + const result = await service.search({ + target: { query: 'BOBO' }, + timeRange: { kind: 'all' }, + query: '话题' + }) + + // 直读读的是权威源,证据拿得到 —— 这是微信机器人"能拿到东西"的关键。 + // 但 coverage 仍如实是 partial:直读只补了索引水位之后那一段,更早的区间还是索引说了算。 + expect(listSpy).toHaveBeenCalledTimes(1) + expect(result).toMatchObject({ + coverage: { state: 'partial' }, + evidenceCount: 1, + evidence: [{ text: '刚聊到过这个话题', sender: 'BOBO' }] + }) + // 结论句必须说明"这段已用直读补上",否则模型会一边拿着证据、一边说"暂时无法确认"。 + const indexCoverage = ( + result as unknown as { indexCoverage?: { covered: boolean; summary: string } } + ).indexCoverage + expect(indexCoverage?.covered).toBe(false) + expect(indexCoverage?.summary).toContain('直读原始记录补齐') + expect(order).toEqual(['begin', 'directRead', 'end']) + }) + + it('索引没覆盖但范围跨多个会话 → 不直读兜底,仍如实 partial', async () => { + knowledge.search.mockResolvedValue({ ...staleIndex(), sourceLatestAt: NOW - 1000 }) + knowledge.requestCatchUp.mockReturnValue({ triggered: true, inProgress: true }) + knowledge.waitForIndexingComplete.mockResolvedValue(false) + const listSpy = listMessagesAsync as unknown as Mock + + const result = await service.search({ + timeRange: { kind: 'all' }, + query: '话题', + scope: { kind: 'all' } + }) + + // 跨会话直读要遍历上千个会话(大会话全量读一次 15s+),只能保持 partial。 + expect(listSpy).not.toHaveBeenCalled() + expect(result).toMatchObject({ coverage: { state: 'partial' }, evidenceCount: 0 }) }) it('追平后 0 结果才允许 complete negative;落后时同一条件只能是 partial', async () => { @@ -413,7 +532,8 @@ describe('LocalQueryApiService — indexCoverage 结论句', () => { }) it('落后时给出可直接引用的本地时间结论,且明确"暂时无法确认"', async () => { - const result = await service2.search({ target: { query: 'BOBO' }, timeRange: { kind: 'all' }, query: '健身' }) + // 同样刻意不带 target —— 见上一条:单会话已经会走直读兜底。 + const result = await service2.search({ timeRange: { kind: 'all' }, query: '健身' }) expect(result.coverage).toEqual({ state: 'partial' }) // 8/30 12:00 的本地时间标签(固定时钟下可断言) expect(result.indexCoverage?.covered).toBe(false) @@ -424,3 +544,111 @@ describe('LocalQueryApiService — indexCoverage 结论句', () => { expect(result.indexCoverage?.summary).not.toMatch(/\d{12,}/) }) }) + +describe('LocalQueryApiService voice transcription', () => { + const voiceMessage = { + id: 'v1', + from: 'user', + type: '语音', + datetime: '2026/8/4 10:00:00', + content: '[语音消息]', + isSender: false, + name: 'BOBO', + sessionId: 'wxid_fixture_member', + localId: 31, + createTime: Math.floor(new Date('2026-08-04T10:00:00+08:00').getTime() / 1000) + } + const textMessage = { id: 't1', from: 'user', type: '文本', datetime: '2026/8/4 10:01:00', content: '你好', isSender: false, name: 'BOBO', createTime: voiceMessage.createTime + 60 } + const voiceRef = encodeMessageRef('md5-bobo', 'v1') + const textRef = encodeMessageRef('md5-bobo', 't1') + + type GatewayStub = { + inFlightCount: number + snapshot: Mock<(reference: VoiceMessageReference) => VoiceTranscriptSnapshot> + modelReady: Mock<() => Promise> + transcribe: Mock<(references: VoiceMessageReference[], options: { force?: boolean; waitMs: number }) => Promise> + } + function makeGateway(): GatewayStub { + return { + inFlightCount: 0, + snapshot: vi.fn(() => ({ state: 'transcribed' as const, transcript: '明天下午三点开会' })), + modelReady: vi.fn(async () => true), + transcribe: vi.fn(async (references: VoiceMessageReference[]) => + references.map(() => ({ state: 'transcribed' as const, transcript: '明天下午三点开会', cached: false })) + ) + } + } + + let service: LocalQueryApiService + let gateway: GatewayStub + beforeEach(() => { + vi.mocked(listMessagesAsync).mockResolvedValue([voiceMessage, textMessage] as never) + gateway = makeGateway() + service = new LocalQueryApiService(undefined, () => new Date('2026-09-09T12:00:00+08:00')) + service.setVoiceTranscriptionGateway(gateway) + }) + + it('reads cached transcripts on query/messages and message-context without triggering recognition', async () => { + const result = await service.messages({ scope: { kind: 'current', conversationId: 'md5-bobo' }, timeRange: { kind: 'all' }, messageTypes: ['voice'] }) + expect(result).toMatchObject({ + messages: [{ messageType: 'voice', text: '[语音消息]', voiceTranscript: '明天下午三点开会', voiceTranscriptState: 'transcribed', derivedSource: 'voice_transcript' }] + }) + + gateway.snapshot.mockReturnValueOnce({ state: 'pending' }) + const context = await service.context({ messageRef: voiceRef, before: 0, after: 1 }) + expect(context).toMatchObject({ anchor: { voiceTranscriptState: 'pending' }, after: [{ messageType: 'text' }] }) + expect(context).not.toHaveProperty('anchor.voiceTranscript') + expect(context).not.toHaveProperty('after.0.voiceTranscriptState') + expect(gateway.transcribe).not.toHaveBeenCalled() + }) + + it('transcribes voice refs and explains refs that cannot be transcribed', async () => { + const result = await service.transcribeVoice({ messageRefs: [voiceRef, voiceRef, textRef, 'not-a-ref'], waitMs: 0 }) + + expect(gateway.transcribe).toHaveBeenCalledTimes(1) + expect(gateway.transcribe).toHaveBeenCalledWith( + [{ sessionId: 'wxid_fixture_member', localId: 31, createTime: voiceMessage.createTime, svrId: undefined }], + { force: undefined, waitMs: 0 } + ) + expect(result.status).toBe('completed') + expect(result.summary).toEqual({ transcribed: 1, pending: 0, failed: 2 }) + expect(result.items).toEqual([ + { messageRef: voiceRef, state: 'transcribed', transcript: '明天下午三点开会', cached: false }, + expect.objectContaining({ messageRef: textRef, state: 'failed', code: 'not_voice_message', hint: expect.stringContaining('不是语音') }), + expect.objectContaining({ messageRef: 'not-a-ref', state: 'failed', code: 'invalid_message_ref', hint: expect.stringContaining('不要自行构造') }) + ]) + }) + + it('reports still-processing and failed recognitions with next-step hints', async () => { + const other = { ...voiceMessage, id: 'v2', localId: 32 } + vi.mocked(listMessagesAsync).mockResolvedValue([voiceMessage, other] as never) + gateway.transcribe.mockResolvedValueOnce([ + { state: 'pending' }, + { state: 'failed', code: 'PREVIOUSLY_FAILED', error: 'decode failed' } + ]) + + const result = await service.transcribeVoice({ messageRefs: [voiceRef, encodeMessageRef('md5-bobo', 'v2')] }) + + expect(result.summary).toEqual({ transcribed: 0, pending: 1, failed: 1 }) + expect(result.items?.[0]).toMatchObject({ state: 'pending', code: 'still_processing', hint: expect.stringContaining('同样的 messageRef') }) + expect(result.items?.[1]).toMatchObject({ state: 'failed', code: 'previously_failed', error: 'decode failed', hint: expect.stringContaining('force=true') }) + expect(result.hint).toContain('同样的 messageRef') + }) + + it('rejects invalid arguments with a correctable hint', async () => { + await expect(service.transcribeVoice({ messageRefs: [] })).resolves.toMatchObject({ status: 'invalid_tool_arguments', field: 'messageRefs' }) + await expect(service.transcribeVoice({ messageRefs: Array.from({ length: 21 }, (_, index) => `ref-${index}`) })).resolves.toMatchObject({ status: 'invalid_tool_arguments', hint: expect.stringContaining('分批') }) + await expect(service.transcribeVoice({ messageRefs: [voiceRef], waitMs: 600_000 })).resolves.toMatchObject({ status: 'invalid_tool_arguments', field: 'waitMs' }) + expect(gateway.transcribe).not.toHaveBeenCalled() + }) + + it('stops before reading messages when the model is not ready or the queue is full', async () => { + gateway.modelReady.mockResolvedValueOnce(false) + await expect(service.transcribeVoice({ messageRefs: [voiceRef] })).resolves.toMatchObject({ status: 'voice_model_not_ready', hint: expect.stringContaining('下载语音识别模型') }) + expect(gateway.transcribe).not.toHaveBeenCalled() + + gateway.inFlightCount = 30 + gateway.transcribe.mockResolvedValueOnce(null) + await expect(service.transcribeVoice({ messageRefs: [voiceRef] })).resolves.toMatchObject({ status: 'busy', retryAfterSeconds: 30 }) + }) +}) diff --git a/tests/unit/scheduled-report-service.test.ts b/tests/unit/scheduled-report-service.test.ts index 69d3e42..5fd626d 100644 --- a/tests/unit/scheduled-report-service.test.ts +++ b/tests/unit/scheduled-report-service.test.ts @@ -323,6 +323,11 @@ describe('定时日报 · 微信异常通知', () => { const text = sendNotification.mock.calls[0][0].text as string expect(text).toContain('每日晚报') expect(text).toContain('日报生成失败') + // 必须带**失败发生时刻**:同一批补发的多条失败文案可能一模一样, + // 只有这个时间戳能把它们区分开。 + expect(text).toContain('8月27日 18:31') + // 必须用空行分隔:微信把单个换行压成空格,否则整条通知连成一行。 + expect(text).toContain('定时日报执行失败\n\n日报生成失败') const notifications = await service.listNotifications() expect(notifications).toHaveLength(1) diff --git a/tests/unit/skill-resource-service.test.ts b/tests/unit/skill-resource-service.test.ts index cb57dae..d3f3867 100644 --- a/tests/unit/skill-resource-service.test.ts +++ b/tests/unit/skill-resource-service.test.ts @@ -1,9 +1,12 @@ -import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'fs' +import { createHash } from 'crypto' +import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'fs' import { tmpdir } from 'os' import { dirname, join, resolve } from 'path' import { afterEach, describe, expect, it } from 'vitest' import { getSkillCandidates, + parseSkillFrontmatter, + readSkillDocument, resolveSkillResourceStatus } from '../../src/main/services/skill-resource-service' @@ -25,9 +28,18 @@ function environment(root: string, packaged: boolean) { } } -function writeSkill(filePath: string): void { +function skillBody(version?: string): string { + const versionLine = version ? `version: ${version}\n` : '' + return `---\nname: tracememo-reader\n${versionLine}description: fixture\n---\n\n# TraceMemo Reader\n\n正文内容。\n` +} + +function writeSkill(filePath: string, version?: string): void { mkdirSync(dirname(filePath), { recursive: true }) - writeFileSync(filePath, '# TraceMemo Reader\n', 'utf8') + writeFileSync(filePath, skillBody(version), 'utf8') +} + +function sha256(content: string): string { + return createHash('sha256').update(content, 'utf8').digest('hex') } describe('Reader Skill resource resolution', () => { @@ -39,44 +51,28 @@ describe('Reader Skill resource resolution', () => { const root = fixtureRoot() const runtime = environment(root, false) const skillPath = join(runtime.cwd, 'docs', 'skill', 'tracememo-reader', 'SKILL.md') - writeSkill(skillPath) + writeSkill(skillPath, '1.3.0') expect(resolveSkillResourceStatus(runtime)).toMatchObject({ available: true, source: 'development', - version: 'v1.2', + name: 'tracememo-reader', + version: '1.3.0', filePath: skillPath, directoryPath: dirname(skillPath) }) }) - it('resolves the Reader Skill from this checkout', () => { - const workspace = resolve(__dirname, '../..') - const status = resolveSkillResourceStatus({ - appPath: workspace, - cwd: workspace, - resourcesPath: join(workspace, 'node_modules', 'electron', 'resources'), - execPath: join(workspace, 'node_modules', 'electron', 'electron.exe'), - packaged: false - }) - - expect(status).toMatchObject({ - available: true, - source: 'development', - version: 'v1.2', - filePath: join(workspace, 'docs', 'skill', 'tracememo-reader', 'SKILL.md') - }) - }) - it('uses the extraResources Skill directory in a packaged runtime', () => { const root = fixtureRoot() const runtime = environment(root, true) const skillPath = join(runtime.resourcesPath, 'skill', 'tracememo-reader', 'SKILL.md') - writeSkill(skillPath) + writeSkill(skillPath, '1.3.0') expect(resolveSkillResourceStatus(runtime)).toMatchObject({ available: true, source: 'bundled', + version: '1.3.0', filePath: skillPath }) }) @@ -104,4 +100,116 @@ describe('Reader Skill resource resolution', () => { expect(status).toMatchObject({ available: false, source: 'development' }) for (const candidate of candidates) expect(status.error).toContain(candidate.path) }) + + it('omits the version when the frontmatter does not declare one', () => { + const root = fixtureRoot() + const runtime = environment(root, false) + const skillPath = join(runtime.cwd, 'docs', 'skill', 'tracememo-reader', 'SKILL.md') + writeSkill(skillPath) + + const status = resolveSkillResourceStatus(runtime) + expect(status.available).toBe(true) + expect(status.version).toBeUndefined() + }) + + // /health 是外部 Agent 的自检入口:环境探测本身出错时只能降级,不能抛出。 + it('degrades to unavailable instead of throwing when the environment is broken', () => { + const status = resolveSkillResourceStatus({ + appPath: undefined as unknown as string, + cwd: undefined as unknown as string, + resourcesPath: '', + execPath: undefined as unknown as string, + packaged: false + }) + + expect(status.available).toBe(false) + expect(status.error).toContain('未找到 TraceMemo Reader Skill 文件') + expect(status.githubUrl).toContain('github.com') + }) +}) + +describe('Reader Skill document identity', () => { + afterEach(() => { + while (roots.length) rmSync(roots.pop()!, { recursive: true, force: true }) + }) + + it('exposes markdown, version and a content hash that matches the file bytes', () => { + const root = fixtureRoot() + const skillPath = join(root, 'docs', 'skill', 'tracememo-reader', 'SKILL.md') + writeSkill(skillPath, '1.3.0') + const content = readFileSync(skillPath, 'utf-8') + + const document = readSkillDocument(skillPath) + expect(document).not.toBeNull() + expect(document?.version).toBe('1.3.0') + expect(document?.name).toBe('tracememo-reader') + expect(document?.markdown).toBe(content) + expect(document?.contentHash).toBe(sha256(content)) + expect(document?.filePath).toBe(skillPath) + expect(Number.isNaN(Date.parse(document?.modifiedAt || ''))).toBe(false) + }) + + it('returns null for a missing file instead of throwing', () => { + const root = fixtureRoot() + expect(readSkillDocument(join(root, 'missing', 'SKILL.md'))).toBeNull() + }) + + // 自助更新的正确性依赖这条:Agent 覆盖 SKILL.md 后,health 必须立刻报出新版本。 + it('invalidates the cache once the file on disk is replaced', () => { + const root = fixtureRoot() + const skillPath = join(root, 'docs', 'skill', 'tracememo-reader', 'SKILL.md') + writeSkill(skillPath, '1.3.0') + expect(readSkillDocument(skillPath)?.version).toBe('1.3.0') + + writeSkill(skillPath, '1.4.0-with-a-longer-body-to-change-the-file-size') + const updated = readSkillDocument(skillPath) + expect(updated?.version).toBe('1.4.0-with-a-longer-body-to-change-the-file-size') + expect(updated?.contentHash).not.toBe(sha256(skillBody('1.3.0'))) + }) +}) + +describe('SKILL.md frontmatter contract', () => { + it('parses name and version from a plain frontmatter block', () => { + expect(parseSkillFrontmatter('---\nname: a\nversion: 2.1.0\n---\nbody')).toEqual({ + name: 'a', + version: '2.1.0' + }) + }) + + it('ignores files without frontmatter and tolerates CRLF, quotes and comments', () => { + expect(parseSkillFrontmatter('# no frontmatter\n')).toEqual({}) + expect(parseSkillFrontmatter('---\r\n# comment\r\nversion: "3.0.1"\r\n---\r\n')).toEqual({ + version: '3.0.1' + }) + }) + + /** + * 防漂移契约:版本号只有一个真源,就是 SKILL.md 的 frontmatter。 + * 这里独立地按行正则提取一次,与解析结果逐字比对 —— 任何"把版本写回源码常量"的 + * 回归都会让这条测试变红。 + */ + it('keeps the reader Skill version declared in the repository SKILL.md', () => { + const workspace = resolve(__dirname, '../..') + const skillPath = join(workspace, 'docs', 'skill', 'tracememo-reader', 'SKILL.md') + const content = readFileSync(skillPath, 'utf-8') + const declared = /^version:[ \t]*(\S+)[ \t]*$/m.exec(content) + + expect(declared).not.toBeNull() + expect(parseSkillFrontmatter(content).version).toBe(declared![1]) + expect(declared![1]).toMatch(/^\d+\.\d+\.\d+$/) + + const status = resolveSkillResourceStatus({ + appPath: workspace, + cwd: workspace, + resourcesPath: join(workspace, 'node_modules', 'electron', 'resources'), + execPath: join(workspace, 'node_modules', 'electron', 'electron.exe'), + packaged: false + }) + expect(status).toMatchObject({ + available: true, + source: 'development', + version: declared![1], + filePath: skillPath + }) + }) }) diff --git a/tests/unit/tray-icon.test.ts b/tests/unit/tray-icon.test.ts new file mode 100644 index 0000000..ebcbfc5 --- /dev/null +++ b/tests/unit/tray-icon.test.ts @@ -0,0 +1,69 @@ +import { describe, expect, it, vi } from 'vitest' +import { createTrayImage, type TrayNativeImage } from '../../src/main/tray-icon' + +function makeImage(empty = false): TrayNativeImage { + const image = { + addRepresentation: vi.fn(), + isEmpty: vi.fn(() => empty), + resize: vi.fn(), + setTemplateImage: vi.fn() + } + image.resize.mockReturnValue(image) + return image as unknown as TrayNativeImage +} + +describe('tray icon creation', () => { + it('uses a monochrome 1x/2x template image on macOS', () => { + const image = makeImage() + const readImageFile = vi.fn((path: string) => Buffer.from(path)) + const nativeImage = { + createEmpty: vi.fn(() => image), + createFromPath: vi.fn(() => makeImage()) + } + + const result = createTrayImage( + 'darwin', + '/app/icon.png', + { oneX: '/resources/trayTemplate.png', twoX: '/resources/trayTemplate@2x.png' }, + nativeImage, + readImageFile + ) + + expect(result).toBe(image) + expect(readImageFile.mock.calls.map(([path]) => path)).toEqual([ + '/resources/trayTemplate.png', + '/resources/trayTemplate@2x.png' + ]) + expect(image.addRepresentation).toHaveBeenNthCalledWith(1, { + scaleFactor: 1, + dataURL: `data:image/png;base64,${Buffer.from('/resources/trayTemplate.png').toString('base64')}` + }) + expect(image.addRepresentation).toHaveBeenNthCalledWith(2, { + scaleFactor: 2, + dataURL: `data:image/png;base64,${Buffer.from('/resources/trayTemplate@2x.png').toString('base64')}` + }) + expect(image.setTemplateImage).toHaveBeenCalledWith(true) + expect(nativeImage.createFromPath).not.toHaveBeenCalled() + }) + + it('preserves the app icon resize policy on Windows', () => { + const appImage = makeImage() + const nativeImage = { + createEmpty: vi.fn(() => makeImage()), + createFromPath: vi.fn(() => appImage) + } + + const result = createTrayImage( + 'win32', + '/app/icon.png', + { oneX: '/resources/trayTemplate.png', twoX: '/resources/trayTemplate@2x.png' }, + nativeImage, + vi.fn(() => Buffer.alloc(0)) + ) + + expect(nativeImage.createFromPath).toHaveBeenCalledWith('/app/icon.png') + expect(appImage.resize).toHaveBeenCalledWith({ width: 24, height: 24, quality: 'best' }) + expect(appImage.setTemplateImage).not.toHaveBeenCalled() + expect(result).toBe(appImage) + }) +}) diff --git a/tests/unit/voice-recognition-use-case.test.ts b/tests/unit/voice-recognition-use-case.test.ts index d127dde..19a1d6f 100644 --- a/tests/unit/voice-recognition-use-case.test.ts +++ b/tests/unit/voice-recognition-use-case.test.ts @@ -1,17 +1,23 @@ -import { mkdtempSync, rmSync } from 'fs' -import { tmpdir } from 'os' import { join } from 'path' -import { afterEach, describe, expect, it, vi } from 'vitest' +import { describe, expect, it, vi } from 'vitest' import { VoiceRecognitionUseCase } from '../../src/main/voice-pipeline/voice-recognition-use-case' -const roots: string[] = [] - +/** + * 这组用例验证的是**转写更新的编排**:命中缓存/新识别是否走同一条 update path、 + * 账号代号中途变化时是否取消发布、force 是否透传给 pipeline。真正的 + * `pipeline.run` 与 `modelManager.getStatus` 都被 mock,所以**不需要真实的 + * 文件系统或 SQLite**。 + * + * 用内存库 + 纯字符串路径(不建目录、不落盘、不删除): + * `SqliteTranscriptRepository` 一旦落盘就会连带生成 `-wal` / `-shm`, + * 每个用例还要 `rmSync` 整棵临时树 —— 这些在 Windows runner 上(Defender 实时扫描 + * 每次文件创建/删除)会放大到秒级,而对被测行为零贡献。 + */ function createUseCase(): VoiceRecognitionUseCase { - const root = mkdtempSync(join(tmpdir(), 'wxe-voice-use-case-')) - roots.push(root) + const root = join('wxe-voice-use-case-fixture', 'account-a') const useCase = new VoiceRecognitionUseCase({ modelRoot: join(root, 'model'), - databasePath: join(root, 'transcripts.sqlite'), + databasePath: ':memory:', workerPath: join(root, 'unused-worker.js') }) const state = useCase as unknown as { @@ -36,10 +42,6 @@ function createUseCase(): VoiceRecognitionUseCase { return useCase } -afterEach(async () => { - for (const root of roots.splice(0)) rmSync(root, { recursive: true, force: true }) -}) - describe('VoiceRecognitionUseCase transcript updates', () => { it('publishes a successful cache hit through the same update path as fresh recognition', async () => { const useCase = createUseCase() diff --git a/tests/unit/voice-transcription-gateway.test.ts b/tests/unit/voice-transcription-gateway.test.ts new file mode 100644 index 0000000..13e1d8a --- /dev/null +++ b/tests/unit/voice-transcription-gateway.test.ts @@ -0,0 +1,142 @@ +import { describe, expect, it, vi, type Mock } from 'vitest' +import type { + VoiceMessageReference, + VoiceModelStatus, + VoiceRecognitionResult, + VoiceTranscriptSnapshot +} from '../../src/shared/voice-recognition' +import { VoiceTranscriptionGateway } from '../../src/main/voice-pipeline/voice-transcription-gateway' + +const reference = (localId: number): VoiceMessageReference => ({ + sessionId: 'wxid_fixture_member', + localId, + createTime: 1_785_895_200 + localId +}) + +function deferred(): { promise: Promise; resolve: (value: T) => void } { + let resolve!: (value: T) => void + const promise = new Promise((done) => { + resolve = done + }) + return { promise, resolve } +} + +type RecognitionStub = { + accountIdentity: string + getModelStatus: Mock<() => Promise>> + getTranscriptSnapshot: Mock<(reference: VoiceMessageReference) => VoiceTranscriptSnapshot> + recognize: Mock<(...args: unknown[]) => Promise> +} + +function makeRecognition(): RecognitionStub { + return { + accountIdentity: 'account-a', + getModelStatus: vi.fn(async () => ({ state: 'ready' as const })), + getTranscriptSnapshot: vi.fn(() => ({ state: 'pending' as const })), + recognize: vi.fn(async () => ({ + success: true, + transcript: ' 转写结果 ', + cached: false, + durationMs: 1200 + })) + } +} + +describe('VoiceTranscriptionGateway', () => { + it('returns cached transcripts without scheduling recognition', async () => { + const recognition = makeRecognition() + recognition.getTranscriptSnapshot.mockReturnValue({ + state: 'transcribed', + transcript: '已转写' + }) + const gateway = new VoiceTranscriptionGateway(recognition as never) + + const result = await gateway.transcribe([reference(1)], { waitMs: 1000 }) + + expect(result).toEqual([{ state: 'transcribed', transcript: '已转写', cached: true }]) + expect(recognition.recognize).not.toHaveBeenCalled() + }) + + it('does not rerun previously failed voice unless force is set', async () => { + const recognition = makeRecognition() + recognition.getTranscriptSnapshot.mockReturnValue({ state: 'failed', error: 'decode failed' }) + const gateway = new VoiceTranscriptionGateway(recognition as never) + + await expect(gateway.transcribe([reference(1)], { waitMs: 1000 })).resolves.toEqual([ + { state: 'failed', code: 'PREVIOUSLY_FAILED', error: 'decode failed' } + ]) + expect(recognition.recognize).not.toHaveBeenCalled() + + await expect( + gateway.transcribe([reference(1)], { force: true, waitMs: 1000 }) + ).resolves.toEqual([ + { state: 'transcribed', transcript: '转写结果', cached: false, durationMs: 1200 } + ]) + expect(recognition.recognize).toHaveBeenCalledWith(reference(1), { + priority: 'background', + force: true + }) + }) + + it('returns pending at the deadline and lets the next call join the same task', async () => { + const recognition = makeRecognition() + const running = deferred() + recognition.recognize.mockReturnValue(running.promise) + const gateway = new VoiceTranscriptionGateway(recognition as never) + + await expect(gateway.transcribe([reference(1)], { waitMs: 0 })).resolves.toEqual([ + { state: 'pending' } + ]) + expect(gateway.inFlightCount).toBe(1) + + const second = gateway.transcribe([reference(1)], { waitMs: 1000 }) + running.resolve({ success: true, transcript: '晚到的结果', cached: false }) + + await expect(second).resolves.toEqual([ + { state: 'transcribed', transcript: '晚到的结果', cached: false } + ]) + expect(recognition.recognize).toHaveBeenCalledTimes(1) + expect(gateway.inFlightCount).toBe(0) + }) + + it('rejects the whole request when the queue cannot take the new work', async () => { + const recognition = makeRecognition() + recognition.recognize.mockReturnValue(new Promise(() => undefined)) + const gateway = new VoiceTranscriptionGateway(recognition as never, 2) + + await gateway.transcribe([reference(1)], { waitMs: 0 }) + await expect( + gateway.transcribe([reference(2), reference(3)], { waitMs: 0 }) + ).resolves.toBeNull() + + expect(recognition.recognize).toHaveBeenCalledTimes(1) + expect(gateway.inFlightCount).toBe(1) + }) + + it('requeues an item preempted by an interactive request', async () => { + const recognition = makeRecognition() + recognition.recognize + .mockResolvedValueOnce({ success: false, code: 'CANCELLED', error: '语音识别已取消' }) + .mockResolvedValueOnce({ success: true, transcript: '重排后完成', cached: false }) + const gateway = new VoiceTranscriptionGateway(recognition as never) + + await expect(gateway.transcribe([reference(1)], { waitMs: 1000 })).resolves.toEqual([ + { state: 'transcribed', transcript: '重排后完成', cached: false } + ]) + expect(recognition.recognize).toHaveBeenCalledTimes(2) + }) + + it('stops requeueing after the account changes', async () => { + const recognition = makeRecognition() + recognition.recognize.mockImplementation(async () => { + recognition.accountIdentity = 'account-b' + return { success: false, code: 'CANCELLED', error: '语音识别已取消' } + }) + const gateway = new VoiceTranscriptionGateway(recognition as never) + + await expect(gateway.transcribe([reference(1)], { waitMs: 1000 })).resolves.toEqual([ + { state: 'failed', code: 'CANCELLED', error: '语音识别已取消' } + ]) + expect(recognition.recognize).toHaveBeenCalledTimes(1) + }) +}) diff --git a/tests/unit/wcdb-message-shards.test.ts b/tests/unit/wcdb-message-shards.test.ts index 44734e8..16ca783 100644 --- a/tests/unit/wcdb-message-shards.test.ts +++ b/tests/unit/wcdb-message-shards.test.ts @@ -97,6 +97,80 @@ describe('WCDB message shard pagination', () => { ]) }) + it.each(['wxid_fixture_peer', 'fixture@chatroom'])( + 'reads %s from all canonical shards when native discovery is empty', + async (username) => { + const root = fs.mkdtempSync(path.join(os.tmpdir(), 'wxe-message-fallback-')) + temporaryDirectories.push(root) + const dbStoragePath = path.join(root, 'db_storage') + const messageRoot = path.join(dbStoragePath, 'message') + fs.ensureDirSync(messageRoot) + for (const name of [ + 'message_0.db', + 'message_7.db', + 'message_6.db', + 'message_0 (同步冲突).db', + 'biz_message_0.db' + ]) { + fs.writeFileSync(path.join(messageRoot, name), '') + } + const tableName = `Msg_${crypto.createHash('md5').update(username).digest('hex')}` + const query = vi.fn((_kind: string, dbPath: string, sql: string) => { + if (sql.includes('sqlite_master')) { + return dbPath.endsWith('message_6.db') + ? [{ name: 'Name2Id' }] + : [{ name: tableName }, { name: 'Name2Id' }] + } + expect(sql).toContain('n.user_name AS sender_username') + expect(sql).toContain('n.rowid = m.real_sender_id') + expect(sql).toContain('"create_time" <= 1800000000') + expect(sql).toContain('ORDER BY "create_time" DESC LIMIT 20') + const isLatestShard = dbPath.endsWith('message_7.db') + return [ + { + local_id: 1, + server_id: isLatestShard ? 'fixture-new' : 'fixture-old', + local_type: 1, + create_time: isLatestShard ? 1700000001 : 1700000000, + message_content: 'fixture text', + sender_username: isLatestShard ? 'wxid_self' : 'wxid_peer' + } + ] + }) + const stats = vi.fn(() => []) + const client = Object.assign(Object.create(Wcdb4Client.prototype), { + dbStoragePath, + accountRoot: path.join(root, 'wxid_self'), + wxid: 'wxid_self', + displayNameCache: new Map(), + avatarCache: new Map(), + wcdbGetMessageTableStats: stats, + wcdbExecQuery: query, + getMessagesByCursor: vi.fn(() => []), + getMessagesByCursorAsync: vi.fn(async () => []), + getGroupNicknames: vi.fn(() => new Map()), + callJson: vi.fn((call) => call(1, [null])), + callJsonAsync: vi.fn(async (fn, ...args) => fn(...args)) + }) as Wcdb4Client + // The synchronous FFI callback includes handle/output arguments. + const syncQuery = vi.fn((_handle, kind, dbPath, sql) => query(kind, dbPath, sql)) + Reflect.set(client, 'wcdbExecQuery', syncQuery) + const synchronous = client.getMessages(username, undefined, 1800000000, { limit: 20 }) + Reflect.set(client, 'wcdbExecQuery', query) + const asynchronous = await client.getMessagesAsync(username, undefined, 1800000000, { + limit: 20 + }) + + expect(asynchronous).toEqual(synchronous) + expect(asynchronous.map((row) => [row.serverId, row.sender, row.mesDes])).toEqual([ + ['fixture-old', 'wxid_peer', 1], + ['fixture-new', 'wxid_self', 0] + ]) + expect(query).toHaveBeenCalledTimes(10) + expect(query.mock.calls.every(([, dbPath]) => /message_(0|6|7)\.db$/.test(dbPath))).toBe(true) + } + ) + it('creates a stable ASCII junction for a Windows account path containing Chinese', () => { const root = fs.mkdtempSync(path.join(os.tmpdir(), 'wxe-path-bridge-')) temporaryDirectories.push(root)